Exemple #1
0
def write_gml(G, path):
    """
    Write the graph G in GML format to the file or file handle path.

    Parameters
    ----------
    path : filename or filehandle
       The filename or filehandle to write.  Filenames ending in
       .gz or .gz2 will be compressed.

    See Also
    --------
    read_gml, parse_gml

    Notes
    -----
    GML specifications indicate that the file should only use
    7bit ASCII text encoding.iso8859-1 (latin-1). 

    For nested attributes for graphs, nodes, and edges you should
    use dicts for the value of the attribute.  

    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")
    """
    fh=_get_fh(path,mode='wb')
    for line in generate_gml(G):
        line+='\n'
        fh.write(line.encode('latin-1'))
Exemple #2
0
def read_gpickle(path):
    """Read graph object in Python pickle format.

    Pickles are a serialized byte stream of a Python object [1]_.
    This format will preserve Python objects used as nodes or edges.

    Parameters
    ----------
    path : file or string
       File or filename to write. 
       Filenames ending in .gz or .bz2 will be uncompressed.

    Returns
    -------
    G : graph
       A NetworkX graph

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_gpickle(G,"test.gpickle")
    >>> G=nx.read_gpickle("test.gpickle")

    References
    ----------
    .. [1] http://docs.python.org/library/pickle.html
    """
    fh=_get_fh(path,'rb')
    return pickle.load(fh)
Exemple #3
0
def read_pajek(path,encoding='UTF-8'):
    """Read graph in Pajek format from path. 

    Parameters
    ----------
    path : file or string
       File or filename to write.  
       Filenames ending in .gz or .bz2 will be uncompressed.

    Returns
    -------
    G : NetworkX MultiGraph or MultiDiGraph.

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_pajek(G, "test.net")
    >>> G=nx.read_pajek("test.net")

    To create a Graph instead of a MultiGraph use

    >>> G1=nx.Graph(G)

    References
    ----------
    See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
    for format information.
    """
    fh=_get_fh(path, 'rb')
    lines = (line.decode(encoding) for line in fh)
    return parse_pajek(lines)
Exemple #4
0
def write_graphml(G, path, encoding='utf-8'):
    """Write G in GraphML XML format to path

    Parameters
    ----------
    G : graph
       A networkx graph
    path : file or string
       File or filename to write.  
       Filenames ending in .gz or .bz2 will be compressed.

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_graphml(G, "test.graphml")

    Notes
    -----
    This implementation does not support mixed graphs (directed and unidirected 
    edges together) hyperedges, nested graphs, or ports. 
    """
    fh = _get_fh(path, mode='wb')
    writer = GraphMLWriter(encoding=encoding)
    writer.add_graph_element(G)
    writer.dump(fh)
Exemple #5
0
def read_graphml(path,node_type=str):
    """Read graph in GraphML format from path.

    Parameters
    ----------
    path : file or string
       File or filename to write.  
       Filenames ending in .gz or .bz2 will be compressed.

    Returns
    -------
    graph: NetworkX graph
        If no parallel edges are found a Graph or DiGraph is returned.
        Otherwise a MultiGraph or MultiDiGraph is returned.

    Notes
    -----
    This implementation does not support mixed graphs (directed and unidirected 
    edges together), hypergraphs, nested graphs, or ports. 
    

    """
    fh=_get_fh(path,mode='rb')
    reader = GraphMLReader(node_type=node_type)
    # need to check for multiple graphs
    glist=list(reader(fh))
    return glist[0]
Exemple #6
0
def write_d3_js(G, path, group=None, encoding="utf-8"):
	"""Writes a NetworkX graph in D3.js JSON graph format to disk.
	
	Parameters
	----------
	G : graph
		a NetworkX graph
	path : file or string
       File or filename to write. If a file is provided, it must be
       opened in 'wb' mode. Filenames ending in .gz or .bz2 will be compressed.
	group : string, optional
		The name 'group' key for each node in the graph. This is used to 
		assign nodes to exclusive partitions, and for node coloring if visualizing.
	encoding: string, optional
       Specify which encoding to use when writing file.
		
	Examples
	--------
	>>> from networkx.readwrite import d3_js
	>>> G = nx.path_graph(4)
	>>> G.add_nodes_from(map(lambda i: (i, {'group': i}), G.nodes()))
	>>> d3_js.write_d3_js(G, 'four_color_line.json')
	"""
	fh = _get_fh(path, 'wb')
	graph_json = d3_json(G, group)
	graph_dump = json.dumps(graph_json, indent=2)
	fh.write(graph_dump.encode(encoding))
Exemple #7
0
def read_leda(path, encoding='UTF-8'):
    """Read graph in LEDA format from path.

    Parameters
    ----------
    path : file or string
       File or filename to read.  Filenames ending in .gz or .bz2  will be 
       uncompressed.

    Returns
    -------
    G : NetworkX graph

    Examples
    --------
    G=nx.read_leda('file.leda')
 
    References
    ----------
    .. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
    """
    fh=_get_fh(path,mode='rb')        
    lines=(line.decode(encoding) for line in fh)
    G=parse_leda(lines)
    fh.close()
    return G
Exemple #8
0
def read_leda(path, encoding='UTF-8'):
    """Read graph in LEDA format from path.

    Parameters
    ----------
    path : file or string
       File or filename to read.  Filenames ending in .gz or .bz2  will be 
       uncompressed.

    Returns
    -------
    G : NetworkX graph

    Examples
    --------
    G=nx.read_leda('file.leda')
 
    References
    ----------
    .. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
    """
    fh = _get_fh(path, mode='rb')
    lines = (line.decode(encoding) for line in fh)
    G = parse_leda(lines)
    fh.close()
    return G
Exemple #9
0
def write_graphml(G, path, encoding='utf-8', prettyprint=True):
    """Write G in GraphML XML format to path

    Parameters
    ----------
    G : graph
       A networkx graph
    path : file or string
       File or filename to write.  
       Filenames ending in .gz or .bz2 will be compressed.
    encoding : string (optional)
       Encoding for text data.
    prettyprint : bool (optional)
       If True use line breaks and indenting in output XML.

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_graphml(G, "test.graphml")

    Notes
    -----
    This implementation does not support mixed graphs (directed and unidirected 
    edges together) hyperedges, nested graphs, or ports. 
    """
    fh = _get_fh(path, mode='wb')
    writer = GraphMLWriter(encoding=encoding, prettyprint=prettyprint)
    writer.add_graph_element(G)
    writer.dump(fh)
Exemple #10
0
def write_gpickle(G, path):
    """Write graph in Python pickle format.

    Pickles are a serialized byte stream of a Python object [1]_.
    This format will preserve Python objects used as nodes or edges.

    Parameters
    ----------
    G : graph
       A NetworkX graph
    path : file or string
       File or filename to write. 
       Filenames ending in .gz or .bz2 will be compressed.

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_gpickle(G,"test.gpickle")

    References
    ----------
    .. [1] http://docs.python.org/library/pickle.html
    """
    fh=_get_fh(path,mode='wb')        
    pickle.dump(G,fh,pickle.HIGHEST_PROTOCOL)
    fh.close()
Exemple #11
0
def read_dimacs(path):
	"""Read graph in DIMACS format from path.

    Parameters
    ----------
    path : string or file
       Filename or file handle to read.

    Returns
    -------
    G: NetworkX graph
        The graph corresponding to the lines in DIMACS format.

    Examples
    --------
    >>> G=nx.DiGraph()
    >>> G.add_edge('s', 'b', capacity = 2)
    >>> G.add_edge('s', 'c', capacity = 1)
    >>> G.add_edge('c', 'd', capacity = 1)
    >>> G.add_edge('d', 'a', capacity = 1)
    >>> G.add_edge('b', 'a', capacity = 2)
    >>> G.add_edge('a', 't', capacity = 2)
    >>> nx.write_dimacs(G, 's', 't', "test.dimacs" )
    >>> [G,s,t]=nx.read_dimacs("test.dimacs")

    See Also
    --------
    write_dimacs
    """
	fh = _get_fh(path, mode='r')
	lines = (line for line in fh)
	return parse_dimacs(lines)
Exemple #12
0
def write_adjlist(G, path, comments="#", delimiter=' '):
    """Write graph G in single-line adjacency-list format to path.

    See read_adjlist for file format details.

    Examples
    --------

    >>> G=nx.path_graph(4)
    >>> nx.write_adjlist(G,"test.adjlist")

    path can be a filehandle or a string with the name of the file.

    >>> fh=open("test.adjlist",'w')
    >>> nx.write_adjlist(G, fh)

    Filenames ending in .gz or .bz2 will be compressed.

    >>> nx.write_adjlist(G, "test.adjlist.gz")

    The file will use the default text encoding on your system.
    It is possible to write files in other encodings by opening
    the file with the codecs module.  See doc/examples/unicode.py
    for hints.

    >>> import codecs

    fh=codecs.open("test.adjlist",encoding='utf=8') # use utf-8 encoding
    nx.write_adjlist(G,fh)

    Does not handle edge data. 
    Use 'write_edgelist' or 'write_multiline_adjlist'
    """
    import sys
    import time
    fh=_get_fh(path,mode='w')        
    pargs=comments+" ".join(sys.argv)
    fh.write("%s\n" % (pargs))
    fh.write(comments+" GMT %s\n" % (time.asctime(time.gmtime())))
    fh.write(comments+" %s\n" % (G.name))

    def make_str(t):
        if is_string_like(t): return t
        return str(t)
    directed=G.is_directed()

    seen=set()
    for s,nbrs in G.adjacency_iter():
        fh.write(make_str(s)+delimiter)
        for t,data in nbrs.iteritems():
            if not directed and t in seen: 
                continue
            if G.is_multigraph():
                for d in data.values():
                    fh.write(make_str(t)+delimiter)
            else:
                fh.write(make_str(t)+delimiter)
        fh.write("\n")            
        if not directed: 
            seen.add(s)
Exemple #13
0
def write_yaml(G, path, encoding='UTF-8', **kwds):
    """Write graph G in YAML format to path. 

    YAML is a data serialization format designed for human readability 
    and interaction with scripting languages [1]_.

    Parameters
    ----------
    G : graph
       A NetworkX graph
    path : file or string
       File or filename to write. 
       Filenames ending in .gz or .bz2 will be compressed.
    encoding: string, optional
       Specify which encoding to use when writing file.

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_yaml(G,'test.yaml')

    References
    ----------
    .. [1] http://www.yaml.org
    """
    try:
        import yaml
    except ImportError:
        raise ImportError("write_yaml() requires PyYAML: http://pyyaml.org/")
    fh=_get_fh(path,mode='w')        
    yaml.dump(G,fh,**kwds)
    fh.close()
Exemple #14
0
def write_pajek(G, path, encoding='UTF-8'):
    """Write graph in Pajek format to path.

    Parameters
    ----------
    G : graph
       A Networkx graph
    path : file or string
       File or filename to write.  
       Filenames ending in .gz or .bz2 will be compressed.

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_pajek(G, "test.net")

    References
    ----------
    See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
    for format information.
    """
    fh=_get_fh(path, 'wb')
    for line in generate_pajek(G):
        line+='\n'
        fh.write(line.encode(encoding))
Exemple #15
0
def write_d3_js(G, path, group=None, encoding="utf-8"):
    """Writes a NetworkX graph in D3.js JSON graph format to disk.
	
	Parameters
	----------
	G : graph
		a NetworkX graph
	path : file or string
       File or filename to write. If a file is provided, it must be
       opened in 'wb' mode. Filenames ending in .gz or .bz2 will be compressed.
	group : string, optional
		The name 'group' key for each node in the graph. This is used to 
		assign nodes to exclusive partitions, and for node coloring if visualizing.
	encoding: string, optional
       Specify which encoding to use when writing file.
		
	Examples
	--------
	>>> from networkx.readwrite import d3_js
	>>> G = nx.path_graph(4)
	>>> G.add_nodes_from(map(lambda i: (i, {'group': i}), G.nodes()))
	>>> d3_js.write_d3_js(G, 'four_color_line.json')
	"""
    fh = _get_fh(path, 'wb')
    graph_json = d3_json(G, group)
    graph_dump = json.dumps(graph_json, indent=2)
    fh.write(graph_dump.encode(encoding))
Exemple #16
0
def read_graphml(path, node_type=str):
    """Read graph in GraphML format from path.

    Parameters
    ----------
    path : file or string
       File or filename to write.  
       Filenames ending in .gz or .bz2 will be compressed.

    Returns
    -------
    graph: NetworkX graph
        If no parallel edges are found a Graph or DiGraph is returned.
        Otherwise a MultiGraph or MultiDiGraph is returned.

    Notes
    -----
    This implementation does not support mixed graphs (directed and unidirected 
    edges together), hypergraphs, nested graphs, or ports. 
    
    Files with the yEd "yfiles" extension will can be read but the graphics
    information is discarded.

    yEd compressed files ("file.graphmlz" extension) can be read by renaming
    the file to "file.graphml.gz".

    """
    fh = _get_fh(path, mode='rb')
    reader = GraphMLReader(fh, node_type)
    return reader()[0]
Exemple #17
0
def read_graphml(path, node_type=str):
    """Read graph in GraphML format from path.

    Parameters
    ----------
    path : file or string
       File or filename to write.  
       Filenames ending in .gz or .bz2 will be compressed.

    Returns
    -------
    graph: NetworkX graph
        If no parallel edges are found a Graph or DiGraph is returned.
        Otherwise a MultiGraph or MultiDiGraph is returned.

    Notes
    -----
    This implementation does not support mixed graphs (directed and unidirected 
    edges together), hypergraphs, nested graphs, or ports. 
    
    Files with the yEd "yfiles" extension will can be read but the graphics
    information is discarded.

    yEd compressed files ("file.graphmlz" extension) can be read by renaming
    the file to "file.graphml.gz".

    """
    fh = _get_fh(path, mode='rb')
    reader = GraphMLReader(fh, node_type)
    return reader()[0]
Exemple #18
0
def read_pajek(path, encoding='UTF-8'):
    """Read graph in Pajek format from path. 

    Parameters
    ----------
    path : file or string
       File or filename to write.  
       Filenames ending in .gz or .bz2 will be uncompressed.

    Returns
    -------
    G : NetworkX MultiGraph or MultiDiGraph.

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_pajek(G, "test.net")
    >>> G=nx.read_pajek("test.net")

    To create a Graph instead of a MultiGraph use

    >>> G1=nx.Graph(G)

    References
    ----------
    See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
    for format information.
    """
    fh = _get_fh(path, 'rb')
    lines = (line.decode(encoding) for line in fh)
    return parse_pajek(lines)
Exemple #19
0
def write_pajek(G, path, encoding='UTF-8'):
    """Write graph in Pajek format to path.

    Parameters
    ----------
    G : graph
       A Networkx graph
    path : file or string
       File or filename to write.  
       Filenames ending in .gz or .bz2 will be compressed.

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_pajek(G, "test.net")

    References
    ----------
    See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
    for format information.
    """
    fh = _get_fh(path, 'wb')
    for line in generate_pajek(G):
        line += '\n'
        fh.write(line.encode(encoding))
Exemple #20
0
def write_graphml(G, path, encoding='utf-8',prettyprint=True):
    """Write G in GraphML XML format to path

    Parameters
    ----------
    G : graph
       A networkx graph
    path : file or string
       File or filename to write.  
       Filenames ending in .gz or .bz2 will be compressed.
    encoding : string (optional)
       Encoding for text data.
    prettyprint : bool (optional)
       If True use line breaks and indenting in output XML.

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_graphml(G, "test.graphml")

    Notes
    -----
    This implementation does not support mixed graphs (directed and unidirected 
    edges together) hyperedges, nested graphs, or ports. 
    """
    fh = _get_fh(path, mode='wb')
    writer = GraphMLWriter(encoding=encoding,prettyprint=prettyprint)
    writer.add_graph_element(G)
    writer.dump(fh)
Exemple #21
0
def read_gpickle(path):
    """Read graph object in Python pickle format.

    Pickles are a serialized byte stream of a Python object [1]_.
    This format will preserve Python objects used as nodes or edges.

    Parameters
    ----------
    path : file or string
       File or filename to write. 
       Filenames ending in .gz or .bz2 will be uncompressed.

    Returns
    -------
    G : graph
       A NetworkX graph

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_gpickle(G,"test.gpickle")
    >>> G=nx.read_gpickle("test.gpickle")

    References
    ----------
    .. [1] http://docs.python.org/library/pickle.html
    """
    fh=_get_fh(path,'rb')
    return pickle.load(fh)
Exemple #22
0
def read_pajek(path):
    """Read graph in Pajek format from path. 

    Returns a MultiGraph or MultiDiGraph.

    Parameters
    ----------
    path : file or string
       File or filename to write.  
       Filenames ending in .gz or .bz2 will be compressed.

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_pajek(G, "test.net")
    >>> G=nx.read_pajek("test.net")

    To create a Graph instead of a MultiGraph use

    >>> G1=nx.Graph(G)


    """
    fh=_get_fh(path,mode='r')        
    G=parse_pajek(fh)
    return G
Exemple #23
0
def read_dot(path):
    """Return a NetworkX MultiGraph or MultiDiGraph from a dot file on path.


    Parameters
    ----------
    path : filename or file handle

    Returns
    -------
    G : NetworkX multigraph
        A MultiGraph or MultiDiGraph.  
    
    Notes
    -----
    Use G=nx.Graph(nx.read_dot(path)) to return a Graph instead of a MultiGraph.
    """
    try:
        import pydot
    except ImportError:
        raise ImportError("read_dot() requires pydot",
                          "http://dkbza.org/pydot.html/")

    fh = _get_fh(path, 'r')
    data = fh.read()
    P = pydot.graph_from_dot_data(data)
    return from_pydot(P)
Exemple #24
0
def write_gpickle(G, path):
    """Write graph in Python pickle format.

    Pickles are a serialized byte stream of a Python object [1]_.
    This format will preserve Python objects used as nodes or edges.

    Parameters
    ----------
    G : graph
       A NetworkX graph
    path : file or string
       File or filename to write. 
       Filenames ending in .gz or .bz2 will be compressed.

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_gpickle(G,"test.gpickle")

    References
    ----------
    .. [1] http://docs.python.org/library/pickle.html
    """
    fh=_get_fh(path,mode='wb')        
    pickle.dump(G,fh,pickle.HIGHEST_PROTOCOL)
    fh.close()
Exemple #25
0
def write_yaml(G, path, encoding='UTF-8', **kwds):
    """Write graph G in YAML format to path. 

    YAML is a data serialization format designed for human readability 
    and interaction with scripting languages [1]_.

    Parameters
    ----------
    G : graph
       A NetworkX graph
    path : file or string
       File or filename to write. 
       Filenames ending in .gz or .bz2 will be compressed.
    encoding: string, optional
       Specify which encoding to use when writing file.

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_yaml(G,'test.yaml')

    References
    ----------
    .. [1] http://www.yaml.org
    """
    try:
        import yaml
    except ImportError:
        raise ImportError("write_yaml() requires PyYAML: http://pyyaml.org/")
    fh = _get_fh(path, mode='w')
    yaml.dump(G, fh, **kwds)
    fh.close()
Exemple #26
0
def read_dot(path):
    """Return a NetworkX MultiGraph or MultiDiGraph from a dot file on path.


    Parameters
    ----------
    path : filename or file handle

    Returns
    -------
    G : NetworkX multigraph
        A MultiGraph or MultiDiGraph.  
    
    Notes
    -----
    Use G=nx.Graph(nx.read_dot(path)) to return a Graph instead of a MultiGraph.
    """
    try:
        import pydot
    except ImportError:
        raise ImportError("read_dot() requires pydot",
                          "http://dkbza.org/pydot.html/")

    fh=_get_fh(path,'r')
    data=fh.read()        
    P=pydot.graph_from_dot_data(data)
    return from_pydot(P)
Exemple #27
0
def write_yaml(G, path, default_flow_style=False, **kwds):
    """Write graph G in YAML text format to path. 

    See http://www.yaml.org

    """
    fh = _get_fh(path, mode='w')
    yaml.dump(G, fh, default_flow_style=default_flow_style, **kwds)
Exemple #28
0
def read_yaml(path):
    """Read graph from YAML format from path.

    See http://www.yaml.org

    """
    fh=_get_fh(path,mode='r')        
    return yaml.load(fh)
Exemple #29
0
def read_yaml(path):
    """Read graph from YAML format from path.

    See http://www.yaml.org

    """
    fh = _get_fh(path, mode='r')
    return yaml.load(fh)
Exemple #30
0
def write_yaml(G, path, default_flow_style=False, **kwds):
    """Write graph G in YAML text format to path. 

    See http://www.yaml.org

    """
    fh=_get_fh(path,mode='w')        
    yaml.dump(G,fh,default_flow_style=default_flow_style,**kwds)
Exemple #31
0
def read_edgelist(path, comments="#", delimiter=' ', create_using=None, 
                  nodetype=None, data=True, edgetype=None, encoding='utf-8'):
    """Read a graph from a list of edges.

    Parameters
    ----------
    path : file or string
       File or filename to write. If a file is provided, it must be
       opened in 'rb' mode.
       Filenames ending in .gz or .bz2 will be uncompressed.
    comments : string, optional
       The character used to indicate the start of a comment. 
    delimiter : string, optional
       The string used to separate values.  The default is whitespace.
    create_using : Graph container, optional, 
       Use specified container to build graph.  The default is networkx.Graph,
       an undirected graph.
    nodetype : int, float, str, Python type, optional
       Convert node data from strings to specified type
    data : bool or list of (label,type) tuples
       Tuples specifying dictionary key names and types for edge data
    edgetype : int, float, str, Python type, optional OBSOLETE
       Convert edge data from strings to specified type and use as 'weight'
    encoding: string, optional
       Specify which encoding to use when reading file.

    Returns
    -------
    G : graph
       A networkx Graph or other type specified with create_using

    Examples
    --------
    >>> nx.write_edgelist(nx.path_graph(4), "test.edgelist")
    >>> G=nx.read_edgelist("test.edgelist")

    >>> fh=open("test.edgelist", 'rb')
    >>> G=nx.read_edgelist(fh)

    >>> G=nx.read_edgelist("test.edgelist", nodetype=int)
    >>> G=nx.read_edgelist("test.edgelist",create_using=nx.DiGraph())

    See parse_edgelist() for more examples of formatting.

    See Also
    --------
    parse_edgelist

    Notes
    -----
    Since nodes must be hashable, the function nodetype must return hashable
    types (e.g. int, float, str, frozenset - or tuples of those, etc.) 
    """
    fh=_get_fh(path, 'rb')
    lines = (line.decode(encoding) for line in fh)
    return parse_edgelist(lines,comments=comments, delimiter=delimiter,
                          create_using=create_using, nodetype=nodetype,
                          data=data)
Exemple #32
0
def write_pajek(G, path):
    """Write in Pajek format to path.

    Parameters
    ----------
    G : graph
       A networkx graph
    path : file or string
       File or filename to write.  
       Filenames ending in .gz or .bz2 will be compressed.

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_pajek(G, "test.net")
    """
    fh=_get_fh(path,mode='w')

    if G.name=='': 
        name="NetworkX"
    else:
        name=G.name
    fh.write("*network %s\n"%name)

    # write nodes with attributes
    fh.write("*vertices %s\n"%(G.order()))
    nodes = G.nodes()
    # make dictionary mapping nodes to integers
    nodenumber=dict(zip(nodes,range(1,len(nodes)+1))) 
    for n in nodes:
        na=G.node[n].copy()
        x=na.pop('x',0.0)
        y=na.pop('y',0.0)
        id=int(na.pop('id',nodenumber[n]))
        nodenumber[n]=id
        shape=na.pop('shape','ellipse')
        fh.write("%d \"%s\" %f %f %s "%(id,n,float(x),float(y),shape))
        for k,v in na.items():
            fh.write("%s %s "%(k,v))
        fh.write("\n")                               
        
    # write edges with attributes         
    if G.is_directed():
        fh.write("*arcs\n")
    else:
        fh.write("*edges\n")
    for u,v,edgedata in G.edges(data=True):
        d=edgedata.copy()
        value=d.pop('weight',1.0) # use 1 as default edge value
        fh.write("%d %d %f "%(nodenumber[u],nodenumber[v],float(value)))
        for k,v in d.items():
            if is_string_like(v):
                # add quotes to any values with a blank space
                if " " in v: 
                    v="\"%s\""%v
            fh.write("%s %s "%(k,v))
        fh.write("\n")                               
Exemple #33
0
def write_edgelist(G, path, comments="#", delimiter=' '):
    """Write graph as a list of edges.

    Parameters
    ----------
    G : graph
       A networkx graph
    path : file or string
       File or filename to write.  
       Filenames ending in .gz or .bz2 will be compressed.
    comments : string, optional
       The character used to indicate the start of a comment 
    delimiter : string, optional
       The string uses to separate values.  The default is whitespace.


    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_edgelist(G, "test.edgelist")

    >>> fh=open("test.edgelist",'w')
    >>> nx.write_edgelist(G,fh)

    >>> nx.write_edgelist(G, "test.edgelist.gz")

    Notes
    -----
    The file will use the default text encoding on your system.
    It is possible to write files in other encodings by opening
    the file with the codecs module.  See doc/examples/unicode.py
    for hints.

    >>> import codecs
    >>> fh=codecs.open("test.edgelist",'w',encoding='utf=8') # utf-8 encoding
    >>> nx.write_edgelist(G,fh)

    See Also
    --------
    networkx.write_edgelist


    """
    fh = _get_fh(path, mode='w')

    pargs = comments + " " + string.join(sys.argv, ' ')
    fh.write("%s\n" % (pargs))
    fh.write(comments + " GMT %s\n" % (time.asctime(time.gmtime())))
    fh.write(comments + " %s\n" % (G.name))

    def make_str(t):
        if is_string_like(t): return t
        return str(t)

    for e in G.edges(data=True):
        fh.write(delimiter.join(map(make_str, e)) + "\n")
Exemple #34
0
def write_edgelist(G, path, comments="#", delimiter=' '):
    """Write graph as a list of edges.

    Parameters
    ----------
    G : graph
       A networkx graph
    path : file or string
       File or filename to write.  
       Filenames ending in .gz or .bz2 will be compressed.
    comments : string, optional
       The character used to indicate the start of a comment 
    delimiter : string, optional
       The string uses to separate values.  The default is whitespace.


    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_edgelist(G, "test.edgelist")

    >>> fh=open("test.edgelist",'w')
    >>> nx.write_edgelist(G,fh)

    >>> nx.write_edgelist(G, "test.edgelist.gz")

    Notes
    -----
    The file will use the default text encoding on your system.
    It is possible to write files in other encodings by opening
    the file with the codecs module.  See doc/examples/unicode.py
    for hints.

    >>> import codecs
    >>> fh=codecs.open("test.edgelist",'w',encoding='utf=8') # utf-8 encoding
    >>> nx.write_edgelist(G,fh)

    See Also
    --------
    networkx.write_edgelist


    """
    fh=_get_fh(path,mode='w')

    pargs=comments+" "+string.join(sys.argv,' ')
    fh.write("%s\n" % (pargs))
    fh.write(comments+" GMT %s\n" % (time.asctime(time.gmtime())))
    fh.write(comments+" %s\n" % (G.name))

    def make_str(t):
        if is_string_like(t): return t
        return str(t)

    for e in G.edges(data=True):
        fh.write(delimiter.join(map(make_str,e))+"\n")
Exemple #35
0
def read_dot(path):
    """Return a NetworkX Graph or DiGraph from a dot file on path.

    Path can be a string or a file handle.

    """
    fh = _get_fh(path, 'r')
    data = fh.read()
    P = pydot.graph_from_dot_data(data)
    return from_pydot(P)
Exemple #36
0
def read_p2g(path):
    """Read graph in p2g format from path. Returns an XDiGraph.

    If you want a DiGraph (with no self loops allowed and no edge data)
    use D=networkx.DiGraph(read_p2g(path))

    """
    fh = _get_fh(path, mode='r')
    G = parse_p2g(fh)
    return G
Exemple #37
0
def write_dot(G, path):
    """Write NetworkX graph G to Graphviz dot format on path.

    Path can be a string or a file handle.
    """
    fh = _get_fh(path, 'w')
    P = to_pydot(G)
    fh.write(P.to_string())
    fh.flush()  # might be a user filehandle so leave open (but flush)
    return
Exemple #38
0
def read_p2g(path):
    """Read graph in p2g format from path. Returns an XDiGraph.

    If you want a DiGraph (with no self loops allowed and no edge data)
    use D=networkx.DiGraph(read_p2g(path))

    """
    fh=_get_fh(path,mode='r')        
    G=parse_p2g(fh)
    return G
Exemple #39
0
def write_dot(G,path):
    """Write NetworkX graph G to Graphviz dot format on path.

    Path can be a string or a file handle.
    """
    fh=_get_fh(path,'w')
    P=to_pydot(G)
    fh.write(P.to_string())
    fh.flush() # might be a user filehandle so leave open (but flush)
    return
Exemple #40
0
def read_dot(path):
    """Return a NetworkX Graph or DiGraph from a dot file on path.

    Path can be a string or a file handle.

    """
    fh=_get_fh(path,'r')
    data=fh.read()        
    P=pydot.graph_from_dot_data(data)
    return from_pydot(P)
def read_sparse6_list(path):
    """Read simple undirected graphs in sparse6 format from path.
    Returns a list of Graphs, one for each line in file."""
    fh=_get_fh(path,mode='r')        
    glist=[]
    for line in fh:
        line = line.strip()
        if not len(line): continue
        glist.append(parse_sparse6(line))
    return glist
Exemple #42
0
def read_sparse6_list(path):
    """Read simple undirected graphs in sparse6 format from path.
    Returns a list of Graphs, one for each line in file."""
    fh = _get_fh(path, mode='r')
    glist = []
    for line in fh:
        line = line.strip()
        if not len(line): continue
        glist.append(parse_sparse6(line))
    return glist
Exemple #43
0
def read_gml(path):
    """Read graph in GML format from path.
    Returns an Graph or DiGraph.

    This doesn't implement the complete GML specification for
    nested attributes for graphs, edges, and nodes. 

    """
    fh = _get_fh(path, mode='r')
    G = parse_gml(fh)
    return G
Exemple #44
0
def read_gml(path):
    """Read graph in GML format from path.
    Returns an Graph or DiGraph.

    This doesn't implement the complete GML specification for
    nested attributes for graphs, edges, and nodes. 

    """
    fh=_get_fh(path,mode='r')        
    G=parse_gml(fh)
    return G
def write_dot(G,path):
    
    try:
        import pydot
    except ImportError:
        raise ImportError, \
          "write_dot() requires pydot http://dkbza.org/pydot.html/"
    fh=_get_fh(path,'w')
    P=to_pydot(G)
    fh.write(P.to_string())
    fh.flush() # might be a user filehandle so leave open (but flush)
    return
Exemple #46
0
def read_graphml(path):
    """Read graph in GraphML format from path.

    Returns a Graph or DiGraph.

    Does not implement full GraphML specification.


    """
    fh = _get_fh(path, mode='r')
    G = parse_graphml(fh)
    return G
def read_dot(path):
    
    try:
        import pydot
    except ImportError:
        raise ImportError, \
          "read_dot() requires pydot http://dkbza.org/pydot.html/"

    fh=_get_fh(path,'r')
    data=fh.read()        
    P=pydot.graph_from_dot_data(data)
    return from_pydot(P)
Exemple #48
0
def read_graphml(path):
    """Read graph in GraphML format from path.

    Returns a Graph or DiGraph.

    Does not implement full GraphML specification.


    """
    fh = _get_fh(path, mode="r")
    G = parse_graphml(fh)
    return G
Exemple #49
0
def write_edgelist(G,
                   path,
                   comments="#",
                   delimiter=' ',
                   data=True,
                   encoding='utf-8'):
    """Write graph as a list of edges.

    Parameters
    ----------
    G : graph
       A NetworkX graph
    path : file or string
       File or filename to write. If a file is provided, it must be
       opened in 'wb' mode. Filenames ending in .gz or .bz2 will be compressed.
    comments : string, optional
       The character used to indicate the start of a comment 
    delimiter : string, optional
       The string used to separate values.  The default is whitespace.
    data : bool or list, optional
       If False write no edge data.
       If True write a string representation of the edge data dictionary..  
       If a list (or other iterable) is provided, write the  keys specified 
       in the list.
    encoding: string, optional
       Specify which encoding to use when writing file.

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_edgelist(G, "test.edgelist")
    >>> G=nx.path_graph(4)
    >>> fh=open("test.edgelist",'wb')
    >>> nx.write_edgelist(G, fh)
    >>> nx.write_edgelist(G, "test.edgelist.gz")
    >>> nx.write_edgelist(G, "test.edgelist.gz", data=False)

    >>> G=nx.Graph()
    >>> G.add_edge(1,2,weight=7,color='red')
    >>> nx.write_edgelist(G,'test.edgelist',data=False)
    >>> nx.write_edgelist(G,'test.edgelist',data=['color'])
    >>> nx.write_edgelist(G,'test.edgelist',data=['color','weight'])
    
    See Also
    --------
    write_edgelist()
    write_weighted_edgelist()
    """
    fh = _get_fh(path, 'wb')

    for line in generate_edgelist(G, delimiter, data):
        line += '\n'
        fh.write(line.encode(encoding))
Exemple #50
0
def write_adjlist(G, path, comments="#", delimiter=' ', encoding = 'utf-8'):
    """Write graph G in single-line adjacency-list format to path.


    Parameters
    ----------
    G : NetworkX graph
    
    path : string or file
       Filename or file handle for data output.
       Filenames ending in .gz or .bz2 will be compressed.

    comments : string, optional
       Marker for comment lines

    delimiter : string, optional
       Separator for node labels 

    encoding : string, optional
       Text encoding. 

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_adjlist(G,"test.adjlist")

    The path can be a filehandle or a string with the name of the file. If a
    filehandle is provided, it has to be opened in 'wb' mode.

    >>> fh=open("test.adjlist",'wb')
    >>> nx.write_adjlist(G, fh)

    Notes
    -----
    This format does not store graph, node, or edge data.

    See Also
    --------
    read_adjlist, generate_adjlist
    """
    import sys
    import time
    fh=_get_fh(path,mode='wb')        
    pargs=comments + " ".join(sys.argv) + '\n'
    header = (pargs
             + comments + " GMT %s\n" % (time.asctime(time.gmtime()))
             + comments + " %s\n" % (G.name))
    fh.write(header.encode(encoding))

    for line in generate_adjlist(G, delimiter):
        line+='\n'
        fh.write(line.encode(encoding))
Exemple #51
0
def write_yaml(G, path, default_flow_style=False, **kwds):
    """Write graph G in YAML text format to path. 

    See http://www.yaml.org

    """
    try:
        import yaml
    except ImportError:
        raise ImportError, \
          "write_yaml() requires PyYAML: http://pyyaml.org/ "
    fh=_get_fh(path,mode='w')        
    yaml.dump(G,fh,default_flow_style=default_flow_style,**kwds)
Exemple #52
0
def write_pajek(G, path):
    """Write NetworkX graph in pajek format to path.
    """
    fh = _get_fh(path, mode='w')

    fh.write("*network %s\n" % G.name)

    # write nodes with attributes
    fh.write("*vertices %s\n" % (G.order()))
    nodes = G.nodes()
    # make dictionary mapping nodes to integers
    nodenumber = dict(zip(nodes, range(1, len(nodes) + 1)))
    try:
        node_attr = G.node_attr
    except:
        node_attr = {}
    for n in nodes:
        na = node_attr.get(n, {})
        x = na.pop('x', 0.0)
        y = na.pop('y', 0.0)
        id = int(na.pop('id', nodenumber[n]))
        nodenumber[n] = id
        shape = na.pop('shape', 'ellipse')
        fh.write("%d \"%s\" %f %f %s " % (id, n, float(x), float(y), shape))
        for k, v in na.items():
            fh.write("%s %s " % (k, v))
        fh.write("\n")

    # write edges with attributes
    if G.is_directed():
        fh.write("*arcs\n")
    else:
        fh.write("*edges\n")
    for e in G.edges():
        if len(e) == 3:
            u, v, d = e
            if type(d) != type({}):
                if d is None:
                    d = 1.0
                d = {'value': float(d)}
        else:
            u, v = e
            d = {}
        value = d.pop('value', 1.0)  # use 1 as default edge value
        fh.write("%d %d %f " % (nodenumber[u], nodenumber[v], float(value)))
        for k, v in d.items():
            if " " in v:  # add quotes to any values with a blank space
                v = "\"%s\"" % v
            fh.write("%s %s " % (k, v))
        fh.write("\n")
    fh.close()
def write_multiline_adjlist(G,
                            path,
                            delimiter=' ',
                            comments='#',
                            encoding='utf-8'):
    """ Write the graph G in multiline adjacency list format to path

    Parameters
    ----------
    G : NetworkX graph
    
    comments : string, optional
       Marker for comment lines

    delimiter : string, optional
       Separator for node labels 

    encoding : string, optional
       Text encoding. 

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_multiline_adjlist(G,"test.adjlist")

    The path can be a file handle or a string with the name of the file. If a
    file handle is provided, it has to be opened in 'wb' mode.

    >>> fh=open("test.adjlist",'wb')
    >>> nx.write_multiline_adjlist(G,fh)

    Filenames ending in .gz or .bz2 will be compressed.

    >>> nx.write_multiline_adjlist(G,"test.adjlist.gz")

    See Also
    --------
    read_multiline_adjlist
    """
    import sys
    import time

    fh = _get_fh(path, mode='wb')
    pargs = comments + " ".join(sys.argv)
    header = ("%s\n" % (pargs) + comments + " GMT %s\n" %
              (time.asctime(time.gmtime())) + comments + " %s\n" % (G.name))
    fh.write(header.encode(encoding))

    for multiline in generate_multiline_adjlist(G, delimiter):
        multiline += '\n'
        fh.write(multiline.encode(encoding))
Exemple #54
0
def write_dot(G,path):
    """Write NetworkX graph G to Graphviz dot format on path.

    Path can be a string or a file handle.
    """
    try:
        import pydot
    except ImportError:
        raise ImportError("write_dot() requires pydot http://dkbza.org/pydot.html/")
    fh=_get_fh(path,'w')
    P=to_pydot(G)
    fh.write(P.to_string())
    fh.flush() # might be a user filehandle so leave open (but flush)
    return
Exemple #55
0
def read_yaml(path):
    """Read graph from YAML format from path.

    See http://www.yaml.org

    """
    try:
        import yaml
    except ImportError:
        raise ImportError, \
              "Import Error: not able to import yaml: http://www.yaml.org "

    fh=_get_fh(path,mode='r')        
    return yaml.load(fh)
Exemple #56
0
def read_yaml(path):
    """Read graph from YAML format from path.

    See http://www.yaml.org

    """
    try:
        import yaml
    except ImportError:
        raise ImportError, \
          "read_yaml() requires PyYAML: http://pyyaml.org/ "

    fh=_get_fh(path,mode='r')        
    return yaml.load(fh)