def update_output(value, step, arg_graph): if self.debate_model is not None and value is not None: if value == 'Merged': merged_value, merged_graph = self.debate_model.get_merged_value( step) print("MERGED VALUE : ", merged_value) nodes, edges = convert_to_visdcc_format( merged_graph, self.debate_model.semantic) title = "Merged Graph Step " + str(step) self.agent_graph = merged_graph return [ visdcc.Network( id='agent-net', selection={ 'nodes': [], 'edges': [] }, data={ 'nodes': nodes, 'edges': edges }, options=dict(height='400px', width='100%', interaction=dict(hover=True))), title, None ] else: for agent in self.debate_model.schedule.agents: if agent.name == value: g = agent.state[step] self.agent_graph = g g.view_graph() nodes, edges = convert_to_visdcc_format( agent.state[step], self.debate_model.semantic) title = "Agent Graphs Step " + str(step) strategy = "Strategy : " + str( self.debate_model.strategies[step][ agent.name][0]) return [ visdcc.Network(id='agent-net', selection={ 'nodes': [], 'edges': [] }, data={ 'nodes': nodes, 'edges': edges }, options=dict(height='400px', width='100%', interaction=dict( hover=True))), title, html.Div( [html.H4('Agent Information'), strategy]) ] return None, 'Agent Graphs', None
def visualize_graph(self): ui_elem = [] for i, use_case_exec in enumerate(self.data): d_list = self.data[use_case_exec] for path_cnt, d in enumerate(d_list): ui_elem.append(html.Hr()) ui_elem.append( html. P(f"Use case #{i}.{path_cnt}: {use_case_exec.use_case.name}" )) network = visdcc.Network(id=f"network_{i}_{path_cnt}", selection={ 'nodes': [], 'edges': [] }, options=BaseVisdccViz.get_options( heigth=self.GRAPH_HEIGHT, hierarchical_layout=True), data=dict(nodes=d['nodes'], edges=d['edges'])) path = d['path'] atds = path.get_filtered_meta_data_by_key( metadata.META_DATA_ATD) atds_info = [str(atd) for atd in atds] ui_elem.append(html.P(f"ATDs: {atds_info}")) container = dbc.Container( id=f"network_{i}_container_{path_cnt}", children=network, style={"border": "1px solid black"}) ui_elem.append(container) return ui_elem
def main(): """Main program""" args = parse_args() ip = args.ip port = args.port # data loading # initialize network object and scrape the HS3 website network = zwiz.Network(ip=ip, port=port) df = network.edges_df.copy() df = df[df['type'] == 'neighbor'] # set temporary visual settings on the nodes for node_id, node in network.nodes.items(): if node_id == 1: node.marker_size = '10' node.marker_shape = 'dot' else: node.marker_size = '7' node.marker_shape = 'dot' # create visdcc-friendly nodes and edges nodes = [] for node_id, node in network.nodes.items(): if node_id not in [n['id'] for n in nodes]: nodes.append({'id': node.node_id, 'label': node.name[0:10]+'...', 'shape': node.marker_shape, 'size': node.marker_size}) edges = [] for _, edge in network.edges.items(): if edge.id not in [e['id'] for e in edges]: if edge.type == 'route': edges.append({'id': edge.id, 'from': edge.source.node_id, 'to': edge.target.node_id, 'width': 2}) # create app app = dash.Dash() # define layout app.layout = html.Div([ visdcc.Network(id='net', # pylint: disable=E1101 data={'nodes': nodes, 'edges': edges}, options=dict(height='800px', width='100%', nodes=dict(color='Grey'))), ]) # main call if __name__ == '__main__': app.run_server(debug=True)
def visualize_graph(self): ui_elems = [ visdcc.Network(id=self.ui_html_id, selection={ 'nodes': [], 'edges': [] }, options=BaseVisdccViz.get_options(), data=self.data), ] return ui_elems
def update_output_div(input_value): searchterm = input_value result = youtube_search(searchterm) just_json = result[1] just_json[1] url1 = "https://www.googleapis.com/youtube/v3/search?part=snippet&relatedToVideoId=" url2 = "&type=video&key=" myvideoids = [] myvideotitles = [] myrange = 3 for i in range(myrange): myvideotitles.append(just_json[i]["snippet"]["title"]) myvideoids.append(just_json[i]["id"]["videoId"]) source, target, videotitles = youtube_spider(myvideoids, url1, url2) source2, target2, videotitles2 = youtube_spider(target, url1, url2) newsource = convertToNumber(source) newsource2 = convertToNumber(source2) newtarget = convertToNumber(target) newtarget2 = convertToNumber(target2) nodes = [] data = {} for i, b in zip(videotitles + videotitles2, newsource + newsource2): nodes.append(dict(id=b, label=i)) nodes = [i for n, i in enumerate(nodes) if i not in nodes[n + 1:]] data["nodes"] = nodes targetids = [] for a, b in zip(newsource + newsource2, newtarget + newtarget2): targetids.append(str(a) + "-" + str(b)) targets = [] for a, b, c in zip(targetids, newsource + newsource2, newtarget + newtarget2): new_dict = dict(id=a, key=b, to=c) new_dict["from"] = new_dict.pop("key") targets.append(new_dict) targets = [i for n, i in enumerate(targets) if i not in targets[n + 1:]] data["edges"] = targets return visdcc.Network(id='net', data=data, options=dict(height='500px', width='90%'))
def update_step_graph(value, final_graph): if value is not None and self.debate_model is not None: graph = self.debate_model.state[value] nodes, edges = convert_to_visdcc_format( graph, self.debate_model.semantic) return [ visdcc.Network(id='step-net', selection={ 'nodes': [], 'edges': [] }, data={ 'nodes': nodes, 'edges': edges }, options=dict(height='400px', width='100%', interaction=dict(hover=True))), "Public Graph Step " + str(value) ] return None, None
def visualize_graph(self): ui_elem = [] for i, use_case_exec in enumerate(self.data): d = self.data[use_case_exec] ui_elem.append(html.Hr()) if use_case_exec.is_verified(): badge = dbc.Badge("verified", color="success", className="mr-1") else: badge = dbc.Badge("computed", color="dark", className="mr-1") ui_elem.append( html.P([ f"Use case #{i}: {use_case_exec.use_case.name} ({use_case_exec.playback_trace_id}) ", badge ])) network = visdcc.Network(id=f"network_{i}", selection={ 'nodes': [], 'edges': [] }, options=BaseVisdccViz.get_options( heigth=self.GRAPH_HEIGHT, hierarchical_layout=True), data=d) if use_case_exec.is_computed(): # Implicitly using the best path path = use_case_exec.get_best_computed_path() atds = path.get_filtered_meta_data_by_key( metadata.META_DATA_ATD) atds_info = [str(atd) for atd in atds] ui_elem.append(html.P(f"ATDs: {atds_info}")) container = dbc.Container(id=f"network_{i}_container", children=network, style={"border": "1px solid black"}) ui_elem.append(container) return ui_elem
'''.replace(' ', ''), className='eight columns offset-by-two') ], className='row', style={ 'text-align': 'center', 'margin-bottom': '15px' }), dcc.Input(id='my-id', value='Global warming', type='text'), html.Div(id='my-div', style={ 'text-align': 'center', 'margin-bottom': '15px' }), visdcc.Network(id='net', data=data, options=dict(height='500px', width='90%')), dcc.RadioItems(id='color', options=[{ 'label': 'Red', 'value': '#ff0000' }, { 'label': 'Green', 'value': '#00ff00' }, { 'label': 'Blue', 'value': '#0000ff' }], value='Red'), ])
}), html.Div(id='kol_from_id', hidden=True), html.Div(id='clicks', hidden=True), dcc.Loading( visdcc.Network(id='net', data={ 'nodes': nodes, 'edges': edges }, options={ 'height': '700px', 'width': '100%', 'nodes': { 'chosen': True, 'shape': 'dot', 'color': { 'highlight': { 'border': '#2B7CE9', 'background': '#D2E5FF' }, 'hover': { 'border': '#2B7CE9', 'background': '#D2E5FF' } } } })) ], style={ "border": "10px white solid", 'font-size': '12px'
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}) # ]) ])
nodes = [{'id': node_name, 'label': node_name, 'shape': 'dot', 'size': 7} for i, node_name in enumerate(node_list)] # create edges from df edges = [] for row in df.to_dict(orient='records'): source, target = row['Source'], row['Target'] edges.append({ 'id': source + "__" + target, 'from': source, 'to': target, 'width': 2, }) # define layout app.layout = html.Div([ visdcc.Network(id = 'net', data = {'nodes': nodes, 'edges': edges}, options = dict(height= '600px', width= '100%')), dcc.RadioItems(id = 'color', options=[{'label': 'Red' , 'value': '#ff0000'}, {'label': 'Green', 'value': '#00ff00'}, {'label': 'Blue' , 'value': '#0000ff'} ], value='Red' ) ]) # define callback @app.callback( Output('net', 'options'), [Input('color', 'value')]) def myfun(x): return {'nodes':{'color': x}}
nodes_list.append({'id': X, 'label': str(X), 'color': '#A9E2F3'}) edge_list = [{ 'id': f'{X}-{i}', 'from': X, 'to': i, 'label': str(round(score, 3)) } for i, score in zip(sim_id, sim_score)] data = { 'nodes': nodes_list, 'edges': edge_list, } return data element1 = visdcc.Network(id='sim-net', options=dict(height='800px', width='80%')) element2 = html.Div(id='test-diff-output') graph_vis = html.Div(children=[ html.Div(element1, style={ 'width': '80%', 'margin-left': '250px' }), element2 ], style={ 'margin-left': '200px', 'margin-right': '100px', 'width': '80%' }) def frontend_layout_with_stats():
from dash.dependencies import Input, Output import dash_core_components as dcc import dash_html_components as html import visdcc from app import app from apps import app1, app2 app.layout = html.Div([ dcc.Location(id='url', refresh=False), html.Div(id='page-content'), html.Div(visdcc.Network(id='net', options=dict( height='600px', width='100%', physics={'barnesHut': { 'avoidOverlap': 0 }}, )), style={'display': 'none'}) ]) @app.callback(Output('page-content', 'children'), [Input('url', 'pathname')]) def display_page(pathname): if pathname == '/apps/app1': return app1.layout elif pathname == '/apps/app2': return app2.layout else: return app1.layout
value = 'off' )], style={'width': '15%', 'padding': '20px 0px 0px 20px', 'display':'inline-block'} ), html.Br(), html.Br(), html.B(id = 'time-value', style={'font-size':18, 'padding': '20px 0px 0px 30px'}), html.Div(dcc.RangeSlider(id = 'time-slider', count = 1, min = time.mktime(mint), max = time.mktime(maxt), step = 400, value = [time.mktime(mint), time.mktime(mint) + 7000], pushable = 3600, marks = labelt ), style={'padding': '20px 20px 70px 20px', 'width': '65%'} ), visdcc.Network(id = 'net', data = { 'nodes' : [{'id':g[i], 'x':li_x[i], 'y':li_y[i] } for i in range(len(g))], 'edges' : [] } , selection = {'nodes':[], 'edges':[]}, style = {'display':'inline-block', 'height':'600px', 'width':'65%', 'padding':'20px', 'vertical-align':'top'}), html.Div([ html.Img(src='/static/legend.png', style={'width': '300px'}), html.Br(), html.B('可能影響的事件:', style={'font-size':20, 'display':'inline-block', 'padding':'20px', 'margin-right':'15px', 'width': '170px'} ), html.B('可能的異常因子:', style={'font-size':20, 'display':'inline-block', 'padding':'20px', 'width': '170px'} ), html.Br(), html.Div(id = 'impact', style = {'background-color':'rgb(255, 239, 225)', 'padding':'20px', 'width': '170px', 'vertical-align':'top', 'margin-right':'15px', 'display':'inline-block'}), html.Div(id = 'factor', style = {'background-color':'rgb(240, 255, 225)', 'padding':'20px', 'width': '170px', 'vertical-align':'top', 'display':'inline-block'}), ], style = {'display':'inline-block', 'text-align': 'center'})
@author: jimmybow """ import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State import visdcc app = dash.Dash() app.layout = html.Div([ visdcc.Network(id='net', selection={ 'nodes': [], 'edges': [] }, options=dict(height='600px', width='100%')), html.Div(id='nodes'), html.Div(id='edges') ]) @app.callback(Output('nodes', 'children'), [Input('net', 'selection')]) def myfun(x): s = 'Selected nodes : ' if len(x['nodes']) > 0: s += str(x['nodes'][0]) return s @app.callback(Output('edges', 'children'), [Input('net', 'selection')])
'height': '200px', } } # styles = { # 'pre': { # 'border': 'thin lightgrey solid', # 'overflowX': 'scroll', # 'width': '70%', # } # } app.layout = dhc.Div([ dhc.Div([ visdcc.Network(id = 'net', options = dict(height= '600px', width= '100%', # physics={'barnesHut': {'avoidOverlap': 1,"damping": 0.4,"centralGravity": 0.3,"springConstant": 0.1,"springLength": 100,}} physics={'barnesHut': {'avoidOverlap': 1,"damping": 0.4,"centralGravity": 0.1,"springConstant": 0.04,}} )), ], className='column', style={'float':'left','height': '600px', 'width': '67%'}), # dcc.Input(id = 'label', # placeholder = 'Enter a label ...', # type = 'text', # value = '' ), dcc.Interval( id='interval-component', interval=3*1000, # in milliseconds n_intervals=0 ), dhc.Div([
visdcc.Network( id='net', data={ 'nodes': [{ 'id': 23, 'label': 'Russia', 'title': 'Class:Country<br>Name:Russia<br>Confidence:high', 'group': 'Country', 'color': '#00ffff' }, { 'id': 24, 'label': 'Ukraine', 'title': 'Class:Country<br>Name:Ukraine<br>Confidence:high', 'group': 'Country' }, { 'id': 32, 'label': 'U.S.', 'title': 'Class:Country<br>Name:U.S.<br>Confidence:medium', 'group': 'Country' }, { 'id': 51, 'label': 'Russian', 'title': 'Class:Country<br>Name:Russian<br>Confidence:low', 'group': 'Country' }, { 'id': 52, 'label': 'British', 'title': 'Class:Country<br>Name:British<br>Confidence:low', 'group': 'Country' }, { 'id': 33, 'label': 'British', 'title': 'Class:Nationality<br>Name:British<br>Confidence:medium', 'group': 'Nationality' }, { 'id': 34, 'label': 'Russian', 'title': 'Class:Nationality<br>Name:Russian<br>Confidence:medium', 'group': 'Nationality' }, { 'id': 35, 'label': 'Ukrainian', 'title': 'Class:Nationality<br>Name:Ukrainian<br>Confidence:medium', 'group': 'Nationality' }, { 'id': 25, 'label': 'Washington', 'title': 'Class:StatesOrProvinces<br>Name:Washington<br>Confidence:high', 'group': 'StatesOrProvinces' }, { 'id': 40, 'label': 'consultant', 'title': 'Class:Title<br>Name:consultant<br>Confidence:low', 'group': 'Title' }, { 'id': 41, 'label': 'candidate', 'title': 'Class:Title<br>Name:candidate<br>Confidence:low', 'group': 'Title' }, { 'id': 42, 'label': 'actress', 'title': 'Class:Title<br>Name:actress<br>Confidence:low', 'group': 'Title' }, { 'id': 43, 'label': 'lawmaker', 'title': 'Class:Title<br>Name:lawmaker<br>Confidence:low', 'group': 'Title' }, { 'id': 44, 'label': 'president', 'title': 'Class:Title<br>Name:president<br>Confidence:low', 'group': 'Title' }, { 'id': 45, 'label': 'businessman', 'title': 'Class:Title<br>Name:businessman<br>Confidence:low', 'group': 'Title' }, { 'id': 46, 'label': 'attorney', 'title': 'Class:Title<br>Name:attorney<br>Confidence:low', 'group': 'Title' }, { 'id': 47, 'label': 'spokesman', 'title': 'Class:Title<br>Name:spokesman<br>Confidence:low', 'group': 'Title' }, { 'id': 48, 'label': 'security adviser', 'title': 'Class:Title<br>Name:security adviser<br>Confidence:low', 'group': 'Title' }, { 'id': 49, 'label': 'chairman', 'title': 'Class:Title<br>Name:chairman<br>Confidence:low', 'group': 'Title' }, { 'id': 50, 'label': 'intelligence officer', 'title': 'Class:Title<br>Name:intelligence officer<br>Confidence:low', 'group': 'Title' }, { 'id': 37, 'label': 'Trump', 'title': 'Class:Facility<br>Name:Trump<br>Confidence:low', 'group': 'Facility' }, { 'id': 38, 'label': 'Trump Organization', 'title': 'Class:Facility<br>Name:Trump Organization<br>Confidence:low', 'group': 'Facility' }, { 'id': 2, 'label': 'Christopher Steele', 'title': 'Class:Person<br>Name:Christopher Steele<br>Confidence:very_high', 'group': 'Person' }, { 'id': 3, 'label': 'Cohen', 'title': 'Class:Person<br>Name:Cohen<br>Confidence:very_high', 'group': 'Person' }, { 'id': 4, 'label': 'Flynn', 'title': 'Class:Person<br>Name:Flynn<br>Confidence:very_high', 'group': 'Person' }, { 'id': 5, 'label': 'Michael Cohen', 'title': 'Class:Person<br>Name:Michael Cohen<br>Confidence:very_high', 'group': 'Person' }, { 'id': 6, 'label': 'Michael Flynn', 'title': 'Class:Person<br>Name:Michael Flynn<br>Confidence:very_high', 'group': 'Person' }, { 'id': 7, 'label': 'Mueller', 'title': 'Class:Person<br>Name:Mueller<br>Confidence:very_high', 'group': 'Person' }, { 'id': 8, 'label': 'Paul Manafort', 'title': 'Class:Person<br>Name:Paul Manafort<br>Confidence:very_high', 'group': 'Person' }, { 'id': 9, 'label': 'Stormy Daniels', 'title': 'Class:Person<br>Name:Stormy Daniels<br>Confidence:very_high', 'group': 'Person' }, { 'id': 10, 'label': 'Trump', 'title': 'Class:Person<br>Name:Trump<br>Confidence:very_high', 'group': 'Person' }, { 'id': 11, 'label': 'Vladimir Putin', 'title': 'Class:Person<br>Name:Vladimir Putin<br>Confidence:very_high', 'group': 'Person' }, { 'id': 15, 'label': 'Manafort', 'title': 'Class:Person<br>Name:Manafort<br>Confidence:high', 'group': 'Person' }, { 'id': 16, 'label': 'Daniels', 'title': 'Class:Person<br>Name:Daniels<br>Confidence:high', 'group': 'Person' }, { 'id': 17, 'label': 'Michael', 'title': 'Class:Person<br>Name:Michael<br>Confidence:high', 'group': 'Person' }, { 'id': 18, 'label': 'Robert S. Mueller III', 'title': 'Class:Person<br>Name:Robert S. Mueller III<br>Confidence:high', 'group': 'Person' }, { 'id': 26, 'label': 'Andrew Harnik/AP', 'title': 'Class:Person<br>Name:Andrew Harnik/AP<br>Confidence:medium', 'group': 'Person' }, { 'id': 27, 'label': 'Democrat', 'title': 'Class:Person<br>Name:Democrat<br>Confidence:medium', 'group': 'Person' }, { 'id': 28, 'label': 'Steele', 'title': 'Class:Person<br>Name:Steele<br>Confidence:medium', 'group': 'Person' }, { 'id': 36, 'label': '130,000', 'title': 'Class:Money<br>Name:130,000<br>Confidence:medium', 'group': 'Money' }, { 'id': 39, 'label': '$130,000', 'title': 'Class:Money<br>Name:$130,000<br>Confidence:low', 'group': 'Money' }, { 'id': 12, 'label': 'BBC', 'title': 'Class:Organization<br>Name:BBC<br>Confidence:very_high', 'group': 'Organization' }, { 'id': 13, 'label': 'Trump', 'title': 'Class:Organization<br>Name:Trump<br>Confidence:very_high', 'group': 'Organization' }, { 'id': 14, 'label': 'Trump Organization', 'title': 'Class:Organization<br>Name:Trump Organization<br>Confidence:very_high', 'group': 'Organization' }, { 'id': 19, 'label': 'New York Times', 'title': 'Class:Organization<br>Name:New York Times<br>Confidence:high', 'group': 'Organization' }, { 'id': 29, 'label': 'Democrat', 'title': 'Class:Organization<br>Name:Democrat<br>Confidence:medium', 'group': 'Organization' }, { 'id': 30, 'label': 'Senate Intelligence Committee', 'title': 'Class:Organization<br>Name:Senate Intelligence Committee<br>Confidence:medium', 'group': 'Organization' }, { 'id': 20, 'label': 'Manhattan', 'title': 'Class:City<br>Name:Manhattan<br>Confidence:high', 'group': 'City' }, { 'id': 21, 'label': 'Prague', 'title': 'Class:City<br>Name:Prague<br>Confidence:high', 'group': 'City' }, { 'id': 22, 'label': 'Moscow', 'title': 'Class:City<br>Name:Moscow<br>Confidence:high', 'group': 'City' }, { 'id': 31, 'label': 'New York City', 'title': 'Class:City<br>Name:New York City<br>Confidence:medium', 'group': 'City' }, { 'id': 1, 'label': 'Article:Why Michael Cohen is poss', 'title': 'Class:Reports<br>Title:Why Michael Cohen is possibly the biggest threat to Trump', 'group': 'Reports' }, { 'id': 0, 'label': 'Provider:washingtonpost', 'title': 'Class:Sources<br>Source:washingtonpost', 'group': 'Sources' }], 'edges': [{ 'from': 0, 'to': 1, 'title': 'created' }, { 'from': 10, 'to': 44, 'title': 'title' }, { 'from': 5, 'to': 46, 'title': 'title' }, { 'from': 10, 'to': 13, 'title': 'employee_or_member_of' }, { 'from': 5, 'to': 13, 'title': 'employee_or_member_of' }, { 'from': 11, 'to': 34, 'title': 'origin' }, { 'from': 11, 'to': 51, 'title': 'origin' }, { 'from': 11, 'to': 44, 'title': 'title' }, { 'from': 9, 'to': 42, 'title': 'title' }, { 'from': 5, 'to': 42, 'title': 'title' }, { 'from': 2, 'to': 33, 'title': 'origin' }, { 'from': 2, 'to': 52, 'title': 'origin' }, { 'from': 2, 'to': 50, 'title': 'title' }, { 'from': 6, 'to': 48, 'title': 'title' }, { 'from': 5, 'to': 44, 'title': 'title' }, { 'from': 5, 'to': 31, 'title': 'cities_of_residence' }, { 'from': 5, 'to': 32, 'title': 'countries_of_residence' }, { 'from': 3, 'to': 32, 'title': 'countries_of_residence' }, { 'from': 5, 'to': 45, 'title': 'title' }, { 'from': 8, 'to': 49, 'title': 'title' }, { 'from': 5, 'to': 49, 'title': 'title' }, { 'from': 5, 'to': 41, 'title': 'title' }] }, options=dict(height='600px', width='100%')),
def dissertation(app): #Set lists about available menus: node_list = ['theory', 'testing', 'about'] about_list = ['about me', 'about project'] program_list = ['chord', 'score'] testing_list = ['field test 1', 'opera'] math_list = ['fourier', 'mfcc', 'critical band', 'spreading function'] theory_list = ['mathematics', 'masking', 'blending', 'orchestration'] initial = ['Orchestration Analyzer'] theory_list_without_math = theory_list.copy() theory_list_without_math.remove( 'mathematics') #Pop out math from theory list, because it has subnodes #initial_data = {'nodes':[{'id': initial[0], 'label': initial[0], 'shape': 'box', 'font':{'size':100}}], 'edges':[]} #List of pages with text in them: def flatten_list(l): return [item for sublist in l for item in sublist] text_pages = flatten_list( [about_list, testing_list, theory_list_without_math]) #Define function to add menu elements def add_nodes(label): return { 'id': label, 'label': label, 'shape': 'text', 'font': { 'size': 20, 'color': 'grey', 'face': 'Arial Black' }, 'color': { 'background': 'black', 'border': 'grey' }, } def add_edges(parent, child): return {'id': parent + "-" + child, 'from': parent, 'to': child} #The starting data for menus: initial_data = { 'nodes': [{ 'id': initial[0], 'label': 'Click here', 'shape': 'text', 'font': { 'size': 24, 'color': 'grey', 'face': 'Arial Black' } }], 'edges': [] } #Unusable function, don't have energy to debug: def not_exist(data, id, nodeid): for val in data: if val[id] == nodeid: return False else: return True #Add menuitems and connect them to clicked node: def append_nodes(data, nodelist, parent): for i in range(len(nodelist)): val = nodelist[i] data['nodes'].append(add_nodes(val)) data['edges'].append(add_edges(val, parent)) return data #When items are clicked, this is the function def act_on_click(data, node_id): text = '' if node_id == 'about': data = append_nodes(data, about_list, node_id) if node_id == initial[0]: data = append_nodes(data, node_list, node_id) if node_id == 'program': data = append_nodes(data, program_list, node_id) if node_id == 'testing': data = append_nodes(data, testing_list, node_id) if node_id == 'theory': data = append_nodes(data, theory_list, node_id) if node_id == 'mathematics': data = append_nodes(data, math_list, node_id) return data, text #This function strips the nodes if node is clicked again def strip_on_click(node_data, node_id): new_nodelist = node_data['nodes'].copy() new_edgelist = node_data['edges'].copy() if node_id == 'about': lista = about_list if node_id == 'testing': lista = testing_list if node_id == initial[0]: return initial_data # If logo is clicked, back to squeare one :) if node_id == 'program': lista = program_list if node_id == 'theory': lista = theory_list if node_id == 'mathematics': lista = math_list for nod in lista: for val in node_data['nodes']: if val['id'] == nod: new_nodelist.remove(val) for val in node_data['edges']: if val['to'] == nod: new_edgelist.remove(val) node_data['nodes'] = [] node_data['edges'] = [] node_data['nodes'] = new_nodelist node_data['edges'] = new_edgelist return node_data import dissertation.about_text import dissertation.field_test_text import dissertation.masking_text import dissertation.history_of_orchestration def text_on_click(node_id): text = html.Div('Sorry, not yet implemented') if node_id == 'about me': text = dissertation.about_text.aboutText() if node_id == 'field test 1': text = dissertation.field_test_text.field_test_text() if node_id == 'masking': text = dissertation.masking_text.masking_text() if node_id == 'orchestration': text = dissertation.history_of_orchestration.history_text() text = dbc.Modal([ dbc.ModalBody( html.Div(children=[html.Div(text, style={'height': '100vh'})], className='fadein')) ], scrollable=True, is_open=True, autoFocus=True, size='xl') return text ############################## # Disseration menu callbacks # ############################## @app.callback( [ Output('testing', 'children'), #The main container for content Output('net', 'data'), #Menu items data Output('nodestore', 'children'), #Hidden place to store data Output('hidden4', 'style'), #To show/hide menuitems Output('back', 'style'), Output('net', 'focus'), #To focus a node, not really working :( Output('hidden2', 'style'), #To show/hide program Output('hidden3', 'style'), ], [ Input('net', 'selection'), #Selected nodes Input('back', 'n_clicks') ], #Backbutton [ State('net', 'data'), State('nodestore', 'children'), ]) def node_function(sel, back_button, data, nodestore): chord = {'display': 'none'} score = {'display': 'none'} nodestore = json.loads(nodestore) #Load things from data store hideshow = {'display': 'block'} back = {'display': 'none'} focus = True # Intro when page loads: intro = html.Div([ html.Div('Orchestration Analyzer', className='fadein', style={ 'fontSize': 80, 'fontFace': 'Arial', 'color': 'grey', 'textAlign': 'center' }), html.Div( 'Artificial intelligence in orchestration by Uljas Pulkkis', className='fadein', style={ 'fontSize': 20, 'fontFace': 'Arial', 'color': 'grey', 'textAlign': 'center', 'margin': '0px' }) ], style={'marginBottom': -120}) intro = '' #Launch back button and set it to none if back_button > 0 and nodestore['back']: #Back button to switch views nodestore['back'] = False score = chord = {'display': 'none'} chord = chord = {'display': 'none'} return [ intro, data, json.dumps(nodestore), { 'display': 'block' }, { 'display': 'none' }, focus, chord, score ] nodestore['back'] = False #data = dict() #data, fit, focus, id, moveTo, options, selection, style if sel != None and 'nodes' in sel: #If clicked for the first time if sel['nodes'] == []: #If empty screen is clicked return [ intro, data, json.dumps(nodestore), hideshow, back, focus, chord, score ] node_id = sel['nodes'][0] focus = node_id #Set focus on clicked node if node_id in text_pages: #node_id == 'about me': #About me text will be shown text = text_on_click(node_id) nodestore['back'] = True hideshow = {'display': 'none'} back = {'display': 'none', 'color': '#404040'} intro = text return [ text, data, json.dumps(nodestore), hideshow, back, focus, chord, score ] if node_id in program_list: nodestore['back'] = True if node_id == 'chord': hideshow = {'display': 'none'} back = {'display': 'none', 'color': '#404040'} score = chord = {'display': 'none'} chord = chord = {'display': 'block'} if node_id == 'score': hideshow = {'display': 'none'} back = {'display': 'none', 'color': '#404040'} score = chord = {'display': 'block'} chord = chord = {'display': 'none'} return [ '', data, json.dumps(nodestore), hideshow, back, focus, chord, score ] elif not node_id in nodestore: #If node is never clicked nodestore[node_id] = True if nodestore[node_id]: #If certain node is selected # data['nodes'][0] ={'id': initial[0], 'label': '', 'shape': 'image', 'size': 100, # 'image': 'data:image/png;base64,{}'.format(encoded_image.decode()), 'font': {'size': 100}} data, msg = act_on_click(data, node_id) nodestore[node_id] = False intro = '' #return [msg, data, json.dumps(nodestore), hideshow, back] elif not nodestore[ node_id]: #If node is clicked for the second time data = strip_on_click(data, node_id) nodestore[node_id] = True intro = '' #return ['', data, json.dumps(nodestore), hideshow, back] #node_index=data['nodes'].index({'id': node_number}) #return json.dumps(data['nodes'][node_index]) #[sel['nodes']] ##[sel['nodes'][0]] #When program starts, this is returned: return [ intro, data, json.dumps(nodestore), hideshow, back, focus, chord, score ] net_nodes = html.Div([ html.Div(id='nodestore', children=json.dumps({initial[0]: True}), style={'display': 'none'}), html.Button(id='back', n_clicks=0, children='BACK TO MASKING SKULL', className='button', style={'display': 'none'}), html.Div(id='testing'), html.Div( id='nethide', children=visdcc.Network( id='net', options=dict(minHeight='900px', animation=True, height='900px', width='100%', clickToUse=False, physics={ 'solver': 'repulsion', 'repulsion': { 'nodeDistance': 150 } }), data=initial_data ), # data=append_nodes(data, node_list, initial[0])), style={ 'width': '100vw', 'display': 'block' }), html.Div(id='diss-hidden-container', style={'display': 'none'}), html.Div(id='hidden2', style={'display': 'none'}), html.Div(id='hidden3', style={'display': 'none'}), html.Div(id='hidden4', style={'display': 'none'}), ]) return net_nodes
row_selectable=False, editable=False, filterable=True, sortable=True, id='edges-data') ], style={ 'width': '19%', 'float': 'left' }), html.Div( [ visdcc.Network(id='net', data={ 'nodes': stations, 'edges': edges }, options=dict(height='{}px'.format(MAP_HEIGHT), width='{}px'.format(MAP_WIDTH), physics={'enabled': False})) ], style={ 'width': '80%', 'float': 'right', 'border-style': 'solid', 'border-width': "0.2px" }) ]), html.Div([ html.H4(' ', style={'clear': 'both'}), html.Article('Undeliverable', style={
""" Created on Sat Feb 3 20:50:16 2018 @author: jimmybow """ import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State import visdcc app = dash.Dash() app.layout = html.Div([ visdcc.Network(id='net', options=dict(height='600px', width='100%')), dcc.Input(id='label', placeholder='Enter a label ...', type='text', value=''), html.Br(), html.Br(), dcc.RadioItems(id='color', options=[{ 'label': 'Red', 'value': '#ff0000' }, { 'label': 'Green', 'value': '#00ff00' }, { 'label': 'Blue',
def run_simulation(nb_agents, nb_args, nb_clones, comfort_limit, p_favor_bias, p_against_bias, nb_clicks, id, protocol): if nb_clicks is not None: changed_id = [ p['prop_id'] for p in dash.callback_context.triggered ][0] if 'run-button' in changed_id: if len(protocol) != 0: protocol = protocol[0] else: protocol = 'complete' print(protocol) if id is not None and len(id) > 0: print(id) self.debate_model, self.game_stats = run_debate_id( id, protocol=protocol) else: try: nb_args = int(nb_args) nb_agents = int(nb_agents) nb_clones = int(nb_clones) comfort_limit = float(comfort_limit) p_favor_bias = float(p_favor_bias) p_against_bias = float(p_against_bias) except: raise ("Invalid Arguments") self.debate_model, self.game_stats = run_debate( nb_args, nb_agents, lightmode=False, comfort_limit=comfort_limit, p_favor_bias=p_favor_bias, p_against_bias=p_against_bias, protocol=protocol, number_of_clones=nb_clones) nodes, edges = convert_to_visdcc_format( self.debate_model.argument_graph, self.debate_model.semantic) final_nodes, final_edges = convert_to_visdcc_format( self.debate_model.public_graph, self.debate_model.semantic) # building the options for the agent dropdown dropdown_options = [{ 'label': 'Merged Graph', 'value': 'Merged' }] for agent in self.debate_model.schedule.agents: dropdown_options += [{ 'label': 'Agent ' + str(agent.name), 'value': agent.name }] return [ visdcc.Network(id='net', selection={ 'nodes': [], 'edges': [] }, data={ 'nodes': nodes, 'edges': edges }, options=dict( height='400px', width='100%', interaction=dict(hover=True))), visdcc.Network(id='f-graph', selection={ 'nodes': [], 'edges': [] }, data={ 'nodes': final_nodes, 'edges': final_edges }, options=dict( height='350px', width='100%', interaction=dict(hover=True))), generate_table(self.game_stats), dropdown_options, self.game_stats['Steps'] - 1, self.game_stats['Steps'] - 1 ] return (None, None, None, [], 0, 0)
def get_app_layout(graph_data): """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( [ # html.H5("Setting Panel"), # html.Hr(className="my-2"), html.H6("Search"), html.Hr(className="my-2"), search_form, html.H6("Filter"), html.Hr(className="my-2"), filter_node_form, filter_edge_form, html.H6("Color"), 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})), 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}) # ]) ])
app.layout = html.Div([ visdcc.Network(id='net', data={ 'nodes': [{ 'id': 1, 'label': 'Node 1', 'color': '#00ffff' }, { 'id': 2, 'label': 'Node 2' }, { 'id': 4, 'label': 'Node 4' }, { 'id': 5, 'label': 'Node 5' }, { 'id': 6, 'label': 'Node 6' }], 'edges': [{ 'id': '1-3', 'from': 1, 'to': 3 }, { 'id': '1-2', 'from': 1, 'to': 2 }] }, options=dict(height='600px', width='100%')), dcc.RadioItems(id='color',
html.H1(children='Language percent', style={ 'textAlign': 'center', 'color': colors['text'] }), dcc.Graph(id='pie-bar'), html.Div([ html.Hr(), html.H2(children='Network', style={ 'textAlign': 'center' }), visdcc.Network(id='net', data=get_network_data(), options=dict(height='400px', width='100%')) ]), html.Iframe(srcDoc=f.read(),height="900",width="1300", id='iframe'), html.Div([ html.Div([ html.H3(children='sentiment data analysis ® 2018') ], className='center-wrap-content'), ], className='rs-footer'), ], className='main-content') ]) @app.callback(Output('intermediate-value', 'children'), [Input('dropdown', 'value')], events=[Event('interval-component', 'interval')])
app.layout = html.Div([ html.Div(json.dumps(data), id = 'data', style = {'display':'none'}), html.Div(id = 'x_input', style = {'display':'none'}), html.Div('{"b1_e": null, "b2_e": null}', id = 'nclick', style = {'display':'none'}), html.H1('Iris 鳶尾花品種預測', style = {'color': '#ae6c0d', 'display':'inline-block', 'width': '80%', 'text-align': 'center', 'vertical-align':'top'}), html.Div([dcc.Dropdown(id = 'choose', options=[{'label': '模型評估', 'value': 'model'}, {'label': '預測', 'value': 'pre'} ], value = 'model' )], style={'width': '15%', 'margin': '21.44px', 'display':'inline-block', 'font-size': 20} ), html.Br(), html.Div([ visdcc.Network(id = 'net', data = data, options = options, selection = {'nodes':[], 'edges':[]}, style = {'width': '82%', 'display':'inline-block', 'vertical-align':'top'}), visdcc.Network(id = 'legend', data = data_legend, options = options_legend, selection = {'nodes':[], 'edges':[]}, style = {'width': '18%', 'display':'inline-block', 'vertical-align':'top'})], style = {'width': '60%', 'display':'inline-block', 'vertical-align':'top'}), html.Div(id = 'right-hand', style = {'width': '40%', 'display':'inline-block', 'text-align': 'center'}) ]) @app.callback( Output('net', 'options'), [Input('net', 'id')]) def myfun(x): return({'layout': {'hierarchical': {'enabled': False} }} ) @app.callback(
html.Button(id='back', n_clicks=0, children='..-- T A K E M E B A C K --..', className='button', style={'display': 'none'}), html.Div(id='chord', style={'display': 'none'}), html.Div(id='score', style={'display': 'none'}), html.Div(id='testing'), #html.Div(children=[ visdcc.Network(id='net', options=dict(minHeight='900px', animation=True, height='900px', width='100%', clickToUse=False, physics={ 'solver': 'repulsion', 'repulsion': { 'nodeDistance': 150 } }), data=initial_data ) #data=append_nodes(data, node_list, initial[0])), #],style={'height':'100%'}), # dcc.Input(id = 'label', # placeholder = 'Enter a label ...', # type = 'text', # value = '' ), # html.Br(),html.Br(), # dcc.RadioItems(id = 'color', # options=[{'label': 'Red' , 'value': '#ff0000'}, # {'label': 'Green', 'value': '#00ff00'},
# uncomment to run cypher query directly from Neo4j # Neo4j should be running #from cypher import title app.title = 'SAGE' app.layout = html.Div([ # represents the URL bar, doesn't render anything dcc.Location(id='url', refresh=False), # content will be rendered in this element html.Div(id='page-content'), # workaround to render table component in sage_table app html.Div(dt.DataTable(rows=[{}]), style={'display': 'none'}), # workaround to render network viz component in app html.Div(visdcc.Network(id='net', data={ 'nodes': [], 'edges': [] })) ]) index_page = layout @app.callback(Output('page-content', 'children'), [Input('url', 'pathname')]) def display_page(pathname): if pathname == '/': return index_page if pathname == '/apps/app1': return app1.layout elif pathname == '/apps/app2': return app2.layout elif pathname == '/apps/sql': return sql.layout