Basic Workflow 2: NetworkX and Cytoscape

by Keiichiro Ono


Introduction

Welcome to the part 2 of basic tutorial. In this example, you will learn how to use Cytoscape with NetworkX, a very poweful network analysis toolkit.

Prerequisites

System Requirments


Questions or Feature Requests?

Please send them to our mailing list


In [1]:
import requests
import json
import networkx as nx

# Basic Setup
PORT_NUMBER = 1234
BASE = 'http://localhost:' + str(PORT_NUMBER) + '/v1/'

# Header for posting data to the server as JSON
HEADERS = {'Content-Type': 'application/json'}

Generate Networks with NetworkX

Generate scale-free networks


In [6]:
graphs = []

# Create 10 small randome networks
for i in range(10):
    # Generate scale-free graph
    g = nx.scale_free_graph(50);
    
    # Perform simple graph analysis
    
    # Node statistics
    bc = nx.betweenness_centrality(g)
    degree = nx.degree(g)
    cc = nx.closeness_centrality(g)
    nx.set_node_attributes(g, 'betweenness', bc)
    nx.set_node_attributes(g, 'closeness', cc)
    nx.set_node_attributes(g, 'degree', degree)
    
    # Network statistics
    g.graph["avg_shortest_path_len"] = nx.average_shortest_path_length(g)
    g.graph["density"] = nx.density(g)
    graphs.append(g)

Send all network models to Cytoscape


In [7]:
# Remove all networks
requests.delete(BASE + 'networks')

import cytoscape.viewer as cy

for graph in graphs:
    cyjs_network = cy.from_networkx(graph)
    res1 = requests.post(BASE + 'networks', data=json.dumps(cyjs_network), headers=HEADERS)

(Now graphs are in Cytoscape. Do analysis, visualization, etc...)

Get the visualization back to this notebook.


In [9]:
response = requests.get(BASE + 'networks?format=SUID')
network_list = json.loads(response.content)
print(network_list)

network_views = []
for suid in network_list:
    response2 = requests.get(BASE + 'networks/' + str(suid) + "/views/first")
    network_views.append(json.loads(response2.content))


[64700, 66370, 66720, 64008, 66054, 64362, 65726, 65028, 67068, 65340]

In [11]:
# Visual Style can be a simple Python object!

my_style = {
  "title" : "My Style 10",
  "defaults" : [ {
    "visualProperty" : "EDGE_WIDTH",
    "value" : 11.0
  }, {
    "visualProperty" : "EDGE_STROKE_UNSELECTED_PAINT",
    "value" : "#00ddff"
  }, {
    "visualProperty" : "NODE_WIDTH",
    "value" : 20
  }, {
    "visualProperty" : "NODE_HEIGHT",
    "value" : 20
  }],
  "mappings" : [ {
    "mappingType" : "discrete",
    "mappingColumn" : "degree",
    "mappingColumnType" : "Integer",
    "visualProperty" : "NODE_FILL_COLOR",
    "map" : [ {
      "key" : "1",
      "value" : "#440055"
    }, {
      "key" : "4",
      "value" : "#00FF11"
    } ]
  }, {
    "mappingType" : "passthrough",
    "mappingColumn" : "name",
    "mappingColumnType" : "String",
    "visualProperty" : "NODE_LABEL"
  } ]
}

requests.post(BASE + "styles", data=json.dumps(my_style), headers=HEADERS)


Out[11]:
<Response [200]>