#!/usr/bin/env python3# -*- coding: utf-8 -*-## This file edgelist.py is referred and derived from project NetworkX,## https://github.com/networkx/networkx/blob/master/networkx/readwrite/edgelist.py## which has the following license:## Copyright (C) 2004-2020, NetworkX Developers# Aric Hagberg <[email protected]># Dan Schult <[email protected]># Pieter Swart <[email protected]># All rights reserved.## This file is part of NetworkX.## NetworkX is distributed under a BSD license; see LICENSE.txt for more# information.#importnetworkx.readwrite.edgelistfromnetworkx.readwrite.edgelistimportparse_edgelistas_parse_edgelistfromnetworkx.readwrite.edgelistimportread_edgelistas_read_edgelistfromnetworkx.utils.decoratorsimportopen_filefromgraphscopeimportnxfromgraphscope.nx.utils.compatimportimport_as_graphscope_nxfromgraphscope.nx.utils.compatimportpatch_docstringimport_as_graphscope_nx(networkx.readwrite.edgelist)@patch_docstring(_parse_edgelist)defparse_edgelist(lines,comments="#",delimiter=None,create_using=None,nodetype=None,data=True,):fromastimportliteral_evalG=nx.empty_graph(0,create_using)edges=[]forlineinlines:p=line.find(comments)ifp>=0:line=line[:p]ifnotline:continue# split line, should have 2 or mores=line.strip().split(delimiter)iflen(s)<2:continueu=s.pop(0)v=s.pop(0)d=sifnodetypeisnotNone:try:u=nodetype(u)v=nodetype(v)exceptExceptionase:raiseTypeError(f"Failed to convert nodes {u},{v} to type {nodetype}.")fromeiflen(d)==0ordataisFalse:# no data or data type specifiededgedata={}elifdataisTrue:# no edge types specifiedtry:# try to evaluate as dictionaryifdelimiter==",":edgedata_str=",".join(d)else:edgedata_str=" ".join(d)edgedata=dict(literal_eval(edgedata_str.strip()))exceptExceptionase:raiseTypeError(f"Failed to convert edge data ({d}) to dictionary.")fromeelse:# convert edge data to dictionary with specified keys and typeiflen(d)!=len(data):raiseIndexError(f"Edge data {d} and data_keys {data} are not the same length")edgedata={}for(edge_key,edge_type),edge_valueinzip(data,d):try:edge_value=edge_type(edge_value)exceptExceptionase:raiseTypeError(f"Failed to convert {edge_key} data {edge_value} "f"to type {edge_type}.")fromeedgedata.update({edge_key:edge_value})edges.append((u,v,edgedata))G.add_edges_from(edges)returnG