本文整理汇总了Python中networkx.generate_gml函数的典型用法代码示例。如果您正苦于以下问题:Python generate_gml函数的具体用法?Python generate_gml怎么用?Python generate_gml使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了generate_gml函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_data_types
def test_data_types(self):
data = [True, False, 10 ** 20, -2e33, "'", '"&&&""',
[{(b'\xfd',): '\x7f', unichr(0x4444): (1, 2)}, (2, "3")]]
try:
data.append(unichr(0x14444)) # fails under IronPython
except ValueError:
data.append(unichr(0x1444))
try:
data.append(literal_eval('{2.3j, 1 - 2.3j, ()}')) # fails under Python 2.7
except ValueError:
data.append([2.3j, 1 - 2.3j, ()])
G = nx.Graph()
G.name = data
G.graph['data'] = data
G.add_node(0, int=-1, data=dict(data=data))
G.add_edge(0, 0, float=-2.5, data=data)
gml = '\n'.join(nx.generate_gml(G, stringizer=literal_stringizer))
G = nx.parse_gml(gml, destringizer=literal_destringizer)
assert_equal(data, G.name)
assert_equal({'name': data, unicode('data'): data}, G.graph)
assert_equal(list(G.nodes(data=True)),
[(0, dict(int=-1, data=dict(data=data)))])
assert_equal(list(G.edges(data=True)), [(0, 0, dict(float=-2.5, data=data))])
G = nx.Graph()
G.graph['data'] = 'frozenset([1, 2, 3])'
G = nx.parse_gml(nx.generate_gml(G), destringizer=literal_eval)
assert_equal(G.graph['data'], 'frozenset([1, 2, 3])')
示例2: ato_write_gml
def ato_write_gml(graph, fileName, labelGraphics):
def writeDict(gml, key, label, contents, space, labelGraphics=None):
gml.write('{1}{0} [\n'.format(key, space))
for subKey in contents:
if type(contents[subKey]) in [str]:
gml.write('{2}\t{0} "{1}"\n'.format(subKey, contents[subKey], space))
elif type(contents[subKey]) in [int]:
gml.write('{2}\t{0} {1}\n'.format(subKey, contents[subKey], space))
elif type(contents[subKey]) in [dict]:
writeDict(gml, subKey, subKey, contents[subKey], space + '\t')
if labelGraphics and label in labelGraphics:
for labelInstance in labelGraphics[label]:
writeDict(gml, 'LabelGraphics', 'LabelGraphics', labelInstance, space + '\t')
gml.write('{0}]\n'.format(space))
gml = StringIO.StringIO()
gml.write('graph [\n')
gml.write('\tdirected 1\n')
for node in graph.node:
writeDict(gml, 'node', node, graph.node[node], '\t', labelGraphics)
flag = False
for x in nx.generate_gml(graph):
if 'edge' in x and not flag:
flag = True
if flag:
gml.write(x + '\n')
#gml.write(']\n')
with open(fileName, 'w') as f:
f.write(gml.getvalue())
nx.read_gml(fileName)
示例3: test_graph_types
def test_graph_types(self):
for directed in [None, False, True]:
for multigraph in [None, False, True]:
gml = 'graph ['
if directed is not None:
gml += ' directed ' + str(int(directed))
if multigraph is not None:
gml += ' multigraph ' + str(int(multigraph))
gml += ' node [ id 0 label "0" ]'
gml += ' edge [ source 0 target 0 ]'
gml += ' ]'
G = nx.parse_gml(gml)
assert_equal(bool(directed), G.is_directed())
assert_equal(bool(multigraph), G.is_multigraph())
gml = 'graph [\n'
if directed is True:
gml += ' directed 1\n'
if multigraph is True:
gml += ' multigraph 1\n'
gml += """ node [
id 0
label "0"
]
edge [
source 0
target 0
"""
if multigraph:
gml += ' key 0\n'
gml += ' ]\n]'
assert_equal(gml, '\n'.join(nx.generate_gml(G)))
示例4: generateGraph
def generateGraph(self, ticket, bnglContents, graphtype):
print ticket
pointer = tempfile.mkstemp(suffix='.bngl', text=True)
with open(pointer[1], 'w') as f:
f.write(bnglContents)
try:
if graphtype in ['regulatory', 'contactmap']:
consoleCommands.setBngExecutable(bngDistro)
consoleCommands.generateGraph(pointer[1], graphtype)
name = pointer[1].split('.')[0].split('/')[-1]
with open('{0}_{1}.gml'.format(name, graphtype), 'r') as f:
graphContent = f.read()
gml = networkx.read_gml('{0}_{1}.gml'.format(name, graphtype))
result = gml2cyjson(gml, graphtype=graphtype)
jsonStr = json.dumps(result, indent=1, separators=(',', ': '))
result = {'jsonStr': jsonStr, 'gmlStr': graphContent}
self.addToDict(ticket, result)
os.remove('{0}_{1}.gml'.format(name, graphtype))
print 'success', ticket
elif graphtype in ['sbgn_er']:
consoleCommands.setBngExecutable(bngDistro)
consoleCommands.generateGraph(pointer[1], 'contactmap')
name = pointer[1].split('.')[0].split('/')[-1]
# with open('{0}_{1}.gml'.format(name,'contactmap'),'r') as f:
# graphContent = f.read()
graphContent = networkx.read_gml(
'{0}_{1}.gml'.format(name, 'contactmap'))
sbgn = libsbgn.createSBNG_ER_gml(graphContent)
self.addToDict(ticket, sbgn)
os.remove('{0}_{1}.gml'.format(name, 'contactmap'))
print 'success', ticket
elif graphtype in ['std']:
consoleCommands.setBngExecutable(bngDistro)
consoleCommands.bngl2xml(pointer[1])
xmlFileName = pointer[1].split('.')[0] + '.xml'
xmlFileName = xmlFileName.split(os.sep)[-1]
graph = stdgraph.generateSTDGML(xmlFileName)
gmlGraph = networkx.generate_gml(graph)
#os.remove('{0}.gml'.format(xmlFileName))
result = gml2cyjson(graph, graphtype=graphtype)
jsonStr = json.dumps(result, indent=1, separators=(',', ': '))
result = {'jsonStr': jsonStr, 'gmlStr': ''.join(gmlGraph)}
#self.addToDict(ticket, ''.join(gmlGraph))
self.addToDict(ticket, result)
print 'success', ticket
except:
import traceback
traceback.print_exc()
self.addToDict(ticket,-5)
print 'failure',ticket
finally:
task.deferLater(reactor, 600, freeQueue, ticket)
示例5: main
def main():
if len(sys.argv) != 3:
sys.stderr.write('Usage: %s /path/to/flavornet.txt output.gml\n'.format(sys.argv[0]))
sys.exit(1)
ingredient2compounds, compound2ingredients = load_data(sys.argv[1])
graph = generate_graph(ingredient2compounds, compound2ingredients)
with open(sys.argv[2], 'w') as f:
for line in nx.generate_gml(graph):
f.write('{}\n'.format(line))
示例6: test_escape_unescape
def test_escape_unescape(self):
gml = """graph [
name "&"䑄��&unknown;"
]"""
G = nx.parse_gml(gml)
assert_equal(
'&"\x0f' + unichr(0x4444) + '��&unknown;',
G.name)
gml = '\n'.join(nx.generate_gml(G))
assert_equal("""graph [
name "&"䑄��&unknown;"
]""", gml)
示例7: test_labels_are_strings
def test_labels_are_strings(self):
# GML requires labels to be strings (i.e., in quotes)
answer = """graph [
node [
id 0
label "1203"
]
]"""
G = nx.Graph()
G.add_node(1203)
data = '\n'.join(nx.generate_gml(G, stringizer=literal_stringizer))
assert_equal(data, answer)
示例8: exportToGML
def exportToGML(n, e) :
G=nx.Graph()
#for node in n :
#G.add_node(node[0], frequency=node[1])
G.add_nodes_from(n)
G.add_edges_from(e)
print len(G.edges())
graph = nx.generate_gml(G)
print graph
nx.write_gml(G, dir + output)
示例9: set_graph_digest
def set_graph_digest(self):
"""
Hashes graph structure with ornamentation
:return:
"""
g_gml = nx.generate_gml(self.graph)
#g_string = self.get_gml_str()
g_string = self.get_graph_str()
#g_string = 'twas brillig'
self.g_string = g_string
g_hash = self.hash_method(g_string)
self.g_hash = g_hash # Move these onto nodes attributes?
self.g_digest = g_hash.hexdigest() # Move these node attributes?
return g_hash.hexdigest()
示例10: download_cmtys
def download_cmtys(request, ds, did, cd, cdname, layer, format):
fname_requested = format
format = format.rsplit('.')[-1]
fname = '%s-%s%s.%s'%(os.path.basename(ds.netfile.name), cdname, layer, format)
if fname_requested != fname:
return redirect(download_cmtys, did=did, cdname=cdname, layer=layer,
format=fname)
cmtys = cd.get_results()[layer]
data = [ ]
content_type = 'text/plain'
force_download = False
if format == 'txt':
for cname, cnodes in cmtys.iteritems():
data.append(' '.join(str(x) for x in cnodes))
data = '\n'.join(data)
elif format == 'nc':
for cname, cnodes in cmtys.iteritems():
for node in cnodes:
data.append('%s %s'%(node, cname))
data = '\n'.join(data)
elif format == 'gexf':
g = ds.get_networkx()
for node, cs in cmtys.nodecmtys().iteritems():
g.node[node]['cmty'] = ' '.join(str(x) for x in cs)
data = nx.generate_gexf(g)
data = '\n'.join(data)
elif format == 'gml':
g = ds.get_networkx()
for node, cs in cmtys.nodecmtys().iteritems():
g.node[node]['cmty'] = ','.join(str(x) for x in cs)
data = nx.generate_gml(g)
data = '\n'.join(data)
response = HttpResponse(content=data, content_type=content_type, )
# If the data size is too big, force a download instead of viewing as text.
if force_download or len(data) > 50 * 2**10:
response['Content-Disposition'] = 'attachment; filename=%s'%fname
return response
示例11: test_tuplelabels
def test_tuplelabels(self):
# https://github.com/networkx/networkx/pull/1048
# Writing tuple labels to GML failed.
G = nx.OrderedGraph()
G.add_edge((0, 1), (1, 0))
data = '\n'.join(nx.generate_gml(G, stringizer=literal_stringizer))
answer = """graph [
node [
id 0
label "(0,1)"
]
node [
id 1
label "(1,0)"
]
edge [
source 0
target 1
]
]"""
assert_equal(data, answer)
示例12: test_bool
def test_bool(self):
G=networkx.Graph()
G.add_node(1,on=True)
G.add_edge(1,2,on=False)
data = '\n'.join(list(networkx.generate_gml(G)))
answer ="""graph [
node [
id 0
label "1"
on 1
]
node [
id 1
label "2"
]
edge [
source 0
target 1
on 0
]
]"""
assert_equal(data,answer)
示例13: getWholeGraph
def getWholeGraph():
str1 = ''.join(nx.generate_gml(G))
return str1
示例14: save
def save(self, graph):
with self.fname.open('w') as fp:
fp.write('\n'.join(html.unescape(line) for line in nx.generate_gml(graph)))
return self.fname
示例15: normalize
pass
else:
g.add_node(target, **gml.vs[edge.target].attributes())
g.add_edge(source,target,**edge.attributes())
def normalize(freqA, freqB, weight):
"""
Normalize edge weights following Dellert's proposal.
"""
return weight ** 2 / (freqA + freqB - weight)
for nA, nB, data in list(g.edges(data=True)):
w = data['families']
fA = occs[g.node[nA]['key']]
fB = occs[g.node[nB]['key']]
nw = normalize(fA, fB, w)
if nw > 0:
data['normalized_weight'] = nw * 100
else:
g.remove_edge(nA, nB)
with open('output/clics_b.gml', 'w') as f:
for line in nx.generate_gml(g):
f.write(line+'\n')
#nx.write_gml(g, 'output/clics_b.gml')