Пример #1
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'
    """
    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)

    directed = G.directed

    seen = {}
    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.multigraph:
                for d in data:
                    fh.write(make_str(t) + delimiter)
            else:
                fh.write(make_str(t) + delimiter)
        fh.write("\n")
        if not directed:
            seen[s] = 1
Пример #2
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'
    """
    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)
    directed=G.directed

    seen={}
    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.multigraph:
                for d in data:
                    fh.write(make_str(t)+delimiter)
            else:
                fh.write(make_str(t)+delimiter)
        fh.write("\n")            
        if not directed: 
            seen[s]=1
Пример #3
0
def write_edgelist(G, path, comments="#", delimiter=' '):
    """Write graph as a list of edges.

    Parameters
    ----------
    G : graph
       A networkx_v099 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_v099.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")
Пример #4
0
def write_edgelist(G, path, comments="#", delimiter=' '):
    """Write graph as a list of edges.

    Parameters
    ----------
    G : graph
       A networkx_v099 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_v099.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")
Пример #5
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_v099.DiGraph(read_p2g(path))

    """
    fh=_get_fh(path,mode='r')        
    G=parse_p2g(fh)
    return G
Пример #6
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_v099.DiGraph(read_p2g(path))

    """
    fh = _get_fh(path, mode='r')
    G = parse_p2g(fh)
    return G
Пример #7
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
Пример #8
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
Пример #9
0
def write_dot(G,path):
    """Write Networkx_v099 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
Пример #10
0
def read_dot(path):
    """Return a Networkx_v099 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)
Пример #11
0
def write_dot(G, path):
    """Write Networkx_v099 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
Пример #12
0
def read_dot(path):
    """Return a Networkx_v099 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)
Пример #13
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
Пример #14
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
Пример #15
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, \
              "Import Error: not able to import yaml: http://www.yaml.org "
    fh=_get_fh(path,mode='w')        
    yaml.dump(G,fh,default_flow_style=default_flow_style,**kwds)
Пример #16
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, \
              "Import Error: not able to import yaml: http://www.yaml.org "
    fh = _get_fh(path, mode='w')
    yaml.dump(G, fh, default_flow_style=default_flow_style, **kwds)
Пример #17
0
def write_pajek(G, path):
    """Write Networkx_v099 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()
Пример #18
0
def write_pajek(G, path):
    """Write Networkx_v099 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()
Пример #19
0
def read_gpickle(path):
    """
    Read graph object in Python pickle format


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

    See cPickle.
    
    """
    fh = _get_fh(path, 'rb')
    return pickle.load(fh)
Пример #20
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)
Пример #21
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)
Пример #22
0
def write_gpickle(G, path):
    """
    Write graph object in Python pickle format.

    This will preserve Python objects used as nodes or edges.

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

    See cPickle.
    
    """
    fh = _get_fh(path, mode='wb')
    pickle.dump(G, fh, pickle.HIGHEST_PROTOCOL)
Пример #23
0
def read_gpickle(path):
    """
    Read graph object in Python pickle format


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

    See cPickle.
    
    """
    fh=_get_fh(path,'rb')
    return pickle.load(fh)
Пример #24
0
def write_gpickle(G, path):
    """
    Write graph object in Python pickle format.

    This will preserve Python objects used as nodes or edges.

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

    See cPickle.
    
    """
    fh=_get_fh(path,mode='wb')        
    pickle.dump(G,fh,pickle.HIGHEST_PROTOCOL)
Пример #25
0
def write_p2g(G, path):
    """Write Networkx_v099 graph in p2g format.

    This format is meant to be used with directed graphs with
    possible self loops.
    """
    
    fh=_get_fh(path,mode='w')

    fh.write("%s\n"%G.name)
    fh.write("%s %s\n"%(G.order(),G.size()))

    nodes = G.nodes()

    # make dictionary mapping nodes to integers
    nodenumber=dict(zip(nodes,range(len(nodes)))) 

    for n in nodes:
        fh.write("%s\n"%n)
        for nbr in G.neighbors(n):
            fh.write("%s "%nodenumber[nbr])
        fh.write("\n")
    fh.close()
Пример #26
0
def write_p2g(G, path):
    """Write Networkx_v099 graph in p2g format.

    This format is meant to be used with directed graphs with
    possible self loops.
    """

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

    fh.write("%s\n" % G.name)
    fh.write("%s %s\n" % (G.order(), G.size()))

    nodes = G.nodes()

    # make dictionary mapping nodes to integers
    nodenumber = dict(zip(nodes, range(len(nodes))))

    for n in nodes:
        fh.write("%s\n" % n)
        for nbr in G.neighbors(n):
            fh.write("%s " % nodenumber[nbr])
        fh.write("\n")
    fh.close()
Пример #27
0
def read_edgelist(path,
                  comments="#",
                  delimiter=' ',
                  create_using=None,
                  nodetype=None,
                  edgetype=None):
    """Read a graph from a list of edges.

    Parameters
    ----------
    path : file or string
       File or filename to write.  
       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 uses to separate values.  The default is whitespace.
    create_using : Graph container, optional       
       Use specified Graph container to build graph.  The default is
       nx.Graph().
    nodetype : int, float, str, Python type, optional
       Convert node data from strings to specified type
    edgetype : int, float, str, Python type, optional
       Convert edge data from strings to specified type

    Returns
    ----------
    out : graph
       A networkx_v099 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")
    >>> G=nx.read_edgelist(fh)

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

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

    Notes
    -----
    Since nodes must be hashable, the function nodetype must return hashable
    types (e.g. int, float, str, frozenset - or tuples of those, etc.) 


    Example edgelist file formats

    Without edge data::

     # source target
     a b
     a c
     d e

    With edge data::: 

     # source target data
     a b 1
     a c 3.14159
     d e apple

    """
    if create_using is None:
        G = networkx_v099.Graph()
    else:
        try:
            G = create_using
            G.clear()
        except:
            raise TypeError("Input graph is not a networkx_v099 graph type")

    fh = _get_fh(path)

    for line in fh.readlines():
        line = line[:line.find(comments)].strip()
        if not len(line): continue
        #        if line.startswith("#") or line.startswith("\n"):
        #            continue
        #        line=line.strip() #remove trailing \n
        # split line, should have 2 or three items
        s = line.split(delimiter)
        if len(s) == 2:
            if nodetype is not None:
                try:
                    (u, v) = map(nodetype, s)
                except:
                    raise TypeError("Failed to convert edge %s to type %s"\
                          %(s,nodetype))
            else:
                (u, v) = s
            G.add_edge(u, v)
        elif len(s) == 3:
            (u, v, d) = s
            if nodetype is not None:
                try:
                    (u, v) = map(nodetype, (u, v))
                except:
                    raise TypeError("Failed to convert edge (%s, %s) to type %s"\
                          %(u,v,nodetype))
            if d is not None and edgetype is not None:
                try:
                    d = edgetype(d)
                except:
                    raise TypeError("Failed to convert edge data (%s) to type %s"\
                                    %(d, edgetype))
            G.add_edge(u, v, d)  # XGraph or XDiGraph
        else:
            raise TypeError("Failed to read line: %s" % line)
    return G
Пример #28
0
def write_gml(G, path):
    """
    Write the graph G in GML format to the file or file handle path.

    Examples
    ---------

    >>> G=nx.path_graph(4)
    >>> nx.write_gml(G,"test.gml")

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

    >>> fh=open("test.gml",'w')
    >>> nx.write_gml(G,fh)

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

    >>> nx.write_gml(G,"test.gml.gz")

    
    The output 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.gml",'w',encoding='iso8859-1')# use iso8859-1
    >>> nx.write_gml(G,fh)

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

    Only a single level of attributes for graphs, nodes, and edges,
    is supported.

    """
    fh=_get_fh(path,mode='w')        
#    comments="#"
#    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))

    # check for attributes or assign empty dict
    if hasattr(G,'graph_attr'):
        graph_attr=G.graph_attr
    else:
        graph_attr={}
    if hasattr(G,'node_attr'):
        node_attr=G.node_attr
    else:
        node_attr={}

    indent=2*' '
    count=iter(range(G.number_of_nodes()))
    node_id={}

    fh.write("graph [\n")
    # write graph attributes 
    for k,v in graph_attr.items():
        if is_string_like(v):
            v='"'+v+'"'
        fh.write(indent+"%s %s\n"%(k,v))
    # write nodes        
    for n in G:
        fh.write(indent+"node [\n")
        # get id or assign number
        if n in node_attr:
            nid=node_attr[n].get('id',count.next())
        else:
            nid=count.next()
        node_id[n]=nid
        fh.write(2*indent+"id %s\n"%nid)
        fh.write(2*indent+"label \"%s\"\n"%n)
        if n in node_attr:
          for k,v in node_attr[n].items():
              if is_string_like(v): v='"'+v+'"'
              if k=='id': continue
              fh.write(2*indent+"%s %s\n"%(k,v))
        fh.write(indent+"]\n")
    # write edges
    for e in G.edges_iter():
        if len(e)==3:
            u,v,d=e
            # try to guess what is on the edge and do something reasonable
            edgedata={}
            if d is None:  # no data 
                pass
            elif hasattr(d,'iteritems'): # try dict-like
                edgedata=dict(d.iteritems())
            elif hasattr(d,'__iter__'): # some kind of container
                edgedata['data']=d.__repr__()
            else: # something else - string, number
                edgedata['data']=d
        else:
            u,v=e
            edgedata={}
        fh.write(indent+"edge [\n")
        fh.write(2*indent+"source %s\n"%node_id[u])
        fh.write(2*indent+"target %s\n"%node_id[v])
        for k,v in edgedata.items():
            if k=='source': continue
            if k=='target': continue
            if is_string_like(v): v='"'+v+'"'
            fh.write(2*indent+"%s %s\n"%(k,v))
        fh.write(indent+"]\n")
    fh.write("]\n")
Пример #29
0
def read_graphml(path):
    """Read graph in GraphML format from path.
    Returns an Graph or DiGraph."""
    fh = _get_fh(path, mode='r')
    G = parse_graphml(fh)
    return G
Пример #30
0
def read_graphml(path):
    """Read graph in GraphML format from path.
    Returns an Graph or DiGraph."""
    fh=_get_fh(path,mode='r')        
    G=parse_graphml(fh)
    return G
Пример #31
0
def read_adjlist(path,
                 comments="#",
                 delimiter=' ',
                 create_using=None,
                 nodetype=None):
    """Read graph in single line adjacency list format from path.

    Examples
    --------

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

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

    >>> fh=open("test.adjlist")
    >>> G=nx.read_adjlist(fh)

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

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

    nodetype is an optional function to convert node strings to nodetype

    For example

    >>> G=nx.read_adjlist("test.adjlist", nodetype=int)

    will attempt to convert all nodes to integer type

    Since nodes must be hashable, the function nodetype must return hashable
    types (e.g. int, float, str, frozenset - or tuples of those, etc.) 

    create_using is an optional networkx_v099 graph type, the default is
    Graph(), an undirected graph. 

    >>> G=nx.read_adjlist("test.adjlist", create_using=nx.DiGraph())

    Does not handle edge data: use 'read_edgelist' or 'read_multiline_adjlist'

    The comments character (default='#') at the beginning of a
    line indicates a comment line.

    The entries are separated by delimiter (default=' ').
    If whitespace is significant in node or edge labels you should use
    some other delimiter such as a tab or other symbol.  

    Sample format::

     # source target
     a b c
     d e

    """
    if create_using is None:
        G = networkx_v099.Graph()
    else:
        try:
            G = create_using
            G.clear()
        except:
            raise TypeError("Input graph is not a networkx_v099 graph type")

    fh = _get_fh(path)

    for line in fh.readlines():
        line = line[:line.find(comments)].strip()
        if not len(line): continue
        #        if line.startswith("#") or line.startswith("\n"):
        #            continue
        #        line=line.strip() #remove trailing \n
        vlist = line.split(delimiter)
        u = vlist.pop(0)
        # convert types
        if nodetype is not None:
            try:
                u = nodetype(u)
            except:
                raise TypeError("Failed to convert node (%s) to type %s"\
                                %(u,nodetype))
        G.add_node(u)
        try:
            vlist = map(nodetype, vlist)
        except:
            raise TypeError("Failed to convert nodes (%s) to type %s"\
                            %(','.join(vlist),nodetype))
        for v in vlist:
            G.add_edge(u, v)
    return G
Пример #32
0
def read_adjlist(path, comments="#", delimiter=' ',
                 create_using=None, nodetype=None):
    """Read graph in single line adjacency list format from path.

    Examples
    --------

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

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

    >>> fh=open("test.adjlist")
    >>> G=nx.read_adjlist(fh)

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

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

    nodetype is an optional function to convert node strings to nodetype

    For example

    >>> G=nx.read_adjlist("test.adjlist", nodetype=int)

    will attempt to convert all nodes to integer type

    Since nodes must be hashable, the function nodetype must return hashable
    types (e.g. int, float, str, frozenset - or tuples of those, etc.) 

    create_using is an optional networkx_v099 graph type, the default is
    Graph(), an undirected graph. 

    >>> G=nx.read_adjlist("test.adjlist", create_using=nx.DiGraph())

    Does not handle edge data: use 'read_edgelist' or 'read_multiline_adjlist'

    The comments character (default='#') at the beginning of a
    line indicates a comment line.

    The entries are separated by delimiter (default=' ').
    If whitespace is significant in node or edge labels you should use
    some other delimiter such as a tab or other symbol.  

    Sample format::

     # source target
     a b c
     d e

    """
    if create_using is None:
        G=networkx_v099.Graph()
    else:
        try:
            G=create_using
            G.clear()
        except:
            raise TypeError("Input graph is not a networkx_v099 graph type")

    fh=_get_fh(path)        

    for line in fh.readlines():
        line = line[:line.find(comments)].strip()
        if not len(line): continue
#        if line.startswith("#") or line.startswith("\n"):
#            continue
#        line=line.strip() #remove trailing \n 
        vlist=line.split(delimiter)
        u=vlist.pop(0)
        # convert types
        if nodetype is not None:
            try:
                u=nodetype(u)
            except:
                raise TypeError("Failed to convert node (%s) to type %s"\
                                %(u,nodetype))
        G.add_node(u)
        try:
            vlist=map(nodetype,vlist)
        except:
            raise TypeError("Failed to convert nodes (%s) to type %s"\
                            %(','.join(vlist),nodetype))
        for v in vlist:
            G.add_edge(u,v)
    return G
Пример #33
0
def read_pajek(path):
    """Read graph in pajek format from path. Returns an XGraph or XDiGraph.
    """
    fh=_get_fh(path,mode='r')        
    G=parse_pajek(fh)
    return G
Пример #34
0
def write_multiline_adjlist(G, path, delimiter=' ', comments='#'):
    """
    Write the graph G in multiline adjacency list format to the file
    or file handle path.

    See read_multiline_adjlist for file format details.

    Examples
    --------

    >>> G=nx.path_graph(4)
    >>> nx.write_multiline_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_multiline_adjlist(G,fh)

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

    >>> nx.write_multiline_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",'w',encoding='utf=8') # utf-8 encoding
    >>> nx.write_multiline_adjlist(G,fh)

    """
    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)

    if G.directed:
        if G.multigraph:
            for s,nbrs in G.adjacency_iter():
                nbr_edges=[ (u,d) for u,dl in nbrs.iteritems() for d in dl]
                deg=len(nbr_edges)
                fh.write(make_str(s)+delimiter+"%i\n"%(deg))
                for u,d in nbr_edges:
                    if d is None:    
                        fh.write(make_str(u)+'\n')
                    else:   
                        fh.write(make_str(u)+delimiter+make_str(d)+"\n")
        else: # directed single edges
            for s,nbrs in G.adjacency_iter():
                deg=len(nbrs)
                fh.write(make_str(s)+delimiter+"%i\n"%(deg))
                for u,d in nbrs.iteritems():
                    if d is None:    
                        fh.write(make_str(u)+'\n')
                    else:   
                        fh.write(make_str(u)+delimiter+make_str(d)+"\n")
    else: #undirected
        if G.multigraph:
            seen={}  # helper dict used to avoid duplicate edges
            for s,nbrs in G.adjacency_iter():
                nbr_edges=[ (u,d) for u,dl in nbrs.iteritems() if u not in seen for d in dl]
                deg=len(nbr_edges)
                fh.write(make_str(s)+delimiter+"%i\n"%(deg))
                for u,d in nbr_edges:
                    if d is None:    
                        fh.write(make_str(u)+'\n')
                    else:   
                        fh.write(make_str(u)+delimiter+make_str(d)+"\n")
                seen[s]=1
        else: # undirected single edges
            seen={}  # helper dict used to avoid duplicate edges
            for s,nbrs in G.adjacency_iter():
                nbr_edges=[ (u,d) for u,d in nbrs.iteritems() if u not in seen]
                deg=len(nbr_edges)
                fh.write(make_str(s)+delimiter+"%i\n"%(deg))
                for u,d in nbr_edges:
                    if d is None:    
                        fh.write(make_str(u)+'\n')
                    else:   
                        fh.write(make_str(u)+delimiter+make_str(d)+"\n")
                seen[s]=1
Пример #35
0
def read_multiline_adjlist(path,
                           comments="#",
                           delimiter=' ',
                           create_using=None,
                           nodetype=None,
                           edgetype=None):
    """Read graph in multi-line adjacency list format from path.

    Examples
    --------

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

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

    >>> fh=open("test.adjlist")
    >>> G=nx.read_multiline_adjlist(fh)

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

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

    nodetype is an optional function to convert node strings to nodetype

    For example

    >>> G=nx.read_multiline_adjlist("test.adjlist", nodetype=int)

    will attempt to convert all nodes to integer type

    Since nodes must be hashable, the function nodetype must return hashable
    types (e.g. int, float, str, frozenset - or tuples of those, etc.) 

    edgetype is a function to convert edge data strings to edgetype

    >>> G=nx.read_multiline_adjlist("test.adjlist", edgetype=int)

    create_using is an optional networkx_v099 graph type, the default is
    Graph(), a simple undirected graph 

    >>> G=nx.read_multiline_adjlist("test.adjlist", create_using=nx.DiGraph())

    The comments character (default='#') at the beginning of a
    line indicates a comment line.

    The entries are separated by delimiter (default=' ').
    If whitespace is significant in node or edge labels you should use
    some other delimiter such as a tab or other symbol.  
    

    Example multiline adjlist file format

    No edge data::

     # source target for Graph or DiGraph
     a 2
     b
     c
     d 1
     e

     Wiht edge data::

     # source target for XGraph or XDiGraph with edge data
     a 2
     b edge-ab-data
     c edge-ac-data
     d 1
     e edge-de-data

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

    >>> import codecs
    >>> fh=codecs.open("test.adjlist",'r',encoding='utf=8') # utf-8 encoding
    >>> G=nx.read_multiline_adjlist(fh)
    """
    if create_using is None:
        G = networkx_v099.Graph()
    else:
        try:
            G = create_using
            G.clear()
        except:
            raise TypeError("Input graph is not a networkx_v099 graph type")

    inp = _get_fh(path)

    for line in inp:
        #        if line.startswith("#") or line.startswith("\n"):
        #            continue
        #        line=line.strip() #remove trailing \n
        line = line[:line.find(comments)].strip()
        if not line: continue
        try:
            (u, deg) = line.split(delimiter)
            deg = int(deg)
        except:
            raise TypeError("Failed to read node and degree on line (%s)" %
                            line)
        if nodetype is not None:
            try:
                u = nodetype(u)
            except:
                raise TypeError("Failed to convert node (%s) to type %s"\
                      %(u,nodetype))
        G.add_node(u)
        for i in range(deg):
            line = inp.next().strip()
            vlist = line.split(delimiter)
            numb = len(vlist)
            if numb > 0:
                v = vlist[0]
                if nodetype is not None:
                    try:
                        v = nodetype(v)
                    except:
                        raise TypeError("Failed to convert node (%s) to type %s"\
                                        %(v,nodetype))
            if numb == 1:
                G.add_edge(u, v)
            elif numb == 2:
                d = vlist[1]
                if edgetype is not None:
                    try:
                        d = edgetype(d)
                    except:
                        raise TypeError\
                              ("Failed to convert edge data (%s) to type %s"\
                                %(d, edgetype))
                G.add_edge(u, v, d)
            else:
                raise TypeError("Failed to read line: %s" % vlist)
    return G
Пример #36
0
def read_leda(path):
    """Read graph in GraphML format from path.
    Returns an XGraph or XDiGraph."""
    fh = _get_fh(path, mode='r')
    G = parse_leda(fh)
    return G
Пример #37
0
def read_leda(path):
    """Read graph in GraphML format from path.
    Returns an XGraph or XDiGraph."""
    fh=_get_fh(path,mode='r')        
    G=parse_leda(fh)
    return G
Пример #38
0
def write_gml(G, path):
    """
    Write the graph G in GML format to the file or file handle path.

    Examples
    ---------

    >>> G=nx.path_graph(4)
    >>> nx.write_gml(G,"test.gml")

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

    >>> fh=open("test.gml",'w')
    >>> nx.write_gml(G,fh)

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

    >>> nx.write_gml(G,"test.gml.gz")

    
    The output 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.gml",'w',encoding='iso8859-1')# use iso8859-1
    >>> nx.write_gml(G,fh)

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

    Only a single level of attributes for graphs, nodes, and edges,
    is supported.

    """
    fh = _get_fh(path, mode='w')
    #    comments="#"
    #    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))

    # check for attributes or assign empty dict
    if hasattr(G, 'graph_attr'):
        graph_attr = G.graph_attr
    else:
        graph_attr = {}
    if hasattr(G, 'node_attr'):
        node_attr = G.node_attr
    else:
        node_attr = {}

    indent = 2 * ' '
    count = iter(range(G.number_of_nodes()))
    node_id = {}

    fh.write("graph [\n")
    # write graph attributes
    for k, v in graph_attr.items():
        if is_string_like(v):
            v = '"' + v + '"'
        fh.write(indent + "%s %s\n" % (k, v))
    # write nodes
    for n in G:
        fh.write(indent + "node [\n")
        # get id or assign number
        if n in node_attr:
            nid = node_attr[n].get('id', count.next())
        else:
            nid = count.next()
        node_id[n] = nid
        fh.write(2 * indent + "id %s\n" % nid)
        fh.write(2 * indent + "label \"%s\"\n" % n)
        if n in node_attr:
            for k, v in node_attr[n].items():
                if is_string_like(v): v = '"' + v + '"'
                if k == 'id': continue
                fh.write(2 * indent + "%s %s\n" % (k, v))
        fh.write(indent + "]\n")
    # write edges
    for e in G.edges_iter():
        if len(e) == 3:
            u, v, d = e
            # try to guess what is on the edge and do something reasonable
            edgedata = {}
            if d is None:  # no data
                pass
            elif hasattr(d, 'iteritems'):  # try dict-like
                edgedata = dict(d.iteritems())
            elif hasattr(d, '__iter__'):  # some kind of container
                edgedata['data'] = d.__repr__()
            else:  # something else - string, number
                edgedata['data'] = d
        else:
            u, v = e
            edgedata = {}
        fh.write(indent + "edge [\n")
        fh.write(2 * indent + "source %s\n" % node_id[u])
        fh.write(2 * indent + "target %s\n" % node_id[v])
        for k, v in edgedata.items():
            if k == 'source': continue
            if k == 'target': continue
            if is_string_like(v): v = '"' + v + '"'
            fh.write(2 * indent + "%s %s\n" % (k, v))
        fh.write(indent + "]\n")
    fh.write("]\n")
Пример #39
0
def write_multiline_adjlist(G, path, delimiter=' ', comments='#'):
    """
    Write the graph G in multiline adjacency list format to the file
    or file handle path.

    See read_multiline_adjlist for file format details.

    Examples
    --------

    >>> G=nx.path_graph(4)
    >>> nx.write_multiline_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_multiline_adjlist(G,fh)

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

    >>> nx.write_multiline_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",'w',encoding='utf=8') # utf-8 encoding
    >>> nx.write_multiline_adjlist(G,fh)

    """
    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)

    if G.directed:
        if G.multigraph:
            for s, nbrs in G.adjacency_iter():
                nbr_edges = [(u, d) for u, dl in nbrs.iteritems() for d in dl]
                deg = len(nbr_edges)
                fh.write(make_str(s) + delimiter + "%i\n" % (deg))
                for u, d in nbr_edges:
                    if d is None:
                        fh.write(make_str(u) + '\n')
                    else:
                        fh.write(make_str(u) + delimiter + make_str(d) + "\n")
        else:  # directed single edges
            for s, nbrs in G.adjacency_iter():
                deg = len(nbrs)
                fh.write(make_str(s) + delimiter + "%i\n" % (deg))
                for u, d in nbrs.iteritems():
                    if d is None:
                        fh.write(make_str(u) + '\n')
                    else:
                        fh.write(make_str(u) + delimiter + make_str(d) + "\n")
    else:  #undirected
        if G.multigraph:
            seen = {}  # helper dict used to avoid duplicate edges
            for s, nbrs in G.adjacency_iter():
                nbr_edges = [(u, d) for u, dl in nbrs.iteritems()
                             if u not in seen for d in dl]
                deg = len(nbr_edges)
                fh.write(make_str(s) + delimiter + "%i\n" % (deg))
                for u, d in nbr_edges:
                    if d is None:
                        fh.write(make_str(u) + '\n')
                    else:
                        fh.write(make_str(u) + delimiter + make_str(d) + "\n")
                seen[s] = 1
        else:  # undirected single edges
            seen = {}  # helper dict used to avoid duplicate edges
            for s, nbrs in G.adjacency_iter():
                nbr_edges = [(u, d) for u, d in nbrs.iteritems()
                             if u not in seen]
                deg = len(nbr_edges)
                fh.write(make_str(s) + delimiter + "%i\n" % (deg))
                for u, d in nbr_edges:
                    if d is None:
                        fh.write(make_str(u) + '\n')
                    else:
                        fh.write(make_str(u) + delimiter + make_str(d) + "\n")
                seen[s] = 1
Пример #40
0
def read_multiline_adjlist(path, comments="#", delimiter=' ',
                           create_using=None,
                           nodetype=None, edgetype=None):
    """Read graph in multi-line adjacency list format from path.

    Examples
    --------

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

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

    >>> fh=open("test.adjlist")
    >>> G=nx.read_multiline_adjlist(fh)

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

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

    nodetype is an optional function to convert node strings to nodetype

    For example

    >>> G=nx.read_multiline_adjlist("test.adjlist", nodetype=int)

    will attempt to convert all nodes to integer type

    Since nodes must be hashable, the function nodetype must return hashable
    types (e.g. int, float, str, frozenset - or tuples of those, etc.) 

    edgetype is a function to convert edge data strings to edgetype

    >>> G=nx.read_multiline_adjlist("test.adjlist", edgetype=int)

    create_using is an optional networkx_v099 graph type, the default is
    Graph(), a simple undirected graph 

    >>> G=nx.read_multiline_adjlist("test.adjlist", create_using=nx.DiGraph())

    The comments character (default='#') at the beginning of a
    line indicates a comment line.

    The entries are separated by delimiter (default=' ').
    If whitespace is significant in node or edge labels you should use
    some other delimiter such as a tab or other symbol.  
    

    Example multiline adjlist file format

    No edge data::

     # source target for Graph or DiGraph
     a 2
     b
     c
     d 1
     e

     Wiht edge data::

     # source target for XGraph or XDiGraph with edge data
     a 2
     b edge-ab-data
     c edge-ac-data
     d 1
     e edge-de-data

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

    >>> import codecs
    >>> fh=codecs.open("test.adjlist",'r',encoding='utf=8') # utf-8 encoding
    >>> G=nx.read_multiline_adjlist(fh)
    """
    if create_using is None:
        G=networkx_v099.Graph()
    else:
        try:
            G=create_using
            G.clear()
        except:
            raise TypeError("Input graph is not a networkx_v099 graph type")

    inp=_get_fh(path)        

    for line in inp:
#        if line.startswith("#") or line.startswith("\n"):
#            continue
#        line=line.strip() #remove trailing \n 
        line = line[:line.find(comments)].strip()
        if not line: continue
        try:
            (u,deg)=line.split(delimiter)
            deg=int(deg)
        except:
            raise TypeError("Failed to read node and degree on line (%s)"%line)
        if nodetype is not None:
            try:
                u=nodetype(u)
            except:
                raise TypeError("Failed to convert node (%s) to type %s"\
                      %(u,nodetype))
        G.add_node(u)
        for i in range(deg):
            line=inp.next().strip()
            vlist=line.split(delimiter)
            numb=len(vlist)
            if numb>0:
                v=vlist[0]
                if nodetype is not None:
                    try:
                        v=nodetype(v)
                    except:
                        raise TypeError("Failed to convert node (%s) to type %s"\
                                        %(v,nodetype))
            if numb==1:
                G.add_edge(u,v)
            elif numb==2:
                d=vlist[1]
                if edgetype is not None:
                    try:
                        d=edgetype(d)
                    except:
                        raise TypeError\
                              ("Failed to convert edge data (%s) to type %s"\
                                %(d, edgetype))
                G.add_edge(u,v,d)
            else:
                raise TypeError("Failed to read line: %s"%vlist)
    return G
Пример #41
0
def read_pajek(path):
    """Read graph in pajek format from path. Returns an XGraph or XDiGraph.
    """
    fh = _get_fh(path, mode='r')
    G = parse_pajek(fh)
    return G
Пример #42
0
def read_edgelist(path, comments="#", delimiter=' ',
                  create_using=None, nodetype=None, edgetype=None):
    """Read a graph from a list of edges.

    Parameters
    ----------
    path : file or string
       File or filename to write.  
       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 uses to separate values.  The default is whitespace.
    create_using : Graph container, optional       
       Use specified Graph container to build graph.  The default is
       nx.Graph().
    nodetype : int, float, str, Python type, optional
       Convert node data from strings to specified type
    edgetype : int, float, str, Python type, optional
       Convert edge data from strings to specified type

    Returns
    ----------
    out : graph
       A networkx_v099 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")
    >>> G=nx.read_edgelist(fh)

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

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

    Notes
    -----
    Since nodes must be hashable, the function nodetype must return hashable
    types (e.g. int, float, str, frozenset - or tuples of those, etc.) 


    Example edgelist file formats

    Without edge data::

     # source target
     a b
     a c
     d e

    With edge data::: 

     # source target data
     a b 1
     a c 3.14159
     d e apple

    """
    if create_using is None:
        G=networkx_v099.Graph()
    else:
        try:
            G=create_using
            G.clear()
        except:
            raise TypeError("Input graph is not a networkx_v099 graph type")

    fh=_get_fh(path)

    for line in fh.readlines():
        line = line[:line.find(comments)].strip()
        if not len(line): continue
#        if line.startswith("#") or line.startswith("\n"):
#            continue
#        line=line.strip() #remove trailing \n 
        # split line, should have 2 or three items
        s=line.split(delimiter)
        if len(s)==2:
            if nodetype is not None:
                try:
                    (u,v)=map(nodetype,s)
                except:
                    raise TypeError("Failed to convert edge %s to type %s"\
                          %(s,nodetype))
            else:
                (u,v)=s
            G.add_edge(u,v) 
        elif len(s)==3:
            (u,v,d)=s
            if nodetype is not None:
                try:
                    (u,v)=map(nodetype,(u,v))
                except:
                    raise TypeError("Failed to convert edge (%s, %s) to type %s"\
                          %(u,v,nodetype))
            if d is not None and edgetype is not None:
                try:
                   d=edgetype(d)
                except:
                    raise TypeError("Failed to convert edge data (%s) to type %s"\
                                    %(d, edgetype))
            G.add_edge(u,v,d)  # XGraph or XDiGraph
        else:
            raise TypeError("Failed to read line: %s"%line)
    return G