def render_output_panel(area_select): data.process_data_for_area(area_select) card = html.Div([ dbc.Card(className="bg-dark text-light", children=[ dbc.CardBody([ html.H4(area_select, id="card-name", className="card-title"), html.Br(), html.H6("Compared to England:", className="card-title"), html.H4("{:,.0f}%".format(data.compare_to_eng), className="card-text text-light"), html.Br(), html.H6( "Compared to previous year:".format(area=area), className="card-title"), html.H4("{:,.0f}%".format(data.change_area), className="card-text text-light"), html.Br(), html.H6("Best period:", className="card-title"), html.H4(data.best_period, className="card-text text-light"), html.H6("with recycling rate {:,.0f}%".format( data.best_rate), className="card-title text-light"), html.Br() ]) ]) ]) return card
def update_div_last_daq_readings(daq_values): ''' App callback that prints the current values of the measurements whenever the page is refreshed ''' div = [ html.H6("Last readings", style={ 'font-weight': 'bold', 'margin-bottom': '0px' }) ] if daq_values: values = [] for key, value in daq_values.items(): if key == 'time' or key == 'datetime': continue name, unit = key_elements(key) val = daq_values[key] values.append( html.Div(f"{val:.4f} {unit}", style={ 'margin-left': '5px', 'font-weight': 'bold' })) div += values return div
def update_data(tab, network_list_active, submit_value): if tab == 'server': # global network_list_values global network_list global network_list_values if network_list_active: if os.path.isdir(BUFFER_DIR) is not True: os.mkdir(BUFFER_DIR) with open(BUFFER_DIR+'/streams.data', 'w') as streams: for sta in network_list_active: streams.write('\n'+sta) else: try: os.remove(BUFFER_DIR+'/streams.data') except FileNotFoundError: pass if network_list_active is not None: return html.Div(children=network_list_active.copy(), id='data-output', hidden=True) else: return html.Div(children=[], id='data-output', hidden=True) elif tab == 'folder': return html.Div([ html.H6('Connection to Folder not implemented'), ])
def __init__(self, project_name, description): super().__init__() self.card = html.A(html.Button( dbc.Card( dbc.CardBody( [ html.H4("Project : {}".format(project_name), className="card-title"), html.H6("Description : {}".format(description), className="card-subtitle", style={"margin-bottom": "8px"}), html.Div([ dbc.CardLink(dbc.Button("Test", style={"margin-right": "16px"}, color="primary"), href="{}/test".format(project_name), style={"float": "left"}), # dbc.CardLink(dbc.Button("Open", style={"margin-right": "20px"}, color="info"), # href=project_name), html.A(dbc.Button("Export CSV", style={"margin-right": "32px"}, color="secondary"), href="{}/export/csv".format(project_name)), html.A(dbc.Button("Export Excel", style={"margin-right": "32px"}, color="secondary"), href="{}/export/excel".format(project_name)), dbc.CardLink(dbc.Button("Delete", color="danger", style={"margin-right": "16px"}), href="{}/delete".format(project_name), style={"float": "right"}), # dbc.Badge("Success", style={"float": "right"}) ], ) ] ), style={"width": "65rem"}, ) ), href=project_name )
def update_div_time_display(daq_values): ''' App callback that prints the elapsed time whenever the page is refreshed ''' # If the DAQ is running, get the elapsed time elapsed_time = 0 if daq_values: elapsed_time = int(daq_values['time']) time_delta = str(datetime.timedelta(seconds=elapsed_time)) return html.H6(f"Run time: {time_delta}", style={ 'font-weight': 'bold', 'margin-top': '3px' })
def display_table(row, score, odo, next_move, self_play=False): header = f'Score = {score} Moves = {odo} ' if next_move == -1: header += 'Game over!' elif not self_play: header += f'Next move = {Game.actions[next_move]}' return dbc.Card([ html.H6(header, className='game-header'), dbc.CardBody([ html.Div(numbers[row[j, i]], className='cell', style={ 'left': x_position[i], 'top': y_position[j], 'background': colors[row[j, i]] }) for j in range(4) for i in range(4) ]) ], style={'width': '400px'})
def __init__(self, project, api, api_id, method, status): super().__init__() print("status", status) status_color = "success" if "success" == status.lower() else "danger" self.card = dbc.Card( dbc.CardBody( [ html.H4("API : {}".format(api), className="card-title"), html.H6("Method : {}".format(method), className="card-subtitle"), html.Div([ dbc.CardLink(dbc.Button("Test", style={"margin-right": "16px"}, color="primary"), href="{}/{}/test".format(project, api_id)), dbc.CardLink(dbc.Button("Delete", color="danger", style={"margin-right": "16px"}), href="{}/{}/delete".format(project, api_id), style={"float": "right"}), dbc.Badge(status, color=status_color, style={"float": "center"}) ], ) ] ), style={"width": "20rem"}, )
def test_mdcap001_dcc_components_as_props(dash_dcc): app = Dash(__name__) app.layout = html.Div( [ dcc.Checklist( [ {"label": html.H2("H2 label"), "value": "h2"}, {"label": html.A("Link in checklist", href="#"), "value": "a"}, ], id="checklist", ), dcc.RadioItems( [ {"label": html.H3("on"), "value": "on"}, {"label": html.P("off"), "value": "off"}, ], id="radio-items", ), dcc.Dropdown( [ {"label": html.H4("h4"), "value": "h4"}, {"label": html.H6("h6"), "value": "h6"}, ], id="dropdown", ), ] ) dash_dcc.start_server(app) dash_dcc.wait_for_text_to_equal("#checklist h2", "H2 label") dash_dcc.wait_for_text_to_equal("#checklist a", "Link in checklist") dash_dcc.wait_for_text_to_equal("#radio-items h3", "on") dash_dcc.wait_for_text_to_equal("#radio-items p", "off") dash_dcc.find_element("#dropdown").click() dash_dcc.wait_for_text_to_equal("#dropdown h4", "h4") dash_dcc.wait_for_text_to_equal("#dropdown h6", "h6")
def parse_contents(contents, filename, date): """ parses csv oor xls """ content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string) try: if 'csv' in filename: # Assume that the user uploaded a CSV file df = pd.read_csv( io.StringIO(decoded.decode('utf-8'))) elif 'xls' in filename: # Assume that the user uploaded an excel file df = pd.read_excel(io.BytesIO(decoded)) except Exception as e: print(e) return html.Div([ 'There was an error processing this file.' ]) return html.Div([ html.H5(f'Loaded file: {filename}'), #html.H6(datetime.datetime.fromtimestamp(date)), html.H6('First Few Rows are:'), dash_table.DataTable( data=df.head().to_dict('records'), columns=[{'name': i, 'id': i} for i in df.columns] ), html.Hr(), # horizontal line # For debugging, display the raw contents provided by the web browser #html.Div('Raw Content'), #html.Pre(contents[0:200] + '...', style={ # 'whiteSpace': 'pre-wrap', # 'wordBreak': 'break-all' #}) ])
def visualise_agent_parameters(k, v): if k == "output_channels_info": output_info_table = create_params_table("agent-parameters-table", v) return html.Div([html.H6(k), output_info_table]) else: return html.H6(k + ": " + str(v))
def div_graph_daq(): """ Generates an HTML div that contains the DAQ graph and the display options """ return html.Div( [ # Graph division html.Div(id='div-graph-daq', className='nine columns', style={'margin-left': '10px'}), # List of options for the graph display html.Div( [ # Dropdown to choose the file from which to extract the data dcc.Dropdown(id='dropdown-file-selection', clearable=False, searchable=True, style={'margin-top': '10px'}), # Selection of the amount of time to represent (not great) html.Div([ html.Div([ dcc.Input(id='input-time-range', value=1, type='number', style={"width": "100%"}) ], style={'margin-top': '10px'}, className='six columns'), html.Div([ dcc.Dropdown(id='dropdown-time-range', clearable=False, searchable=True, options=[{ 'label': 'second(s)', 'value': 'seconds' }, { 'label': 'minute(s)', 'value': 'minutes' }, { 'label': 'hour(s)', 'value': 'hours' }, { 'label': 'day(s)', 'value': 'days' }], value='hours', style={"width": "100%"}) ], style={'margin-top': '10px'}, className='six columns') ], style={'margin-bottom': '10px'}, className='twelve columns'), # Box that shows the elapsed time html.Div(id="div-time-display", style={'margin-top': '10px'}), # Choice of graph display type (overlapped or separated) html.Div([ html.H6("Display mode", style={ 'font-weight': 'bold', 'margin-bottom': '0px', 'margin-top': '10px' }), dcc.RadioItems(options=[{ 'label': ' Separate (Vertical)', 'value': 'separate_vertical' }, { 'label': ' Separate (Horizontal)', 'value': 'separate_horizontal' }, { 'label': ' Overlapping', 'value': 'overlap' }], value='separate_vertical', id='radio-display-mode-daq', style={'margin-left': '5px'}) ]), # Checklist of the measurements to plot and their last readings html.Div([ html.Div([ html.H6("Display selection", style={ 'font-weight': 'bold', 'margin-bottom': '0px' }), dcc.Checklist(options=[], value=[], id='checklist-display-options-daq', style={'margin-left': '5px'}) ], className='six columns'), html.Div(id='div-last-daq-value', className='six columns') ], className='row', style={ 'margin-top': '0px', 'position': 'relative' }) ], className='three columns'), ], className="row", style={ "border-radius": "5px", "border-width": "5px", "border": "2px solid rgb(216, 216, 216)", "position": "relative", "height": "480px" })
className="border"), ], className="mb-2", ) badge_sizes = html.Div([ html.H1(["Example heading", dbc.Badge("New", className="ms-1")]), html.H2(["Example heading", dbc.Badge("New", className="ms-1")]), html.H3(["Example heading", dbc.Badge("New", className="ms-1")]), html.H4(["Example heading", dbc.Badge("New", className="ms-1")]), html.H5(["Example heading", dbc.Badge("New", className="ms-1")]), html.H6(["Example heading", dbc.Badge("New", className="ms-1")]), ]) badges = html.Div( [ make_subheading("Badge", "badge"), badge, badge_pills, badge_text, badge_sizes, ], className="mb-4", )
'value': 'Betweeness' }, { 'label': 'Closeness', 'value': 'Closeness' }, { 'label': 'Eigenvector', 'value': 'Eigenvector' }, ], value='Degree', searchable=False, ), html.H5('Appearence', className="mt-5 mb-3"), html.H6('Label Size', className="mt-1 mb-2"), dcc.RangeSlider(id='label_size_map', min=0, max=10, step=1, marks={ 0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9',
def get_map_map(tab, dataset_selection, traveler, centrality_index, label_size, node_size): map_graph = diogenetGraph("map", dataset_selection, dataset_selection, 'locations_data.csv', 'travels_blacklist.csv') if tab == "map_maps": data = None mapa = None map_graph.current_centrality_index = centrality_index if traveler == "All" or traveler == []: map_graph.edges_filter = [] else: for m_filter in traveler: map_graph.set_edges_filter(m_filter) map_graph.create_subgraph() data = map_graph.get_map_data(min_weight=node_size[0], max_weight=node_size[1]) df = pd.DataFrame(data) #Folium base map configurations url = 'https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}' attribution = '© <a href="https://developers.arcgis.com/">ArcGIS</a> ' base_map = folium.Map(location=[35, 30], min_zoom=4, max_zoom=7, zoom_start=6, tiles=None, attr=attribution) folium.TileLayer( tiles=url, show=True, attr=attribution, min_zoom=3, max_zoom=8, name="USGS - The National Map", ).add_to(base_map) markers_source = folium.FeatureGroup(name='Source').add_to(base_map) markers_target = folium.FeatureGroup(name='Target').add_to(base_map) for i in range(len(df['Source'])): #source marker popup_source = folium.Popup(str( "{} \n (lat = {:.1f}, \n lon={:.1f})".format( df['Source'][i], df["SourceLatitude"][i], df["SourceLongitude"][i])), parse_html=True, max_width=450) tooltip_source = "{} (lat = {:.1f}, lon={:.1f})".format( df['Source'][i], df["SourceLatitude"][i], df["SourceLongitude"][i]) markers_source.add_child( folium.CircleMarker(location=(float(df["SourceLatitude"][i]), float(df["SourceLongitude"][i])), popup=popup_source, tooltip=tooltip_source, fill=True, color=df["SourceColor"][i], fill_color=df["SourceColor"][i], radius=int(df["SourceSize"][i] * 1.3))) #target marker popup_target = folium.Popup(str( "{} \n (lat = {:.1f}, \n lon={:.1f})".format( df['Destination'][i], df["DestLatitude"][i], df["DestLongitude"][i])), parse_html=True, max_width=450) tooltip_target = "{} (lat = {:.1f}, lon={:.1f})".format( df['Destination'][i], df["DestLatitude"][i], df["DestLongitude"][i]) markers_target.add_child( folium.CircleMarker(location=(float(df["DestLatitude"][i]), float(df["DestLongitude"][i])), popup=popup_target, tooltip=tooltip_target, fill=True, color=df["DestinationColor"][i], fill_color=df["DestinationColor"][i], radius=int(df["DestinationSize"][i] * 1.3))) # travel info line folium.PolyLine( [[df["SourceLatitude"][i], df["SourceLongitude"][i]], [df["DestLatitude"][i], df["DestLongitude"][i]]], popup=folium.Popup(str("{} travel from {} to {}".format( df['Philosopher'][i], df["Source"][i], df["Destination"][i])), parse_html=True, max_width=450), tooltip="{} travel from {} to {}".format( df['Philosopher'][i], df["Source"][i], df["Destination"][i]), color='#ced4da', weight=1.5, ).add_to(base_map) suffix = ".html" temp_file_name = next(tempfile._get_candidate_names()) + suffix full_filename = os.path.abspath( os.path.join(os.path.dirname(__file__), '.', 'assets', temp_file_name)) #saving folium .html file folium.LayerControl().add_to(base_map) base_map.save(full_filename) return [ html.Iframe(src=app.get_asset_url(f'{temp_file_name}'), style={ "height": "100%", "width": "100%" }) ] if tab == "map_metrics": if traveler == "All": all_travelers = sorted(list(set(map_graph.get_edges_names()))) map_graph.edges_filter = [] for m_filter in all_travelers: map_graph.set_edges_filter(m_filter) map_graph.create_subgraph() elif traveler == []: all_travelers = sorted(list(set(map_graph.get_edges_names()))) map_graph.edges_filter = [] for m_filter in all_travelers: map_graph.set_edges_filter(m_filter) map_graph.create_subgraph() else: map_graph.edges_filter = [] for m_filter in traveler: map_graph.set_edges_filter(m_filter) map_graph.create_subgraph() def round_list_values(list_in): return [round(value, 4) for value in list_in] calculated_network_betweenness = list( pd.DataFrame.from_dict( nx.betweenness_centrality( map_graph.networkx_subgraph).items())[1]) calculated_network_degree = list( pd.DataFrame.from_dict( nx.degree_centrality(map_graph.networkx_subgraph).items())[1]) calculated_network_closeness = list( pd.DataFrame.from_dict( nx.closeness_centrality( map_graph.networkx_subgraph).items())[1]) calculated_network_eigenvector = list( pd.DataFrame.from_dict( nx.eigenvector_centrality( map_graph.networkx_subgraph).items())[1]) calculated_degree = [ round(value) for value in map_graph.calculate_degree() ] calculated_betweenness = round_list_values( map_graph.calculate_betweenness()) calculated_closeness = round_list_values( map_graph.calculate_closeness()) calculated_eigenvector = round_list_values( map_graph.calculate_eigenvector()) dict_map_data_tables = { "City": map_graph.get_vertex_names(), "Degree": round_list_values(calculated_network_degree), "Betweeness": round_list_values(calculated_network_eigenvector), "Closeness": round_list_values(calculated_network_closeness), "Eigenvector": round_list_values(calculated_network_eigenvector), } df_map_data_tables = pd.DataFrame(dict_map_data_tables) dt_map = dash_table.DataTable(id='table-map', columns=[{ "name": i, "id": i, 'deletable': True } for i in df_map_data_tables.columns], style_data_conditional=[{ 'if': { 'row_index': 'odd' }, 'backgroundColor': 'rgb(220, 220, 220)', }], style_cell={'textAlign': 'center'}, style_header={'textAlign': 'center'}, page_current=0, page_size=20, page_action='custom', sort_mode='single', sort_by=[{ 'column_id': 'Degree', 'direction': 'asc' }]) foot_note = html.Div(children=[ html.Span('Metrics obtained using the algorithms of '), html.A('Networkx', href='https://networkx.org/documentation/stable/', target='_blank') ]) return [ html.H6('Centrality Scores', className="mt-1 mb-2"), html.Hr(className='py-0'), dt_map, foot_note ] if tab == "map_graphs": map_graph.current_centrality_index = centrality_index graph_layout = "fr" pvis_graph = None if traveler == "All" or traveler == []: #map_graph.edges_filter = [] pvis_graph = map_graph.get_pyvis( min_weight=node_size[0], max_weight=node_size[1], min_label_size=label_size[0], max_label_size=label_size[1], layout=graph_layout, ) else: for m_filter in traveler: map_graph.set_edges_filter(m_filter) map_graph.create_subgraph() pvis_graph = map_graph.get_pyvis() if pvis_graph: suffix = ".html" temp_file_name = next(tempfile._get_candidate_names()) + suffix full_filename = os.path.abspath( os.path.join(os.path.dirname(__file__), '.', 'assets', temp_file_name)) pvis_graph.write_html(full_filename) return [ html.Iframe(src=app.get_asset_url(f'{temp_file_name}'), style={ "height": "100%", "width": "100%" }) ]
def _layout(self) -> dhtml.Div: """Create the HTML content to be displayed by the app Returns: An HTML component """ update_interval_ms = self._update_interval * 1000 # The interval in milliseconds page_update_interval = dcc.Interval(id='interval', interval=update_interval_ms) # The page has left and right columns which we build separately # Here we start building the left column left_column = \ dhtml.Div(className='three columns div-left-panel', children=[ ecomp.custom.Logo(), dcc.Markdown( 'This interface provides a general pipeline overview for testing and debugging purposes. ' 'Please consult with a system administrator before running on a cluster environment. ' f'For more information see the [official documentation]({ecomp.custom.DOC_URL}).' ), dhtml.P( 'The structural preview of your pipeline will load with an automatically optimized ' 'layout. Depending on the number of nodes in your pipeline and the size of your ' 'window, you may need to manually reposition plot elements by dragging them around ' 'the window. Predefined layouts are also provided via the dropdown box at the top ' 'of the page.' ), dhtml.H6('Pipeline Summary', id='h6-summary'), ecomp.custom.SummaryTable(self._pipeline) ]) # Here we start building the right column dropdown_layout_selector = \ dhtml.Div(className='div-dropdown-layout', children=[ dcc.Dropdown( id='dropdown-layout', value=DEFAULT_LAYOUT, clearable=False, options=[{'label': label, 'value': name} for name, label in zip(CYTOSCAPE_FORMATS, FORMAT_LABELS)] ) ]) right_column = \ dhtml.Div(className='nine columns div-right-panel', children=[ dropdown_layout_selector, ecomp.cyto.PipelineCytoscape(self._pipeline, id='pipeline-cyto'), dhtml.H4('Pipeline Load'), dhtml.Div( className='div-pipeline-load', children=[ ecomp.graphs.PipelineQueueSize(self._pipeline, id='graph-queue-size') ]), dhtml.H4('System Load'), dhtml.Div( className='div-system-load', children=[ ecomp.graphs.CpuPercentageGraph(id='graph-cpu-usage'), ecomp.graphs.RamPercentageGraph(id='graph-mem-usage') ]), ]) # Return the fully assembled page with both columns return dhtml.Div( className='row', children=[left_column, right_column, page_update_interval])
timeline_all_start = Timeline(data=data, countries=DEFAULT_COUNTRIES, type=DEFAULT_TYPE) timeline_one_start = Timeline(data=data, countries=[DEFAULT_COUNTRY], type=DEFAULT_TYPE) timeline_dayone_start = Timeline(data=data, countries=DEFAULT_COUNTRIES, type=DEFAULT_TYPE, dayone_mode=True) forecast_start = Forecast(data=data, country=DEFAULT_COUNTRY, type=DEFAULT_TYPE) map_start = Map(data=data, countries=DEFAULT_COUNTRIES, type=DEFAULT_TYPE, tots=tots) bar = Bar(data=data[DEFAULT_COUNTRY], type=DEFAULT_TYPE, country=DEFAULT_COUNTRY) timeline_france_vaccine = Timeline(data=vaccine_data, type=DEFAULT_TYPE) bar_france_hosp = Bar(data=hosp_data, type=DEFAULT_TYPE) hidden = '' if os.environ.get('FORECAST', "0") != "1": hidden = 'hidden' app.layout = html.Div(children=[ html.H1(f"COVID-19 Worldwide data", style={"textAlign": "center", "padding": "20px 0 10px 0"}), html.H6(f"Last update on : {tots['last_date']:%Y-%m-%d}", style={"textAlign": "center", "paddingBottom": "20px"}), html.Header([ dbc.Row( [ html.Div( dbc.Card( dbc.CardBody( [ html.H4('{0:n}'.format(tots['confirmed']), className="card-title"), html.H6("Confirmed", className="card-subtitle") ] ) ), className="col-md-6" ), html.Div( dbc.Card(
def dash_report( sessions, info=None, max_cycles=None, tags=None, signals=None, recreate_plots=None, video_only=None, ): """Create a gait report dash app. Parameters ---------- sessions : list List of session directories. For more than one session dirs, a comparison report will be created. Up to three sessions can be compared in the report. info : dict | None The patient info. If not None, some info will be shown in the report. max_cycles : dict | None Maximum number of gait cycles to plot for each variable type. If None, taken from config. tags : list | None Eclipse tags for finding dynamic gait trials. If None, will be taken from config. signals : ProgressSignals | None Instance of ProgressSignals, used to send progress updates across threads and track the cancel flag which aborts the creation of the report. If None, a dummy one will be created. recreate_plots : bool If True, force recreation of the report figures. Otherwise, cached figure data will be used, unless the report c3d files have changed (a checksum mechanism is used to verify this). video_only : bool If True, create a video-only report (no gait curves). Returns ------- dash.Dash | None The dash (flask) app, or None if report creation failed. """ sessions = [Path(s) for s in sessions] if recreate_plots is None: recreate_plots = False if video_only is None: video_only = False # relative width of left panel (1-12) # uncomment to use narrower video panel for 3-session comparison # LEFT_WIDTH = 8 if len(sessions) == 3 else 7 LEFT_WIDTH = 8 VIDS_TOTAL_HEIGHT = 88 # % of browser window height if len(sessions) < 1 or len(sessions) > 3: raise ValueError('Need a list of one to three sessions') is_comparison = len(sessions) > 1 report_name = _report_name(sessions) info = info or sessionutils.default_info() # tags for dynamic trials if tags is None: dyn_tags = cfg.eclipse.tags else: dyn_tags = tags # signals is used to track progress across threads; if not given, create a dummy one if signals is None: signals = ProgressSignals() # this tag will be shown in the menu for static trials static_tag = 'Static' # get the camera labels # reduce to a set, since there may be several labels for given id camera_labels = set(cfg.general.camera_labels.values()) # add camera labels for overlay videos # XXX: may cause trouble if camera labels already contain the string 'overlay' camera_labels_overlay = [lbl + ' overlay' for lbl in camera_labels] camera_labels.update(camera_labels_overlay) # build dict of videos for given tag / camera label # videos will be listed in session order vid_urls = dict() all_tags = dyn_tags + [static_tag] + cfg.eclipse.video_tags for tag in all_tags: vid_urls[tag] = dict() for camera_label in camera_labels: vid_urls[tag][camera_label] = list() # collect all session enfs into dict enfs = {session: dict() for session in sessions} data_enfs = list() # enfs that are used for data signals.progress.emit('Collecting trials...', 0) for session in sessions: if signals.canceled: return None enfs[session] = dict(dynamic=dict(), static=dict(), vid_only=dict()) # collect dynamic trials for each tag for tag in dyn_tags: dyns = sessionutils.get_enfs(session, tags=tag, trial_type='dynamic') if len(dyns) > 1: logger.warning(f'multiple tagged trials ({tag}) for {session}') dyn_trial = dyns[-1:] enfs[session]['dynamic'][tag] = dyn_trial # may be empty list if dyn_trial: data_enfs.extend(dyn_trial) # require at least one dynamic trial for each session if not any(enfs[session]['dynamic'][tag] for tag in dyn_tags): raise GaitDataError(f'No tagged dynamic trials found for {session}') # collect static trial (at most 1 per session) # rules: # -prefer enfs that have a corresponding c3d file, even for a video-only report # (so that the same static gets used for both video-only and full reports) # -prefer the newest static trial sts = sessionutils.get_enfs(session, trial_type='static') for st in reversed(sts): # newest first st_c3d = sessionutils.enf_to_trialfile(st, '.c3d') if st_c3d.is_file(): static_trial = [st] break else: # no c3ds were found - just pick the latest static trial static_trial = sts[-1:] enfs[session]['static'][static_tag] = static_trial if static_trial: data_enfs.extend(static_trial) # collect video-only dynamic trials for tag in cfg.eclipse.video_tags: dyn_vids = sessionutils.get_enfs(session, tags=tag) if len(dyn_vids) > 1: logger.warning( f'multiple tagged video-only trials ({tag}) for {session}' ) enfs[session]['vid_only'][tag] = dyn_vids[-1:] # collect all videos for given tag and camera, listed in session order signals.progress.emit('Finding videos...', 0) for session in sessions: for trial_type in enfs[session]: for tag, enfs_this in enfs[session][trial_type].items(): if enfs_this: enf = enfs_this[0] # only one enf per tag and session for camera_label in camera_labels: overlay = 'overlay' in camera_label real_camera_label = ( camera_label[: camera_label.find(' overlay')] if overlay else camera_label ) # need to convert filename, since get_trial_videos cannot # deal with enf names c3d = enf_to_trialfile(enf, 'c3d') vids_this = videos.get_trial_videos( c3d, camera_label=real_camera_label, vid_ext='.ogv', overlay=overlay, ) if vids_this: vid = vids_this[0] url = f'/static/{vid.name}' vid_urls[tag][camera_label].append(url) # build dcc.Dropdown options list for cameras and tags # list cameras which have videos for any tag opts_cameras = list() for camera_label in sorted(camera_labels): if any(vid_urls[tag][camera_label] for tag in all_tags): opts_cameras.append({'label': camera_label, 'value': camera_label}) # list tags which have videos for any camera opts_tags = list() for tag in all_tags: if any(vid_urls[tag][camera_label] for camera_label in camera_labels): opts_tags.append({'label': f'{tag}', 'value': tag}) # add null entry in case we got no videos at all if not opts_tags: opts_tags.append({'label': 'No videos', 'value': 'no videos', 'disabled': True}) # create (or load) the figures # this section is only run if we have c3d data if not video_only: data_c3ds = [enf_to_trialfile(enffile, 'c3d') for enffile in data_enfs] # at this point, all the c3ds need to exist missing = [fn for fn in data_c3ds if not fn.is_file()] if missing: missing_trials = ', '.join([fn.stem for fn in missing]) raise GaitDataError( f'c3d files missing for following trials: {missing_trials}' ) # see whether we can load report figures from disk digest = numutils._files_digest(data_c3ds) logger.debug(f'report data digest: {digest}') # the cached data is always saved into alphabetically first session data_dir = sorted(sessions)[0] data_fn = data_dir / f'web_report_{digest}.dat' if data_fn.is_file() and not recreate_plots: logger.info(f'loading saved report data from {data_fn}') signals.progress.emit('Loading saved report...', 0) try: with open(data_fn, 'rb') as f: saved_report_data = pickle.load(f) except UnicodeDecodeError: logger.warning('cannot open report (probably made with legacy version)') logger.warning('recreating...') saved_report_data = dict() else: saved_report_data = dict() logger.info('no saved data found or recreate forced') # make Trial instances for all dynamic and static trials # this is currently necessary even if saved figures are used trials_dyn = list() trials_dyn_dict = dict() # also organize dynamic trials by session trials_static = list() for session in sessions: trials_dyn_dict[session] = list() for tag in dyn_tags: if enfs[session]['dynamic'][tag]: if signals.canceled: return None c3dfile = enf_to_trialfile(enfs[session]['dynamic'][tag][0], 'c3d') tri = Trial(c3dfile) trials_dyn.append(tri) trials_dyn_dict[session].append(tri) if enfs[session]['static'][static_tag]: c3dfile = enf_to_trialfile(enfs[session]['static']['Static'][0], 'c3d') tri = Trial(c3dfile) trials_static.append(tri) emg_auto_layout = None # stuff that's needed to (re)create the figures if not saved_report_data: age = None if info['hetu'] is not None: # compute subject age at session time session_dates = [ sessionutils.get_session_date(session) for session in sessions ] ages = [age_from_hetu(info['hetu'], d) for d in session_dates] try: age = max(ages) except TypeError: age = None # create Markdown text for patient info patient_info_text = '##### %s ' % ( info['fullname'] if info['fullname'] else 'Name unknown' ) if info['hetu']: patient_info_text += f"({info['hetu']})" patient_info_text += '\n\n' # if age: # patient_info_text += 'Age at measurement time: %d\n\n' % age # load normal data for gait models; we have to do it here instead of # leaving it up to plot_trials, since it's session (age) specific signals.progress.emit('Loading normal data...', 0) model_normaldata = normaldata._read_configured_model_normaldata(age) # make average trials for each session avg_trials = [ AvgTrial.from_trials(trials_dyn_dict[session], sessionpath=session) for session in sessions ] # prepare for the curve-extracted value plots logger.debug('extracting values for curve-extracted plots...') vardefs_dict = dict(cfg.report.vardefs) allvars = [ vardef[0] for vardefs in vardefs_dict.values() for vardef in vardefs ] from_models = set(models.model_from_var(var) for var in allvars) if None in from_models: raise GaitDataError(f'unknown variables in extract list: {allvars}') curve_vals = { session.name: _trials_extract_values(trials, from_models=from_models) for session, trials in trials_dyn_dict.items() } # in EMG layout, keep chs that are active in any of the trials signals.progress.emit('Reading EMG data', 0) try: emgs = [tr.emg for tr in trials_dyn] emg_auto_layout = layouts._rm_dead_channels(emgs, cfg.layouts.std_emg) if not emg_auto_layout: emg_auto_layout = None except GaitDataError: emg_auto_layout = None # the layouts are specified as lists of tuples: (title, layout_spec) # where title is the page title, and layout_spec is either string or tuple. # if string, it denotes a special layout (e.g. 'patient_info') # if tuple, the first element should be the string 'layout_name' and the second # a gaitutils configured layout name; # alternatively the first element can be 'layout' and the second element a # valid gaitutils layout page_layouts = dict(cfg.web_report.page_layouts) # pick desired single variables from model and append pigvars = ( models.pig_lowerbody.varlabels_nocontext | models.pig_lowerbody_kinetics.varlabels_nocontext ) pigvars = sorted(pigvars.items(), key=lambda item: item[1]) pigvars_louts = {varlabel: ('layout', [[var]]) for var, varlabel in pigvars} page_layouts.update(pigvars_louts) # add supplementary data for normal layouts supplementary_default = dict() dd_opts_multi_upper = list() dd_opts_multi_lower = list() # loop through the layouts, create or load figures report_data_new = dict() for k, (page_label, layout_spec) in enumerate(page_layouts.items()): signals.progress.emit( f'Creating plot: {page_label}', 100 * k / len(page_layouts) ) if signals.canceled: return None # for comparison report, include session info in plot legends and # use session specific line style emg_mode = None if is_comparison: legend_type = cfg.report.comparison_legend_type style_by = cfg.report.comparison_style_by color_by = cfg.report.comparison_color_by if cfg.report.comparison_emg_as_envelope: emg_mode = 'envelope' else: legend_type = cfg.report.legend_type style_by = cfg.report.style_by color_by = cfg.report.color_by try: if saved_report_data: logger.debug(f'loading {page_label} from saved report data') if page_label not in saved_report_data: # will be caught, resulting in empty menu item raise RuntimeError else: figdata = saved_report_data[page_label] else: logger.debug(f'creating figure data for {page_label}') # the 'special' layouts are indicated by a string if isinstance(layout_spec, str): if layout_spec == 'time_dist': figdata = timedist.plot_comparison( sessions, big_fonts=False, backend='plotly' ) elif layout_spec == 'patient_info': figdata = patient_info_text elif layout_spec == 'static_kinematics': layout_ = cfg.layouts.lb_kinematics figdata = plot_trials( trials_static, layout_, model_normaldata=False, cycles='unnormalized', legend_type='short_name_with_cyclename', style_by=style_by, color_by=color_by, big_fonts=True, ) elif layout_spec == 'static_emg': layout_ = cfg.layouts.std_emg figdata = plot_trials( trials_static, layout_, model_normaldata=False, cycles='unnormalized', legend_type='short_name_with_cyclename', style_by=style_by, color_by=color_by, big_fonts=True, ) elif layout_spec == 'emg_auto': if emg_auto_layout is None: # no valid EMG channels raise RuntimeError else: figdata = plot_trials( trials_dyn, emg_auto_layout, emg_mode=emg_mode, legend_type=legend_type, style_by=style_by, color_by=color_by, supplementary_data=supplementary_default, big_fonts=True, ) elif layout_spec == 'kinematics_average': layout_ = cfg.layouts.lb_kinematics figdata = plot_trials( avg_trials, layout_, style_by=style_by, color_by=color_by, model_normaldata=model_normaldata, big_fonts=True, ) elif layout_spec == 'disabled': # exception will be caught in this loop, resulting in empty menu item raise RuntimeError else: # unrecognized layout; this will cause an exception raise Exception(f'Invalid page layout: {str(layout_spec)}') # regular layouts and curve-extracted layouts are indicated by tuple elif isinstance(layout_spec, tuple): if layout_spec[0] in ['layout_name', 'layout']: if layout_spec[0] == 'layout_name': # get a configured layout by name layout = layouts.get_layout(layout_spec[1]) else: # it's already a valid layout layout = layout_spec[1] # plot according to layout figdata = plot_trials( trials_dyn, layout, model_normaldata=model_normaldata, max_cycles=max_cycles, emg_mode=emg_mode, legend_type=legend_type, style_by=style_by, color_by=color_by, supplementary_data=supplementary_default, big_fonts=True, ) elif layout_spec[0] == 'curve_extracted': the_vardefs = vardefs_dict[layout_spec[1]] figdata = plot_extracted_box(curve_vals, the_vardefs) else: raise Exception(f'Invalid page layout: {str(layout_spec)}') else: raise Exception(f'Invalid page layout: {str(layout_spec)}') # save the newly created data if not saved_report_data: if isinstance(figdata, go.Figure): # serialize go.Figures before saving # this makes them much faster for pickle to handle # apparently dcc.Graph can eat the serialized json directly, # so no need to do anything on load figdata_ = figdata.to_plotly_json() else: figdata_ = figdata report_data_new[page_label] = figdata_ # make the upper and lower panel graphs from figdata, depending # on data type def _is_base64(s): """Test for valid base64 encoding""" try: return base64.b64encode(base64.b64decode(s)) == s except Exception: return False # this is for old style timedist figures that were in base64 # encoded svg if layout_spec == 'time_dist' and _is_base64(figdata): graph_upper = html.Img( src=f'data:image/svg+xml;base64,{figdata}', id='gaitgraph%d' % k, style={'height': '100%'}, ) graph_lower = html.Img( src=f'data:image/svg+xml;base64,{figdata}', id='gaitgraph%d' % (len(page_layouts) + k), style={'height': '100%'}, ) elif layout_spec == 'patient_info': graph_upper = dcc.Markdown(figdata) graph_lower = graph_upper else: # plotly fig -> dcc.Graph graph_upper = dcc.Graph( figure=figdata, id='gaitgraph%d' % k, style={'height': '100%'} ) graph_lower = dcc.Graph( figure=figdata, id='gaitgraph%d' % (len(page_layouts) + k), style={'height': '100%'}, ) dd_opts_multi_upper.append({'label': page_label, 'value': graph_upper}) dd_opts_multi_lower.append({'label': page_label, 'value': graph_lower}) except (RuntimeError, GaitDataError) as e: # could not create a figure logger.warning(f'failed to create figure for {page_label}: {e}') # insert the menu options but make them disabled dd_opts_multi_upper.append( {'label': page_label, 'value': page_label, 'disabled': True} ) dd_opts_multi_lower.append( {'label': page_label, 'value': page_label, 'disabled': True} ) continue opts_multi, mapper_multi_upper = _make_dropdown_lists(dd_opts_multi_upper) opts_multi, mapper_multi_lower = _make_dropdown_lists(dd_opts_multi_lower) # if plots were newly created, save them to disk if not saved_report_data: logger.debug(f'saving report data into {data_fn}') signals.progress.emit('Saving report data to disk...', 99) with open(data_fn, 'wb') as f: pickle.dump(report_data_new, f, protocol=-1) def make_left_panel(split=True, upper_value='Kinematics', lower_value='Kinematics'): """Helper to make the left graph panels. If split=True, make two stacked panels""" # the upper graph & dropdown items = [ dcc.Dropdown( id='dd-vars-upper-multi', clearable=False, options=opts_multi, value=upper_value, ), html.Div( id='div-upper', style={'height': '50%'} if split else {'height': '100%'} ), ] if split: # add the lower one items.extend( [ dcc.Dropdown( id='dd-vars-lower-multi', clearable=False, options=opts_multi, value=lower_value, ), html.Div(id='div-lower', style={'height': '50%'}), ] ) return html.Div(items, style={'height': '80vh'}) # create the app app = dash.Dash('gaitutils') # use local packaged versions of JavaScript libs etc. (no internet needed) app.css.config.serve_locally = True app.scripts.config.serve_locally = True app.title = _report_name(sessions, long_name=False) # this is for generating the classnames in the CSS num2words = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', } classname_left = f'{num2words[LEFT_WIDTH]} columns' classname_right = f'{num2words[12 - LEFT_WIDTH]} columns' if video_only: app.layout = html.Div( [ # row html.Div( [ # single main div dcc.Dropdown( id='dd-camera', clearable=False, options=opts_cameras, value='Front camera', ), dcc.Dropdown( id='dd-video-tag', clearable=False, options=opts_tags, value=opts_tags[0]['value'], ), html.Div(id='videos'), ], className='12 columns', ), ], className='row', ) else: # the two-panel layout with graphs and video app.layout = html.Div( [ # row html.Div( [ # left main div html.H6(report_name), dcc.Checklist( id='split-left', options=[{'label': 'Two panels', 'value': 'split'}], value=[], ), # need split=True so that both panels are in initial layout html.Div(make_left_panel(split=True), id='div-left-main'), ], className=classname_left, ), html.Div( [ # right main div dcc.Dropdown( id='dd-camera', clearable=False, options=opts_cameras, value='Front camera', ), dcc.Dropdown( id='dd-video-tag', clearable=False, options=opts_tags, value=opts_tags[0]['value'], ), html.Div(id='videos'), ], className=classname_right, ), ], className='row', ) @app.callback( Output('div-left-main', 'children'), [Input('split-left', 'value')], [State('dd-vars-upper-multi', 'value')], ) def update_panel_layout(split_panels, upper_value): split = 'split' in split_panels return make_left_panel(split, upper_value=upper_value) @app.callback( Output('div-upper', 'children'), [Input('dd-vars-upper-multi', 'value')] ) def update_contents_upper_multi(sel_var): return mapper_multi_upper[sel_var] @app.callback( Output('div-lower', 'children'), [Input('dd-vars-lower-multi', 'value')] ) def update_contents_lower_multi(sel_var): return mapper_multi_lower[sel_var] def _video_elem(title, url, max_height): """Create a video element with title""" if not url: return 'No video found' vid_el = html.Video( src=url, controls=True, loop=True, preload='auto', title=title, style={'max-height': max_height, 'max-width': '100%'}, ) # return html.Div([title, vid_el]) # titles above videos return vid_el @app.callback( Output('videos', 'children'), [Input('dd-camera', 'value'), Input('dd-video-tag', 'value')], ) def update_videos(camera_label, tag): """Create a list of video divs according to camera and tag selection""" if tag == 'no videos': return 'No videos found' vid_urls_ = vid_urls[tag][camera_label] if not vid_urls_: return 'No videos found' nvids = len(vid_urls_) max_height = str(int(VIDS_TOTAL_HEIGHT / nvids)) + 'vh' return [_video_elem('video', url, max_height) for url in vid_urls_] # add a static route to serve session data. be careful outside firewalls @app.server.route('/static/<resource>') def serve_file(resource): for session in sessions: filepath = session / resource if filepath.is_file(): return flask.send_from_directory(str(session), resource) return None # add shutdown method - see http://flask.pocoo.org/snippets/67/ @app.server.route('/shutdown') def shutdown(): logger.debug('Received shutdown request...') _shutdown_server() return 'Server shutting down...' # inject some info of our own app._gaitutils_report_name = report_name # XXX: the Flask app ends up with a logger by the name of 'gaitutils', which has a default # stderr handler. since logger hierarchy corresponds to package hierarchy, # this creates a bug where all gaitutils package loggers propagate their messages into # the app logger and they get shown multiple times. as a dirty fix, we disable the # handlers for the app logger (they still get shown since they propagate to the root logger) app.logger.handlers = [] return app
inline=True), ]), ], style={'display': 'block'}) ]), id='collapse-parameters', is_open=True ) ] models_card = [ dbc.Row([ dbc.Col([ dbc.CardImg(id='activity_plot', top=True), dbc.Card( dbc.CardBody([ html.Div([ html.H6('Activity', id='activity_title', className='card-title'), dcc.Dropdown(id='activity', value='', clearable=False), html.Hr(id='activity_hr'), ], id='activity_div'), html.H6('Similarity Information', className='card-title'), html.Div(id='div-similarity-metrics-value', children=''), html.Div(id='div-differences', children=''), ]), style={'backgroundColor': 'rgba(232, 236, 241, 1)'}, className='mt-1' ) ], width=3), dbc.Col([ dcc.Slider( id='window-slider', step=None,
dbc.Row( dbc.Col( html.H2( "Asset Allocation Visualizer", className="text-center bg-primary text-white p-2", ), )), dbc.Row( [ dbc.Col(tabs, width=12, lg=5, className="mt-4 border"), dbc.Col( [ dcc.Graph(id="allocation_pie_chart", className="mb-2"), dcc.Graph(id="returns_chart", className="pb-4"), html.Hr(), html.Div(id="summary_table"), html.H6(datasource_text, className="my-2"), ], width=12, lg=7, className="pt-4", ), ], className="ms-1", ), dbc.Row(dbc.Col(footer)), ], fluid=True, ) """ ========================================================================== Callbacks
def render_page_content(pathname): if pathname in ["/", "/page-1"]: return html.Div([ dbc.Container([ html.H4("About the Data and the App", className="display-about"), html.P( "Getting insights from the docs", className="lead", ), html.Hr(className="my-2"), dcc.Markdown( ''' Pellentesque posuere pellentesque imperde laoreet’s Velit leading pulvinar velit a hendrerit Donec non pellentesque jus businesses tincidunt. Suspendisse at maximus turpis, non loborsrt. Dolor sit amet consectetur elit sed do eiusmod tempor incididunt labore et dolore magna aliqua enim ad minim veniam quis nostrud exercitation ulac laboris aliquip ex ea commodo consequat duis aute irure.dolor in repre henderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excep teur sint cupidatat non proident. Pellentesque posuere pellentesque imperde laoreet’s Velit leading pulvinar velit a hendrerit Donec non pellentesque jus businesses tincidunt. Suspendisse at maximus turpis, non loborsrt. * consectetur elit sed do eius * consectetur elit sed * consectetur elit sed do ''' ), ]) ]) elif pathname == "/page-2": if 'data' in globals(): del data data = load_data() return html.Div([ html.H3('Text Data', style={'font-weight': 'bold'}), html.P('Preprocessed: stopwords removed; words in original form; without numbers; predefined phrase linked by "_"'), dash_table.DataTable( id='table', # columns=[{"name": i, "id": i} for i in textdata.columns], # data=textdata.to_dict('records'), columns=[{"name": i, "id": i} for i in data[['FileID','Text','text']].columns], data=data[['FileID','Text','text']].to_dict('records'), editable=False, filter_action="native", sort_action="native", sort_mode="multi", column_selectable=False, row_selectable=False, row_deletable=False, selected_columns=[], selected_rows=[], page_action="native", page_current= 0, page_size= 20, # style_cell_conditional=[ # {'if': {'column_id': 'Member'}, # 'width': '100px'}, # ] style_data={ 'whiteSpace': 'normal', 'height': 'auto' }, style_cell={ # 'height': 'auto', 'minWidth': '20px', 'maxWidth': '300px', # 'whiteSpace': 'normal', 'textAlign': 'left', 'verticalAlign': 'top', 'fontSize':12, }, ) ]) elif pathname in ["/page-3"]: return html.Div([ # Chart 1 dbc.Row([ dbc.Col([ html.H3('Summary Statistics of Documents', style={'font-weight': 'bold'}), html.P( id="description", children=dcc.Markdown( children=( ''' Member submisions, and Chair and Secretariat summaries/notes. ''') ) ), html.Br(), html.H6('Number of documents by year', style={'font-weight': 'bold'}), ], lg=10), ]), dbc.Row([ dbc.Col([ html.Label('Select Pillar:'), dcc.Dropdown( id='stat-year-dropdown-pillar', options=[{'label': v, 'value': k} for k, v in dict_pillar.items()], multi=False, value= 'All', ), ], lg=4), dbc.Col([ html.Label('Select Proponent:'), dcc.Dropdown( id='stat-year-dropdown-proponent', options=[{'label': v, 'value': k} for k, v in dict_proponent.items()], multi=False, value= 'All Members & Groups', ), ], lg=4) ]), dbc.Row([ dbc.Col([ dcc.Graph( id='stat-plot-year-pillar-proponent' ), ], lg=10), ]), # Chart 2 dbc.Row([ dbc.Col([ html.Label('Select topic:'), dcc.Dropdown( id='stat-year-dropdown-topic', options=[{'label': v, 'value': k} for k, v in dict_topic.items()], multi=False, value= 'All', ), ], lg=4), dbc.Col([ html.Label('Select Proponent:'), dcc.Dropdown( id='stat-year-dropdown-proponent2', options=[{'label': v, 'value': k} for k, v in dict_proponent.items()], multi=False, value= 'All Members & Groups', ), ], lg=4) ]), dbc.Row([ dbc.Col([ dcc.Graph( id='stat-plot-year-topic-proponent' ), ], lg=10), ]), # Chart 3 dbc.Row([ dbc.Col([ html.H6('Number of documents by proponent', style={'font-weight': 'bold'}), html.Label('Select Year:'), dcc.Dropdown( id='stat-3-dropdown-year', options=[{'label': v, 'value': k} for k, v in dict_year.items()], multi=False, value= 'All', ), ], lg=4), # dbc.Col([ # html.Label('Select Proponent:'), # dcc.Dropdown( # id='stat-year-dropdown-proponent2', # options=[{'label': v, 'value': k} # for k, v in dict_proponent.items()], # multi=False, # value= 'All Members & Groups', # ), # ], lg=4) ]), dbc.Row([ dbc.Col([ dcc.Graph( id='stat-3-proponent' ), ], lg=10), ]), # Chart 4 dbc.Row([ dbc.Col([ html.Br(), html.Br(), html.H6('Number of documents by topic', style={'font-weight': 'bold'}), html.Label('Select Year:'), dcc.Dropdown( id='stat-4-dropdown-year', options=[{'label': v, 'value': k} for k, v in dict_year.items()], multi=False, value= 'All', ), ], lg=4), # dbc.Col([ # html.Label('Select Proponent:'), # dcc.Dropdown( # id='stat-year-dropdown-proponent2', # options=[{'label': v, 'value': k} # for k, v in dict_proponent.items()], # multi=False, # value= 'All Members & Groups', # ), # ], lg=4) ]), dbc.Row([ dbc.Col([ dcc.Graph( id='stat-4-topic' ), ], lg=10), ]), ]) elif pathname in ["/page-4"]: # if 'data' in globals(): # del data # data = load_data() return html.Div([ dbc.Row([ # dbc.Col(lg=1), dbc.Col([ html.H3('Similarity within topics', style={'font-weight': 'bold'}), # html.H5('Updata on 14 June 2020'), html.P( id="description", children=dcc.Markdown( children=( ''' Similarity between two docs in a topic. ''') ) ), html.Br(), # html.H6('Number of Proposals by year', style={'font-weight': 'bold'}), # dcc.Dropdown( # id='my-dropdown', # options=[{'label': v, 'value': k} # for k, v in dict_pillar.items()], # multi=False, # value= [0,1,2,3,4,5,6,7,8,9], # ), ], lg=10), ]), dbc.Row([ dbc.Col([ html.Label('Select Topic:'), dcc.Dropdown( id='plot-year-dropdown-pillar1', options=[{'label': v, 'value': k} for k, v in dict_topic.items()], multi=False, value= 'COT', ), ], lg=4), # dbc.Col([ # html.Label('Select Proponent:'), # dcc.Dropdown( # id='plot-year-dropdown-proponent1', # options=[{'label': v, 'value': k} # for k, v in dict_proponent.items()], # multi=False, # value= 'All', # ), # ], lg=4) ]), dbc.Row([ # dbc.Col(lg=1), # dbc.Col([ # dcc.Graph( # id='top_topics' # ), # ], lg=3), dbc.Col([ dcc.Graph( id='plot_year1' ), ], lg=10), ]), ]) elif pathname in ["/page-5"]: # return html.H5("Content to be added page 2.") return html.Div([ dbc.Row([ # dbc.Col(lg=1), dbc.Col([ html.H3('WordCloud by topic', style={'font-weight': 'bold'}), # html.H5('Updata on 14 June 2020'), html.P( id="description", children=dcc.Markdown( children=( ''' Word frequency in a topic. ''') ) ), html.Br(), ], lg=10), ]), dbc.Row([ dbc.Col([ html.Label('Select Topic:'), dcc.Dropdown( id='plot-year-dropdown-pillar2', options=[{'label': v, 'value': k} for k, v in dict_topic.items()], multi=False, value= 'COT', ), ], lg=4), ]), dbc.Row([ dbc.Col([ dcc.Graph( id='plot_year2' ), ], lg=10), ]), ]) elif pathname in ["/page-6"]: return html.Div([ # html.H1('Title'), html.H3('Networks: proposal proponents & document cross reference', style={'font-weight': 'bold'}), html.Embed(src = "assets/network_proponent.html", width=850, height=850), html.Embed(src = "assets/network_crossreference.html", width=850, height=850) ]) elif pathname in ["/page-7"]: return html.Div([ dbc.Row([ dbc.Col([ html.H3('Term Frequency', style={'font-weight': 'bold'}), html.P( id="description", children=dcc.Markdown( children=( ''' Term frequency across time ''') ) ), ]), ]), dbc.Row([ dbc.Col([ dbc.Input(id='term-freq-input', value='tariff ams', type='text'), dbc.Button(id='term-freq-button', type='submit', children='Submit', className="mr-2"), html.P(id='term-freq-invalid'), ], lg=6), ]), dbc.Row([ dbc.Col([ dcc.Graph( id='term-freq-plot' ), # dbc.Button(id='term-freq-button', type='submit', children='Submit', className="mr-2"), ], lg=10), ]) ]) elif pathname in ["/page-8"]: return html.Div([ dbc.Row([ dbc.Col([ html.H3('TF-IDF keywords', style={'font-weight': 'bold'}), html.P( id="description2", children=dcc.Markdown( children=( ''' Keywords based on TF-IDF. Select documents ''') ) ), ]), ]), dbc.Row([ dbc.Col([ html.P(id='tfidf-invalid'), dcc.Dropdown(id='tfidf-dropdown', multi=True, value=['AIE-1', 'AIE-2','AIE-3','AIE-4','AIE-5'], placeholder='Select members', options=[{'label': country, 'value': country} for country in allfileid]), ],lg=10), ]), dbc.Row([ dbc.Col([ dcc.Graph( id='tfidf-plot' ), ], lg=10), ]) ]) # If the user tries to reach a different page, return a 404 message return dbc.Container( [ html.H1("404: Not found", className="text-danger"), html.Hr(), html.P(f"The pathname {pathname} was not recognised..."), ] )
import dash_bootstrap_components as dbc from dash import html card = dbc.Card( dbc.CardBody([ html.H4("Title", className="card-title"), html.H6("Card subtitle", className="card-subtitle"), html.P( "Some quick example text to build on the card title and make " "up the bulk of the card's content.", className="card-text", ), dbc.CardLink("Card link", href="#"), dbc.CardLink("External link", href="https://google.com"), ]), style={"width": "18rem"}, )
def set_layout(parent): update_txt = "Well data update: " + parent.well_update if parent.production_update != "": update_txt = (update_txt + " Production data update: " + parent.production_update) return html.Div( id=parent.uuid("layout"), children=[ html.H6("Webviz-4D " + parent.label), wcc.FlexBox( style={"fontSize": "1rem"}, children=[ html.Div( id=parent.uuid("settings-view1"), style={ "margin": "10px", "flex": 4 }, children=[ parent.selector.layout, ensemble_layout( parent=parent, map_number=0, ensemble_id=parent.uuid("ensemble"), ens_prev_id=parent.uuid("ensemble-prev"), ens_next_id=parent.uuid("ensemble-next"), real_id=parent.uuid("realization"), real_prev_id=parent.uuid("realization-prev"), real_next_id=parent.uuid("realization-next"), ), ], ), html.Div( style={ "margin": "10px", "flex": 4 }, id=parent.uuid("settings-view2"), children=[ parent.selector2.layout, ensemble_layout( parent=parent, map_number=1, ensemble_id=parent.uuid("ensemble2"), ens_prev_id=parent.uuid("ensemble2-prev"), ens_next_id=parent.uuid("ensemble2-next"), real_id=parent.uuid("realization2"), real_prev_id=parent.uuid("realization2-prev"), real_next_id=parent.uuid("realization2-next"), ), ], ), html.Div( style={ "margin": "10px", "flex": 4 }, id=parent.uuid("settings-view3"), children=[ parent.selector3.layout, ensemble_layout( parent=parent, map_number=2, ensemble_id=parent.uuid("ensemble3"), ens_prev_id=parent.uuid("ensemble3-prev"), ens_next_id=parent.uuid("ensemble3-next"), real_id=parent.uuid("realization3"), real_prev_id=parent.uuid("realization3-prev"), real_next_id=parent.uuid("realization3-next"), ), ], ), ], ), wcc.FlexBox( style={"fontSize": "1rem"}, children=[ html.Div( style={ "margin": "10px", "flex": 4 }, children=[ html.Div( id=parent.uuid("heading1"), style={ "textAlign": "center", "fontSize": 20, "fontWeight": "bold", }, ), html.Div( id=parent.uuid("sim_info1"), style={ "textAlign": "center", "fontSize": 15, "fontWeight": "bold", }, ), LayeredMap( sync_ids=[ parent.uuid("map2"), parent.uuid("map3") ], id=parent.uuid("map"), height=600, layers=[], hillShading=False, ), html.Div( id=parent.uuid("interval-label1"), style={ "textAlign": "center", "fontSize": 20, "fontWeight": "bold", }, ), ], ), html.Div( style={ "margin": "10px", "flex": 4 }, children=[ html.Div( id=parent.uuid("heading2"), style={ "textAlign": "center", "fontSize": 20, "fontWeight": "bold", }, ), html.Div( id=parent.uuid("sim_info2"), style={ "textAlign": "center", "fontSize": 15, "fontWeight": "bold", }, ), LayeredMap( sync_ids=[ parent.uuid("map"), parent.uuid("map3") ], id=parent.uuid("map2"), height=600, layers=[], hillShading=False, ), html.Div( id=parent.uuid("interval-label2"), style={ "textAlign": "center", "fontSize": 20, "fontWeight": "bold", }, ), ], ), html.Div( style={ "margin": "10px", "flex": 4 }, children=[ html.Div( id=parent.uuid("heading3"), style={ "textAlign": "center", "fontSize": 20, "fontWeight": "bold", }, ), html.Div( id=parent.uuid("sim_info3"), style={ "textAlign": "center", "fontSize": 15, "fontWeight": "bold", }, ), LayeredMap( sync_ids=[ parent.uuid("map"), parent.uuid("map2") ], id=parent.uuid("map3"), height=600, layers=[], hillShading=False, ), html.Div( id=parent.uuid("interval-label3"), style={ "textAlign": "center", "fontSize": 20, "fontWeight": "bold", }, ), ], ), dcc.Store( id=parent.uuid("attribute-settings"), data=json.dumps(parent.attribute_settings), ), ], ), html.H6(update_txt), ], )
import dash from dash import dcc from dash import html from dash.dependencies import Input, Output external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) app.layout = html.Div([ html.H6("Change the value in the text box to see callbacks in action!"), html.Div(["Input: ", dcc.Input(id='my-input', value='initial value', type='text')]), html.Br(), html.P(id='my-output'), ]) @app.callback( Output(component_id='my-output', component_property='children'), Input(component_id='my-input', component_property='value') ) def update_output_P(input_value): return ['Output: {}'.format(input_value), "text"] if __name__ == '__main__': app.run_server(debug=True)