from tulip import tlp
def generate_svg(distances, cutoff, output, alg="GEM (Frick)", fillcolors=None):
nodenumbers = range(0, len(distances))
tlp.initTulipLib(tulip_bin_dir)
tlp.loadPlugins()
# Create the network in tulip (add nodes and edges).
graph = tlp.newGraph()
graphnodes = [graph.addNode() for n in nodenumbers]
for i, j in itertools.product(nodenumbers, nodenumbers) if i > j:
if distances[i][j] <= cutoff:
graph.addEdge(graphnodes[i], graphnodes[j])
# Use tulip to do a force directed layout.
dataSet = tlp.getDefaultPluginParameters(alg, graph)
viewlayout = graph.getLayoutProperty("viewLayout")
graph.computeLayoutProperty(alg, viewlayout, dataSet)
# Generate and write svgs
svgtext = svg_from_graph(graph, fillcolors, viewlayout)
svgfile = open(output, "w")
svgfile.write(svgtext)
svgfile.close()
linetempl = '<line x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}" style="stroke:black;stroke-width:2"/>'
circltempl = '<circle cx="{cx}" cy="{cy}" r="{r}" stroke="black" stroke-width="2" fill="{fillcolor}" />'
svg_header = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">'
svg_footer = '</svg>'
display_r = 10
def svg_from_graph(graph, fillcolors, viewlayout):
svgoutput = []
svgoutput.append(svg_header)
nodes = list(graph.getNodes())
for node in nodes:
cx, cy = viewlayout[node]
for node2 in graph.getOutNodes(node):
x2, y2 = viewlayout[node2]
svgoutput.append(linetempl.format(x1=cx, y1=cy, x2=x2, y2=y2))
if fillcolors is None:
fillcolors = [default_fillcolor,] * len(nodes)
for fillcolor, node in zip(fillcolors, nodes):
cx, cy = viewlayout[node]
svgoutput.append(circltempl.format(cx=cx, cy=cy, r=display_r, fillcolor=fillcolor))
svgoutput.append(svg_footer)
svgtext = '\n'.join(svgoutput)
return svgtext