#!/usr/bin/env python3# -*- coding: utf-8 -*-## This file adjlist.py is referred and derived from project NetworkX,## https://github.com/networkx/networkx/blob/master/networkx/readwrite/adjlist.py## which has the following license:## Copyright (C) 2004-2020, NetworkX Developers# Aric Hagberg <hagberg@lanl.gov># Dan Schult <dschult@colgate.edu># Pieter Swart <swart@lanl.gov># All rights reserved.## This file is part of NetworkX.## NetworkX is distributed under a BSD license; see LICENSE.txt for more# information.#importnetworkx.readwrite.adjlistfromnetworkx.readwrite.adjlistimportparse_adjlistas_parse_adjlistfromnetworkx.utils.decoratorsimportopen_filefromgraphscopeimportnxfromgraphscope.nx.utils.compatimportimport_as_graphscope_nxfromgraphscope.nx.utils.compatimportpatch_docstringimport_as_graphscope_nx(networkx.readwrite.adjlist)@patch_docstring(_parse_adjlist)defparse_adjlist(lines,comments="#",delimiter=None,create_using=None,nodetype=None):G=nx.empty_graph(0,create_using)edges=[]nodes=[]# nodes that has not any adjacencyforlineinlines:p=line.find(comments)ifp>=0:line=line[:p]ifnotline:continuevlist=line.strip().split(delimiter)u=vlist.pop(0)# convert typesifnodetypeisnotNone:try:u=nodetype(u)exceptExceptionase:raiseTypeError("Failed to convert node ({}) to type {}".format(u,nodetype))fromeiflen(vlist)==0:nodes.append(u)ifnodetypeisnotNone:try:vlist=map(nodetype,vlist)exceptExceptionase:raiseTypeError("Failed to convert nodes ({}) to type {}".format(",".join(vlist),nodetype))fromeedges.extend([u,v]forvinvlist)# N.B: batch add edges to graph.ifnodes:G.add_nodes_from(nodes)G.add_edges_from(edges)returnG
[docs]@open_file(0,mode="rb")defread_adjlist(path,comments="#",delimiter=None,create_using=None,nodetype=None,encoding="utf-8",):"""Read graph in adjacency list format from path. Parameters ---------- path : string or file Filename or file handle to read. Filenames ending in .gz or .bz2 will be uncompressed. create_using : graphscope.nx graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. nodetype : int, str, float, tuple, bool Python object, optional Convert nodes to this type. comments : string, optional Marker for comment lines delimiter : string, optional Separator for node labels. The default is whitespace. Returns ------- G: graphscope.nx graph The graph corresponding to the lines in adjacency list format. Notes ----- This format does not store graph or node data. See Also -------- read_edgelist """lines=(line.decode(encoding)forlineinpath)returnparse_adjlist(lines,comments=comments,delimiter=delimiter,create_using=create_using,nodetype=nodetype,)
# fixture for pytestdefteardown_module(module):importosforfnamein["test.adjlist","test.adjlist.gz"]:ifos.path.isfile(fname):os.unlink(fname)