In [32]:
import networkx as nx
from decimal import *
from re import compile
In [2]:
g = nx.Graph()
In [3]:
g.add_node(1)
In [4]:
g.add_node(2)
In [5]:
g.add_edge(1,2)
In [6]:
%matplotlib inline
In [7]:
nx.draw(g)
In [8]:
g.node[1]['weight'] = str(1e6)
In [16]:
g.edge[1][2]['weight'] = Decimal(0.00000000000000001)
In [17]:
for line in nx.generate_gml(g):
print line
In [18]:
def remove_exponent(d):
'''Remove exponent and trailing zeros.
>>> remove_exponent(Decimal('5E+3'))
Decimal('5000')
'''
return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
In [22]:
g.edge[1][2]['weight'] = remove_exponent(Decimal(1e12))
In [23]:
for line in nx.generate_gml(g):
print line
In [49]:
def read_gml_and_normalize_floats(file):
"""
Read a GML file line by line, looking for scientific notation
and when found, normalize it using the Decimal library.
Then pass the lines of text to networkx parse_gml to
parse it. This is a drop-in replacement for read_gml()
"""
exp_regex = compile(r"(\d+(\.\d+)?)[Ee](\+|-)(\d+)")
input_lines = []
with open(file, 'rb') as gmlfile:
for line in gmlfile:
result = exp_regex.search(line)
if result is not None:
matched_value = result.group(0)
replacement = str(remove_exponent(Decimal(float(matched_value))))
line = line.replace(matched_value, replacement)
print "Replacing %s with %s" %( matched_value, replacement)
print line
input_lines.append(line)
return nx.parse_gml(input_lines)
In [35]:
file = '/Users/mark/seriationct/experiments/seriationct-7/seriation-results/a7eb7f58-d34e-11e4-93bf-b8f6b1154c9b-0-sampled-0.1/a7eb7f58-d34e-11e4-93bf-b8f6b1154c9b-0-sampled-0.1-minmax-by-weight.png.gml'
In [28]:
g2 = nx.read_gml(file)
In [50]:
g2 = read_gml_and_normalize_floats(file)
In [47]:
g2
Out[47]:
In [51]:
nx.draw(g2)
In [ ]: