Skip to content

Instantly share code, notes, and snippets.

@kantale
Last active March 20, 2018 17:11
Show Gist options
  • Save kantale/88e45257de684b4a5128a13423a4aba4 to your computer and use it in GitHub Desktop.
Save kantale/88e45257de684b4a5128a13423a4aba4 to your computer and use it in GitHub Desktop.
cytoscape
def cytoscape_nodes(nodes):
ret = []
for n in nodes:
ret.append("{ data: { id: '%s', name: '%s' } }" % (n['id'], n['name']))
print ('NODES: {}'.format(len(ret)))
return ',\n'.join(ret) + '\n'
def cytoscape_edges(edges, remove_duplicate_edges = False):
types = {
'str' : lambda x : "'%s'" % (x),
'unicode': lambda x : "'%s'" % (x),
'int': lambda x : "%s" % (x),
'float': lambda x : "%s" % (x),
}
ret = []
# ret.append("{ data: { source: '%s', target: '%s', xyz: '%s', jaccard: %s } }")
edge_keys = {}
duplicate_edges = 0
for e in edges:
if remove_duplicate_edges:
edge_key = '$$'.join(sorted([e['source'], e['target']]))
if edge_key in edge_keys:
duplicate_edges += 1
continue
else:
edge_keys[edge_key] = None
e_data = ", ".join(["%s: %s" % (k, types[type(v).__name__](v)) for k,v in e.items()])
ret.append("{ data: { %s } }" % (e_data))
if remove_duplicate_edges:
print ('Duplicate edges: {}'.format(duplicate_edges))
print ('EDGES: {}'.format(len(ret)))
return ', \n'.join(ret) + '\n'
def cytoscape(nodes, edges, output_filename, remove_duplicate_edges=False):
'''
idealEdgeLength: function( edge ){ return 500.0 * edge.data('jaccard'); }
curve-style: bezier, haystack
.selector('node'):
'text-outline-width': 2,
'background-color': '#999',
'text-outline-color': '#999'
.selector('edge')
'target-arrow-shape': 'triangle',
'target-arrow-color': '#ccc',
nodes = [{'name': ..., 'id': '...'}]
edges = [{'source': ... 'target': ...., 'label': ...OPTIONAL...}]
'''
nodes_html = cytoscape_nodes(nodes)
edges_html = cytoscape_edges(edges, remove_duplicate_edges=remove_duplicate_edges)
labels_html = "'label': 'data(label)'," if 'label' in edges[0].keys() else ''
html = '''
<!DOCTYPE html>
<!-- This code is for demonstration purposes only. You should not hotlink to Github, Rawgit, or files from the Cytoscape.js documentation in your production apps. -->
<html>
<head>
<meta name="description" content="[An example of getting started with Cytoscape.js]" />
<style>
body {
font: 14px helvetica neue, helvetica, arial, sans-serif;
}
#cy {
height: 100%;
width: 100%;
position: absolute;
left: 0;
top: 0;
}
#info {
color: #c88;
font-size: 1em;
position: absolute;
z-index: -1;
left: 1em;
top: 1em;
}
</style>
<meta charset=utf-8 />
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui">
<title>Cytoscape.js initialisation</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.2.3/cytoscape.min.js"></script>
</head>
<body>
<div id="cy"></div>
<!-- Load appplication code at the end to ensure DOM is loaded -->
<script>
var cy = cytoscape({
container: document.querySelector('#cy'),
boxSelectionEnabled: false,
autounselectify: true,
style: cytoscape.stylesheet()
.selector('node')
.css({
'content': 'data(name)',
'text-valign': 'center',
'color': 'black'
})
.selector('edge')
.css({
'curve-style': 'haystack',
'line-color': '#000',
$$LABELS$$
'width': 1
})
.selector(':selected')
.css({
'background-color': 'black',
'line-color': 'black',
'target-arrow-color': 'black',
'source-arrow-color': 'black'
})
.selector('.faded')
.css({
'opacity': 0.25,
'text-opacity': 0
}),
elements: {
nodes: [
$$NODES$$
],
edges: [
$$EDGES$$
]
},
layout: {
name: 'cose',
nodeOverlap: 20,
refresh: 20,
fit: true,
padding: 30,
randomize: false,
componentSpacing: 100,
nodeRepulsion: 400000,
edgeElasticity: 100,
nestingFactor: 5,
gravity: 80,
numIter: 1000,
initialTemp: 200,
coolingFactor: 0.95,
minTemp: 1.0,
idealEdgeLength: 100
}
});
cy.on('tap', 'node', function(e){
var node = e.cyTarget;
var neighborhood = node.neighborhood().add(node);
cy.elements().addClass('faded');
neighborhood.removeClass('faded');
});
cy.on('tap', function(e){
if( e.cyTarget === cy ){
cy.elements().removeClass('faded');
}
});
</script>
</body>
</html>
'''.replace('$$NODES$$', nodes_html).replace('$$EDGES$$', edges_html).replace('$$LABELS$$', labels_html)
print ('Saving cytoscape to: {}'.format(output_filename))
with open(output_filename, 'w') as f:
f.write(html)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment