本文整理匯總了Python中networkx.read_gml方法的典型用法代碼示例。如果您正苦於以下問題:Python networkx.read_gml方法的具體用法?Python networkx.read_gml怎麽用?Python networkx.read_gml使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類networkx
的用法示例。
在下文中一共展示了networkx.read_gml方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: read_graph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import read_gml [as 別名]
def read_graph(self, subgraph_file=None):
if subgraph_file is None:
subraph_file = self.context_graph_file
logging.info("Writing graph.")
# write the graph out
file_format = subgraph_file.split(".")[-1]
if file_format == "graphml":
return nx.read_graphml(subgraph_file)
elif file_format == "gml":
return nx.read_gml(subgraph_file)
elif file_format == "gexf":
return nx.read_gexf(subgraph_file)
elif file_format == "net":
return nx.read_pajek(subgraph_file)
elif file_format == "yaml":
return nx.read_yaml(subgraph_file)
elif file_format == "gpickle":
return nx.read_gpickle(subgraph_file)
else:
logging.warning("File format not found, returning empty graph.")
return nx.MultiDiGraph()
示例2: test_relabel_duplicate
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import read_gml [as 別名]
def test_relabel_duplicate(self):
data = """
graph
[
label ""
directed 1
node
[
id 0
label "same"
]
node
[
id 1
label "same"
]
]
"""
fh = io.BytesIO(data.encode('UTF-8'))
fh.seek(0)
assert_raises(
nx.NetworkXError, nx.read_gml, fh, label='label')
示例3: test_relabel_duplicate
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import read_gml [as 別名]
def test_relabel_duplicate(self):
data = """
graph
[
label ""
directed 1
node
[
id 0
label "same"
]
node
[
id 1
label "same"
]
]
"""
fh = io.BytesIO(data.encode('UTF-8'))
fh.seek(0)
assert_raises(
nx.NetworkXError, nx.read_gml, fh, label='label')
示例4: main
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import read_gml [as 別名]
def main():
args = get_options()
# make sure trailing forward slash is present
args.output_dir = os.path.join(args.output_dir, "")
# Create temporary directory
temp_dir = os.path.join(tempfile.mkdtemp(dir=args.output_dir), "")
# Load isolate names
seen = set()
isolate_names = []
with open(args.output_dir + "gene_data.csv", 'r') as infile:
next(infile)
for line in infile:
iso = line.split(",")[0]
if iso not in seen:
isolate_names.append(iso)
seen.add(iso)
# Load graph
G = nx.read_gml(args.output_dir + "final_graph.gml")
#Write out core/pan-genome alignments
if args.aln == "pan":
if args.verbose: print("generating pan genome MSAs...")
generate_pan_genome_alignment(G, temp_dir, args.output_dir, args.n_cpu,
args.alr, isolate_names)
core_nodes = get_core_gene_nodes(G, args.core, len(args.input_files))
concatenate_core_genome_alignments(core_nodes, args.output_dir)
elif args.aln == "core":
if args.verbose: print("generating core genome MSAs...")
generate_core_genome_alignment(G, temp_dir, args.output_dir,
args.n_cpu, args.alr, isolate_names,
args.core, len(isolate_names))
# remove temporary directory
shutil.rmtree(temp_dir)
return
示例5: ReadGraph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import read_gml [as 別名]
def ReadGraph(graphName):
if (graphName.find("gml") >= 0):
g= nx.read_gml(graphName)
elif (graphName.find("gexf") >= 0):
g= nx.read_gexf(graphName)
elif (graphName.find("graphml") >= 0):
g=nx.read_graphml(graphName)
else:
print "ERROR, could not determine graph format " + graphName
sys.exit(0)
return g
示例6: test_read_gml
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import read_gml [as 別名]
def test_read_gml(self):
(fd, fname) = tempfile.mkstemp()
fh = open(fname, 'w')
fh.write(self.simple_data)
fh.close()
Gin = nx.read_gml(fname, label='label')
G = nx.parse_gml(self.simple_data, label='label')
assert_equals(sorted(G.nodes(data=True)), sorted(Gin.nodes(data=True)))
assert_equals(sorted(G.edges(data=True)), sorted(Gin.edges(data=True)))
os.close(fd)
os.unlink(fname)
示例7: load_graphs
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import read_gml [as 別名]
def load_graphs(graph_files, n_cpu=1):
for graph_file in graph_files:
if not os.path.isfile(graph_file):
print("Missing:", graph_file)
raise RuntimeError("Missing graph file!")
graphs = [nx.read_gml(graph_file) for graph_file in tqdm(graph_files)]
isolate_names = list(
itertools.chain.from_iterable(
[G.graph['isolateNames'] for G in graphs]))
member_count = 0
node_count = 0
id_mapping = []
for i, G in enumerate(graphs):
id_mapping.append({})
# relabel nodes to be consecutive integers from 1
mapping = {}
for n in G.nodes():
mapping[n] = node_count
node_count += 1
G = nx.relabel_nodes(G, mapping, copy=True)
# set up edge members and remove conflicts.
for e in G.edges():
G[e[0]][e[1]]['members'] = intbitset([
m + member_count for m in conv_list(G[e[0]][e[1]]['members'])
])
# set up node parameters and remove conflicts.
max_mem = -1
for n in G.nodes():
ncentroids = []
for sid in G.nodes[n]['centroid'].split(";"):
nid = update_sid(sid, member_count)
id_mapping[i][sid] = nid
if "refound" not in nid:
ncentroids.append(nid)
G.nodes[n]['centroid'] = ncentroids
new_ids = set()
for sid in conv_list(G.nodes[n]['seqIDs']):
nid = update_sid(sid, member_count)
id_mapping[i][sid] = nid
new_ids.add(nid)
G.nodes[n]['seqIDs'] = new_ids
G.nodes[n]['protein'] = del_dups(G.nodes[n]['protein'].replace(
'*', 'J').split(";"))
G.nodes[n]['dna'] = del_dups(G.nodes[n]['dna'].split(";"))
G.nodes[n]['lengths'] = conv_list(G.nodes[n]['lengths'])
G.nodes[n]['longCentroidID'][1] = update_sid(
G.nodes[n]['longCentroidID'][1], member_count)
G.nodes[n]['members'] = intbitset(
[m + member_count for m in conv_list(G.nodes[n]['members'])])
max_mem = max(max_mem, max(G.nodes[n]['members']))
member_count = max_mem + 1
graphs[i] = G
return graphs, isolate_names, id_mapping
示例8: read_gml
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import read_gml [as 別名]
def read_gml(path, label='label', destringizer=None):
"""Read graph in GML format from path.
Parameters
----------
path : filename or filehandle
The filename or filehandle to read from.
label : string, optional
If not None, the parsed nodes will be renamed according to node
attributes indicated by ``label``. Default value: ``'label'``.
destringizer : callable, optional
A destringizer that recovers values stored as strings in GML. If it
cannot convert a string to a value, a ``ValueError`` is raised. Default
value : ``None``.
Returns
-------
G : NetworkX graph
The parsed graph.
Raises
------
NetworkXError
If the input cannot be parsed.
See Also
--------
write_gml, parse_gml
Notes
-----
The GML specification says that files should be ASCII encoded, with any
extended ASCII characters (iso8859-1) appearing as HTML character entities.
References
----------
GML specification:
http://www.infosun.fim.uni-passau.de/Graphlet/GML/gml-tr.html
Examples
--------
>>> G = nx.path_graph(4)
>>> nx.write_gml(G, 'test.gml')
>>> H = nx.read_gml('test.gml')
"""
def filter_lines(lines):
for line in lines:
try:
line = line.decode('ascii')
except UnicodeDecodeError:
raise NetworkXError('input is not ASCII-encoded')
if not isinstance(line, str):
lines = str(lines)
if line and line[-1] == '\n':
line = line[:-1]
yield line
G = parse_gml_lines(filter_lines(path), label, destringizer)
return G
示例9: write_gml
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import read_gml [as 別名]
def write_gml(G, path, stringizer=None):
"""Write a graph ``G`` in GML format to the file or file handle ``path``.
Parameters
----------
G : NetworkX graph
The graph to be converted to GML.
path : filename or filehandle
The filename or filehandle to write. Files whose names end with .gz or
.bz2 will be compressed.
stringizer : callable, optional
A stringizer which converts non-int/non-float/non-dict values into
strings. If it cannot convert a value into a string, it should raise a
``ValueError`` to indicate that. Default value: ``None``.
Raises
------
NetworkXError
If ``stringizer`` cannot convert a value into a string, or the value to
convert is not a string while ``stringizer`` is ``None``.
See Also
--------
read_gml, generate_gml
Notes
-----
Graph attributes named ``'directed'``, ``'multigraph'``, ``'node'`` or
``'edge'``,node attributes named ``'id'`` or ``'label'``, edge attributes
named ``'source'`` or ``'target'`` (or ``'key'`` if ``G`` is a multigraph)
are ignored because these attribute names are used to encode the graph
structure.
Examples
--------
>>> G = nx.path_graph(4)
>>> nx.write_gml(G, "test.gml")
Filenames ending in .gz or .bz2 will be compressed.
>>> nx.write_gml(G, "test.gml.gz")
"""
for line in generate_gml(G, stringizer):
path.write((line + '\n').encode('ascii'))
# fixture for nose
示例10: write_gml
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import read_gml [as 別名]
def write_gml(G, path, stringizer=None):
"""Write a graph `G` in GML format to the file or file handle `path`.
Parameters
----------
G : NetworkX graph
The graph to be converted to GML.
path : filename or filehandle
The filename or filehandle to write. Files whose names end with .gz or
.bz2 will be compressed.
stringizer : callable, optional
A `stringizer` which converts non-int/non-float/non-dict values into
strings. If it cannot convert a value into a string, it should raise a
`ValueError` to indicate that. Default value: None.
Raises
------
NetworkXError
If `stringizer` cannot convert a value into a string, or the value to
convert is not a string while `stringizer` is None.
See Also
--------
read_gml, generate_gml, literal_stringizer
Notes
-----
Graph attributes named 'directed', 'multigraph', 'node' or
'edge', node attributes named 'id' or 'label', edge attributes
named 'source' or 'target' (or 'key' if `G` is a multigraph)
are ignored because these attribute names are used to encode the graph
structure.
GML files are stored using a 7-bit ASCII encoding with any extended
ASCII characters (iso8859-1) appearing as HTML character entities.
Without specifying a `stringizer`/`destringizer`, the code is capable of
handling `int`/`float`/`str`/`dict`/`list` data as required by the GML
specification. For other data types, you need to explicitly supply a
`stringizer`/`destringizer`.
For additional documentation on the GML file format, please see the
`GML website <http://www.infosun.fim.uni-passau.de/Graphlet/GML/gml-tr.html>`_.
See the module docstring :mod:`networkx.readwrite.gml` for additional details.
Examples
--------
>>> G = nx.path_graph(4)
>>> nx.write_gml(G, "test.gml")
Filenames ending in .gz or .bz2 will be compressed.
>>> nx.write_gml(G, "test.gml.gz")
"""
for line in generate_gml(G, stringizer):
path.write((line + '\n').encode('ascii'))
# fixture for nose