Python networkx.read_gml() Examples

The following are 13 code examples of networkx.read_gml(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module networkx , or try the search function .
Example #1
Source File: test_gml.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
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') 
Example #2
Source File: test_gml.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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') 
Example #3
Source File: test_gml.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
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') 
Example #4
Source File: networkx.py    From Verum with Apache License 2.0 5 votes vote down vote up
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() 
Example #5
Source File: post_run_alignment_gen.py    From panaroo with MIT License 5 votes vote down vote up
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 
Example #6
Source File: ABPUtils.py    From SDA with MIT License 5 votes vote down vote up
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 
Example #7
Source File: test_gml.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #8
Source File: test_gml.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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) 
Example #9
Source File: test_gml.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
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) 
Example #10
Source File: merge_graphs.py    From panaroo with MIT License 4 votes vote down vote up
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 
Example #11
Source File: gml.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 4 votes vote down vote up
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 
Example #12
Source File: gml.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 4 votes vote down vote up
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 
Example #13
Source File: gml.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
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