Exemple #1
0
        #["Click on the word ", html.Span("popover", id="popover-target")]
        # It seems the popover target needs to be a html.Span(), it cannot be a DataTable???
        [html.Span("", id="popover-target")]),
    dbc.Popover(
        [
            #dbc.PopoverHeader("Popover header"),
            #dbc.PopoverBody("Popover body"),
            colorPicker,
            dbc.Button("OK",
                       color="primary",
                       outline=True,
                       size="sm",
                       id='ok-color-button'),
            dbc.Button("Cancel",
                       color="primary",
                       outline=True,
                       size="sm",
                       id='cancel-color-button'),
        ],
        id='popover',
        is_open=False,
        target='popover-target',
        #target='horizontal-popover-position',
        #target="file-list-table",
        delay={
            'show': 100,
            'hide': 500
        },
    ),
])
###
###
Exemple #2
0
def card_main_volumn_based_measures(app):

    return dbc.Card(dbc.CardBody([
        html.H1("Volume Based Measures",
                className="mb-3",
                style={"font-size": "1.5rem"}),
        html.Div(
            [
                dbc.Button(
                    "Edit Measures",
                    id="button-add-measure",
                    className="mb-3",
                    style={
                        "background-color": "#38160f",
                        "border": "none",
                        "border-radius": "10rem",
                        "font-family": "NotoSans-Regular",
                        "font-size": "0.6rem"
                    },
                ),
                dbc.Popover(
                    [
                        dbc.PopoverHeader("Eidt Measures"),
                        dbc.PopoverBody([
                            html.Div([
                                dbc.Checklist(
                                    options=[
                                        {
                                            'label': "Market Share",
                                            'value': "Market Share"
                                        },
                                        {
                                            'label': "Utilizer Count",
                                            'value': "Utilizer Count"
                                        },
                                        {
                                            'label':
                                            "Avg Script (30-day adj) per Utilizer",
                                            'value':
                                            "Avg Script (30-day adj) per Utilizer"
                                        },
                                        {
                                            'label':
                                            "Total Script Count (30-day adj) by Dosage (in thousand)",
                                            'value':
                                            "Total Script Count (30-day adj) by Dosage (in thousand)"
                                        },
                                        {
                                            'label':
                                            "Total Units by Dosage (Mn)",
                                            'value':
                                            "Total Units by Dosage (Mn)"
                                        },
                                    ],
                                    value=[
                                        "Market Share", "Utilizer Count",
                                        "Avg Script (30-day adj) per Utilizer"
                                    ],
                                    labelCheckedStyle={"color": "#057aff"},
                                    id="checklist-add-measure",
                                    style={
                                        "font-family": "NotoSans-Condensed",
                                        "font-size": "0.8rem",
                                        "padding": "1rem"
                                    },
                                ),
                            ],
                                     style={
                                         "padding-top": "0.5rem",
                                         "padding-bottom": "2rem"
                                     }),
                            html.Div([
                                dbc.Button(
                                    "Comfirm",
                                    id="add-button-add-measure",
                                    className="mb-3",
                                    style={
                                        "background-color": "#38160f",
                                        "border": "none",
                                        "border-radius": "10rem",
                                        "font-family": "NotoSans-Regular",
                                        "font-size": "0.6rem"
                                    },
                                )
                            ],
                                     style={"text-align": "center"})
                        ]),
                    ],
                    id="popover-add-measure",
                    is_open=False,
                    target="button-add-measure",
                    placement="top",
                ),
            ],
            style={"text-align": "end"},
        ),
        html.Div(
            [
                card_sub1_volumn_based_measures(
                    app, "Market Share", piechart_utilizer1, 'fig', 0.85),
                card_sub1_volumn_based_measures(app, "Utilizer Count",
                                                tbl_utilizer1, 'dash', 0.6),
                card_sub1_volumn_based_measures(
                    app, "Avg Script (30-day adj) per Utilizer",
                    bargraph_script_per_util, 'fig', 0.6),
                card_sub2_volumn_based_measures(
                    app,
                    "Total Script Count (30-day adj) by Dosage (in thousand)",
                    bargraph_tot_script, bargraph_tot_script_split, 'fig',
                    'fig', 1, 1),
                card_sub2_volumn_based_measures(
                    app, "Total Units by Dosage (Mn)", bargraph_tot_unit,
                    bargraph_tot_unit_split, 'fig', 'fig', 1, 1),
            ],
            className="mb-3",
        ),
    ]),
                    style={
                        "box-shadow":
                        "0 4px 8px 0 rgba(0, 0, 0, 0.05), 0 6px 20px 0 rgba(0, 0, 0, 0.05)",
                        "border": "none",
                        "border-radius": "0.5rem"
                    })
Exemple #3
0
    def __init__(self, parent_app, converter_class):
        """
        Forms to interface user input with NWB converters.

        INPUT:
        ------
        parent_app : running Dash app
        converter : NWB converter class
        """
        super().__init__([])
        self.parent_app = parent_app
        self.converter_class = converter_class
        self.export_controller = False
        self.convert_controller = False
        self.get_metadata_controller = False
        self.conversion_messages = ''
        self.conversion_msg_controller = True
        self.msg_buffer = StringIO()

        self.downloads_path = Path(
            __file__).parent.parent.parent.parent.parent.absolute(
            ) / 'downloads'
        self.root_path = Path(
            self.parent_app.server.config['NWB_GUI_ROOT_PATH'])

        if not self.downloads_path.is_dir():
            self.downloads_path.mkdir()

        self.source_json_schema = converter_class.get_source_schema()
        self.conversion_json_schema = converter_class.get_conversion_options_schema(
        )

        # Source data Form
        self.source_forms = SchemaFormContainer(id='sourcedata',
                                                schema=self.source_json_schema,
                                                parent_app=self.parent_app,
                                                root_path=self.root_path)

        # Conversion Option Form
        self.conversion_options_forms = SchemaFormContainer(
            id='conversiondata',
            schema=self.conversion_json_schema,
            parent_app=self.parent_app,
            root_path=self.root_path)

        self.metadata_forms = SchemaFormContainer(id='metadata',
                                                  schema=dict(),
                                                  parent_app=self.parent_app,
                                                  root_path=self.root_path)
        self.style = {'background-color': '#f0f0f0', 'min-height': '100vh'}

        self.children = [
            html.Br(),
            dbc.Container([
                dbc.Row([
                    html.Br(),
                    dbc.Col(dbc.Card(
                        [
                            dbc.Col(html.H4('Source Data'),
                                    style={
                                        'text-align': 'center',
                                        'justify-content': 'center',
                                        "margin-top": "15px"
                                    },
                                    width={'size': 12}),
                            dbc.CardBody(self.source_forms)
                        ],
                        style={
                            'background-color': '##eceef7',
                            "box-shadow": "2px 2px 2px 2px rgba(0,0,0,0.1)"
                        }),
                            width={'size': 12}),
                    dbc.Col(dbc.Button('Get Metadata Form',
                                       id='get_metadata_btn',
                                       color='dark'),
                            style={
                                'justify-content': 'left',
                                'text-align': 'left',
                                'margin-top': '1%'
                            },
                            width={'size': 4})
                ]),
                dbc.Row([
                    dbc.Col(
                        dcc.Upload(dbc.Button('Load Metadata', color='dark'),
                                   id='button_load_metadata',
                                   style={'display': 'none'}),
                        width={'size': 2},
                        style={
                            'justify-content': 'left',
                            'text-align': 'left',
                            'margin-top': '1%'
                        },
                    ),
                    dbc.Col(
                        html.Div([
                            dbc.Button('Export Metadata',
                                       id='button_export_metadata',
                                       color='dark',
                                       style={'display': 'none'}),
                            dbc.Popover(
                                [
                                    dbc.PopoverBody([
                                        html.Div([
                                            html.
                                            A(dbc.
                                              Button("Download as JSON",
                                                     id='button_export_json',
                                                     color="link"),
                                              href=
                                              '/downloads/exported_metadata.json'
                                              ),
                                            html.
                                            A(dbc.
                                              Button("Download as YAML",
                                                     id='button_export_yaml',
                                                     color="link"),
                                              href=
                                              '/downloads/exported_metadata.yaml'
                                              )
                                        ])
                                    ])
                                ],
                                id="popover_export_metadata",
                                target='button_export_metadata',
                                is_open=False,
                                placement='top',
                            )
                        ]),
                        width={'size': 2},
                        style={
                            'justify-content': 'left',
                            'text-align': 'left',
                            'margin-top': '1%'
                        },
                    ),
                    dbc.Col(
                        dbc.Button('Refresh',
                                   id='button_refresh',
                                   color='dark',
                                   style={'display': 'none'}),
                        width={'size': 2},
                        style={
                            'justify-content': 'left',
                            'text-align': 'left',
                            'margin-top': '1%'
                        },
                    )
                ]),
                dbc.Row([
                    dbc.Col(
                        dbc.Alert(children=[],
                                  id="alert_required_source",
                                  dismissable=True,
                                  is_open=False,
                                  color='danger')),
                    dbc.Col(
                        dbc.Alert(children=[],
                                  id="alert_required",
                                  dismissable=True,
                                  is_open=False,
                                  color='danger'))
                ]),
                dbc.Row(dbc.Col(id='metadata-col', width={'size': 12}),
                        style={
                            'margin-top': '1%',
                            'margin-bottom': '10px'
                        }),
                dbc.Row(
                    dbc.Col([
                        dbc.Card(
                            [
                                dbc.Col(html.H4('Conversion Options'),
                                        style={
                                            'text-align': 'center',
                                            'justify-content': 'center',
                                            "margin-top": "15px"
                                        },
                                        width={'size': 12}),
                                dbc.CardBody(self.conversion_options_forms)
                            ],
                            style={
                                'background-color': '##eceef7',
                                "box-shadow": "2px 2px 2px 2px rgba(0,0,0,0.1)"
                            }),
                    ],
                            id='conversion-col',
                            width={'size': 12},
                            style={'display': 'none'})),
                dbc.Row(dbc.Col(dbc.InputGroup([
                    dbc.InputGroupAddon("Output file: ", addon_type="prepend"),
                    dbc.Input(id="output-nwbfile-name",
                              value=str(self.root_path) + '/'),
                    dbc.InputGroupAddon(
                        dbc.Button('Run Conversion',
                                   id='button_run_conversion'),
                        addon_type="append",
                    ),
                ]),
                                width={'size': 11}),
                        style={
                            'text-align': 'left',
                            'margin-top': '15px',
                            'display': 'none'
                        },
                        id='row_output_conversion'),
                dbc.Row([
                    dbc.Col(
                        dbc.Alert(children=[],
                                  id="alert-required-conversion",
                                  dismissable=True,
                                  is_open=False,
                                  color='danger'))
                ]),
                dbc.Textarea(id='text-conversion-results',
                             className='string_input',
                             bs_size="lg",
                             readOnly=True,
                             style={
                                 'font-size': '16px',
                                 'display': 'none'
                             }),
                dbc.Button(id='pause_loop', style={'display': 'none'}),
                dcc.Interval(
                    id='interval-text-results', max_intervals=0, interval=500),
                html.Br(),
                html.Div(id='export-output', style={'display': 'none'}),
                html.Div(id='export-input', style={'display': 'none'}),
                dbc.Button(id='get_metadata_done', style={'display': 'none'}),
            ],
                          style={'min-height': '110vh'})
        ]

        @self.parent_app.callback([
            Output("popover_export_metadata", "is_open"),
            Output('alert_required', 'is_open'),
            Output('alert_required', 'children'),
        ], [Input('metadata-output-update-finished-verification', 'children')
            ], [
                State("popover_export_metadata", "is_open"),
                State('alert_required', 'is_open')
            ])
        def export_metadata(trigger, fileoption_is_open, req_is_open):
            """
            Export Metadata Form data to JSON and YAML file
            This function is triggered when metadata internal dict is updated
            and export controller is setted to true.
            If export controller is not setted to true but the metadata internal dict was updated
            the function will return the current application state
            """
            # Prevent default
            if not self.export_controller or not trigger:
                return fileoption_is_open, req_is_open, []

            if self.export_controller and fileoption_is_open:
                self.export_controller = False
                return not fileoption_is_open, req_is_open, []

            alerts, output = self.metadata_forms.data_to_nested()

            # If required fields missing return alert
            if alerts is not None:
                return fileoption_is_open, not req_is_open, alerts

            updated_data = dict_deep_update(self.start_metadata_data, output)

            # Make temporary files on server side
            # JSON
            exported_file_path = self.downloads_path / 'exported_metadata.json'
            with open(exported_file_path, 'w') as outfile:
                json.dump(updated_data, outfile, indent=4)

            # YAML
            exported_file_path = self.downloads_path / 'exported_metadata.yaml'
            with open(exported_file_path, 'w') as outfile:
                yaml.dump(updated_data, outfile, default_flow_style=False)

            return not fileoption_is_open, req_is_open, []

        @self.parent_app.callback(
            [
                Output('metadata-external-trigger-update-internal-dict',
                       'children'),
                Output('conversiondata-external-trigger-update-internal-dict',
                       'children')
            ],
            [
                Input('button_export_metadata', 'n_clicks'),
                Input('button_run_conversion', 'n_clicks')
            ],
        )
        def update_internal_metadata(click_export, click_conversion):
            """
            Trigger metadata internal dict update and then:
            1) set export_controller to true, when exporting to json/yaml
            2) set convert_controller to true, when running conversion
            """
            ctx = dash.callback_context
            if not ctx.triggered:
                return dash.no_update
            else:
                button_id = ctx.triggered[0]['prop_id'].split('.')[0]
                if button_id == 'button_export_metadata':
                    self.export_controller = True
                    self.convert_controller = False
                elif button_id == 'button_run_conversion':
                    self.export_controller = False
                    self.convert_controller = True
                return str(np.random.rand()), str(np.random.rand())

        @self.parent_app.callback([
            Output('metadata-col', 'children'),
            Output('button_load_metadata', 'style'),
            Output('button_export_metadata', 'style'),
            Output('button_refresh', 'style'),
            Output('row_output_conversion', 'style'),
            Output('text-conversion-results', 'style'),
            Output('get_metadata_done', 'n_clicks'),
            Output('alert_required_source', 'is_open'),
            Output('alert_required_source', 'children'),
            Output('conversion-col', 'style')
        ], [
            Input('sourcedata-output-update-finished-verification', 'children')
        ], [
            State('alert_required_source', 'is_open'),
            State('button_load_metadata', 'style'),
            State('button_export_metadata', 'style'),
            State('button_refresh', 'style'),
            State('row_output_conversion', 'style'),
            State('text-conversion-results', 'style'),
            State('conversion-col', 'style')
        ])
        def get_metadata(trigger, alert_is_open, *styles):
            """
            Render Metadata forms based on Source Data Form
            This function is triggered when sourcedata internal dict is updated
            and get metadata controller is setted to true.
            If get metadata controller is not setted to true but the sourcedata
            internal dict was updated the function will return the current
            application state
            """
            if not trigger or not self.get_metadata_controller:
                # If metadata forms defined reset to default state
                if self.metadata_forms.children_forms:
                    self.metadata_forms.children_forms = []
                    self.metadata_forms.children = self.metadata_forms.children_triggers
                    self.metadata_forms.data = dict()
                    self.metadata_forms.schema = dict()
                return [
                    self.metadata_forms, styles[0], styles[1], styles[2],
                    styles[3], styles[4], None, alert_is_open, [], styles[5]
                ]

            # Get forms data
            alerts, source_data = self.source_forms.data_to_nested()

            if alerts is not None:
                return [
                    self.metadata_forms, styles[0], styles[1], styles[2],
                    styles[3], styles[4], None, True, alerts, styles[5]
                ]

            self.get_metadata_controller = False

            # Get metadata schema from converter
            self.converter = self.converter_class(source_data=source_data)
            self.metadata_json_schema = self.converter.get_metadata_schema()

            # Get metadata data from converter
            self.metadata_json_data = self.converter.get_metadata()
            self.start_metadata_data = self.metadata_json_data

            if self.metadata_forms.children_forms:
                # Clean form children if exists to render new one
                self.metadata_forms.children_forms = []

            self.metadata_forms.schema = self.metadata_json_schema
            self.metadata_forms.construct_children_forms()

            output_form = dbc.Card(
                [
                    dbc.Col(html.H4('Metadata'),
                            style={
                                'text-align': 'center',
                                'justify-content': 'center',
                                "margin-top": "15px"
                            },
                            width={'size': 12}),
                    dbc.CardBody(self.metadata_forms)
                ],
                style={
                    'background-color': '##eceef7',
                    "box-shadow": "2px 2px 2px 2px rgba(0,0,0,0.1)"
                })

            self.conversion_options_data = self.converter.get_conversion_options(
            )

            try:
                self.metadata_forms.update_data(data=self.metadata_json_data)
                self.conversion_options_forms.update_data(
                    data=self.conversion_options_data)
            except Exception as e:
                alert_field = ' '.join([
                    w for w in str(e).strip().split('-')[1:]
                    if not w.isdigit()
                ])
                if alert_field == '':
                    alert_field = "One or more form fields failed to auto-fill. Please check if your Converter's metadata complies to its schema."
                exception_alert = [
                    html.H4('Field not found on schema',
                            className='alert-heading'),
                    html.Hr(),
                    html.A(alert_field,
                           href="#" + f'wrapper-{alert_field}',
                           className="alert-link")
                ]
                return [
                    output_form, {
                        'display': 'block'
                    }, {
                        'display': 'block'
                    }, {
                        'display': 'block'
                    }, {
                        'display': 'block',
                        'text-align': 'left',
                        'margin-top': '15px'
                    }, {
                        'font-size': '16px',
                        'display': 'block',
                        'height': '100%',
                        "min-height": "200px",
                        "max-height": "600px"
                    }, 1, True, exception_alert, {
                        'display': 'block',
                        "margin-top": "15px"
                    }
                ]

            return [
                output_form, {
                    'display': 'block'
                }, {
                    'display': 'block'
                }, {
                    'display': 'block'
                }, {
                    'display': 'block',
                    'text-align': 'left',
                    'margin-top': '15px'
                }, {
                    'font-size': '16px',
                    'display': 'block',
                    'height': '100%',
                    "min-height": "200px",
                    "max-height": "600px"
                }, 1, alert_is_open, [], {
                    'display': 'block',
                    "margin-top": "15px"
                }
            ]

        @self.parent_app.callback(
            Output('sourcedata-external-trigger-update-internal-dict',
                   'children'), [Input('get_metadata_btn', 'n_clicks')])
        def update_internal_sourcedata(click):
            """Update sourcedata internal dictionary to Get Metadata Forms from it"""
            if click:
                self.get_metadata_controller = True
                return str(np.random.rand())

        @self.parent_app.callback(
            Output(
                {
                    'type': 'external-trigger-update-links-values',
                    'index': 'metadata-external-trigger-update-links-values'
                }, 'children'), [Input('button_refresh', 'n_clicks')])
        def refresh_forms_links(click):

            if click:
                return str(np.random.rand())

            raise dash.exceptions.PreventUpdate

        @self.parent_app.callback(
            Output(
                {
                    'type': 'external-trigger-update-forms-values',
                    'index': 'metadata-external-trigger-update-forms-values'
                }, 'children'), [
                    Input('button_load_metadata', 'contents'),
                    Input('get_metadata_done', 'n_clicks')
                ], [State('button_load_metadata', 'filename')])
        def update_forms_values_metadata(contents, click, filename):
            """
            Updates forms values (except links) when:
            - Forms are created (receives metadata dict from Converter)
            - User uploads metadata json / yaml file
            """
            ctx = dash.callback_context
            trigger_source = ctx.triggered[0]['prop_id'].split('.')[0]

            if trigger_source != 'button_load_metadata' and click is None:
                output = []
                return output

            if trigger_source != 'button_load_metadata' and click is not None:
                output = str(np.random.rand())
                return output

            content_type, content_string = contents.split(',')
            filename_extension = filename.split('.')[-1]

            # Update SchemaFormContainer internal data dictionary
            if filename_extension == 'json':
                bs4decode = base64.b64decode(content_string)
                json_string = bs4decode.decode('utf8').replace("'", '"')
                self.metadata_json_data = json.loads(json_string)
                self.metadata_forms.update_data(data=self.metadata_json_data)
            elif filename_extension in ['yaml', 'yml']:
                bs4decode = base64.b64decode(content_string)
                yaml_data = yaml.load(bs4decode, Loader=yaml.BaseLoader)
                self.metadata_json_data = yaml_data
                self.metadata_forms.update_data(data=self.metadata_json_data)
            # Trigger update of React components
            output = str(np.random.rand())

            return output

        @self.parent_app.server.route('/downloads/<path:filename>')
        def download_file(filename):
            return flask.send_from_directory(
                directory=self.downloads_path,
                path=filename,
                as_attachment=True,
            )

        @self.parent_app.callback([
            Output('interval-text-results', 'max_intervals'),
            Output('alert-required-conversion', 'is_open'),
            Output('alert-required-conversion', 'children'),
        ], [
            Input('metadata-output-update-finished-verification', 'children'),
            Input('pause_loop', 'n_clicks')
        ], [
            State('output-nwbfile-name', 'value'),
            State('alert-required-conversion', 'is_open')
        ])
        def trigger_conversion(trigger, pause, output_nwbfile, alert_is_open):
            ctx = dash.callback_context
            trigger_source = ctx.triggered[0]['prop_id'].split('.')[0]

            if trigger_source == 'metadata-output-update-finished-verification' and self.convert_controller:
                # run conversion
                alerts, metadata_form_data = self.metadata_forms.data_to_nested(
                )

                _, conversion_options_data = self.conversion_options_forms.data_to_nested(
                )  # use this metadata to conversion

                metadata = dict_deep_update(self.start_metadata_data,
                                            metadata_form_data)

                if alerts is not None:
                    return 0, True, alerts

                nwbfile_path = output_nwbfile

                self.msg_buffer.truncate(0)

                self.t = threading.Thread(target=self.conversion,
                                          daemon=True,
                                          args=(metadata, nwbfile_path,
                                                conversion_options_data))
                self.t.start()

                self.conversion_msg_controller = True
                return -1, False, []  # run loop

            elif trigger_source == 'pause_loop' and pause is not None:
                # Pause interval component that reads conversion messages and terminate conversion thread
                if self.t.is_alive():
                    self.t.terminate()
                return 0, False, []

            return dash.no_update

        @self.parent_app.callback([
            Output('text-conversion-results', 'value'),
            Output('pause_loop', 'n_clicks')
        ], [Input('interval-text-results', 'n_intervals')])
        def update_conversion_messages(n_intervals):
            self.conversion_messages = self.msg_buffer.getvalue()

            if self.conversion_msg_controller:
                return self.conversion_messages, None
            return self.conversion_messages, 1
Exemple #4
0
            style={"margin-top": "70px"},
            children=[html.H1('Anomaly Detector Dashboard')]),
])
navbar = dbc.Nav(
    className="nav nav-pills",
    children=[
        ## logo/home
        ## about
        dbc.NavItem(
            html.Div([
                dbc.NavLink("About",
                            href="/",
                            id="about-popover",
                            active=False),
                dbc.Popover(id="about",
                            is_open=False,
                            target="about-popover",
                            children=[dbc.PopoverHeader("How it works")])
            ])),
        ## links
        dbc.DropdownMenu(
            label="Links",
            nav=True,
            children=[
                dbc.DropdownMenuItem(
                    [html.I(className="fa fa-linkedin"), "  Contacts"],
                    href="#",
                    target="_blank"),
                dbc.DropdownMenuItem(
                    [html.I(className="fa fa-github"), "  Code"],
                    href="#",
                    target="_blank")
Exemple #5
0
            "top": 66,
            "right": 10,
            "width": 850
        })
])

# Instructions toast
instructions_pop = html.Div([
    dbc.Button("Instructions",
               id='instructions-toggle',
               color='primary',
               size='sm'),
    dbc.Popover(
        [dbc.PopoverHeader('Instructions'),
         dbc.PopoverBody(instructions)],
        id='instructions',
        is_open=False,
        # top: 66 positions the toast below the navbar
        target='instructions-toggle',
        placement='bottom')
])

# LAYOUT 1
layout1 = html.Div([
    navbar,
    dbc.Container(
        dbc.Row([
            dbc.Col([
                dbc.Row([
                    dbc.Col(html.H5(
                        'FY20 Annual Work Plan Dashboard (Updated with May 2020 Actuals)',
                        style={
Exemple #6
0
 [
     dbc.Col(
         dbc.Button("Info", id="info-open-button", n_clicks=0),
         id="info-open-col", 
         width="auto"
     ),
     dbc.Popover(
         [
             dbc.PopoverBody(
                 [   
                     dbc.NavLink(dbc.Button("Select node", id="select-node-button", n_clicks=0),
                     href="/article",
                     id="node-link"
                     ),
                     dbc.NavLink(dbc.Button("Select article", id="select-article-button", n_clicks=0),
                     href="/article",
                     id="article-link"
                     )
                 ]
             ),
         ],
         id="popover",
         is_open=False,
         target="popover-target",
         placement="top"
     ),
     dbc.Modal(
         [
             dbc.ModalHeader("Instructions"),
             dbc.ModalBody(
                 dcc.Tabs([
                     dcc.Tab([
Exemple #7
0
def get_app_layout(graph_data, color_legends=[], directed=False):
    """Create and return the layout of the app

    Parameters
    --------------
    graph_data: dict{nodes, edges}
        network data in format of visdcc
    """
    # Step 1: find categorical features of nodes
    node_df = pd.DataFrame(graph_data['nodes'])
    cat_node_features = ['None'] + node_df.columns[(node_df.dtypes == 'object') & (node_df.apply(pd.Series.nunique) <= 20)].tolist()
    try: # remove irrelevant cols
        cat_node_features.remove('shape')
        cat_node_features.remove('label')
        cat_node_features.remove('id')
    except:
        pass
    # Step 2: find categorical features of edges
    edge_df = pd.DataFrame(graph_data['edges']).drop(columns=['color'])
    cat_edge_features = ['None'] + edge_df.columns[(edge_df.dtypes == 'object') & (edge_df.apply(pd.Series.nunique) <= 20)].tolist()
    try: # remove irrelevant cols
        cat_edge_features.remove('from')
        cat_edge_features.remove('to')
        cat_edge_features.remove('id')
    except:
        pass
    # Step 3: create and return the layout
    # resolve path
    this_dir, _ = os.path.split(__file__)
    image_filename = os.path.join(this_dir, "assest", "logo.png")
    encoded_image = base64.b64encode(open(image_filename, 'rb').read())
    return html.Div([
            # create_row(html.H2(children="Jaal")), # Title
            create_row(html.Img(src='data:image/png;base64,{}'.format(encoded_image.decode()), width="80px")),
            create_row([
                dbc.Col([
                    # setting panel
                    dbc.Form([
                        # ---- search section ----
                        html.H6("Search"),
                        html.Hr(className="my-2"),
                        search_form,
                        
                        # ---- filter section ----
                        html.H6("Filter"),
                        html.Hr(className="my-2"),
                        filter_node_form, 
                        filter_edge_form,
                        
                        # ---- color section ----
                        create_row([
                            html.H6("Color"), # heading
                            dbc.Button("Legends", id="color-legend-toggle", outline=True, color="secondary", size="sm"), # legend
                            # add the legends popup
                            dbc.Popover(
                                children=color_legends,
                                id="color-legend-popup", is_open=False, target="color-legend-toggle",
                            ),
                        ], {**fetch_flex_row_style(), 'margin-left': 0, 'margin-right':0, 'justify-content': 'space-between'}),
                        html.Hr(className="my-2"), 
                        get_select_form_layout(
                            id='color_nodes',
                            options=[{'label': opt, 'value': opt} for opt in cat_node_features],
                            label='Color nodes by',
                            description='Select the categorical node property to color nodes by'
                        ), 
                        get_select_form_layout(
                            id='color_edges',
                            options=[{'label': opt, 'value': opt} for opt in cat_edge_features],
                            label='Color edges by',
                            description='Select the categorical edge property to color edges by'
                        ), 
                    ], className="card", style={'padding': '5px', 'background': '#e5e5e5'}), 
                ],width=3, style={'display': 'flex', 'justify-content': 'center', 'align-items': 'center'}),
                # graph 
                dbc.Col(
                    visdcc.Network(id = 'graph', 
                                data = graph_data,
                                options = dict(height= '600px', width= '100%', 
                                               interaction={'hover': True},
                                               edges={'arrows':{'to': directed}},
                                               physics={'stabilization': {'iterations': 100}}
                                               ))
                , width=9)]),
            # stats cards
            # dbc.Row([
            #     dbc.Col(create_card(id="nodes_count", value="NA", description='Nodes'),width={'offset':3}),
            #     dbc.Col(create_card(id="edges_count", value="NA", description='Edges'),width={'offset':6})
            # ])
        ])
    
)

charts_deck = dbc.CardDeck(
            children=[
                dbc.Card(
                    children=[
                        dbc.CardHeader(
                            dbc.Row(
                                children=[
                                    html.H5('Confirmed Cases', className='card-title', style={'text-align': 'center'}),
                                    dbc.Popover(
                                        children=[
                                            dbc.PopoverHeader('Infection Map'),
                                            dbc.PopoverBody('Area of the bubble is related to acumulative '
                                                            'number of cases in the region / country. Hover over '
                                                            'to see the actual numbers. Scroll to zoom in/out '
                                                            'and double click to reset view.')
                                        ],
                                        id='map-popover',
                                        is_open=False,
                                        target='map-popover-target'
                                    ),
                                    dbc.Button('?', id='map-popover-target', className='button', color='info')
                                ],
                                align='center',
                                justify='between',
                                className='pl-2 pr-2'
                        )),
                        dbc.CardBody(
                            children=[
                                dcc.Graph(
                                    id='infection-map',
Exemple #9
0
def header():
    return html.Div(
        id='app-page-header',
        children=[
            html.Div(
                children=[
                    html.A(
                        id='lsm-logo',
                        children=[
                            html.Img(style={
                                'height': '6%',
                                'width': '6%'
                            },
                                     src='data:image/png;base64,{}'.format(
                                         base64.b64encode(
                                             open(f"{logo1path}",
                                                  'rb').read()).decode()))
                        ],
                        href=f"{logo1URL}",
                        target="_blank",  #open link in new tab
                        style={"margin-left": "10px"}),
                    html.Div(children=[
                        html.H5("Exchange option replication strategy app"),
                        html.H6("Black-Scholes-Merton model")
                    ],
                             style={
                                 "display": "inline-block",
                                 "font-family": 'sans-serif',
                                 'transform': 'translateY(+32%)',
                                 "margin-left": "10px"
                             }),
                    html.Div(children=[
                        dbc.Button("About",
                                   id="popover-target",
                                   outline=True,
                                   style={
                                       "color": "white",
                                       'border': 'solid 1px white'
                                   }),
                        dbc.Popover(children=[
                            dbc.PopoverHeader("About"),
                            dbc.PopoverBody([
                                f"{author}", f"\n {emailAuthor}",
                                html.Hr(),
                                f"This app was built for my Master's Thesis, under the supervision of {supervisor} ({emailSupervisor})."
                            ]),
                        ],
                                    id="popover",
                                    is_open=False,
                                    target="popover-target"),
                    ],
                             style={
                                 "display": "inline-block",
                                 "font-family": "sans-serif",
                                 "marginLeft": "53%",
                                 "margin-right": "10px"
                             }),
                    html.A(id="nova-logo",
                           children=[
                               html.Img(style={
                                   "height": "9%",
                                   "width": "9%"
                               },
                                        src="data:image/png;base64,{}".format(
                                            base64.b64encode(
                                                open(f"{logo2path}",
                                                     "rb").read()).decode()))
                           ],
                           href=f"{logo2URL}",
                           target="_blank",
                           style={})
                ],
                style={"display": "inline-block"}),
        ],
        style={
            'background': bg_color,
            'color': font_color,
            "padding-bottom": "10px",
            "padding-top": "-10px"
        })
Exemple #10
0
import dash_bootstrap_components as dbc
from dash import html

popovers = html.Div([
    dbc.Button(
        "Click Me",
        id="component-target",
        n_clicks=0,
    ),
    dbc.Popover(
        [
            dbc.PopoverHeader("Popover header"),
            dbc.PopoverBody("And here's some amazing content. Cool!"),
        ],
        target="component-target",
        trigger="click",
    ),
])
])
''' The Following are the all the popover components. 
They consist of the blue ? button, The popover itself with the header and the validation message 
telling the user why/why not the current input is valid'''

mass_popover = html.Div([
    dbc.Button(
        "?",
        id="mass-popover-target-BE",
        color="info",
    ),
    dbc.Popover(
        [
            dbc.PopoverHeader("Mass Input"),
            dbc.PopoverBody([], id="mass_validation_message-BE"),
        ],
        id="mass_popover-BE",
        is_open=False,
        target="mass-popover-target-BE",
    ),
], )

springConst_popover = html.Div([
    dbc.Button(
        "?",
        id="springConst-popover-target-BE",
        color="info",
    ),
    dbc.Popover(
        [
            dbc.PopoverHeader("Sprint Constant Input"),
Exemple #12
0
body = dbc.Container(
    [
        dbc.Row([
            dbc.Col(
                [
                    html.H2("O que é o ODE?"),
                    html.P("""\
A extensão universitária é uma ferramenta de promoção do desenvolvimento social e de difusão do conhecimento dentro e fora da universidade. Muitas são as ações desenvolvidas na UFPB com este objetivo. No que concerne a gerência dessas ações, ainda, existem poucas ferramentas sendo implementadas para avaliar dados gerados e permitir um acompanhamento de tais atividades de forma quantitativa. A proposta submetida, é uma opção para permitir uma visão mais quantitativa dos dados criados por meio dessas ações. Usando ferramentas de análise de dados e propondo métricas que auxiliam a gestão das ações de extensão dentro da UFPB, por meio da PRAC ou mesmo das Assessorias de Extensão. Esta iniciativa, agora em seu segundo ano, é batizada de Observatório de Dados da Extensão, e forneceu informações estratégicas para um melhor conhecimento das ações de extensão desenvolvidas na UFPB.""",
                           style={'text-align': 'justify'}),
                    dbc.Button(
                        "Versão", color="secondary", id='popover_target'),
                    dbc.Popover([
                        dbc.PopoverHeader("Ultima Atualização"),
                        dbc.PopoverBody("V.0.2, 15/06/2020"),
                    ],
                                id="popover",
                                is_open=False,
                                target="popover_target",
                                placement='top'),
                ],
                md=4,
            ),
            dbc.Col([
                html.Img(id='img_logo_ufpb',
                         height='480px',
                         style={
                             'display': 'block',
                             'max-width': '100%',
                             'height': 'auto'
                         },
                         srcSet='data:image/png;base64,{}'.format(
Exemple #13
0
                if removein:
                    if len(removein) > 0 and removein in current_tickers:
                        current_tickers.remove(removein)
                        current_tickers.sort()
                return [html.P(", ".join(current_tickers))]
    else:
        raise dash.exceptions.PreventUpdate


popover = html.Div([
    dbc.Button("Last Refreshed", id="popover-target", color="danger"),
    dbc.Popover(
        [
            dbc.PopoverHeader("Matrix was last refreshed at:"),
            dbc.PopoverBody("", id="body"),
        ],
        id="popover",
        is_open=False,
        target="popover-target",
    ),
],
                   style={
                       "margin-left": "10px",
                       "margin-bottom": "12px"
                   })


@app.callback(
    Output("tick_popover", "is_open"),
    [Input("popover-tar", "n_clicks")],
    [State("tick_popover", "is_open")],
def L_table():
    A = html.Div(
        [
            html.Button("Leaderboard",
                        id="popover-target",
                        className='button-primary',
                        style={
                            'font-size': '1.0vw',
                            'height': '2vw',
                            'width': '100%',
                            'textAlign': 'center'
                        }),
            dbc.Popover(
                [
                    dbc.PopoverHeader("Leaderboard",
                                      style={
                                          'backgroundColor': app.color_6,
                                          'color': app.color_4,
                                          'font-size': '1.2vw',
                                          'textAlign': 'center'
                                      }),
                    dbc.PopoverBody(
                        [
                            html.Div(
                                [
                                    dt.DataTable(
                                        id='table-editing-simple',
                                        # columns=(
                                        #         [{'id': p, 'name': p} for p in app.lead_board.columns]
                                        # ),
                                        # data=[
                                        #     {p : app.lead_board.at[i,p] for p in app.lead_board.columns}
                                        #     # dict(Model=i, **{param: app.lead_board[i]['index'] for param in params})
                                        #
                                        #     # dict(Model=i, **{param: 0 for param in params})
                                        #     for i in range(len(app.lead_board['index']))
                                        # ],
                                        editable=False,
                                        style_table={
                                            'overflowX': 'scroll',
                                            'overflowY': 'scroll',
                                            'maxHeight': '19vw',
                                            'maxWidth': '39vw',
                                            'font-size': '1.0vw'
                                        },
                                        style_cell={
                                            'textAlign': 'center',
                                            'backgroundColor': app.color_1,
                                            'color': app.color_3,
                                            'font-size': '0.8vw'
                                        },
                                        style_header={
                                            'backgroundColor': app.color_3,
                                            'color': app.color_4
                                        },
                                        sort_action="native",
                                        sort_mode="multi",
                                    ),
                                ],
                                style={
                                    'width': '40vw',
                                    'textAlign': 'right'
                                },
                            )
                        ],
                        style={
                            'width': '40vw',
                            'height': '20vw'
                        }),
                ],
                id="popover",
                is_open=False,
                target="popover-target",
                style={'backgroundColor': app.color_6},
            ),
        ],
        style={'textAlign': 'center'})

    return A
Exemple #15
0
                      src="assets/boton-de-informacion.svg",
                      n_clicks=0,
                      className="info-icon",
                      style={"margin": "5px"},
                  )
              ]),
     dbc.Popover(
         [
             dbc.PopoverHeader("HTTP vs HTTPS"),
             dbc.PopoverBody(children=[
                 html.
                 P("HTTP: unsecured Hypertext Transfer Protocol. Does not require domain validation. No encryption."
                   ),
                 html.
                 P("HTTPS: secure Hypertext Transfer Protocol. Requires domain validation. Encryption."
                   ),
             ],
                             style={"padding": "15px"}),
         ],
         id="popover",
         target=
         "popover-bottom-target",  # needs to be the same as dbc.Button id
         placement="bottom",
         is_open=False,
         style={"backgroundColor": "white"}),
     dcc.Graph(id='line_chart',
               figure=create_pie_chart_button(
                   graphs.metrics["bioschemas_ssl_https_license"][-1]
                   ["total"]["https"], ['HTTPS', 'HTTP'],
                   "HTTP vs HTTPS")),
 ]),
Exemple #16
0
def get_data_sources():
    df_summary = pd.DataFrame(columns=["Source", "Domain", "Count"])

    for num, [source, group] in enumerate(df_sources_summary_groups):
        df_summary_sectors = group.groupby("Domain")
        for num, [sector, sector_group] in enumerate(df_summary_sectors):
            df_summary = df_summary.append(
                {
                    "Source": source,
                    "Domain": sector,
                    "Count": len(sector_group)
                },
                ignore_index=True,
            )
        # Add the total count
        df_summary = df_summary.append(
            {
                "Source": "Subtotal",
                "Domain": "",
                "Count": len(group)
            },
            ignore_index=True,
        )
    # Add the total count
    df_summary = df_summary.append(
        {
            "Source": "Total",
            "Domain": "",
            "Count": len(df_sources)
        },
        ignore_index=True,
    )

    summary_tab = dcc.Tab(
        label="Summary (" + str(len(df_sources)) + ")",
        children=[
            html.Br(),
            html.Div(
                className="heading-panel",
                style={"padding": 20},
                children=[
                    html.H1(
                        "Summary of Indicators by Source",
                        id="source_title",
                        className="heading-title",
                        style={"fontSize": 24},
                    ),
                ],
            ),
            html.Br(),
            dash_table.DataTable(
                columns=[{
                    "name": i,
                    "id": i
                } for i in [
                    "Source",
                    "Domain",
                    "Count",
                ]],
                data=df_summary.to_dict("records"),
                style_cell={
                    "textAlign": "center",
                    "fontWeight": "bold"
                },
                style_data={
                    "whiteSpace": "normal",
                    "height": "auto",
                    "textAlign": "left",
                    "fontWeight": "regular",
                },
                style_data_conditional=[
                    {
                        "if": {
                            "row_index": "odd"
                        },
                        "backgroundColor": "#c5effc"
                    },
                    {
                        "if": {
                            "state": "active"
                        },
                        "backgroundColor": "#808080",
                        "border": "1px solid #FFFFFF",
                    },
                    {
                        "if": {
                            "filter_query":
                            "{Source} = 'Total' or {Source} = 'Subtotal'",
                        },
                        "backgroundColor": "grey",
                        "color": "white",
                        "fontWeight": "bold",
                    },
                ],
                filter_action="native",
                sort_action="native",
                sort_mode="multi",
                column_selectable="single",
                page_action="native",
                page_current=0,
                page_size=20,
                export_format="xlsx",
                export_headers="display",
                # hidden_columns=["Source"],
                export_columns="all",
                css=[{
                    "selector": ".show-hide",
                    "rule": "display: none"
                }],
            ),
            dbc.Popover(
                [
                    dbc.PopoverBody("Summary"),
                ],
                id="hover",
                target="summary-sources",
                placement="bottom",
                trigger="hover",
            ),
        ],
        style={"fontWeight": "bold"},
        id="summary-sources",
    )

    sources_tabs = [
        dcc.Tab(
            label=f"{source} (" + str(len(group)) + ")",
            children=[
                html.Br(),
                html.Div(
                    className="heading-panel",
                    style={"padding": 20},
                    children=[
                        html.H1(
                            data_sources[source],
                            id="source_title",
                            className="heading-title",
                            style={"fontSize": 24},
                        ),
                    ],
                ),
                html.Br(),
                dash_table.DataTable(
                    columns=[{
                        "name": i,
                        "id": i
                    } for i in [
                        "Domain",
                        "Subdomain",
                        "Indicator",
                        "Source_Full",
                    ]],
                    data=group.to_dict("records"),
                    style_cell={
                        "textAlign": "center",
                        "fontWeight": "bold"
                    },
                    style_data={
                        "whiteSpace": "normal",
                        "height": "auto",
                        "textAlign": "left",
                        "fontWeight": "regular",
                    },
                    style_data_conditional=[
                        {
                            "if": {
                                "row_index": "odd"
                            },
                            "backgroundColor": "#c5effc"
                        },
                        {
                            "if": {
                                "state": "active"
                            },
                            "backgroundColor": "#808080",
                            "border": "1px solid #FFFFFF",
                        },
                    ],
                    sort_action="native",
                    sort_mode="multi",
                    column_selectable="single",
                    page_action="native",
                    page_current=0,
                    page_size=20,
                    export_format="xlsx",
                    export_headers="display",
                    hidden_columns=["Source_Full"],
                    export_columns="all",
                    css=[{
                        "selector": ".show-hide",
                        "rule": "display: none"
                    }],
                ),
                dbc.Popover(
                    [
                        dbc.PopoverBody(data_sources[source]),
                    ],
                    id="hover",
                    target=f"source-{num}",
                    placement="bottom",
                    trigger="hover",
                ),
            ],
            style={
                "fontWeight": "bold",
                "padding": 7
            },
            selected_style={"padding": 7},
            id=f"source-{num}",
        ) for num, [source, group] in enumerate(df_sources_groups)
    ]

    sources_tabs.insert(0, summary_tab)
    return dcc.Tabs(id="sources-tabs", children=sources_tabs)
Exemple #17
0
def make_area(area_name):
    area_id = {"type": "area", "index": area_name}
    popover_id = {"type": "area_sources", "index": area_name}
    historical_data_style = {"display": "none"}
    exclude_outliers_style = {"paddingLeft": 20, "display": "block"}
    breakdowns_style = {"display": "block"}

    # lbassil: still differentiating main area id from other areas ids because the call backs are still not unified
    if area_name == "MAIN":
        area_id = f"{area_name.lower()}_area"
        popover_id = f"{area_name.lower()}_area_sources"
        historical_data_style = {"display": "block"}
        exclude_outliers_style = {"display": "none"}
        breakdowns_style = {"display": "none"}

    # lbassil: unifying both main and figure area generations by tweaking the ids and styles
    area = dbc.Card(
        [
            dbc.CardHeader(
                id={
                    "type": "area_title",
                    "index": area_name
                },
                style={"fontWeight": "bold"},
            ),
            dbc.CardBody([
                dcc.Dropdown(
                    id={
                        "type": "area_options",
                        "index": area_name
                    },
                    className="dcc_control",
                ),
                html.Br(),
                dbc.Checklist(
                    options=[{
                        "label": "Show historical data",
                        "value": 1,
                    }],
                    value=[],
                    id={
                        "type": "historical_data_toggle",
                        "index": area_name,
                    },
                    switch=True,
                    style=historical_data_style,
                ),
                html.Br(),
                dbc.RadioItems(
                    id={
                        "type": "area_types",
                        "index": area_name
                    },
                    inline=True,
                ),
                dcc.Loading([dcc.Graph(id=area_id)]),
                dbc.Checklist(
                    options=[{
                        "label": "Exclude outliers ",
                        "value": 1,
                    }],
                    value=[1],
                    id={
                        "type": "exclude_outliers_toggle",
                        "index": area_name,
                    },
                    switch=True,
                    style=exclude_outliers_style,
                ),
                html.Br(),
                dbc.RadioItems(
                    id={
                        "type": "area_breakdowns",
                        "index": area_name
                    },
                    inline=True,
                    style=breakdowns_style,
                ),
                html.Div(
                    fa("fas fa-info-circle"),
                    id=f"{area_name.lower()}_area_info",
                    className="float-right",
                ),
                dbc.Popover(
                    [
                        dbc.PopoverHeader("Sources"),
                        dbc.PopoverBody(id=popover_id),
                    ],
                    id="hover",
                    target=f"{area_name.lower()}_area_info",
                    trigger="hover",
                ),
            ]),
        ],
        id={
            "type": "area_parent",
            "index": area_name
        },
    )
    return area
Exemple #18
0
 children=[
     ## logo/home
     dbc.NavItem(html.Img(src=link_picture, height="40px")),
     ## about
     dbc.Col(width="auto"),
     dbc.NavItem(
         html.Div([
             dbc.NavLink("About",
                         href="/",
                         id="about-popover",
                         active=False),
             dbc.Popover(
                 id="about",
                 is_open=False,
                 target="about-popover",
                 children=[
                     dbc.PopoverHeader("Try it out!"),
                     dbc.PopoverBody(
                         "Choose the different interactive tools and see how the mortgage market evolves"
                     )
                 ])
         ])),
     ## links
     dbc.DropdownMenu(
         label="Code",
         nav=True,
         children=[
             dbc.DropdownMenuItem(
                 [html.I(className="fa fa-github"), "  Github"],
                 href=
                 "https://github.com/vinwinter/Production-ready-dash.git",
                 target="_blank")
def input_session():
	return dbc.ListGroup([
		dbc.ListGroupItem([html.H4("Client Input Assumptions")]),
		dbc.ListGroupItem([
			dbc.ListGroupItemHeading("Plan Information", style={"font-family":"NotoSans-SemiBold","font-size":"1.2rem"}),
			dbc.ListGroupItemText([
				dbc.Row([
					dbc.Col("Plan Type", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Input(value = "MAPD", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Total Members", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Input(value = "150,000", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Age Distribution", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col([
						dbc.Button("···", id = 'button-popover-age', size="sm", color='primary', style={"border-radius":"10rem"}),
						dbc.Popover([
							dbc.PopoverHeader("Age Distribution", style={"font-family":"NotoSans-SemiBold","font-size":"1rem"}),
							dbc.PopoverBody([dbc.Row([
									dbc.Col("Age Band", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
									dbc.Col("Member %", style={"font-family":"NotoSans-Regular","font-size":"1rem"})
									], style={"padding-top":"1rem"}),
								dbc.Row([
									dbc.Col("<65", style={"font-family":"NotoSans-Regular","font-size":"0.8rem"}),
									dbc.Col(dbc.Input(value = "12%", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
									], style={"padding-top":"1rem"}),
								dbc.Row([
									dbc.Col("65-74", style={"font-family":"NotoSans-Regular","font-size":"0.8rem"}),
									dbc.Col(dbc.Input(value = "48%", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
									], style={"padding-top":"1rem"}),
								dbc.Row([
									dbc.Col("75-84", style={"font-family":"NotoSans-Regular","font-size":"0.8rem"}),
									dbc.Col(dbc.Input(value = "27%", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
									], style={"padding-top":"1rem"}),
								dbc.Row([
									dbc.Col(">=85", style={"font-family":"NotoSans-Regular","font-size":"0.8rem"}),
									dbc.Col(dbc.Input(value = "13%", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
									], style={"padding-top":"1rem"}),
								dbc.Row([
									dbc.Col(dbc.Button("Save", id = 'popover-age-submit', size="sm", color='primary')),
									], style={"padding":"2rem","text-align":"center"}),
								], style={"font-family":"NotoSans-Regular","font-size":"1rem", "padding-left":"1rem", "padding-right":"1rem"}),
							
							],id = 'popover-age', is_open = False, target = 'button-popover-age')
						])
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Gender Distribution", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Button("···", size="sm", color='primary', style={"border-radius":"10rem"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Region", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Input(value = "Northeast", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("MSA (if applicable)", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Input(value = "New York-Newark-Jersey City, NY-NJ-PA MSA", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Formulary Tier for Entresto", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Input(value = "Preferred Brand", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Copayment for Entresto by Channel and Days of Supply", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Button("···", size="sm", color='primary', style={"border-radius":"10rem"}))
					], style={"padding-top":"1rem"}),
				]),
			]),
		dbc.ListGroupItem([
			dbc.ListGroupItemHeading("Drug Information", style={"font-family":"NotoSans-SemiBold","font-size":"1.2rem"}),
			dbc.ListGroupItemText([
				dbc.Row([
					dbc.Col("Entresto Pricing Information", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Input(value = "$9.6 / unit (tablet)", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Assumptions for Each Measure", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(html.A('Download the template file'), style={"font-family":"NotoSans-Regular","font-size":"1rem","text-decoration":"underline","color":"#1357DD"}),
						], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col(
						dcc.Upload(
						id = 'upload-data',
						children = html.Div([
							'Select Related Files to Upload'
							],style={"font-family":"NotoSans-Regular","font-size":"1rem","text-decoration":"underline","color":"#1357DD"}),
						style={
							'height': '60px',
							'lineHeight': '60px',
							'borderWidth': '1px',
							'borderStyle': 'dashed',
							'borderRadius': '5px',
							'textAlign': 'center',
							'margin': '10px'
							}
						),style={"padding-top":"1rem"}, width=12),
					]),
				dbc.Row([
					html.Div(id = 'output-data-upload', style={"text-align":"center","padding":"0.5rem","font-family":"NotoSans-Regular","font-size":"0.6rem"}),
					], style={"padding-top":"1rem"}),
				]),
			]),
		dbc.ListGroupItem([html.H4("Modeling Assumptions")]),
		dbc.ListGroupItem([
			dbc.ListGroupItemHeading("CHF Prevalence Rate & Severity Assumptions", style={"font-family":"NotoSans-SemiBold","font-size":"1.2rem"}),
			dbc.ListGroupItemText([
				dbc.Row([
					dbc.Col("Projected CHF Patients as a % of Total Plan Members", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Input(value = "13.6%", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("CHF Comorbidity Condition %CHF Comorbidity Condition %", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Button("···", size="sm", color='primary', style={"border-radius":"10rem"}))
					], style={"padding-top":"1rem"}),
				]),
			]),
		dbc.ListGroupItem([
			dbc.ListGroupItemHeading("CHF Patient Cost and Utilization Assumptions", style={"font-family":"NotoSans-SemiBold","font-size":"1.2rem"}),
			dbc.ListGroupItemText([
				dbc.Row([
					dbc.Col("CHF Patient Cost Assumptions", style={"font-family":"NotoSans-Regular","font-size":"1.2rem"}),
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Total Cost PPPY (Per Patient Per Year) Before Taking Entresto", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Input(value = "$ 42,000", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("CHF Related Cost as a % of Total Cost", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Input(value = "60%", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Total Cost PPPY by Service Category", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Button("···", size="sm", color='primary', style={"border-radius":"10rem"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Total Cost PPPY by Patient Cohort", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Button("···", size="sm", color='primary', style={"border-radius":"10rem"}))
					], style={"padding-top":"1rem"}),


				dbc.Row([
					dbc.Col("CHF Patient Cost Trend Assumptions", style={"font-family":"NotoSans-Regular","font-size":"1.2rem"}),
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Annual PPPY Cost Trend Before Taking Entresto", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Input(value = "7%", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Annual PPPY Cost Trend by Service Category", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Button("···", size="sm", color='primary', style={"border-radius":"10rem"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Annual PPPY Cost Trend by Patient Cohort", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Button("···", size="sm", color='primary', style={"border-radius":"10rem"}))
					], style={"padding-top":"1rem"}),


				dbc.Row([
					dbc.Col("CHF Patient Utilization Assumptions", style={"font-family":"NotoSans-Regular","font-size":"1.2rem"}),
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Projected Inpatient Admissions PPPY Before Taking Entresto", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Input(value = "1.4", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("CHF Related Inpatient Admissions as a % of Total Admissions", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Input(value = "80%", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Total Inpatient Admissions PPPY by Medical Condition", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Button("···", size="sm", color='primary', style={"border-radius":"10rem"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Total Inpatient Admissions PPPY by Patient Cohort", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Button("···", size="sm", color='primary', style={"border-radius":"10rem"}))
					], style={"padding-top":"1rem"}),


				dbc.Row([
					dbc.Col("CHF Patient Utilization Trend Assumptions", style={"font-family":"NotoSans-Regular","font-size":"1.2rem"}),
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Annual PPPY Inpatient Utilization Trend Before Taking Entresto", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Input(value = "5.4%", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Annual PPPY Inpatient Utilization Trend by Patient Cohort", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Button("···", size="sm", color='primary', style={"border-radius":"10rem"}))
					], style={"padding-top":"1rem"}),

				]),
			]),


		dbc.ListGroupItem([
			dbc.ListGroupItemHeading("Entresto Utilization Assumptions", style={"font-family":"NotoSans-SemiBold","font-size":"1.2rem"}),
			dbc.ListGroupItemText([
				dbc.Row([
					dbc.Col("Projected Entresto Utilizer as a % of Total CHF Population", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Input(value = "7%", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Entresto Utilizer Monthly Ramp Up Rate", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Button("···", size="sm", color='primary', style={"border-radius":"10rem"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Average Entresto Script PPPY (Per Patient Per Year)", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Input(value = "6.9", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
					], style={"padding-top":"1rem"}),
				dbc.Row([
					dbc.Col("Average Units/ Script", style={"font-family":"NotoSans-Regular","font-size":"1rem"}),
					dbc.Col(dbc.Input(value = "70", bs_size="sm", style={"border-radius":"5rem","padding-left":"1rem","padding-right":"1rem","color":"#000","font-family":"NotoSans-Regular"}))
					], style={"padding-top":"1rem"}),
				]),
			]),
		],
		style={"border-radius":"0.5rem"})
Exemple #20
0
def render_tab_content(active_tab, data, data_int, pathname):
    """
    This callback takes the 'active_tab' property as input, as well as the
    stored graphs, and renders the tab content depending on what the value of
    'active_tab' is.
    """
    path = pathname.replace("/", "")
    if active_tab and data is not None:
        if active_tab == "atual":
            # TODO Insert sample time
            container = dbc.Container(
                [
                    dbc.Row(
                        [
                            dbc.Col(html.P("Horário da medição: "), width=4),
                            dbc.Col(html.P(data[f"sample-time-{path}"]), width=4),
                        ]
                    ),
                    dbc.Row(dbc.Col(dcc.Graph(figure=data[f"head-{path}"]), width=12)),
                    dbc.Row(dbc.Col(dcc.Graph(figure=data[f"eff-{path}"]), width=12)),
                    dbc.Row(dbc.Col(dcc.Graph(figure=data[f"power-{path}"]), width=12)),
                ],
            )
            return container
        elif active_tab == "intervalo":

            if data_int is None:
                data_int = data
            else:
                if f"head-{path}" not in data_int:
                    data_int = data
            container = dbc.Container(
                [
                    dbc.Row(
                        [
                            dbc.Col(
                                dbc.FormGroup(
                                    [
                                        dbc.Input(
                                            id="start-date",
                                            persistence=True,
                                            type="text",
                                        ),
                                        dbc.FormText("Data e Horário"),
                                        dbc.Popover(
                                            dbc.PopoverBody(
                                                "Data e Horário em formato aceito pelo PI."
                                            ),
                                            id="popover-start-date",
                                            target="start-date",
                                            trigger="hover",
                                            placement="bottom",
                                        ),
                                    ]
                                ),
                                width=6,
                            ),
                            dbc.Col(
                                dbc.Button(
                                    "Calcular",
                                    color="primary",
                                    block=True,
                                    id="calcular",
                                ),
                                width=6,
                            ),
                        ]
                    ),
                    dbc.Row(
                        dbc.Col(dcc.Graph(figure=data_int[f"head-{path}"]), width=12)
                    ),
                    dbc.Row(
                        dbc.Col(dcc.Graph(figure=data_int[f"eff-{path}"]), width=12)
                    ),
                    dbc.Row(
                        dbc.Col(dcc.Graph(figure=data_int[f"power-{path}"]), width=12)
                    ),
                ],
            )
            return container
        elif active_tab == "trend":
            return dbc.Row(
                [
                    dbc.Col(dcc.Graph(figure=data["hist_1"]), width=6),
                    dbc.Col(dcc.Graph(figure=data["hist_2"]), width=6),
                ]
            )
    return "No tab selected"
Exemple #21
0
    ], style={"margin": 5, "marginTop": 20}),

    html.Div(children=[
        dbc.Button("Toggle fade", id="fade-button"),
        dbc.Fade(
            dbc.Card(dbc.CardBody(dbc.CardText("This content fades in and out"))),
            id="fade",
            is_in=True,
            appear=False,
        ),
    ], style={"margin": 5}),

    html.Div(children=[
        html.P(["Click on the word ", html.Span("popover", id="popover-target")]),
        dbc.Popover([
            dbc.PopoverHeader("Popover header"),
            dbc.PopoverBody("Popover body"),
        ], id="popover", is_open=False, target="popover-target"),
    ], style={"margin": 5, "backgroundColor": color_secondary_light}),

    html.Div(children=[
        html.P([
            "I wonder what ",
            html.Span("floccinaucinihilipilification", id="tooltip-target", style={"color": color_info}),
            " means?",
        ]),
        dbc.Tooltip(
            "Noun: rare, the action or habit of estimating something as worthless.",
            target="tooltip-target",
            placement="auto",  # top, left, bottom, right
        ),
    ], style={"margin": 5}),
Exemple #22
0
def final(patientID, encid, server, random_number):
    #cam_name = camname(patientID, encid)

    print("im in the final")

    import plotly.offline as pyo
    import plotly.graph_objs as go
    import plotly as py
    import dash
    import dash_core_components as dcc
    import dash_html_components as html
    import dash_bootstrap_components as dbc
    from dash.dependencies import Input, Output, State
    #app = dash.Dash()

    url = '/dashplot/' + str(patientID) + str(random_number) + '/'
    app = dash.Dash(__name__, server=server, url_base_pathname=url)

    #webbrowser.open_new_tab('http://127.0.0.1:5000/'+url)

    #dbc.Spinner(size = "sm", color = "success", type="border", fullscreen = "True")

    #cam_name = encid
    #print(cam_name)
    print("Entering Combine")
    merged_file = combine(patientID, encid)
    fhr0 = []
    fhr1 = []
    fhr2 = []
    fhr3 = []
    fhr_avg = []
    mhr0 = []
    mhr1 = []
    mhr2 = []
    mhr3 = []
    mhr_avg = []
    toco0 = []
    toco1 = []
    toco2 = []
    toco3 = []
    toco_avg = []
    with open(merged_file, 'r') as csvfile:
        plots = csv.reader(csvfile, delimiter=',')
        # Start reading from the second row in CSV to leave out column names
        header = next(plots)
        # Get Acquired Time
        # timestamp_list = [datetime.datetime.strptime(str(row[1][:-4])
        #                  ,"%Y-%m-%d::%H:%M:%S") for row in plots]
        timestamp_list = [
            datetime.datetime.strptime(str(row[1]), "%Y-%m-%d::%H:%M:%S.%f")
            for row in plots
        ]
    # print(timestamp_list)
    timestamp_list.reverse()
    with open(merged_file, 'r') as csvfile:
        plots = csv.reader(csvfile, delimiter=',')
        header = next(plots)
        counter = 0
        # Collect the four FHR samples in different lists
        for d, t in zip(plots, timestamp_list):
            counter += 1

            # get C1 HRO
            hr1_0 = int(float(d[3]))

            # get C1 HR1
            hr1_1 = int(float(d[4]))

            # get C1 HR2
            hr1_2 = int(float(d[5]))

            # get C1 HR3
            hr1_3 = int(float(d[6]))
            # get MHR 0
            mhr1_0 = int(float(d[11]))

            # get MHR 1
            mhr1_1 = int(float(d[12]))

            # get MHR 2
            mhr1_2 = int(float(d[13]))

            # get MHR 3
            mhr1_3 = int(float(d[14]))
            # get TOCO 0
            toco_0 = int(float(d[15]))

            # get TOCO 1
            toco_1 = int(float(d[16]))

            # get TOCO 2
            toco_2 = int(float(d[17]))

            # get TOCO 3
            toco_3 = int(float(d[18]))
            time1 = t + datetime.timedelta(milliseconds=250)
            time2 = t + datetime.timedelta(milliseconds=500)
            time3 = t + datetime.timedelta(milliseconds=750)

            toco3.append((toco_3, time3))
            toco2.append((toco_2, time2))
            toco1.append((toco_1, time1))
            toco0.append((toco_0, t))
            toco_avg.append((toco_0 + toco_1 + toco_2 + toco_3) // 4)

            mhr3.append((mhr1_3, time3))
            mhr2.append((mhr1_2, time2))
            mhr1.append((mhr1_1, time1))
            mhr0.append((mhr1_0, t))
            mhr_avg.append((mhr1_0 + mhr1_1 + mhr1_2 + mhr1_3) // 4)

            fhr3.append((hr1_3, time3))
            fhr2.append((hr1_2, time2))
            fhr1.append((hr1_1, time1))
            fhr0.append((hr1_0, t))

            fhr_avg.append((hr1_0 + hr1_1 + hr1_2 + hr1_3) // 4)

    fhr0 = np.array(zero_to_nannew(fhr0))
    fhr1 = np.array(zero_to_nannew(fhr1))
    fhr2 = np.array(zero_to_nannew(fhr2))
    fhr3 = np.array(zero_to_nannew(fhr3))
    # fhr_avg = np.array(zero_to_nan(fhr_avg))
    mhr0 = np.array(zero_to_nannew(mhr0))
    mhr1 = np.array(zero_to_nannew(mhr1))
    mhr2 = np.array(zero_to_nannew(mhr2))
    mhr3 = np.array(zero_to_nannew(mhr3))
    # mhr_avg = np.array(zero_to_nannew(mhr_avg))
    toco0 = np.array(zero_to_nannew(toco0))
    toco1 = np.array(zero_to_nannew(toco1))
    toco2 = np.array(zero_to_nannew(toco2))
    toco3 = np.array(zero_to_nannew(toco3))
    # toco_avg=np.array(zero_to_nannew(toco_avg))

    listx = []
    listy = []
    for i, j, k, l in zip(fhr0, fhr1, fhr2, fhr3):
        listx.append(l[1])
        listx.append(k[1])
        listx.append(j[1])
        listx.append(i[1])
        listy.append(l[0])
        listy.append(k[0])
        listy.append(j[0])
        listy.append(i[0])
    listx1 = []
    listy1 = []
    for i, j, k, l in zip(mhr0, mhr1, mhr2, mhr3):
        listx1.append(l[1])
        listx1.append(k[1])
        listx1.append(j[1])
        listx1.append(i[1])
        listy1.append(l[0])
        listy1.append(k[0])
        listy1.append(j[0])
        listy1.append(i[0])
    listx2 = []
    listy2 = []
    for i, j, k, l in zip(toco0, toco1, toco2, toco3):
        listx2.append(l[1])
        listx2.append(k[1])
        listx2.append(j[1])
        listx2.append(i[1])
        listy2.append(l[0])
        listy2.append(k[0])
        listy2.append(j[0])
        listy2.append(i[0])

    timestamp_list = np.array(timestamp_list)
    # print(timestamp_list[0],timestamp_list[-1])
    from plotly.subplots import make_subplots

    import plotly.graph_objects as go
    print(counter, "number of sessions")
    firsttime = listx[len(listx) // 2]
    nexttime = firsttime + datetime.timedelta(minutes=5)
    nexttimesec = firsttime + datetime.timedelta(seconds=10)
    diff = int(((nexttime - firsttime).total_seconds()) // 10)
    list_x = [(listx[0] - i).total_seconds() for i in listx]
    list_x1 = [(listx1[0] - i).total_seconds() for i in listx1]
    list_x2 = [(listx2[0] - i).total_seconds() for i in listx2]
    # aa=int(aa)
    print(len(list_x), "-----", counter)
    if aa:
        print(aa)
        list_x = list_x[:int(aa) * 4]
        list_x1 = list_x1[:int(aa) * 4]
        list_x2 = list_x2[:int(aa) * 4]
        listy = listy[:int(aa) * 4]
        listy1 = listy1[:int(aa) * 4]
        listy2 = listy2[:int(aa) * 4]
    print(len(list_x), "-----", counter)
    # print(list_x)
    ft = listx[0]
    newlist = [(ft + datetime.timedelta(seconds=i + 10)).strftime('%B')
               for i in list_x]
    print(len(newlist), len(list_x), newlist[0])
    print(ft)

    d1 = datetime.datetime.strptime(str(listx[0]), '%Y-%m-%d %H:%M:%S.%f')
    d2 = datetime.datetime.strptime(str(listx[-1]), '%Y-%m-%d %H:%M:%S.%f')
    print(d1, d2)
    timer = (d1 - d2).total_seconds()
    t = 0
    new1 = []
    new2 = [i for i in range(0, int(timer), 300)]
    while t < timer:
        t += 60
        new1.append(str(ft))
        ft = (ft - datetime.timedelta(seconds=300))
    print(new1[0], new1[1])
    # 2017-02-22 10:18:00.002000
    newfinal = []
    for i in new1:
        j = i.split(' ')
        dt = j[0].split('-')
        tm = j[1].split(':')[:2]
        fnl = dt[1] + '/' + dt[2] + '/' + dt[0] + ' ' + tm[0] + ':' + tm[1]
        newfinal.append(fnl)
    print(newfinal[0])
    # print(list_x)
    newlist = newlist[:int(aa)]
    tf = time.time()
    n_feats = 3
    n_timesteps = len(list_x)
    shapes = []
    # print(listy)
    # fig = dict(data=data, layout=layout)
    t3 = time.time()
    fig1 = go.Figure()
    min_x = 0
    max_x = 300

    min_y = 0
    max_y = 240

    # Generate random data for testing

    fig1 = make_subplots(rows=2,
                         cols=1,
                         shared_xaxes=False,
                         vertical_spacing=0.1)

    fig1.add_trace(go.Scatter(
        x=list_x,
        y=listy,
        name="FHR data",
        yaxis="y1",
        xaxis="x1",
    ),
                   row=1,
                   col=1)
    fig1.add_trace(go.Scatter(
        x=list_x1,
        y=listy1,
        name="MHR data",
        yaxis="y1",
        xaxis="x1",
    ),
                   row=1,
                   col=1)
    fig1.add_trace(go.Scatter(
        x=list_x2,
        y=listy2,
        name="TOCO data",
        yaxis="y2",
        xaxis="x2",
    ),
                   row=2,
                   col=1)

    fig1.add_trace(
        go.Scatter(
            x=[],
            y=[],
            # name="yaxis3 data",
            yaxis="y3",
            xaxis="x3",
        ))

    fig1.add_trace(
        go.Scatter(
            x=[],
            y=[],
            # name="yaxis4 data",
            yaxis="y4",
            xaxis="x4",
        ))

    fig1.add_trace(
        go.Scatter(
            x=[],
            y=[],
            # name="yaxis5 data",
            yaxis="y5",
            xaxis="x5"))

    fig1.add_trace(
        go.Scatter(
            x=[],
            y=[],
            # name="yaxis6 data",
            yaxis="y6",
            xaxis="x6",
        ))

    fig1.add_trace(
        go.Scatter(
            x=[],
            y=[],
            # name="yaxis7 data",
            yaxis="y7",
            xaxis="x7",
        ))

    fig1.add_trace(
        go.Scatter(
            x=[],
            y=[],
            # name="yaxis8 data",
            yaxis="y8",
            xaxis="x8"))

    # Create axis objects
    fig1.update_layout(
        xaxis=dict(
            showgrid=False,
            showticklabels=False,
            range=(600, min_x),
            zeroline=False,
            showline=True,
            linewidth=0.5,
            linecolor='black',
            mirror=True,
        ),
        xaxis2=dict(
            showgrid=False,
            showticklabels=False,
            range=(min_x, 600),
            zeroline=False,
            showline=True,
            linewidth=0.5,
            linecolor='black',
            mirror=True,
            #     rangeslirangeslider=dict(
            #     visible = True,
            #     bgcolor=' #FFFFFF'
            # ),
        ),
        xaxis3=dict(showgrid=True,
                    gridwidth=0.5,
                    gridcolor='rgba(0,0,0,0.1)',
                    dtick=10,
                    tick0=min_x,
                    showticklabels=False,
                    overlaying='x',
                    range=(min_x, max_x),
                    zeroline=False),
        xaxis4=dict(
            showgrid=True,
            gridwidth=0.5,
            gridcolor='rgba(0,0,0,0.3)',
            dtick=60,
            tick0=min_x,
            overlaying='x',
            range=(min_x, max_x),
            zeroline=False,
            showticklabels=False,
        ),
        xaxis5=dict(showgrid=True,
                    gridwidth=1.5,
                    gridcolor='rgba(0,0,0,1.0)',
                    dtick=300,
                    tick0=min_x,
                    overlaying='x',
                    range=(min_x, max_x),
                    zeroline=False,
                    side='top',
                    tickmode='array',
                    tickvals=new2,
                    ticktext=newfinal),
        xaxis6=dict(
            showgrid=True,
            gridwidth=0.5,
            gridcolor='rgba(0,0,0,0.1)',
            dtick=10,
            tick0=min_x,
            showticklabels=False,
            overlaying='x2',
            range=(min_x, max_x),
            zeroline=False,
        ),
        xaxis7=dict(
            showgrid=True,
            gridwidth=0.5,
            gridcolor='rgba(0,0,0,0.3)',
            dtick=60,
            tick0=min_x,
            overlaying='x2',
            range=(min_x, max_x),
            zeroline=False,
            showticklabels=False,
        ),
        xaxis8=dict(showgrid=True,
                    gridwidth=1.5,
                    gridcolor='rgba(0,0,0,1.0)',
                    dtick=300,
                    tick0=min_x,
                    overlaying='x2',
                    range=(min_x, max_x),
                    zeroline=False,
                    tickmode='array',
                    side='top',
                    tickvals=new2,
                    ticktext=newfinal),

        # data axis
        yaxis=dict(showgrid=False,
                   showticklabels=False,
                   range=(30, max_y),
                   fixedrange=True,
                   zeroline=False),
        yaxis2=dict(showgrid=False,
                    showticklabels=False,
                    range=(min_y, 100),
                    fixedrange=True,
                    zeroline=False),

        # For left ticks
        yaxis3=dict(showgrid=True,
                    gridwidth=0.5,
                    gridcolor='rgba(0,0,0,0.1)',
                    dtick=10,
                    tick0=30,
                    showticklabels=False,
                    side='left',
                    mirror=True,
                    overlaying='y',
                    range=(30, max_y),
                    fixedrange=True,
                    zeroline=False),
        # For right ticks
        yaxis4=dict(showgrid=True,
                    gridwidth=0.5,
                    gridcolor='rgba(0,0,0,0.1)',
                    dtick=30,
                    tick0=30,
                    showticklabels=True,
                    side='right',
                    overlaying='y',
                    range=(30, max_y),
                    fixedrange=True,
                    zeroline=False),
        # For 30 increments
        yaxis5=dict(showgrid=True,
                    gridwidth=0.5,
                    gridcolor='rgba(0,0,0,1.0)',
                    dtick=30,
                    tick0=30,
                    overlaying='y',
                    range=(30, max_y),
                    fixedrange=True,
                    zeroline=False),
        yaxis6=dict(showgrid=True,
                    gridwidth=0.5,
                    gridcolor='rgba(0,0,0,0.1)',
                    dtick=10,
                    tick0=min_y,
                    showticklabels=False,
                    side='left',
                    mirror=True,
                    overlaying='y2',
                    range=(min_y, 100),
                    fixedrange=True,
                    zeroline=False),
        # For right ticks
        yaxis7=dict(showgrid=True,
                    gridwidth=0.5,
                    gridcolor='rgba(0,0,0,0.1)',
                    dtick=20,
                    tick0=min_y,
                    showticklabels=True,
                    side='right',
                    overlaying='y2',
                    range=(min_y, 100),
                    fixedrange=True,
                    zeroline=False),
        # For 30 increments
        yaxis8=dict(showgrid=True,
                    gridwidth=0.5,
                    gridcolor='rgba(0,0,0,1.0)',
                    dtick=20,
                    tick0=min_y,
                    overlaying='y2',
                    range=(min_y, 100),
                    fixedrange=True,
                    zeroline=False),
    )

    t4 = time.time()
    print("axis adding: ", t4 - t3)

    fig1.update_layout(
        paper_bgcolor='rgba(1.0,1.0,1.0,0.0)',
        plot_bgcolor='rgba(1.0,1.0,1.0,1.0)',
        autosize=False,
        height=1000,
        width=1000,
        #title_text="Subplots: START DATETIME:" + str(listx[0]) + ", END DATETIME:" + str(listx[-1]),
        title_text="PatientId: " + patientID + " Encounter Id: " + encid +
        "<br>" + "Subplots: START DATETIME:" + str(listx[0])[:-7] +
        ", END DATETIME:" + str(listx[-1])[:-7],
        dragmode='pan',
        showlegend=True)
    # print(fig)
    fig1.update_xaxes(matches='x')

    # Add shape regions
    fig1.update_layout(shapes=[
        # 1st highlight during Feb 4 - Feb 6
        dict(
            type="rect",
            # x-reference is assigned to the x-values
            xref="x",
            # y-reference is assigned to the plot paper [0,1]
            # yref="paper",
            yref="y",
            x0=0,
            y0=110,
            x1=list_x[-1],
            y1=170,
            fillcolor="Gray",
            opacity=0.2,
        ),
    ])
    t6 = time.time()
    print("total time", t6 - tf)
    # fig1.show()

    print("--------")

    fig2 = go.Figure()
    min_x = 0
    max_x = 300

    min_y = 0
    max_y = 240

    # Generate random data for testing
    fig2 = make_subplots(rows=2,
                         cols=1,
                         shared_xaxes=False,
                         vertical_spacing=0.1)

    fig2.add_trace(go.Scatter(
        x=list_x,
        y=listy,
        name="FHR data",
        yaxis="y1",
        xaxis="x1",
    ),
                   row=1,
                   col=1)
    fig2.add_trace(go.Scatter(
        x=list_x1,
        y=listy1,
        name="MHR data",
        yaxis="y1",
        xaxis="x1",
    ),
                   row=1,
                   col=1)
    fig2.add_trace(go.Scatter(
        x=list_x2,
        y=listy2,
        name="TOCO data",
        yaxis="y2",
        xaxis="x2",
    ),
                   row=2,
                   col=1)

    fig2.add_trace(
        go.Scatter(
            x=[],
            y=[],
            # name="yaxis3 data",
            yaxis="y3",
            xaxis="x3",
        ))

    fig2.add_trace(
        go.Scatter(
            x=[],
            y=[],
            # name="yaxis4 data",
            yaxis="y4",
            xaxis="x4",
        ))

    fig2.add_trace(
        go.Scatter(
            x=[],
            y=[],
            # name="yaxis5 data",
            yaxis="y5",
            xaxis="x5"))

    fig2.add_trace(
        go.Scatter(
            x=[],
            y=[],
            # name="yaxis6 data",
            yaxis="y6",
            xaxis="x6",
        ))

    fig2.add_trace(
        go.Scatter(
            x=[],
            y=[],
            # name="yaxis7 data",
            yaxis="y7",
            xaxis="x7",
        ))

    fig2.add_trace(
        go.Scatter(
            x=[],
            y=[],
            # name="yaxis8 data",
            yaxis="y8",
            xaxis="x8"))

    # Create axis objects
    fig2.update_layout(
        xaxis=dict(
            showgrid=False,
            showticklabels=False,
            range=(900, min_x),
            zeroline=False,
            showline=True,
            linewidth=0.5,
            linecolor='black',
            mirror=True,
        ),
        xaxis2=dict(
            showgrid=False,
            showticklabels=False,
            range=(min_x, 900),
            zeroline=False,
            showline=True,
            linewidth=0.5,
            linecolor='black',
            mirror=True,
            #     rangeslirangeslider=dict(
            #     visible = True,
            #     bgcolor=' #FFFFFF'
            # ),
        ),
        xaxis3=dict(
            showgrid=True,
            gridwidth=0.5,
            gridcolor='rgba(0,0,0,0.1)',
            dtick=10,
            tick0=min_x,
            showticklabels=False,
            overlaying='x',
            range=(min_x, max_x),
            zeroline=False,
            # side='top',
        ),
        xaxis4=dict(
            showgrid=True,
            gridwidth=0.5,
            gridcolor='rgba(0,0,0,0.3)',
            dtick=60,
            tick0=min_x,
            overlaying='x',
            range=(min_x, max_x),
            zeroline=False,
            showticklabels=False,
            # side='top',
        ),
        xaxis5=dict(showgrid=True,
                    gridwidth=1.5,
                    gridcolor='rgba(0,0,0,1.0)',
                    dtick=300,
                    tick0=min_x,
                    overlaying='x',
                    range=(min_x, max_x),
                    zeroline=False,
                    side='top',
                    tickmode='array',
                    tickvals=new2,
                    ticktext=newfinal),
        xaxis6=dict(
            showgrid=True,
            gridwidth=0.5,
            gridcolor='rgba(0,0,0,0.1)',
            dtick=10,
            tick0=min_x,
            showticklabels=False,
            overlaying='x2',
            range=(min_x, max_x),
            zeroline=False,
        ),
        xaxis7=dict(
            showgrid=True,
            gridwidth=0.5,
            gridcolor='rgba(0,0,0,0.3)',
            dtick=60,
            tick0=min_x,
            overlaying='x2',
            range=(min_x, max_x),
            zeroline=False,
            showticklabels=False,
        ),
        xaxis8=dict(showgrid=True,
                    gridwidth=1.5,
                    gridcolor='rgba(0,0,0,1.0)',
                    dtick=300,
                    tick0=min_x,
                    overlaying='x2',
                    range=(min_x, max_x),
                    zeroline=False,
                    side='top',
                    tickmode='array',
                    tickvals=new2,
                    ticktext=newfinal),

        # data axis
        yaxis=dict(showgrid=False,
                   showticklabels=False,
                   range=(30, max_y),
                   fixedrange=True,
                   zeroline=False),
        yaxis2=dict(showgrid=False,
                    showticklabels=False,
                    range=(min_y, 100),
                    fixedrange=True,
                    zeroline=False),

        # For left ticks
        yaxis3=dict(showgrid=True,
                    gridwidth=0.5,
                    gridcolor='rgba(0,0,0,0.1)',
                    dtick=10,
                    tick0=30,
                    showticklabels=False,
                    side='left',
                    mirror=True,
                    overlaying='y',
                    range=(30, max_y),
                    fixedrange=True,
                    zeroline=False),
        # For right ticks
        yaxis4=dict(showgrid=True,
                    gridwidth=0.5,
                    gridcolor='rgba(0,0,0,0.1)',
                    dtick=30,
                    tick0=30,
                    showticklabels=True,
                    side='right',
                    overlaying='y',
                    range=(30, max_y),
                    fixedrange=True,
                    zeroline=False),
        # For 30 increments
        yaxis5=dict(showgrid=True,
                    gridwidth=0.5,
                    gridcolor='rgba(0,0,0,1.0)',
                    dtick=30,
                    tick0=30,
                    overlaying='y',
                    range=(30, max_y),
                    fixedrange=True,
                    zeroline=False),
        yaxis6=dict(showgrid=True,
                    gridwidth=0.5,
                    gridcolor='rgba(0,0,0,0.1)',
                    dtick=10,
                    tick0=min_y,
                    showticklabels=False,
                    side='left',
                    mirror=True,
                    overlaying='y2',
                    range=(min_y, 100),
                    fixedrange=True,
                    zeroline=False),
        # For right ticks
        yaxis7=dict(showgrid=True,
                    gridwidth=0.5,
                    gridcolor='rgba(0,0,0,0.1)',
                    dtick=20,
                    tick0=min_y,
                    showticklabels=True,
                    side='right',
                    overlaying='y2',
                    range=(min_y, 100),
                    fixedrange=True,
                    zeroline=False),
        # For 30 increments
        yaxis8=dict(showgrid=True,
                    gridwidth=0.5,
                    gridcolor='rgba(0,0,0,1.0)',
                    dtick=20,
                    tick0=min_y,
                    overlaying='y2',
                    range=(min_y, 100),
                    fixedrange=True,
                    zeroline=False),
    )

    fig2.update_layout(paper_bgcolor='rgba(1.0,1.0,1.0,0.0)',
                       plot_bgcolor='rgba(1.0,1.0,1.0,1.0)',
                       autosize=False,
                       height=1000,
                       width=1200,
                       title_text="Subplots: START DATETIME:" +
                       str(listx[0])[:-7] + ", END DATETIME:" +
                       str(listx[-1])[:-7],
                       dragmode='pan',
                       showlegend=True)
    # print(fig)
    fig2.update_xaxes(matches='x')
    fig2.update_layout(shapes=[
        # 1st highlight during Feb 4 - Feb
        dict(
            type="rect",
            # x-reference is assigned to the x-values
            xref="x",
            # y-reference is assigned to the plot paper [0,1]
            # yref="paper",
            yref="y",
            x0=0,
            y0=110,
            x1=list_x[-1],
            y1=170,
            fillcolor="Gray",
            opacity=0.2,
        ),
    ])
    FHRClick = [-1, -1]
    MHRClick = [-1, -1]
    TOCOClick = [-1, -1]
    # t6=time.time()
    # fig1.show()
    # fig2.show()
    fig4 = go.Figure()
    fig4 = make_subplots(rows=2,
                         cols=1,
                         shared_xaxes=False,
                         vertical_spacing=0.1)
    fig4.update_layout(paper_bgcolor='rgba(1.0,1.0,1.0,0.0)',
                       plot_bgcolor='rgba(1.0,1.0,1.0,1.0)',
                       xaxis={
                           'showgrid': False,
                           'showline': False,
                           'zeroline': False,
                           'showticklabels': False
                       },
                       yaxis={
                           'showgrid': False,
                           'showline': False,
                           'zeroline': False,
                           'showticklabels': False
                       },
                       width=700,
                       height=700)

    text_markdown = "Hello World"

    html.Div([
        html.Div([
            html.Div([
                html.H3('Column 1'),
                dcc.Graph(id='g1', figure={'data': [{
                    'y': [1, 2, 3]
                }]})
            ],
                     className="six columns"),
            html.Div([
                html.H3('Column 2'),
                dcc.Graph(id='g2', figure={'data': [{
                    'y': [1, 2, 3]
                }]})
            ],
                     className="six columns"),
        ],
                 className="row")
    ])

    app.layout = html.Div([
        #dbc.Spinner()
        html.Div([
            html.Div([
                dbc.Button('Open filtered graph',
                           id='open-backdrop',
                           color='secondary',
                           className='mr-1',
                           style={'margin-left': '50%'}),
            ]),
            dbc.Popover([dbc.PopoverBody(dcc.Graph(id='live_graph'))],
                        id='modal',
                        is_open=False,
                        target='open-backdrop',
                        placement='bottom',
                        style={
                            'background-color': '#fff',
                            'border': ' 2px solid black'
                        }),
            dcc.Graph(figure=fig1, id="fig1"),
            dcc.Graph(figure=fig2, id="fig2"),
            html.Div(id='intermediate-value'),
            html.Div(id='intermediate-value2', style={'display': 'none'}),
            html.Button('Generate Graph',
                        id='button',
                        style={'display': 'none'})
        ])
    ])

    # for figure 1
    @app.callback(output=Output('intermediate-value', 'children'),
                  inputs=[Input('fig1', 'clickData')])
    def display_click_data(clickData):
        if clickData:
            index = clickData['points'][0]['pointIndex']
            curveNumber = clickData['points'][0]['curveNumber']
            if curveNumber == 0:
                if FHRClick[0] == -1:
                    FHRClick[0] = index
                    return [FHRClick[0]]
                else:
                    FHRClick[1] = index
                    click1 = FHRClick[0]
                    click2 = FHRClick[1]
                    print("FHR index range clicked is " + str(FHRClick))
                    # print("y values are: " +  str(list_x[FHRClick[0]]))
                    # print("y values are: " + str(list_x1[FHRClick[0]]))
                    # print("y values are: " + str(list_x2[FHRClick[0]]))
                    print("Values between range are: ")
                    temp = listy[FHRClick[0]:FHRClick[1]]
                    temp1 = listy1[FHRClick[0]:FHRClick[1]]
                    temp2 = listy2[FHRClick[0]:FHRClick[1]]
                    print(temp)
                    print("----------------------------------------------")
                    FHRClick[0] = -1
                    FHRClick[1] = -1
                    return [click1, click2]
                # print("FHR data from list " + str(list_x[index]) + " " + str(listy[index]))
                # print("data from click " + str(clickData['points'][0]['x']) + " " + str(clickData['points'][0]['y']))
            elif curveNumber == 1:
                if MHRClick[0] == -1:
                    MHRClick[0] = index
                    return [MHRClick[0]]
                else:
                    MHRClick[1] = index
                    click1 = MHRClick[0]
                    click2 = MHRClick[1]
                    print("MHR index range clicked is " + str(MHRClick))
                    print("Values between range are: ")
                    temp = listy1[MHRClick[0]:MHRClick[1]]
                    print(temp)
                    print("----------------------------------------------")
                    MHRClick[0] = -1
                    MHRClick[1] = -1
                    return [click1, click2]
                # print("MHR data from list " + str(list_x1[index]) + " " + str(listy1[index]))
                # print("data from click " + str(clickData['points'][0]['x']) + " " + str(clickData['points'][0]['y']))
            else:
                if TOCOClick[0] == -1:
                    TOCOClick[0] = index
                    return [TOCOClick[0]]
                else:
                    TOCOClick[1] = index
                    click1 = TOCOClick[0]
                    click2 = TOCOClick[1]
                    print("TOCO index range clicked is " + str(TOCOClick))
                    print("Values between range are: ")
                    temp = listy2[TOCOClick[0]:TOCOClick[1]]
                    print(temp)
                    print("----------------------------------------------")
                    TOCOClick[0] = -1
                    TOCOClick[1] = -1
                    return [click1, click2]
                # print("TOCO from list " + str(list_x2[index]) + " " + str(listy2[index]))
                # print("data from click " + str(clickData['points'][0]['x']) + " " + str(clickData['points'][0]['y']))

    # @app.callback(
    #     output=Output('intermediate-value2', 'children'),
    #     inputs=[Input('fig2', 'clickData')])
    # def display_click_data(clickData):
    #     if clickData:
    #         print("fig2 " + str(clickData))
    #         return None

    @app.callback(output=Output('live_graph', 'figure'),
                  inputs=[
                      Input('button', 'n_clicks'),
                      Input('intermediate-value', 'children')
                  ])
    def update_graph(n_clicks, children):
        if not children or len(children) == 1:
            return fig4
        else:

            temp = listy[children[0]:children[1]]
            temp1 = listy1[children[0]:children[1]]
            temp2 = listy2[children[0]:children[1]]
            poplistfhrx = list_x[children[0]:children[1]]
            poplistfhrxy = listy[children[0]:children[1]]
            poplistmhrx = list_x1[children[0]:children[1]]
            poplistmhry = listy1[children[0]:children[1]]
            poplisttocox = list_x2[children[0]:children[1]]
            poplisttocoy = listy2[children[0]:children[1]]
            minstart = poplistfhrx[0]
            poplistfhrx = [(i - poplistfhrx[0]) for i in poplistfhrx]
            poplistmhrx = [(i - poplistmhrx[0]) for i in poplistmhrx]
            poplisttocox = [(i - poplisttocox[0]) for i in poplisttocox]
            min_x = 0
            max_x = 300

            min_y = 0
            max_y = 240

            fig3 = make_subplots(rows=2,
                                 cols=1,
                                 shared_xaxes=False,
                                 vertical_spacing=0.1)

            fig3.add_trace(go.Scatter(
                x=poplistfhrx,
                y=poplistfhrxy,
                name="FHR data",
                yaxis="y1",
                xaxis="x1",
            ),
                           row=1,
                           col=1)
            fig3.add_trace(go.Scatter(
                x=poplistmhrx,
                y=poplistmhry,
                name="MHR data",
                yaxis="y1",
                xaxis="x1",
            ),
                           row=1,
                           col=1)
            fig3.add_trace(go.Scatter(
                x=poplisttocox,
                y=poplisttocoy,
                name="TOCO data",
                yaxis="y2",
                xaxis="x2",
            ),
                           row=2,
                           col=1)

            fig3.add_trace(
                go.Scatter(
                    x=[],
                    y=[],
                    # name="yaxis3 data",
                    yaxis="y3",
                    xaxis="x3",
                ))

            fig3.add_trace(
                go.Scatter(
                    x=[],
                    y=[],
                    # name="yaxis4 data",
                    yaxis="y4",
                    xaxis="x4",
                ))

            fig3.add_trace(
                go.Scatter(
                    x=[],
                    y=[],
                    # name="yaxis5 data",
                    yaxis="y5",
                    xaxis="x5"))

            fig3.add_trace(
                go.Scatter(
                    x=[],
                    y=[],
                    # name="yaxis6 data",
                    yaxis="y6",
                    xaxis="x6",
                ))

            fig3.add_trace(
                go.Scatter(
                    x=[],
                    y=[],
                    # name="yaxis7 data",
                    yaxis="y7",
                    xaxis="x7",
                ))

            fig3.add_trace(
                go.Scatter(
                    x=[],
                    y=[],
                    # name="yaxis8 data",
                    yaxis="y8",
                    xaxis="x8"))

            # Create axis objects
            fig3.update_layout(
                xaxis=dict(
                    showgrid=False,
                    showticklabels=False,
                    range=(min_x, 120),
                    zeroline=False,
                    showline=True,
                    linewidth=0.5,
                    linecolor='black',
                    mirror=True,
                ),
                xaxis2=dict(
                    showgrid=False,
                    showticklabels=False,
                    range=(min_x, 120),
                    zeroline=False,
                    showline=True,
                    linewidth=0.5,
                    linecolor='black',
                    mirror=True,
                    #     rangeslirangeslider=dict(
                    #     visible = True,
                    #     bgcolor=' #FFFFFF'
                    # ),
                ),
                xaxis3=dict(showgrid=True,
                            gridwidth=0.5,
                            gridcolor='rgba(0,0,0,0.1)',
                            dtick=10,
                            tick0=min_x,
                            showticklabels=False,
                            overlaying='x',
                            range=(min_x, max_x),
                            zeroline=False),
                xaxis4=dict(
                    showgrid=True,
                    gridwidth=0.5,
                    gridcolor='rgba(0,0,0,0.3)',
                    dtick=60,
                    tick0=min_x,
                    overlaying='x',
                    range=(min_x, max_x),
                    zeroline=False,
                    showticklabels=False,
                ),
                xaxis5=dict(
                    showgrid=True,
                    gridwidth=1.5,
                    gridcolor='rgba(0,0,0,1.0)',
                    dtick=300,
                    tick0=min_x,
                    overlaying='x',
                    range=(min_x, max_x),
                    zeroline=False,
                    side='top',
                    # tickmode='array',
                    showticklabels=False,
                    # tickvals=new2,
                    # ticktext=newfinal
                ),
                xaxis6=dict(
                    showgrid=True,
                    gridwidth=0.5,
                    gridcolor='rgba(0,0,0,0.1)',
                    dtick=10,
                    tick0=min_x,
                    showticklabels=False,
                    overlaying='x2',
                    range=(min_x, max_x),
                    zeroline=False,
                ),
                xaxis7=dict(
                    showgrid=True,
                    gridwidth=0.5,
                    gridcolor='rgba(0,0,0,0.3)',
                    dtick=60,
                    tick0=min_x,
                    overlaying='x2',
                    range=(min_x, max_x),
                    zeroline=False,
                    showticklabels=False,
                ),
                xaxis8=dict(
                    showgrid=True,
                    gridwidth=1.5,
                    gridcolor='rgba(0,0,0,1.0)',
                    dtick=300,
                    tick0=min_x,
                    overlaying='x2',
                    range=(min_x, max_x),
                    zeroline=False,
                    # tickmode='array',
                    side='top',
                    showticklabels=False,
                    # tickvals=new2,
                    # ticktext=newfinal
                ),

                # data axis
                yaxis=dict(showgrid=False,
                           showticklabels=False,
                           range=(30, max_y),
                           fixedrange=True,
                           zeroline=False),
                yaxis2=dict(showgrid=False,
                            showticklabels=False,
                            range=(min_y, 100),
                            fixedrange=True,
                            zeroline=False),

                # For left ticks
                yaxis3=dict(showgrid=True,
                            gridwidth=0.5,
                            gridcolor='rgba(0,0,0,0.1)',
                            dtick=10,
                            tick0=30,
                            showticklabels=False,
                            side='left',
                            mirror=True,
                            overlaying='y',
                            range=(30, max_y),
                            fixedrange=True,
                            zeroline=False),
                # For right ticks
                yaxis4=dict(showgrid=True,
                            gridwidth=0.5,
                            gridcolor='rgba(0,0,0,0.1)',
                            dtick=30,
                            tick0=30,
                            showticklabels=True,
                            side='right',
                            overlaying='y',
                            range=(30, max_y),
                            fixedrange=True,
                            zeroline=False),
                # For 30 increments
                yaxis5=dict(showgrid=True,
                            gridwidth=0.5,
                            gridcolor='rgba(0,0,0,1.0)',
                            dtick=30,
                            tick0=30,
                            overlaying='y',
                            range=(30, max_y),
                            fixedrange=True,
                            zeroline=False),
                yaxis6=dict(showgrid=True,
                            gridwidth=0.5,
                            gridcolor='rgba(0,0,0,0.1)',
                            dtick=10,
                            tick0=min_y,
                            showticklabels=False,
                            side='left',
                            mirror=True,
                            overlaying='y2',
                            range=(min_y, 100),
                            fixedrange=True,
                            zeroline=False),
                # For right ticks
                yaxis7=dict(showgrid=True,
                            gridwidth=0.5,
                            gridcolor='rgba(0,0,0,0.1)',
                            dtick=20,
                            tick0=min_y,
                            showticklabels=True,
                            side='right',
                            overlaying='y2',
                            range=(min_y, 100),
                            fixedrange=True,
                            zeroline=False),
                # For 30 increments
                yaxis8=dict(showgrid=True,
                            gridwidth=0.5,
                            gridcolor='rgba(0,0,0,1.0)',
                            dtick=20,
                            tick0=min_y,
                            overlaying='y2',
                            range=(min_y, 100),
                            fixedrange=True,
                            zeroline=False),
            )

            fig3.update_layout(
                paper_bgcolor='rgba(1.0,1.0,1.0,0.0)',
                plot_bgcolor='rgba(1.0,1.0,1.0,1.0)',
                autosize=False,
                # title_text="Subplots: START DATETIME:" + str(listx[0]) + ", END DATETIME:" + str(listx[-1]),
                dragmode='pan',
                showlegend=False)
            # print(fig)
            fig3.update_xaxes(matches='x')

            # Add shape regions
            fig3.update_layout(shapes=[
                # 1st highlight during Feb 4 - Feb 6
                dict(
                    type="rect",
                    # x-reference is assigned to the x-values
                    xref="x",
                    # y-reference is assigned to the plot paper [0,1]
                    # yref="paper",
                    yref="y",
                    x0=0,
                    y0=110,
                    x1=list_x[-1],
                    y1=170,
                    fillcolor="Gray",
                    opacity=0.2,
                ),
            ])
            return fig3

    @app.callback(
        Output("modal", "is_open"),
        [Input("open-backdrop", "n_clicks")],
        [State("modal", "is_open")],
    )
    def toggle_modal(n1, is_open):
        if n1:
            return not is_open
        return is_open
Exemple #23
0
from dash import Input, Output, State, html

popover = html.Div([
    dbc.Button(
        "Toggle",
        id="toggle",
        color="success",
        className="me-4",
        n_clicks=0,
    ),
    dbc.Button("Target", id="target", color="danger", n_clicks=0),
    dbc.Popover(
        [
            dbc.PopoverHeader("Popover header"),
            dbc.PopoverBody("And here's some amazing content. Cool!"),
        ],
        id="popover",
        is_open=False,
        target="target",
    ),
])


@app.callback(
    Output("popover", "is_open"),
    [Input("toggle", "n_clicks")],
    [State("popover", "is_open")],
)
def toggle_popover(n, is_open):
    if n:
        return not is_open
Exemple #24
0
dropdown_states = dbc.Row(
    justify="center",
    children=[
        html.Tbody("xsxsxs", id="g_status", style={"margin": "10px"}),
        html.Tbody("xsxsxs", id="g_winner", style={"margin": "10px"}),
        html.Tbody("xsxsxs", id="g_time_control", style={"margin": "10px"}),
        html.Tbody(children="111", id="g_game_type", style={"margin": "10px"}),
    ],
)

popover_status = dbc.Popover(
    [
        dbc.PopoverHeader("Status of the Game"),
        dbc.PopoverBody(
            "Games can be over in a myriad of ways, either by checkmate, draw, player resignation, or when a player runs out of time. Filter the games by these conditions here."
        ),
    ],
    trigger="hover",
    target="dropdown_status",
    placement="left",
)

popover_time_control = dbc.Popover(
    [
        dbc.PopoverHeader("Time Control Filter"),
        dbc.PopoverBody(
            "Players have a specific time to make their moves. The games in the dataset follow this convention: Bullet Games (0-3 minutes), Blitz(3-10 minutes), Classical(10 minutes+). Note: Lichess uses a slight different system today."
        ),
    ],
    trigger="hover",
    target="dropdown_time_control",
def body():
    return html.Div(children=[
        html.Div(
            id='left-column',
            children=[
                dcc.Tabs(
                    id='tabs',
                    value='About this App',
                    children=[
                        dcc.Tab(label='About this App',
                                value='About this App',
                                children=html.Div(children=[
                                    html.Br(),
                                    html.H4('What is this app?',
                                            style={"text-align": "center"}),
                                    html.P("""
                                    This app computes the replication strategy of vanilla European options on a set of given inputs, in the Black-Scholes-Merton (BSM) framework.
                                    """),
                                    html.P("""
                                    The goal is to showcase that under the BSM model's assumptions (see "Model" tab), the price \(V_0\) given by the BSM formula is "arbitrage-free". Indeed, we show that in this case, 
                                    it is possible to build a strategy that 
                                    """),
                                    html.Ul([
                                        html.
                                        Li("Can be initiated with \(V_0\) cash at time \(0\)."
                                           ),
                                        html.
                                        Li('Is self-financing (i.e., no need to "feed" the strategy  with extra cash later'
                                           ),
                                        html.
                                        Li("Will deliver exactly the payoff of the option at maturity"
                                           )
                                    ]),
                                    html.Hr(),
                                    html.H4("Type of options",
                                            style={"text-align": "center"}),
                                    html.P([
                                        """
                                  The considered options are European options paying \(\psi(S_T)\) at maturity \(T\) where \(\psi(X)\) is the payoff function.
                                  For a call, the payoff function is \(\psi(S_T)=max(0,S_T-K)\) and for a put \(\psi(S_T)=max(0,K-S_T)\) where K is the strike price.
                                  """
                                    ]),
                                    html.Hr(),
                                    html.P("""
                                    Read more about options : 
                                    https://en.wikipedia.org/wiki/Option_(finance)
                                    """),
                                ])),
                        dcc.Tab(
                            label="Model",
                            value="Model",
                            children=[
                                html.Div(children=[
                                    html.Br(),
                                    html.H4(
                                        "Model assumptions",
                                        style={"text-align": "center"}),
                                    "The BSM main assumptions are:",
                                    html.Ul([
                                        html.
                                        Li("It does not consider dividends and transaction costs"
                                           ),
                                        html.
                                        Li("The volatility and risk-free rate are assumed constant"
                                           ),
                                        html.Li(
                                            "Fraction of shares can be traded")
                                    ]),
                                    html.P([
                                        """Under BSM, the underlying asset's dynamics are modeled with a geometric Brownian motion: 
                              $$dS_t = \mu S_tdt+\sigma S_tdW_t$$ Where \(\mu\) is the drift, \(\sigma\) the volatility, and \(dW_t\) the increment of a Brownian motion."""
                                    ]),
                                    html.Hr(),
                                    html.H4("Option price",
                                            style={"text-align": "center"}),
                                    html.P([
                                        """
                              The call and put BSM pricing formula are well-known:
                              $$C_t = S_t\Phi(d_1)-Ke^{-r(T-t)}\Phi(d_2)$$$$P_t = S_t\Phi(d_1)-Ke^{-r(T-t)}\Phi(d_2)$$ Where \(\Phi\) is the standard normal cumulative distribution function, 
                              \(d_1\) and \(d_2\) constants \(d_1=\\frac{1}{\sigma\sqrt{T-t}}\left[ln(\\frac{S_t}{K})+(r+\\frac{\sigma^2}{2})(T-t)\\right]\), \(d_2=d_1-\sigma\\sqrt{T-t}\) where
                              \(r\) is the risk-free rate. 
                              These pricing formula originate from the BSM partial differential equation, which is valid for any type of European option:
                              $$\\frac{\partial V_t}{\partial t}+\\frac{\sigma^{2}S^{2}_t}{2}\\frac{\partial^{2}V_t}{\partial S^{2}}+rS_t\\frac{\partial V_t}{\partial S} = rV_t$$
                              Where \(V_t=f(t,S_t)\) the price of the option at time t. To get the pricing formulas, solve the PDE with terminal condition the payoff \(\psi(X)\) of the desired European-type option.
                              """
                                    ]),
                                    html.Hr(),
                                    html.H4("Academical references",
                                            style={"text-align": "center"}),
                                    "The main academical references used were:",
                                    html.Ul([
                                        html.
                                        Li("Vrins, F.  (2020). Course notes for LLSM2226:  Credit & Interest Rates Risk. (Financial Engineering Program, Louvain School of Management, Université catholique de Louvain)"
                                           ),
                                        html.
                                        Li("Shreve, S. E. (2004). Stochastic calculus for finance II continuous-time models (2nd ed.). Springer Finance."
                                           ),
                                    ]),
                                ])
                            ]),
                        #
                        dcc.Tab(label="Appro-ach",
                                value="Appro-ach",
                                children=[
                                    html.Div(children=[
                                        html.Br(),
                                        html.H4("Methodology followed",
                                                style={"text-align": "center"
                                                       }),
                                        html.P([
                                            """
                              To prove that the BSM price is arbitrage-free, let us try to perfectly replicate it with a strategy. If the strategy is successfull, then 
                              the BSM price is unique and therefore arbitrage-free.
                              """
                                        ]),
                                        html.Hr(),
                                        html.H4("Stock simulation",
                                                style={"text-align": "center"
                                                       }),
                                        html.P([
                                            """
                              We use the analytical solution to the GBM SDE, using Îto: \(S_t=S_0exp((\mu-\\frac{\sigma^2}{2})t+\sigma W_t)\). Then, suppose that the stock price
                              observations are equally spaced: \(t_i=i\delta, i \in \{1,2,\dots,n\}, n=T/\delta\)\(,\\forall \delta>0\)
                              This corresponds to $$S_{t+\delta}=S_texp((\mu-\\frac{\sigma^2}{2})\delta+\sigma\sqrt{\delta}Z), Z\sim \mathcal{N}(0,1)$$
                              """
                                        ]),
                                        html.Hr(),
                                        html.H4("Replicating portfolio",
                                                style={"text-align": "center"
                                                       }),
                                        html.Label(
                                            "Step 1",
                                            style={'font-weight': 'bold'}),
                                        html.P([
                                            """
                              We infer the dynamics of the option price by applying Ito's lemma to the BSM PDE. Complying with Ito \(V_t=f(t,S_t)\):
                              $$dV_t=\\left(f_t(t,S_t)+\\frac{\sigma^2S_t^2}{2}f_{xx}(t,S_t)\\right)dt+f_x(t,S_t)dS_t$$ Where \(f_i(t,S_t)\) are the partial derivatives.
                              """
                                        ]),
                                        html.Label(
                                            "Step 2",
                                            style={'font-weight': 'bold'}),
                                        html.P([
                                            """
                              The randomness embedded in \(S_t\), i.e. not knowing \(f(t,x)\), is taken care of by hedging \(dS_t\). This is better understood later on. Let us now  
                              create a portfolio \(\Pi\) composed of a cash account and an equity account. At inception, we buy \(\Delta_0\) shares at cost \(\Delta_0S_0\). The reminder \(\Pi_0-\Delta_0S_0\) is cash.
                              If the strategy is financially self-sufficiant, then 
                              $$d\Pi_t=r(\Pi_t-\Delta_tS_t)dt+\Delta_tdS_t$$ 
                              This means that the change in portfolio value results from the interests earned on the cash account and the gains/losses obtained by holding the stock. When we rebalance the portfolio to hold more
                              (resp. less) shares, the cash is taken from (resp. placed on) the cash account. Notice that the cash account can go negative, in which case the interests will have to be paid (not received).                 
                              """
                                        ]),
                                        html.Label(
                                            "Step 3",
                                            style={'font-weight': 'bold'}),
                                        html.P([
                                            """
                              In other words, the created portfolio \(\Pi\) will perfectly replicate the option price if \(\Delta_t=f_x(t,S_t)\). Indeed, the BSM PDE can be found from equating the two equations with that.
                              """
                                        ]),
                                        html.P([
                                            """
                              \(\Delta_t=f_x(t,S_t)\) indicates the number of shares to hold at any instant in order to replicate the BSM price. 
                              Deriving it, it is equal to \(\Delta_t = \nu\Phi(\nu d_1)\) Where \(\nu\) equals 1 for a call and -1 for a put.
                              """
                                        ]),
                                        html.P([
                                            """
                              Holding \(\Delta_t = \nu\Phi(\nu d_1(t,S_t))\) at all times, we have found a strategy that perfectly replicates the BSM price, therefore proving it is the unique 
                              price that prevents arbitrage opportunities. 
                              """
                                        ]),
                                        html.P([
                                            """ 
                              Indeed, because it is possible to generate the option’s payoff by being given exactly the cash amount \(V_0\) given by the BSM 
                              formula, the option price must agree with \(V_0\). Otherwise, for \(k>0\), if the price of the option is \(V_0+k\), you can sell the option at \(V_0+k\), launch the strategy (which only requires \(V_0\)), and get a 
                              profit of \(k\) today. At maturity, the strategy will deliver exactly the amount that you have to pay to the option’s buyer. If \(k<0\), do the opposite (buy the option, sell the strategy).
                              """
                                        ]),
                                        html.P([
                                            """
                              The delta-hedging strategy is visually summarized in this table by Prof. Vrins (LSM, 2020). 
                              """
                                        ]),
                                        dbc.Button(
                                            "Show me the table",
                                            id="bsm-table-target",
                                            color="primary",
                                            className="mr-1",
                                        ),
                                        dbc.Popover(
                                            children=[
                                                dbc.PopoverHeader(
                                                    "delta-hedging strategy table"
                                                ),
                                                dbc.PopoverBody([
                                                    html.Img(
                                                        src=
                                                        "data:image/png;base64,{}"
                                                        .format(
                                                            base64.b64encode(
                                                                open(
                                                                    "./pictures/bsm-math.png",
                                                                    'rb').read(
                                                                    )).decode(
                                                                    )),
                                                        style={
                                                            "width": "250%"
                                                        })
                                                ]),
                                            ],
                                            id="bsm-table",
                                            is_open=False,
                                            target="bsm-table-target",
                                        ),
                                    ])
                                ]),
                        #
                        #
                        dcc.Tab(
                            label='Inputs',
                            value='Inputs',
                            children=html.Div(children=[
                                html.Br(),
                                #
                                html.P("""
                                            Place your mouse over any input to get its definition. 
                                            """),
                                dcc.
                                Dropdown(id='CallOrPut',
                                         options=[{
                                             'label': 'European Call option',
                                             'value': "Call"
                                         }, {
                                             'label': 'European Put option',
                                             'value': "Put"
                                         }],
                                         value='Call'),
                                #
                                html.Br(),
                                #
                                html.Div(children=[
                                    html.Label('Spot price',
                                               title=list_input["Spot price"],
                                               style={
                                                   'font-weight': 'bold',
                                                   "text-align": "left",
                                                   "width": "25%",
                                                   'display': 'inline-block'
                                               }),
                                    dcc.Input(id="S",
                                              value=100,
                                              debounce=True,
                                              type='number',
                                              style={
                                                  "width": "16%",
                                                  'display': 'inline-block'
                                              }),
                                    html.P("",
                                           id="message_S",
                                           style={
                                               "font-size": 12,
                                               "color": "red",
                                               "padding": 5,
                                               'width': '55%',
                                               "text-align": "left",
                                               'display': 'inline-block'
                                           })
                                ]),
                                html.Div(children=[
                                    html.Label("Strike",
                                               title=list_input["Strike"],
                                               style={
                                                   'font-weight': 'bold',
                                                   "text-align": "left",
                                                   "width": "25%",
                                                   'display': 'inline-block'
                                               }),
                                    dcc.Input(id="K",
                                              value=100,
                                              debounce=True,
                                              type='number',
                                              style={
                                                  "width": "16%",
                                                  'display': 'inline-block'
                                              }),
                                    html.P("",
                                           id="message_K",
                                           style={
                                               "font-size": 12,
                                               "color": "red",
                                               "padding": 5,
                                               'width': '55%',
                                               "text-align": "left",
                                               'display': 'inline-block'
                                           })
                                ], ),
                                #
                                html.Div(children=[
                                    html.Label("Drift",
                                               title=list_input["Drift"],
                                               style={
                                                   'font-weight': 'bold',
                                                   'display': 'inline-block'
                                               }),
                                    html.Label(
                                        id="drift",
                                        style={'display': 'inline-block'}),
                                ]),
                                #
                                dcc.Slider(id='mu',
                                           min=-0.40,
                                           max=0.40,
                                           value=0.10,
                                           step=0.01,
                                           marks={
                                               -0.40: '-40%',
                                               0: "0%",
                                               0.40: '40%'
                                           }),
                                #
                                html.Div([
                                    html.Label('Volatility',
                                               title=list_input["Volatility"],
                                               style={
                                                   'font-weight': 'bold',
                                                   "display": "inline-block"
                                               }),
                                    html.Label(
                                        id="sigma",
                                        style={"display": "inline-block"}),
                                ]),
                                #
                                dcc.Slider(id='vol',
                                           min=0,
                                           max=0.50,
                                           step=0.01,
                                           value=0.25,
                                           marks={
                                               0: "0%",
                                               0.25: "25%",
                                               0.50: "50%"
                                           }),
                                #
                                html.Div([
                                    html.Label(
                                        'Risk-free rate',
                                        title=list_input["Risk-free rate"],
                                        style={
                                            'font-weight': 'bold',
                                            "display": "inline-block"
                                        }),
                                    html.Label(
                                        id="riskfree",
                                        style={"display": "inline-block"}),
                                ]),
                                dcc.Slider(id='Rf',
                                           min=0,
                                           max=0.1,
                                           step=0.01,
                                           value=0.03,
                                           marks={
                                               0: "0%",
                                               0.05: "5%",
                                               0.1: "10%"
                                           }),
                                #
                                html.Div([
                                    html.Label('Maturity',
                                               title=list_input["Maturity"],
                                               style={
                                                   'font-weight': 'bold',
                                                   "display": "inline-block"
                                               }),
                                    html.Label(
                                        id="matu",
                                        style={"display": "inline-block"}),
                                ]),
                                dcc.Slider(
                                    id='T',
                                    min=0.25,
                                    max=
                                    5,  # marks={i: '{}'.format(i) for i in range(6)},
                                    marks={
                                        0.25: "3 months",
                                        3: "3 years",
                                        5: "5 years"
                                    },
                                    step=0.25,
                                    value=3),
                                #
                                html.Br(),
                                html.Div([
                                    html.Label('Discretization step',
                                               title=list_input[
                                                   "Discretization step"],
                                               style={
                                                   'font-weight': 'bold',
                                                   "text-align": "left",
                                                   'width': '50%',
                                                   'display': 'inline-block'
                                               }),
                                    dcc.Input(id="dt",
                                              value=0.01,
                                              min=0.0001,
                                              debounce=True,
                                              type='number',
                                              style={
                                                  "width": "16%",
                                                  'display': 'inline-block'
                                              }),
                                    html.P("",
                                           id="message_dt",
                                           style={
                                               "font-size": 12,
                                               "color": "red",
                                               'width': '34%',
                                               "text-align": "left",
                                               'display': 'inline-block'
                                           })
                                ]),
                                #
                                html.Div([
                                    html.Label(
                                        "Time between two rebalancing (in dt unit)",
                                        title=list_input[
                                            "Rebalancing frequency"],
                                        style={
                                            'font-weight': 'bold',
                                            'width': '50%',
                                            "text-align": "left",
                                            'display': 'inline-block'
                                        }),
                                    dcc.Input(id="dt_p",
                                              value=1,
                                              min=1,
                                              debounce=True,
                                              type='number',
                                              style={
                                                  "width": "16%",
                                                  'display': 'inline-block'
                                              }),
                                    html.P("",
                                           id="message_dt_p",
                                           style={
                                               "font-size": 12,
                                               "color": "red",
                                               'width': '34%',
                                               "text-align": "left",
                                               'display': 'inline-block'
                                           })
                                ]),
                                #
                                html.Div([
                                    html.Label(
                                        'Transaction costs',
                                        title=list_input["Transaction costs"],
                                        style={
                                            'font-weight': 'bold',
                                            "text-align": "left",
                                            'width': '50%',
                                            'display': 'inline-block'
                                        }),
                                    dcc.Input(id="TransactionCosts",
                                              value=0,
                                              min=0,
                                              debounce=True,
                                              type='number',
                                              style={
                                                  "width": "16%",
                                                  'display': 'inline-block'
                                              }),
                                    html.Label(id="unit_TC",
                                               style={
                                                   "padding": 5,
                                                   "display": "inline-block"
                                               })
                                ]),
                                #
                                dcc.RadioItems(id="FixedOrPropor",
                                               options=[{
                                                   'label': 'No TC',
                                                   'value': 'NTC'
                                               }, {
                                                   'label': 'Fixed TC',
                                                   'value': 'FTC'
                                               }, {
                                                   'label': 'Proportional TC',
                                                   'value': 'PTC'
                                               }],
                                               value='NTC',
                                               labelStyle={
                                                   'padding': 5,
                                                   'font-weight': 'bold',
                                                   'display': 'inline-block'
                                               }),

                                #
                                html.Label(children=[
                                    dbc.Button(
                                        "Change stock trajectory",
                                        id="ButtonChangeStockTrajectory",
                                        color="primary",
                                        className="mr-1",
                                    )
                                ],
                                           title=list_input["Seed"]),
                                html.Div(children=[
                                    html.Label(
                                        "The current stock trajectory scenario is: ",
                                        style={
                                            'display': 'inline-block',
                                            "padding": 5
                                        }),
                                    dcc.Input(id='seed',
                                              readOnly=False,
                                              debounce=True,
                                              value='1',
                                              min=1,
                                              max=500000,
                                              type='number',
                                              style={
                                                  "width": "20%",
                                                  'display': 'inline-block'
                                              })
                                ]  #stockScenario
                                         ),

                                # html.Label(children=[dcc.Checklist(id = "seed",
                                #                          options=[{'label': 'New Brownian motion', 'value': "seed"}],
                                #                          value=[],
                                #                          labelStyle={'font-weight': 'bold', "text-align":"left", 'display': 'inline-block'}
                                #                          )],
                                #            title=list_input["Seed"]),
                                #
                                html.Br(),
                                html.A('Download Data',
                                       id='download-link',
                                       download="rawdata.csv",
                                       href="",
                                       target="_blank"),
                            ])),
                    ],
                ),
            ],
            style={
                'float': 'left',
                'width': '25%',
                'margin': "30px"
            }),
    ])
Exemple #26
0
def create_brain_region_browser_layout(region_name):
    region_name = region_name.replace('%20', ' ')
    valid_coords = _get_valid_coords(region_name)
    if region_name not in dataset.region_label_to_dissection_region_dict:
        return None
    first_row = dbc.Row(
        [
            # brain region info
            dbc.Col(
                [
                    dbc.Jumbotron(
                        [
                            html.H1(region_name, id='region-name'),
                            dcc.Markdown(children=_brain_region_info_markdown(region_name))
                        ],
                        className='h-100'
                    )
                ],
                width=12, lg=3
            ),
            # 3D mesh control
            dbc.Col(
                [
                    dbc.Card(
                        [
                            dbc.CardHeader('3D Mesh Control'),
                            dbc.CardBody(
                                [
                                    dbc.FormGroup(
                                        [
                                            dbc.Label('Dissection Regions', html_for='cemba-mesh-dropdown'),
                                            dcc.Dropdown(
                                                options=[
                                                    {'label': region,
                                                     'value': region}
                                                    for region in
                                                    dataset.region_label_to_dissection_region_dict.keys()],
                                                id="cemba-mesh-dropdown",
                                                value=[region_name],
                                                multi=True),
                                            dbc.FormText('Load dissection regions from this study.')
                                        ]
                                    ),
                                    html.Hr(className='my-3'),
                                    dbc.FormGroup(
                                        [
                                            dbc.Label('Anatomical Structures',
                                                      html_for="ccf-mesh-dropdown"),
                                            dcc.Dropdown(
                                                options=[
                                                    {'label': region if region != 'root' else 'Brain',
                                                     'value': region}
                                                    for region in dataset.allen_ccf_regions
                                                ],
                                                id="ccf-mesh-dropdown",
                                                value=_default_ccf_mesh_selection(region_name),
                                                multi=True),
                                            dbc.FormText(
                                                dcc.Markdown(
                                                    "Load anatomical structures from "
                                                    "[the Allen CCFv3]"
                                                    "(http://atlas.brain-map.org/). "
                                                    "All the abbreviations are from "
                                                    "[the Allen Mouse Reference Atlas]"
                                                    "(http://atlas.brain-map.org/atlas?atlas=602630314)."
                                                )
                                            ),
                                            dbc.Label('Anatomical Structures Opacity',
                                                      html_for='ccf-mesh-opacity-slider',
                                                      className='mt-2'),
                                            dcc.Slider(
                                                id='ccf-mesh-opacity-slider',
                                                min=0.1,
                                                max=1,
                                                step=0.05,
                                                value=0.1,
                                                marks={i: str(i) for i in [0.1, 0.3, 0.5, 0.7, 0.9]}
                                            )
                                        ]
                                    )
                                ]
                            )
                        ],
                        className='h-100'
                    )
                ],
                width=12, lg=3
            ),
            # 3D mesh
            dbc.Col(
                [
                    dbc.Card(
                        [
                            dbc.CardHeader('Brain Dissection Regions & Anatomical Structures'),
                            dbc.CardBody(
                                [
                                    html.P(
                                        'Click legend to toggle structures. '
                                        'Note that tissues were dissected from both hemisphere.',
                                        className="text-muted"),
                                    dcc.Loading(
                                        [
                                            dcc.Graph(
                                                id='3d-mesh-graph',
                                                config={'displayModeBar': False}
                                            )
                                        ]
                                    )
                                ]
                            )
                        ],
                        className='h-100'
                    )
                ],
                width=12, lg=6
            )
        ]
    )

    second_row = dbc.Card(
        [
            dbc.CardHeader(
                [
                    html.P(
                        [
                            'Cell Scatter Control (For more details, go to the ',
                            dbc.CardLink('Paired Scatter Browser', id='brain-region-pair-scatter-url'),
                            ')'
                        ],
                        className='mb-0'
                    )
                ]
            ),
            dbc.CardBody(
                [
                    dbc.Row(
                        [
                            dbc.Col(
                                [
                                    dbc.FormGroup(
                                        [
                                            dbc.Label('Scatter Coords',
                                                      html_for='scatter-coords-dropdown',
                                                      className='mr-2'),
                                            dcc.Dropdown(
                                                options=[
                                                    {'label': name,
                                                     'value': name,
                                                     'disabled': False if (name in valid_coords) else True}
                                                    for name in dataset.coord_names],
                                                value='L1UMAP',
                                                id="scatter-coords-dropdown",
                                                clearable=False
                                            ),
                                            dbc.FormText(
                                                'Coordinates of both scatter plots.'
                                            )
                                        ],
                                        className='mr-3'
                                    )
                                ]
                            ),
                            dbc.Col(
                                [
                                    dbc.FormGroup(
                                        [
                                            dbc.Label('Region Level',
                                                      html_for='region-level-dropdown',
                                                      className='mr-2'),
                                            dcc.Dropdown(
                                                options=[
                                                    {'label': 'Dissection Region', 'value': 'RegionName'},
                                                    {'label': 'Sub-region', 'value': 'SubRegion'},
                                                    {'label': 'Major Region', 'value': 'MajorRegion'},
                                                ],
                                                value='RegionName',
                                                id="region-level-dropdown",
                                                clearable=False
                                            ),
                                            dbc.FormText('Color of the left scatter plot.')
                                        ],
                                        className='mr-3'
                                    )
                                ]
                            ),
                            dbc.Col(
                                [
                                    dbc.FormGroup(
                                        [
                                            dbc.Label('Cell Type Level',
                                                      html_for='cell-type-level-selector',
                                                      className='mr-2'),
                                            dcc.Dropdown(
                                                options=[
                                                    {'label': 'Cell Class', 'value': 'CellClass'},
                                                    {'label': 'Major Type', 'value': 'MajorType'},
                                                    {'label': 'Subtype', 'value': 'SubType'},
                                                ],
                                                value='MajorType',
                                                id="cell-type-level-selector",
                                                clearable=False
                                            ),
                                            dbc.FormText('Color of the middle scatter plots.')
                                        ],
                                        className='mr-3'
                                    )
                                ]
                            )
                        ],
                        form=True
                    )
                ]
            )
        ],
        className='my-3'
    )

    third_row = dbc.Row(
        [
            dbc.Col(
                [
                    dbc.Card(
                        [
                            dbc.CardHeader('Brain Region Scatter'),
                            dbc.Container(
                                [
                                    dcc.Graph(id='dissection-umap-graph')
                                ],
                                className='pt-3'
                            )
                        ],
                        className='h-100'
                    )
                ],
                width=12, xl=4
            ),
            dbc.Col(
                [
                    dbc.Card(
                        [
                            dbc.CardHeader('Cell Type Scatter'),
                            dbc.Container(
                                [
                                    dcc.Graph(id='cell-type-umap-graph')
                                ],
                                className='pt-3'
                            )
                        ],
                        className='h-100'
                    )
                ],
                width=12, xl=4
            ),
            dbc.Col(
                [
                    dbc.Card(
                        [
                            dbc.CardHeader('Cell Type Sunburst'),
                            dbc.CardBody(
                                [
                                    dcc.Graph(id='sunburst-graph'),
                                    html.A('Notes on cell type composition', className='text-muted',
                                           id='sunburst-notes'),
                                    dbc.Popover(
                                        [
                                            dbc.PopoverBody(
                                                SUNBURST_NOTES
                                            ),
                                        ],
                                        id="sunburst-notes-popover",
                                        is_open=False,
                                        target="sunburst-notes",
                                    ),
                                ]
                            )
                        ],
                        className='h-100'
                    )
                ],
                width=12, xl=4
            )
        ]
    )

    layout = html.Div(
        children=[
            # first row, info and anatomy
            first_row,
            # second row, UMAP control
            second_row,
            # third row, UMAP graphs
            third_row,
        ]
    )
    return layout
    color="light",
)

graph_card = dbc.Card(
    [
        dbc.CardBody([
            html.H4("Graffiti in Berlin 2012-2019",
                    className="card-title",
                    style={"text-align": "center"}),
            dbc.Button("About Berlin", id="popover-target", color="info"),
            dbc.Popover(
                [
                    dbc.PopoverHeader("All About Berlin:"),
                    dbc.PopoverBody(
                        "Berlin (/bɜːrˈlɪn/; German: [bɛʁˈliːn] is the capital and largest city of Germany by both area and population. Its 3,769,495 (2019) inhabitants make it the most populous city proper of the European Union. The city is one of Germany's 16 federal states. It is surrounded by the state of Brandenburg, and contiguous with Potsdam, Brandenburg's capital. The two cities are at the center of the Berlin-Brandenburg capital region, which is, with about six million inhabitants and an area of more than 30,000 km2, Germany's third-largest metropolitan region after the Rhine-Ruhr and Rhine-Main regions. (Wikipedia)"
                    ),
                ],
                id="popover",
                is_open=False,
                target="popover-target",  # attach the dbc.popover to the button
            ),
            dcc.Graph(id='line_chart', figure={}),
        ]),
    ],
    color="light",
)

# *********************************************************************************************************
app.layout = html.Div([
    dbc.Row([dbc.Col(image_card, width=3),
             dbc.Col(graph_card, width=8)],
Exemple #28
0
])
''' The Following are the all the popover components. 
They consist of the blue ? button, The popover itself with the header and the validation message 
telling the user why/why not the current input is valid'''

mass_popover = html.Div([
    dbc.Button(
        "?",
        id="mass-popover-target",
        color="info",
    ),
    dbc.Popover(
        [
            dbc.PopoverHeader("Mass Input"),
            dbc.PopoverBody([], id="mass_validation_message"),
        ],
        id="mass_popover",
        is_open=False,
        target="mass-popover-target",
    ),
], )

springConst_popover = html.Div([
    dbc.Button(
        "?",
        id="springConst-popover-target",
        color="info",
    ),
    dbc.Popover(
        [
            dbc.PopoverHeader("Sprint Constant Input"),
Exemple #29
0
def outcome_fn(month,beta_L,beta_H,death_stat_1st,herd_stat_1st,dat3_1st,death_stat_2nd,herd_stat_2nd,dat3_2nd,preset,number_strategies,which_strat): # hosp
    
    death_stat_1st = 100*death_stat_1st
    herd_stat_1st = 100*herd_stat_1st

    death_stat_2nd = 100*death_stat_2nd
    herd_stat_2nd = 100*herd_stat_2nd


    on_or_off = {'display': 'block','textAlign': 'center'}
    if number_strategies=='one':
        num_st = ''
        if which_strat==2:
            on_or_off = {'display': 'none'}
    else:
        num_st = 'One '
    strat_name = presets_dict[preset]

    if which_strat==1:
        Outcome_title = strat_name + ' Strategy ' + num_st
    else:
        Outcome_title = strat_name + ' Strategy Two'
    



    death_thresh1 = 66
    death_thresh2 = 33

    herd_thresh1 = 66
    herd_thresh2 = 33

    ICU_thresh1 = 5
    ICU_thresh2 = 10


    red_col    = 'danger' # 'red' #  '#FF4136'
    orange_col = 'warning' # 'red' #  '#FF851B'
    green_col  = 'success' # 'red' #  '#2ECC40'
    color_1st_death = green_col
    if death_stat_1st<death_thresh1:
        color_1st_death = orange_col
    if death_stat_1st<death_thresh2:
        color_1st_death = red_col

    color_1st_herd = green_col
    if herd_stat_1st<herd_thresh1:
        color_1st_herd = orange_col
    if herd_stat_1st<herd_thresh2:
        color_1st_herd = red_col

    color_1st_ICU = green_col
    if dat3_1st>ICU_thresh1:
        color_1st_ICU = orange_col
    if dat3_1st>ICU_thresh2:
        color_1st_ICU = red_col

    
    color_2nd_death = green_col
    if death_stat_2nd<death_thresh1:
        color_2nd_death = orange_col
    if death_stat_2nd<death_thresh2:
        color_2nd_death = red_col

    color_2nd_herd = green_col
    if herd_stat_2nd<herd_thresh1:
        color_2nd_herd = orange_col
    if herd_stat_2nd<herd_thresh2:
        color_2nd_herd = red_col

    color_2nd_ICU = green_col
    if dat3_2nd>ICU_thresh1:
        color_2nd_ICU = orange_col
    if dat3_2nd>ICU_thresh2:
        color_2nd_ICU = red_col




    if on_or_off['display']=='none':
        return None
    else:
        return html.Div([


                
                    dbc.Row([
                        html.H3(Outcome_title,style={'fontSize':'250%'},className='display-4'),
                    ],
                    justify='center'
                    ),
                    html.Hr(),


                    dbc.Row([
                        html.I('Compared to doing nothing. Traffic light colours indicate relative success or failure.'),
                    ],
                    justify='center', style={'marginTop': '20px'}
                    ),

            
            # dbc
            dbc.Row([

            
                dbc.Col([


                                html.H3('After 1 year:',style={'fontSize': '150%', 'marginTop': '30px', 'marginBottom': '30px'}),

                                dbc.Row([
                                    dbc.Col([
                                        dbc.Button('Reduction in deaths 🛈',
                                                    color='primary',
                                                    className='mb-3',
                                                    id="popover-red-deaths-target",
                                                    size='sm',
                                                    style = {'cursor': 'pointer'}),
                                                    dbc.Popover(
                                                        [
                                                        dbc.PopoverHeader('Reduction in deaths'),
                                                        dbc.PopoverBody(html.Div(
                                                        'This box shows the reduction in deaths due to the control strategy choice.'
                                                        ),),
                                                        ],
                                                        id = "popover-red-deaths",
                                                        is_open=False,
                                                        target="popover-red-deaths-target",
                                                        placement='top',
                                                    ),
                                    ],width=4,style={'textAlign': 'center'}),

                                    dbc.Col([

                                                    dbc.Button('ICU requirement 🛈',
                                                    color='primary',
                                                    className='mb-3',
                                                    size='sm',
                                                    id='popover-ICU-target',
                                                    style={'cursor': 'pointer'}
                                                    ),

                                                    
                                                    dbc.Popover(
                                                        [
                                                        dbc.PopoverHeader('ICU requirement'),
                                                        dbc.PopoverBody(html.Div(
                                                        'COVID-19 can cause a large number of serious illnesses very quickly. This box shows the extent to which the NHS capacity would be overwhelmed by the strategy choice (if nothing was done to increase capacity).'
                                                        ),),
                                                        ],
                                                        id = "popover-ICU",
                                                        is_open=False,
                                                        target="popover-ICU-target",
                                                        placement='top',
                                                    ),
                                    ],width=4,style={'textAlign': 'center'}),
                                    
                                    dbc.Col([

                                                    dbc.Button('Herd immunity 🛈',
                                                    color='primary',
                                                    className='mb-3',
                                                    size='sm',
                                                    id='popover-herd-target',
                                                    style={'cursor': 'pointer'}
                                                    ),               
                                                                        
                                                    dbc.Popover(
                                                        [
                                                        dbc.PopoverHeader('Herd immunity'),
                                                        dbc.PopoverBody(dcc.Markdown(
                                                        '''

                                                        This box shows how close to the safety threshold for herd immunity we got. If we reached (or exceeded) the threshold it will say 100%.
                                                        
                                                        However, this is the least important goal since an uncontrolled pandemic will reach safe levels of immunity very quickly, but cause lots of serious illness in doing so.
                                                        ''',
                                                        style={'font-family': 'sans-serif'}
                                                        ),),
                                                        ],
                                                        id = "popover-herd",
                                                        is_open=False,
                                                        target="popover-herd-target",
                                                        placement='top',
                                                    ),
                                ],width=4,style={'textAlign': 'center'}),

                                ],no_gutters=True),
                    
                                cards_fn(death_stat_1st,dat3_1st,herd_stat_1st,color_1st_death,color_1st_herd,color_1st_ICU),

                                html.H3('After 2 years:',style={'fontSize': '150%', 'marginTop': '30px', 'marginBottom': '30px'}),

                                cards_fn(death_stat_2nd,dat3_2nd,herd_stat_2nd,color_2nd_death,color_2nd_herd,color_2nd_ICU),


                ],
                width=12,
                ),


            ],
            align='center',
            ),

            ],style=on_or_off)
Exemple #30
0
 dbc.Popover(
     [
         dbc.PopoverHeader("Instructions:"),
         dbc.PopoverBody(
             " - Single click on a legend item to exclude"),
         dbc.PopoverBody(
             " - Double click on a legend item to isolate"),
         dbc.PopoverBody(
             " - Use drag and scroll to change the view of the map"
         ),
         dbc.PopoverBody(
             " - Double click anywhere to reset the view"),
         dbc.PopoverHeader("Information: "),
         dbc.PopoverBody(
             " - Choropleth: color encodes aggregated prevalence (saturation)/category "
             "of the least or most prevalent allergen (hue)"),
         dbc.PopoverBody(
             " - Bubble map: size encodes aggregated prevalence"
         ),
         dbc.PopoverBody(
             " - Bubble map: color encodes aggregated prevalence (saturation)/category "
             "of the least or most prevalent allergen (hue)"),
     ],
     id="popover",
     is_open=False,
     target="popover-target",
     placement='bottom-start',
     style={
         "background-color": "rgba(0, 0, 0, 0.8)",
         'font-size': '15px',
         'color': 'white',
         'margin': '5px',
         'padding': '0px 5px 5px 5px',
         "font-family": "Segoe UI",
         'border-radius': '6px'
     }),