def _make_cytoscape_widget(self, old_widget=None): widget = cyto.CytoscapeWidget() widget.set_layout( animate=self.animate, randomize=True, # Fast animation time for initial graph maxSimulationTime=1000, ) widget.layout.height = "100%" # copy handlers/style from the old widget if old_widget: for item, events in old_widget._interaction_handlers.items(): for event, dispatcher in events.items(): for callback in dispatcher.callbacks: callback_owner = getattr(callback, "__self__", None) if callback_owner == old_widget: callback = getattr(widget, callback.__name__) widget.on(item, event, callback) widget.set_style(old_widget.get_style()) else: widget.set_style(self.cyto_style) return widget
def network_widget( topics_tokens: pd.DataFrame) -> ipycytoscape.CytoscapeWidget: source_network_data = ttn_gui.to_dict(topics_tokens=topics_tokens) w = ipycytoscape.CytoscapeWidget(cytoscape_layout={'name': 'euler'}) w.graph.add_graph_from_json(source_network_data) return w
def draw_cytograph_graph(graph_data, style_data=common_graph_style, layout="cose", clusters=[], **kwargs): ipython_cytoscapeobj = ipycytoscape.CytoscapeWidget() ipython_cytoscapeobj.graph.add_graph_from_networkx(graph_data) # ipython_cytoscapeobj.set_tooltip_source('label') ipython_cytoscapeobj.set_style(style_data) ipython_cytoscapeobj.set_layout(name=layout, animate=False, **kwargs) #show leaf button btn1 = widgets.Checkbox( value=False, description="Show Label", disabled=False, ) btn1.observe(showhide_label(ipython_cytoscapeobj)) #show leaf button btn = widgets.Checkbox( value=False, description="Highlight leaf", disabled=False, ) btn.observe(highlight_leaf(ipython_cytoscapeobj)) #show layout layout_choice_widget = widgets.Dropdown(options=[ 'cola', 'concentric', 'grid', 'breadthfirst', 'cose', 'klay', 'dagre', 'circle', 'fcose', 'avsdf', 'spread', 'euler', 'cise' ], description='Layout', value=layout) top_row = widgets.HBox([btn1, btn, layout_choice_widget]) #cluster coloring? # middle_row_childs = [] # for c in clusters: # w1 = widgets.Dropdown( # options=[c.elements], # value=2, # description='Number:', # ) # w2 = widgets.ColorPicker( # concise=True, # description="", # value=c.color, # disabled=False # ) # middle_row_childs.append(widgets.HBox([w1,w2])) # middle_row = widgets.HBox(middle_row_childs) bottom_row = widgets.HBox([]) layout_cb = set_layout(ipython_cytoscapeobj, bottom_row) layout_choice_widget.observe(layout_cb) #initializes layout layout_cb({"name": "value", "new": layout}) return widgets.VBox([top_row, bottom_row]), ipython_cytoscapeobj
def test_create_network2(): topics_tokens_str = ';topic;token;weight;topic_id;position\n0;Topic #0;och;0.04476533457636833;0;1\n1;Topic #0;valv;0.02178177796304226;0;2\n2;Topic #0;i;0.02060970477759838;0;3\n3;Topic #1;och;0.02447959966957569;1;1\n4;Topic #1;som;0.02074943669140339;1;2\n5;Topic #1;av;0.020712170749902725;1;3\n6;Topic #2;som;0.02533087506890297;2;1\n7;Topic #2;en;0.023466676473617557;2;2\n8;Topic #2;är;0.022432737052440643;2;3\n9;Topic #3;de;0.02712307684123516;3;1\n10;Topic #3;är;0.023767853155732155;3;2\n11;Topic #3;i;0.019748181104660038;3;3\n' topics_tokens = pd.read_csv(io.StringIO(topics_tokens_str), sep=';', index_col=0) network = ttn_gui.create_network(topics_tokens) assert network is not None source_network_data = ttn_gui.to_dict(topics_tokens=topics_tokens) w = ipycytoscape.CytoscapeWidget(cytoscape_layout={'name': 'euler'}) w.graph.add_graph_from_json(source_network_data)
def create_network3( topics_tokens: pd.DataFrame) -> ipycytoscape.CytoscapeWidget: source_network_data = to_dict(topics_tokens=topics_tokens) w = ipycytoscape.CytoscapeWidget( layout={'height': '800px'}, pixelRatio=1.0, ) w.min_zoom = 0.2 w.max_zoom = 1.5 w.graph.add_graph_from_json(source_network_data) return w
def _draw(self, subgraph, layout_kwargs): """Private: create the cytoscape widget from a subgraph.""" if subgraph.number_of_nodes() >= 100: warnings.warn('graphs with > 100 nodes may be slow to render') embed_node_mol_images(subgraph) layout = {} layout.update(DEFAULT_LAYOUT) if layout_kwargs: layout.update(layout_kwargs) widget = cy.CytoscapeWidget() widget.set_style(self._style) widget.set_layout(**layout) widget.graph.add_graph_from_networkx(subgraph, directed=True) return widget
def render(self, layout_name, graph_style, rank_dir): cytoscapeobj = ipycytoscape.CytoscapeWidget() cytoscapeobj.set_style(graph_style) cytoscapeobj.graph.add_graph_from_networkx(self.graph_model.G) cytoscapeobj.set_layout(name=layout_name, nodeSpacing=10, edgeLenghVal=10, rankDir=rank_dir) # klay, dagre, cola cytoscapeobj.set_tooltip_source('label') return cytoscapeobj
def draw_graph(self, method="nx"): df = pd.DataFrame(self.list_of_rules, columns=["source", "target", "conf"]) G = nx.from_pandas_edgelist( df, source="source", target="target", edge_attr="conf", create_using=nx.DiGraph, ) if method == "nx": nx.draw_networkx(G) plt.axis("off") plt.savefig("rule_mining.png") if method == "ipycytoscape": # for jupyter notebooks import ipycytoscape directed = ipycytoscape.CytoscapeWidget() directed.graph.add_graph_from_networkx(G, directed=True) directed.set_style( [ { "selector": "node", "css": { "content": "data(id)", "text-valign": "center", "color": "white", "text-outline-width": 2, "text-outline-color": "blue", "text-wrap": "wrap", "text-max-width": "10px", "text-overflow-wrap": "whitespace", "background-color": "blue", }, }, { "selector": "edge", "css": { "mid-target-arrow-shape": "triangle", "mid-target-arrow-fill": "filled", "arrow-scale": 2, }, }, ] ) directed.set_layout(name="cose", nodeOverlap=40, idealEdgeLength=60) return directed
def create_network(co_occurrences: pd.DataFrame, category_column_name: str) -> ipycytoscape.CytoscapeWidget: unique_tokens = co_occurrences['token'].unique().tolist() unique_categories = co_occurrences[category_column_name].unique().tolist() token_nodes = [ ipycytoscape.Node( data={ "id": token, "label": token, "node_type": "token", "token_id": token, } ) for token in unique_tokens ] category_nodes = [ ipycytoscape.Node( data={ "id": str(category), "label": str(category), "node_type": "category", "category_id": str(category), } ) for category in unique_categories ] edges = [ ipycytoscape.Edge( data={ "id": f"{edge[category_column_name]}_{edge['token']}", "source": str(edge[category_column_name]), "target": edge['token'], "weight": 10.0 * edge['count'], "category_id": str(edge[category_column_name]), } ) for edge in co_occurrences[[category_column_name, 'token', 'count']].to_dict('records') ] w = ipycytoscape.CytoscapeWidget( layout={'height': '800px'}, pixelRatio=1.0, ) w.graph.add_nodes(category_nodes) w.graph.add_nodes(token_nodes) w.graph.add_edges(edges) return w
def create_network( topics_tokens: pd.DataFrame) -> ipycytoscape.CytoscapeWidget: unique_topics = topics_tokens.groupby( ['topic', 'topic_id']).size().reset_index()[['topic', 'topic_id']] unique_tokens = topics_tokens.groupby('token')['topic_id'].apply(list) topic_nodes = [ ipycytoscape.Node( data={ "id": node['topic'], "label": node['topic'], "node_type": "topic", "topic_id": str(node['topic_id']), }) for node in unique_topics.to_dict('records') ] token_nodes = [ ipycytoscape.Node( data={ "id": w, "label": w, "node_type": "token", "topic_id": str(unique_tokens[w][0]) if len(unique_tokens[w]) == 1 else "", }) for w in unique_tokens.index ] edges = [ ipycytoscape.Edge( data={ "id": f"{edge['topic_id']}_{edge['token']}", "source": edge['topic'], "target": edge['token'], "weight": 10.0 * edge['weight'], "topic_id": str(edge['topic_id']), }) for edge in topics_tokens[ ['topic', 'token', 'topic_id', 'weight']].to_dict('records') ] w = ipycytoscape.CytoscapeWidget( layout={'height': '800px'}, pixelRatio=1.0, ) w.graph.add_nodes(topic_nodes) w.graph.add_nodes(token_nodes) w.graph.add_edges(edges) return w
def cytoscapegraph(graph, onto=None, infobox=None, style=None): """Returns and instance of icytoscape-figure for an instance Graph of OntoGraph, the accomanying ontology is required for mouse actions""" from ipywidgets import Output, VBox, GridspecLayout from IPython.display import display, Image from pathlib import Path import networkx as nx import pydotplus import ipycytoscape from networkx.readwrite.json_graph import cytoscape_data # Define the styles, this has to be aligned with the graphviz values dotplus = pydotplus.graph_from_dot_data(graph.dot.source) # if graph doesn't have multiedges, use dotplus.set_strict(true) G = nx.nx_pydot.from_pydot(dotplus) colours, styles, fill = cytoscape_style() data = cytoscape_data(G)['elements'] for d in data['edges']: d['data']['label'] = d['data']['label'].rsplit(' ', 1)[0].lstrip('"') lab = d['data']['label'].replace('Inverse(', '').rstrip(')') try: d['data']['colour'] = colours[lab] except KeyError: d['data']['colour'] = 'black' try: d['data']['style'] = styles[lab] except KeyError: d['data']['style'] = 'solid' if d['data']['label'].startswith('Inverse('): d['data']['targetarrow'] = 'diamond' d['data']['sourcearrow'] = 'none' else: d['data']['targetarrow'] = 'triangle' d['data']['sourcearrow'] = 'none' try: d['data']['fill'] = fill[lab] except KeyError: d['data']['fill'] = 'filled' cytofig = ipycytoscape.CytoscapeWidget() cytofig.graph.add_graph_from_json(data, directed=True) cytofig.set_style([ { 'selector': 'node', 'css': { 'content': 'data(label)', # 'text-valign': 'center', # 'color': 'white', # 'text-outline-width': 2, # 'text-outline-color': 'red', 'background-color': 'blue' }, }, { 'selector': 'node:parent', 'css': { 'background-opacity': 0.333 } }, { 'selector': 'edge', 'style': { 'width': 2, 'line-color': 'data(colour)', # 'content': 'data(label)', 'line-style': 'data(style)' } }, { 'selector': 'edge.directed', 'style': { 'curve-style': 'bezier', 'target-arrow-shape': 'data(targetarrow)', 'target-arrow-color': 'data(colour)', 'target-arrow-fill': 'data(fill)', 'mid-source-arrow-shape': 'data(sourcearrow)', 'mid-source-arrow-color': 'data(colour)' }, }, { 'selector': 'edge.multiple_edges', 'style': { 'curve-style': 'bezier' } }, { 'selector': ':selected', 'css': { 'background-color': 'black', 'line-color': 'black', 'target-arrow-color': 'black', 'source-arrow-color': 'black', 'text-outline-color': 'black' }, }, ]) if onto is not None: out = Output(layout={'border': '1px solid black'}) def log_clicks(node): with out: print((onto.get_by_label(node["data"]["label"]))) p = onto.get_by_label(node["data"]["label"]).get_parents() print(f'parents: {p}') try: elucidation = onto.get_by_label( node["data"]["label"]).elucidation print(f'elucidation: {elucidation[0]}') except (AttributeError, IndexError): pass try: annotations = onto.get_by_label( node["data"]["label"]).annotations for e in annotations: print(f'annotation: {e}') except AttributeError: pass # Try does not work... try: iri = onto.get_by_label(node["data"]["label"]).iri print(f'iri: {iri}') except Exception: pass try: fig = node["data"]["label"] if os.path.exists(Path(fig + '.png')): display(Image(fig + '.png', width=100)) elif os.path.exists(Path(fig + '.jpg')): display(Image(fig + '.jpg', width=100)) except Exception: # FIXME: make this more specific pass out.clear_output(wait=True) def log_mouseovers(node): with out: print(onto.get_by_label(node["data"]["label"])) # print(f'mouseover: {pformat(node)}') out.clear_output(wait=True) cytofig.on('node', 'click', log_clicks) cytofig.on('node', 'mouseover', log_mouseovers) # , remove=True) cytofig.on('node', 'mouseout', out.clear_output(wait=True)) grid = GridspecLayout(1, 3, height='400px') if infobox == 'left': grid[0, 0] = out grid[0, 1:] = cytofig elif infobox == 'right': grid[0, 0:-1] = cytofig grid[0, 2] = out else: return VBox([cytofig, out]) return grid return cytofig
def widget_from_graph(G, node_scores=None, node_partition=None, node_palette=None, show_ids=True): """ Creates a ipycytoscape-widget from a given graph. The returned widget already contains all nodes and edges from the graph. The graph is colored using an array of norm. rgb-values based on seaborn perceptually uniform color map (rocket) or a user given custom color array. See matplotlib color maps for the correct formatting: https://matplotlib.org/api/_as_gen/matplotlib.colors.Colormap.html#matplotlib.colors.Colormap Parameters: ----------- G : networkit.graph.Graph Graph (nodes, edges), which should be visualized node_scores : list of numbers List of scores for each nodes, for example scores from a centrality measure. This is used for color-calculation of the nodes (continuous distribution). Provide either node_scores or node_partition - not both. node_partition : networkit.structures.Partition Partition object. This is used for color-calculation of the nodes (discrete distribution). Provide either node_scores or node_partition - not both. node_palette : list of tuples Array consisting of normalized rgb-values. If none is given, seaborn.color_palette.colors is used show_ids : boolean Set whether node ids should be visible in plot-widget. Is set to True by default. """ # Sanity checks if not have_cyto: raise MissingDependencyError("ipycytoscape") if node_scores is not None: if node_partition is not None: raise Exception( "Provide either node_scores or node_partition - not both.") if len(node_scores) != G.upperNodeIdBound(): raise Exception( "node_scores should include scores for every node.") # Set color palettes (maybe overwritten below) if node_palette is not None: palette = node_palette else: if not have_seaborn: raise MissingDependencyError("seaborn") palette = seaborn.color_palette("rocket_r", as_cmap=True).colors # Color calculation: score = continuous distribution, partition = discrete distribution hc_colors = [] # Partition if node_partition is not None: if node_palette is None: palette = seaborn.color_palette("hls", node_partition.numberOfSubsets()) else: if len(node_palette) < node_partition.numberOfSubsets(): raise Exception( "Number of partitions higher than number of colors in provided palette. Provide node_palette with enough colors." ) partitions = node_partition.getVector() if len(palette) < node_partition.numberOfSubsets(): raise Exception( "Number of partitions to high for default coloring. Provide node_palette with enough colors." ) for i in G.iterNodes(): hc_colors.append((palette[partitions[i]][0] * 255, palette[partitions[i]][1] * 255, palette[partitions[i]][2] * 255)) # Score elif node_scores is not None: minhc = min(node_scores) maxhc = max(node_scores) # calculate coloring of nodes def get_rgb(minimum, maximum, value): minimum, maximum, value = float(minimum), float(maximum), float( value) ratio = int( (len(palette) - 1) * (value - minimum) / (maximum - minimum) * (value - minimum) / (maximum - minimum)) r = int(palette[ratio][0] * 255) g = int(palette[ratio][1] * 255) b = int(palette[ratio][2] * 255) return r, g, b if abs(maxhc - minhc) > 0: for score in node_scores: hc_colors.append(get_rgb(minhc, maxhc, score)) else: color = palette[int((len(palette) - 1) / 2)] for i in G.iterNodes(): hc_colors.append( (color[0] * 255, color[1] * 255, color[2] * 255)) # No node values else: color = palette[0] for i in G.iterNodes(): hc_colors.append((color[0] * 255, color[1] * 255, color[2] * 255)) # Set styling if show_ids: s = [{ 'selector': 'node', 'css': { 'background-color': 'data(color)', 'content': 'data(id)' } }] else: s = [{'selector': 'node', 'css': {'background-color': 'data(color)'}}] # Create widget cytoWidget = ipycytoscape.CytoscapeWidget() nodes = [] edges = [] if G.isDirected(): edge_class = "directed " else: edge_class = "undirected " for i in G.iterNodes(): n = ipycytoscape.Node(data={"id": i, "color": hc_colors[i]}) nodes.append(n) for u, v in G.iterEdges(): e = ipycytoscape.Edge(data={ "source": u, "target": v, "classes": edge_class }) edges.append(e) # It is much faster to add edges and nodes in bulk. cytoWidget.graph.add_nodes(nodes) cytoWidget.graph.add_edges(edges, G.isDirected()) cytoWidget.set_style(s) cytoWidget.set_layout(name='cose') return cytoWidget
def _create_cyto_graph(self): return ipycytoscape.CytoscapeWidget()
# extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import ipycytoscape import ipywidgets as widgets import networkx as nx G = nx.complete_graph(5) directed = ipycytoscape.CytoscapeWidget() directed.graph.add_graph_from_networkx(G, directed=True) directed # # # Custom networkx Node Objects # # The most common choices for Nodes in networkx are numbers or strings as shown above. A node can also be any hashable object (except None) which work as well. # # + class Node: def __init__(self, name): self.name = name
def _create_cytoscape_widget(self): return cyto.CytoscapeWidget()