def test_attrs_deprecation(): G = nx.path_graph(3) # No warnings when `attrs` kwarg not used with pytest.warns(None) as record: data = cytoscape_data(G) H = cytoscape_graph(data) assert len(record) == 0 # Future warning raised with `attrs` kwarg attrs = {"name": "foo", "ident": "bar"} with pytest.warns(DeprecationWarning): data = cytoscape_data(G, attrs) with pytest.warns(DeprecationWarning): H = cytoscape_graph(data, attrs)
def main(): df = get_df() print('There are', len(df.index), 'Hoyts listed') g = df_to_graph(df) with open(CYTOSCAPE, 'w') as file: json.dump(cytoscape_data(g, attrs={'name': 'Name'}), file, indent=2)
def test_multigraph(): G = nx.MultiGraph() G.add_edge(1, 2, key="first") G.add_edge(1, 2, key="second", color="blue") H = cytoscape_graph(cytoscape_data(G)) assert nx.is_isomorphic(G, H) assert H[1][2]["second"]["color"] == "blue"
def test_multigraph(self): G = nx.MultiGraph() G.add_edge(1, 2, key='first') G.add_edge(1, 2, key='second', color='blue') H = cytoscape_graph(cytoscape_data(G)) assert nx.is_isomorphic(G, H) assert H[1][2]['second']['color'] == 'blue'
def get_cytoscape_elts(G: networkx.Graph): """ Returns the elements as required in a format for dash-cytoscape """ cjs = json_graph.cytoscape_data(G) elements = cjs['elements']['nodes'] + cjs['elements']['edges'] for elt in elements: d = elt['data'] # networkx sets the value attribute to the type passed when creating the # node. It may not be passable as json, which will create errors when serialising # as JSON. So we replace it person = d.pop('value', '') if isinstance(person, Person) and not person.healthy: d['infected'] = 'true' else: d['infected'] = 'false' d['label'] = str(person) # Do the same as above if it is an edge if d.get('source', None): d['source'] = str(d['source']) if d.get('target', None): d['target'] = str(d['target']) return elements
def test_input_data_is_not_modified_when_building_graph(): G = nx.path_graph(4) input_data = cytoscape_data(G) orig_data = copy.deepcopy(input_data) # Ensure input is unmodified by cytoscape_graph (gh-4173) cytoscape_graph(input_data) assert input_data == orig_data
def __init__(self): service = [ 'ClinicalInformatics', 'ClinApps', 'TeleHealth-Ray', 'TeleHealth-Alon', 'Clinical Services', 'Cardioogy', 'Ophthalmology', 'Anesthesiology', 'Infection Disease', 'Infection Prevention - CLC', 'Anti-Microbial Stewardship', 'LEAF', 'TH Volunteers' 'GPM office', 'Personnel Development', 'CERNER', ] link = ['../nodes/' + s + '.html' for s in service] self.G = nx.DiGraph() for n, lbl, in enumerate(service): self.G.add_node(n) self.G.node[n]['label'] = lbl self.G.node[n]['link'] = "./nodes/deck.js/boilerplate.html" for e in range(1, len(service)): self.G.add_edge(e, 0) # add edges for n, d in self.G.in_degree(): self.G.node[n]['width'] = d + 2 self.G.node[n]['height'] = d + 2 self.graph = cytoscape_data(self.G) with open('BriefGraph.json', 'w') as f: json.dump(self.graph['elements'], f, indent=4)
def networkx_to_cytoscape(graph): cy_graph = json_graph.cytoscape_data(graph) cy_nodes = cy_graph['elements']['nodes'] cy_edges = cy_graph['elements']['edges'] cy_elements = cy_nodes cy_elements.extend(cy_edges) mouseover_node = dict(graph.nodes(data=True)) return cy_elements, mouseover_node
def test_graph_attributes(): G = nx.path_graph(4) G.add_node(1, color="red") G.add_edge(1, 2, width=7) G.graph["foo"] = "bar" G.graph[1] = "one" G.add_node(3, name="node", id="123") H = cytoscape_graph(cytoscape_data(G)) assert H.graph["foo"] == "bar" assert H.nodes[1]["color"] == "red" assert H[1][2]["width"] == 7 assert H.nodes[3]["name"] == "node" assert H.nodes[3]["id"] == "123" d = json.dumps(cytoscape_data(G)) H = cytoscape_graph(json.loads(d)) assert H.graph["foo"] == "bar" assert H.graph[1] == "one" assert H.nodes[1]["color"] == "red" assert H[1][2]["width"] == 7 assert H.nodes[3]["name"] == "node" assert H.nodes[3]["id"] == "123"
def test_graph_attributes(self): G = nx.path_graph(4) G.add_node(1, color='red') G.add_edge(1, 2, width=7) G.graph['foo'] = 'bar' G.graph[1] = 'one' G.add_node(3, name="node", id="123") H = cytoscape_graph(cytoscape_data(G)) assert H.graph['foo'] == 'bar' assert H.nodes[1]['color'] == 'red' assert H[1][2]['width'] == 7 assert H.nodes[3]['name'] == 'node' assert H.nodes[3]['id'] == '123' d = json.dumps(cytoscape_data(G)) H = cytoscape_graph(json.loads(d)) assert H.graph['foo'] == 'bar' assert H.graph[1] == 'one' assert H.nodes[1]['color'] == 'red' assert H[1][2]['width'] == 7 assert H.nodes[3]['name'] == 'node' assert H.nodes[3]['id'] == '123'
def networkx_to_cytoscape(graph): cy_graph = json_graph.cytoscape_data(graph) cy_nodes = cy_graph['elements']['nodes'] cy_edges = cy_graph['elements']['edges'] cy_elements = cy_nodes cy_elements.extend(cy_edges) layout = { 'name': 'cose', 'idealEdgeLength': 100, 'nodeOverlap': '4', 'refresh': 20, 'fit': True, #'padding': 30, 'randomize': True, 'componentSpacing': 100, 'nodeRepulsion': 400000, 'edgeElasticity': 100, 'nestingFactor': 5, 'gravity': '10', 'numIter': 1000, 'initialTemp': 200, 'coolingFactor': 0.95, 'minTemp': 1.0, 'height': '1000', 'width': '1400' } stylesheet = [{ 'selector': 'node', 'style': { 'label': 'data(name)', 'width': 5, 'height': 5, 'font-size': 1, 'background-color': '#3182bd' } }, { 'selector': 'edge', 'style': { 'curve-style': 'bezier', 'width': 0.5 } }] return cy_elements, layout, stylesheet
def __init__(self): service = [ 'ClinicalInformatics', 'cardiology', 'ClinApps', 'GastroEnterology', 'GPM office' ] self.G = nx.DiGraph() for n, lbl in enumerate(service): self.G.add_node(n) self.G.node[n]['label'] = lbl self.G.node[n]['link'] = "../nodes/cardiology.html" for e in range(1, len(service)): self.G.add_edge(e, 0) # add edges for n, d in self.G.in_degree(): self.G.node[n]['width'] = d + 2 self.G.node[n]['height'] = d + 2 self.graph = cytoscape_data(self.G) with open('BriefGraph.json', 'w') as f: json.dump(self.graph['elements'], f, indent=4)
def execute(n, a, cmax): G = nx.DiGraph() for i in range(a): G.add_edge(randint(0, n), randint(0, n), capacity=randint(0, cmax)) data = json_graph.cytoscape_data(G) num_vertex = len(data["elements"]["nodes"]) num_edges = len(data["elements"]["edges"]) print("Vertices: ", num_vertex, " Arestas: ", num_edges) json_ = {} json_["nome"] = "GRAFO_ALEATORIO_" + str(num_vertex) vertices = [] for i in range(num_vertex): vertices.append(str(data["elements"]["nodes"][i]["data"]['value'])) ordered_vertices = sorted(vertices, key=lambda x: int(x)) #print(vertices) #print(ordered_vertices) #ordered_edges = sorted(vertices, key=itemgetter(0)) json_["vertices"] = ordered_vertices arestas = [] min_ = 1000000000 max_ = -10000 for i in range(num_edges): edge = [] if data["elements"]["edges"][i]["data"]['source'] < min_: min_ = data["elements"]["edges"][i]["data"]['source'] if data["elements"]["edges"][i]["data"]['target'] > max_: max_ = data["elements"]["edges"][i]["data"]['target'] edge.append(str(data["elements"]["edges"][i]["data"]['source'])) edge.append(str(data["elements"]["edges"][i]["data"]['target'])) edge.append(str(data["elements"]["edges"][i]["data"]['capacity'])) arestas.append(edge) ordered_arestas = sorted(arestas, key=lambda x: (int(x[0]), int(x[1]))) json_["arestas"] = ordered_arestas print("min vertex:", min_) print("max vertex:", max_) flow_value, flow_dict = nx.maximum_flow(G, min_, max_) print("max_flow:", flow_value) with open( 'graph_' + str(num_vertex) + "_" + str(flow_value) + "_" + str(min_) + "_" + str(max_) + '.json', 'w') as json_file: json.dump(json_, json_file)
def execute(n,p): G= nx.erdos_renyi_graph(n,p) data = json_graph.cytoscape_data(G) num_vertex = len(data["elements"]["nodes"]) num_edges = len(data["elements"]["edges"]) print("Vertices: ",num_vertex, " Arestas: ",num_edges) json_ = {} json_["nome"]="GRAFO_ALEATORIO_"+str(num_vertex) vertices=[] for i in range(num_vertex): vertices.append(str(data["elements"]["nodes"][i]["data"]['value'])) json_["vertices"]=vertices arestas=[] for i in range(num_edges): edge = [] edge.append(str(data["elements"]["edges"][i]["data"]['source'])) edge.append(str(data["elements"]["edges"][i]["data"]['target'])) arestas.append(edge) json_["arestas"]=arestas with open('graph_'+str(num_vertex)+'.json', 'w') as json_file: json.dump(json_, json_file)
def test_graph(): G = nx.path_graph(4) H = cytoscape_graph(cytoscape_data(G)) nx.is_isomorphic(G, H)
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 test_exception(): with pytest.raises(nx.NetworkXError): G = nx.MultiDiGraph() cytoscape_data(G, name="foo", ident="foo")
def test_multidigraph(): G = nx.MultiDiGraph() nx.add_path(G, [1, 2, 3]) H = cytoscape_graph(cytoscape_data(G)) assert H.is_directed() assert H.is_multigraph()
def test_digraph(): G = nx.DiGraph() nx.add_path(G, [1, 2, 3]) H = cytoscape_graph(cytoscape_data(G)) assert H.is_directed() nx.is_isomorphic(G, H)
def test_exception(self): with pytest.raises(nx.NetworkXError): G = nx.MultiDiGraph() attrs = dict(name="node", ident="node") cytoscape_data(G, attrs)
if n in idDescription: pdg.graph.nodes[n]['Description'] = idDescription[n] else: pdg.graph.nodes[n]['Description'] = '' # print(pdg.graph.nodes.data()) # Save graph in pickle format. if args.ofile is not None: logging.info("Saving pickled graph to: {0}".format(args.ofile)) pdg.save(args.ofile) # Save graph in CYJS format. if args.cyjsfile is not None: logging.info("Saving KG to CYJS file: {0}".format(args.cyjsfile)) gdata = cytoscape_data(pdg.graph) with open(args.cyjsfile, 'w') as fcyjs: json.dump(gdata, fcyjs, indent=2) # Save graph in GraphML format. if args.graphmlfile is not None: logging.info("Saving KG to GraphML file: {0}".format(args.graphmlfile)) with open(args.graphmlfile, 'w') as fgraphml: for line in generate_graphml(pdg.graph, encoding="utf-8", prettyprint=True): fgraphml.write(line + "\n") # Log node and edge info. if args.logfile is not None: edgeCount = 0