code
stringlengths 239
50.1k
| apis
list | extract_api
stringlengths 246
34.7k
|
---|---|---|
import networkx.algorithms.community.tests.test_modularity_max
import pytest
from graphscope.nx.utils.compat import import_as_graphscope_nx
from graphscope.nx.utils.compat import with_graphscope_nx_context
import_as_graphscope_nx(networkx.algorithms.community.tests.test_modularity_max,
decorators=pytest.mark.usefixtures("graphscope_session"))
from networkx.algorithms.community.tests.test_modularity_max import TestNaive
@pytest.mark.usefixtures("graphscope_session")
@with_graphscope_nx_context(TestNaive)
class TestNaive():
@pytest.mark.skip(reason="stuck, too long.")
def test_karate_club(self):
john_a = frozenset(
[8, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33])
mr_hi = frozenset([0, 4, 5, 6, 10, 11, 16, 19])
overlap = frozenset([1, 2, 3, 7, 9, 12, 13, 17, 21])
self._check_communities({john_a, overlap, mr_hi})
|
[
"pytest.mark.skip",
"graphscope.nx.utils.compat.with_graphscope_nx_context",
"pytest.mark.usefixtures"
] |
[((453, 498), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (476, 498), False, 'import pytest\n'), ((500, 537), 'graphscope.nx.utils.compat.with_graphscope_nx_context', 'with_graphscope_nx_context', (['TestNaive'], {}), '(TestNaive)\n', (526, 537), False, 'from graphscope.nx.utils.compat import with_graphscope_nx_context\n'), ((562, 605), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""stuck, too long."""'}), "(reason='stuck, too long.')\n", (578, 605), False, 'import pytest\n'), ((324, 369), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (347, 369), False, 'import pytest\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import json
import os
import random
import string
import numpy as np
import pandas as pd
from google.protobuf.any_pb2 import Any
from graphscope.client.archive import OutArchive
from graphscope.framework.errors import check_argument
from graphscope.proto import attr_value_pb2
from graphscope.proto import data_types_pb2
from graphscope.proto import types_pb2
def random_string(nlen):
"""Create random string which length is `nlen`."""
return "".join([random.choice(string.ascii_lowercase) for _ in range(nlen)])
def read_file_to_bytes(file_path):
abs_dir = os.path.abspath(os.path.expanduser(file_path))
if os.path.isfile(abs_dir):
with open(abs_dir, "rb") as b:
content = b.read()
return content
else:
raise IOError("No such file: " + file_path)
def i_to_attr(i: int) -> attr_value_pb2.AttrValue:
check_argument(isinstance(i, int))
return attr_value_pb2.AttrValue(i=i)
def b_to_attr(b: bool) -> attr_value_pb2.AttrValue:
check_argument(isinstance(b, bool))
return attr_value_pb2.AttrValue(b=b)
def s_to_attr(s: str) -> attr_value_pb2.AttrValue:
check_argument(isinstance(s, str))
return attr_value_pb2.AttrValue(s=s.encode("utf-8"))
def bytes_to_attr(s: bytes) -> attr_value_pb2.AttrValue:
check_argument(isinstance(s, bytes))
return attr_value_pb2.AttrValue(s=s)
def f_to_attr(f: float) -> attr_value_pb2.AttrValue:
check_argument(isinstance(f, float))
return attr_value_pb2.AttrValue(f=f)
def type_to_attr(t):
return attr_value_pb2.AttrValue(type=t)
def graph_type_to_attr(t):
return attr_value_pb2.AttrValue(graph_type=t)
def modify_type_to_attr(t):
return attr_value_pb2.AttrValue(modify_type=t)
def report_type_to_attr(t):
return attr_value_pb2.AttrValue(report_type=t)
def list_str_to_attr(list_of_str):
attr = attr_value_pb2.AttrValue()
attr.list.s[:] = [
item.encode("utf-8") if isinstance(item, str) else item for item in list_of_str
]
return attr
def list_i_to_attr(list_i):
attr = attr_value_pb2.AttrValue()
attr.list.i[:] = list_i
return attr
def graph_type_to_cpp_class(graph_type):
if graph_type == types_pb2.IMMUTABLE_EDGECUT:
return "grape::ImmutableEdgecutFragment"
if graph_type == types_pb2.DYNAMIC_PROPERTY:
return "gs::DynamicFragment"
if graph_type == types_pb2.DYNAMIC_PROJECTED:
return "gs::DynamicProjectedFragment"
if graph_type == types_pb2.ARROW_PROPERTY:
return "vineyard::ArrowFragment"
if graph_type == types_pb2.ARROW_PROJECTED:
return "gs::ArrowProjectedFragment"
return "null"
def pack(v):
param = Any()
if isinstance(v, bool):
param.Pack(data_types_pb2.BoolValue(value=v))
elif isinstance(v, int):
param.Pack(data_types_pb2.Int64Value(value=v))
elif isinstance(v, float):
param.Pack(data_types_pb2.DoubleValue(value=v))
elif isinstance(v, str):
param.Pack(data_types_pb2.StringValue(value=v))
elif isinstance(v, bytes):
param.Pack(data_types_pb2.BytesValue(value=v))
else:
raise ValueError("Wrong type of query param {}".format(type(v)))
return param
def pack_query_params(*args, **kwargs):
params = []
for i in args:
params.append(pack(i))
for k, v in kwargs.items():
params.append(pack(v))
return params
def is_numpy(*args):
"""Check if the input type is numpy.ndarray."""
for arg in args:
if arg is not None and not isinstance(arg, np.ndarray):
raise ValueError("The parameter %s should be a numpy ndarray" % arg)
def is_file(*args):
"""Check if the input type is file."""
for arg in args:
if arg is not None and not isinstance(arg, str):
raise ValueError("the parameter %s should be a file path" % arg)
def _context_protocol_to_numpy_dtype(dtype):
dtype_map = {
1: np.dtype("bool"),
2: np.dtype("int32"),
3: np.dtype("uint32"),
4: np.dtype("int64"),
5: np.dtype("uint64"),
6: np.dtype("float32"),
7: np.dtype("float64"),
8: object, # string
}
npdtype = dtype_map.get(dtype)
if npdtype is None:
raise NotImplementedError("Don't support type {}".format(dtype))
return npdtype
def decode_numpy(value):
if not value:
raise RuntimeError("Value to decode should not be empty")
archive = OutArchive(value)
shape_size = archive.get_size()
shape = []
for i in range(shape_size):
shape.append(archive.get_size())
dtype = _context_protocol_to_numpy_dtype(archive.get_int())
array_size = archive.get_size()
check_argument(array_size == np.prod(shape))
if dtype is object:
data_copy = []
for i in range(array_size):
data_copy.append(archive.get_string())
array = np.array(data_copy, dtype=dtype)
else:
array = np.ndarray(
shape=shape,
dtype=dtype,
buffer=archive.get_block(array_size * dtype.itemsize),
order="C",
)
return array
def decode_dataframe(value):
if not value:
raise RuntimeError("Value to decode should not be empty")
archive = OutArchive(value)
column_num = archive.get_size()
row_num = archive.get_size()
arrays = {}
for i in range(column_num):
col_name = archive.get_string()
dtype = _context_protocol_to_numpy_dtype(archive.get_int())
if dtype is object:
data_copy = []
for i in range(row_num):
data_copy.append(archive.get_string())
array = np.array(data_copy, dtype=dtype)
else:
array = np.ndarray(
shape=(row_num,),
dtype=dtype,
buffer=archive.get_block(row_num * dtype.itemsize),
)
arrays[col_name] = array
return pd.DataFrame(arrays)
def unify_type(t):
# If type is None, we deduce type from source file.
if t is None:
return types_pb2.INVALID
if isinstance(t, str):
t = t.lower()
if t == "int":
return types_pb2.INT
elif t in ("int32_t", "int32"):
return types_pb2.INT32
elif t == "long":
return types_pb2.LONG
elif t in ("int64_t", "int64"):
return types_pb2.INT64
elif t in ("uint32_t", "uint32"):
return types_pb2.UINT32
elif t in ("uint64_t", "uint64"):
return types_pb2.UINT64
elif t == "float":
return types_pb2.FLOAT
elif t == "double":
return types_pb2.DOUBLE
elif t in ("str", "string", "std::string"):
return types_pb2.STRING
elif t in ("empty", "grape::emptytype"):
return types_pb2.NULLVALUE
elif isinstance(t, type):
if t is int:
return types_pb2.LONG
elif t is float:
return types_pb2.DOUBLE
elif t is str:
return types_pb2.STRING
elif isinstance(t, int): # types_pb2.DataType
return t
raise TypeError("Not supported type {}".format(t))
def data_type_to_cpp(t):
if t == types_pb2.INT or t == types_pb2.INT32:
return "int32_t"
elif t == types_pb2.LONG or t == types_pb2.INT64:
return "int64_t"
elif t == types_pb2.UINT32:
return "uint32_t"
elif t == types_pb2.UINT64:
return "uint64_t"
elif t == types_pb2.FLOAT:
return "float"
elif t == types_pb2.DOUBLE:
return "double"
elif t == types_pb2.STRING:
return "std::string"
elif t is None or t == types_pb2.NULLVALUE:
return "grape::EmptyType"
elif t == types_pb2.INVALID:
return ""
raise ValueError("Not support type {}".format(t))
def normalize_data_type_str(data_type):
data_type = data_type.lower()
if data_type in ("int8", "int8_t"):
return "int8_t"
if data_type in ("int16", "int16_t"):
return "int16_t"
if data_type in ("int", "int32_t", "int32"):
return "int32_t"
elif data_type in ("long", "int64_t", "int64"):
return "int64_t"
elif data_type in ("uint32_t", "uint32"):
return "uint32_t"
elif data_type in ("uint64_t", "uint64"):
return "uint64_t"
elif data_type in ("str", "string", "std::string"):
return "std::string"
else:
return data_type
def _transform_vertex_data_v(selector):
if selector not in ("v.id", "v.data"):
raise SyntaxError("selector of v must be 'id' or 'data'")
return selector
def _transform_vertex_data_e(selector):
if selector not in ("e.src", "e.dst", "e.data"):
raise SyntaxError("selector of e must be 'src', 'dst' or 'data'")
return selector
def _transform_vertex_data_r(selector):
if selector != "r":
raise SyntaxError("selector or r must be 'r'")
return selector
def _transform_vertex_property_data_r(selector):
# The second part of selector or r is user defined name.
# So we will allow any str
return selector
def _transform_labeled_vertex_data_v(schema, label, prop):
label_id = schema.get_vertex_label_id(label)
if prop == "id":
return "label{}.{}".format(label_id, prop)
else:
prop_id = schema.get_vertex_property_id(label, prop)
return "label{}.property{}".format(label_id, prop_id)
def _transform_labeled_vertex_data_e(schema, label, prop):
label_id = schema.get_edge_label_id(label)
if prop in ("src", "dst"):
return "label{}.{}".format(label_id, prop)
else:
prop_id = schema.get_vertex_property_id(label, prop)
return "label{}.property{}".format(label_id, prop_id)
def _transform_labeled_vertex_data_r(schema, label):
label_id = schema.get_vertex_label_id(label)
return "label{}".format(label_id)
def _transform_labeled_vertex_property_data_r(schema, label, prop):
label_id = schema.get_vertex_label_id(label)
return "label{}.{}".format(label_id, prop)
def transform_vertex_data_selector(selector):
if selector is None:
raise RuntimeError("selector cannot be None")
segments = selector.split(".")
if len(segments) > 2:
raise SyntaxError("Invalid selector: %s." % selector)
if segments[0] == "v":
selector = _transform_vertex_data_v(selector)
elif segments[0] == "e":
selector = _transform_vertex_data_e(selector)
elif segments[0] == "r":
selector = _transform_vertex_data_r(selector)
else:
raise SyntaxError("Invalid selector: %s, choose from v / e / r." % selector)
return selector
def transform_vertex_property_data_selector(selector):
if selector is None:
raise RuntimeError("selector cannot be None")
segments = selector.split(".")
if len(segments) != 2:
raise SyntaxError("Invalid selector: %s." % selector)
if segments[0] == "v":
selector = _transform_vertex_data_v(selector)
elif segments[0] == "e":
selector = _transform_vertex_data_e(selector)
elif segments[0] == "r":
selector = _transform_vertex_property_data_r(selector)
else:
raise SyntaxError("Invalid selector: %s, choose from v / e / r." % selector)
return selector
def transform_labeled_vertex_data_selector(graph, selector):
"""Formats: 'v:x.y/id', 'e:x.y/src/dst', 'r:label',
x denotes label name, y denotes property name.
Returned selector will change label name to 'label{id}', where id is x's id in labels.
And change property name to 'property{id}', where id is y's id in properties.
"""
if selector is None:
raise RuntimeError("selector cannot be None")
schema = graph.schema
ret_type, segments = selector.split(":")
if ret_type not in ("v", "e", "r"):
raise SyntaxError("Invalid selector: " + selector)
segments = segments.split(".")
ret = ""
if ret_type == "v":
ret = _transform_labeled_vertex_data_v(schema, *segments)
elif ret_type == "e":
ret = _transform_labeled_vertex_data_e(schema, *segments)
elif ret_type == "r":
ret = _transform_labeled_vertex_data_r(schema, *segments)
return "{}:{}".format(ret_type, ret)
def transform_labeled_vertex_property_data_selector(graph, selector):
"""Formats: 'v:x.y/id', 'e:x.y/src/dst', 'r:x.y',
x denotes label name, y denotes property name.
Returned selector will change label name to 'label{id}', where id is x's id in labels.
And change property name to 'property{id}', where id is y's id in properties.
"""
if selector is None:
raise RuntimeError("selector cannot be None")
schema = graph.schema
ret_type, segments = selector.split(":")
if ret_type not in ("v", "e", "r"):
raise SyntaxError("Invalid selector: " + selector)
segments = segments.split(".")
ret = ""
if ret_type == "v":
ret = _transform_labeled_vertex_data_v(schema, *segments)
elif ret_type == "e":
ret = _transform_labeled_vertex_data_e(schema, *segments)
elif ret_type == "r":
ret = _transform_labeled_vertex_property_data_r(schema, *segments)
return "{}:{}".format(ret_type, ret)
def transform_vertex_range(vertex_range):
if vertex_range:
return json.dumps(vertex_range)
else:
return None
def _from_numpy_dtype(dtype):
dtype_reverse_map = {
np.dtype(np.int8): types_pb2.INT8,
np.dtype(np.int16): types_pb2.INT16,
np.dtype(np.int32): types_pb2.INT32,
np.dtype(np.int64): types_pb2.INT64,
np.dtype(np.uint8): types_pb2.UINT8,
np.dtype(np.uint16): types_pb2.UINT16,
np.dtype(np.uint32): types_pb2.UINT32,
np.dtype(np.uint64): types_pb2.UINT64,
np.dtype(np.intc): types_pb2.INT,
np.dtype(np.long): types_pb2.LONG,
np.dtype(np.bool): types_pb2.BOOLEAN,
np.dtype(np.float): types_pb2.FLOAT,
np.dtype(np.double): types_pb2.DOUBLE,
}
pbdtype = dtype_reverse_map.get(dtype)
if pbdtype is None:
raise NotImplementedError("Do not support type {}".format(dtype))
return pbdtype
def _to_numpy_dtype(dtype):
dtype_map = {
types_pb2.INT8: np.int8,
types_pb2.INT16: np.int16,
types_pb2.INT32: np.int32,
types_pb2.INT64: np.int64,
types_pb2.UINT8: np.uint8,
types_pb2.UINT16: np.uint16,
types_pb2.UINT32: np.uint32,
types_pb2.UINT64: np.uint64,
types_pb2.INT: np.intc,
types_pb2.LONG: np.long,
types_pb2.BOOLEAN: np.bool,
types_pb2.FLOAT: np.float,
types_pb2.DOUBLE: np.double,
}
npdtype = dtype_map.get(dtype)
if npdtype is None:
raise NotImplementedError("Do not support type {}".format(dtype))
return npdtype
|
[
"pandas.DataFrame",
"google.protobuf.any_pb2.Any",
"graphscope.proto.data_types_pb2.BytesValue",
"numpy.dtype",
"graphscope.proto.data_types_pb2.DoubleValue",
"random.choice",
"json.dumps",
"graphscope.proto.data_types_pb2.StringValue",
"os.path.isfile",
"graphscope.proto.attr_value_pb2.AttrValue",
"numpy.array",
"graphscope.proto.data_types_pb2.BoolValue",
"graphscope.proto.data_types_pb2.Int64Value",
"graphscope.client.archive.OutArchive",
"os.path.expanduser",
"numpy.prod"
] |
[((1297, 1320), 'os.path.isfile', 'os.path.isfile', (['abs_dir'], {}), '(abs_dir)\n', (1311, 1320), False, 'import os\n'), ((1580, 1609), 'graphscope.proto.attr_value_pb2.AttrValue', 'attr_value_pb2.AttrValue', ([], {'i': 'i'}), '(i=i)\n', (1604, 1609), False, 'from graphscope.proto import attr_value_pb2\n'), ((1715, 1744), 'graphscope.proto.attr_value_pb2.AttrValue', 'attr_value_pb2.AttrValue', ([], {'b': 'b'}), '(b=b)\n', (1739, 1744), False, 'from graphscope.proto import attr_value_pb2\n'), ((2005, 2034), 'graphscope.proto.attr_value_pb2.AttrValue', 'attr_value_pb2.AttrValue', ([], {'s': 's'}), '(s=s)\n', (2029, 2034), False, 'from graphscope.proto import attr_value_pb2\n'), ((2142, 2171), 'graphscope.proto.attr_value_pb2.AttrValue', 'attr_value_pb2.AttrValue', ([], {'f': 'f'}), '(f=f)\n', (2166, 2171), False, 'from graphscope.proto import attr_value_pb2\n'), ((2206, 2238), 'graphscope.proto.attr_value_pb2.AttrValue', 'attr_value_pb2.AttrValue', ([], {'type': 't'}), '(type=t)\n', (2230, 2238), False, 'from graphscope.proto import attr_value_pb2\n'), ((2279, 2317), 'graphscope.proto.attr_value_pb2.AttrValue', 'attr_value_pb2.AttrValue', ([], {'graph_type': 't'}), '(graph_type=t)\n', (2303, 2317), False, 'from graphscope.proto import attr_value_pb2\n'), ((2359, 2398), 'graphscope.proto.attr_value_pb2.AttrValue', 'attr_value_pb2.AttrValue', ([], {'modify_type': 't'}), '(modify_type=t)\n', (2383, 2398), False, 'from graphscope.proto import attr_value_pb2\n'), ((2440, 2479), 'graphscope.proto.attr_value_pb2.AttrValue', 'attr_value_pb2.AttrValue', ([], {'report_type': 't'}), '(report_type=t)\n', (2464, 2479), False, 'from graphscope.proto import attr_value_pb2\n'), ((2528, 2554), 'graphscope.proto.attr_value_pb2.AttrValue', 'attr_value_pb2.AttrValue', ([], {}), '()\n', (2552, 2554), False, 'from graphscope.proto import attr_value_pb2\n'), ((2729, 2755), 'graphscope.proto.attr_value_pb2.AttrValue', 'attr_value_pb2.AttrValue', ([], {}), '()\n', (2753, 2755), False, 'from graphscope.proto import attr_value_pb2\n'), ((3349, 3354), 'google.protobuf.any_pb2.Any', 'Any', ([], {}), '()\n', (3352, 3354), False, 'from google.protobuf.any_pb2 import Any\n'), ((5120, 5137), 'graphscope.client.archive.OutArchive', 'OutArchive', (['value'], {}), '(value)\n', (5130, 5137), False, 'from graphscope.client.archive import OutArchive\n'), ((5928, 5945), 'graphscope.client.archive.OutArchive', 'OutArchive', (['value'], {}), '(value)\n', (5938, 5945), False, 'from graphscope.client.archive import OutArchive\n'), ((6607, 6627), 'pandas.DataFrame', 'pd.DataFrame', (['arrays'], {}), '(arrays)\n', (6619, 6627), True, 'import pandas as pd\n'), ((1259, 1288), 'os.path.expanduser', 'os.path.expanduser', (['file_path'], {}), '(file_path)\n', (1277, 1288), False, 'import os\n'), ((4605, 4621), 'numpy.dtype', 'np.dtype', (['"""bool"""'], {}), "('bool')\n", (4613, 4621), True, 'import numpy as np\n'), ((4634, 4651), 'numpy.dtype', 'np.dtype', (['"""int32"""'], {}), "('int32')\n", (4642, 4651), True, 'import numpy as np\n'), ((4664, 4682), 'numpy.dtype', 'np.dtype', (['"""uint32"""'], {}), "('uint32')\n", (4672, 4682), True, 'import numpy as np\n'), ((4695, 4712), 'numpy.dtype', 'np.dtype', (['"""int64"""'], {}), "('int64')\n", (4703, 4712), True, 'import numpy as np\n'), ((4725, 4743), 'numpy.dtype', 'np.dtype', (['"""uint64"""'], {}), "('uint64')\n", (4733, 4743), True, 'import numpy as np\n'), ((4756, 4775), 'numpy.dtype', 'np.dtype', (['"""float32"""'], {}), "('float32')\n", (4764, 4775), True, 'import numpy as np\n'), ((4788, 4807), 'numpy.dtype', 'np.dtype', (['"""float64"""'], {}), "('float64')\n", (4796, 4807), True, 'import numpy as np\n'), ((5561, 5593), 'numpy.array', 'np.array', (['data_copy'], {'dtype': 'dtype'}), '(data_copy, dtype=dtype)\n', (5569, 5593), True, 'import numpy as np\n'), ((14034, 14058), 'json.dumps', 'json.dumps', (['vertex_range'], {}), '(vertex_range)\n', (14044, 14058), False, 'import json\n'), ((14155, 14172), 'numpy.dtype', 'np.dtype', (['np.int8'], {}), '(np.int8)\n', (14163, 14172), True, 'import numpy as np\n'), ((14198, 14216), 'numpy.dtype', 'np.dtype', (['np.int16'], {}), '(np.int16)\n', (14206, 14216), True, 'import numpy as np\n'), ((14243, 14261), 'numpy.dtype', 'np.dtype', (['np.int32'], {}), '(np.int32)\n', (14251, 14261), True, 'import numpy as np\n'), ((14288, 14306), 'numpy.dtype', 'np.dtype', (['np.int64'], {}), '(np.int64)\n', (14296, 14306), True, 'import numpy as np\n'), ((14333, 14351), 'numpy.dtype', 'np.dtype', (['np.uint8'], {}), '(np.uint8)\n', (14341, 14351), True, 'import numpy as np\n'), ((14378, 14397), 'numpy.dtype', 'np.dtype', (['np.uint16'], {}), '(np.uint16)\n', (14386, 14397), True, 'import numpy as np\n'), ((14425, 14444), 'numpy.dtype', 'np.dtype', (['np.uint32'], {}), '(np.uint32)\n', (14433, 14444), True, 'import numpy as np\n'), ((14472, 14491), 'numpy.dtype', 'np.dtype', (['np.uint64'], {}), '(np.uint64)\n', (14480, 14491), True, 'import numpy as np\n'), ((14519, 14536), 'numpy.dtype', 'np.dtype', (['np.intc'], {}), '(np.intc)\n', (14527, 14536), True, 'import numpy as np\n'), ((14561, 14578), 'numpy.dtype', 'np.dtype', (['np.long'], {}), '(np.long)\n', (14569, 14578), True, 'import numpy as np\n'), ((14604, 14621), 'numpy.dtype', 'np.dtype', (['np.bool'], {}), '(np.bool)\n', (14612, 14621), True, 'import numpy as np\n'), ((14650, 14668), 'numpy.dtype', 'np.dtype', (['np.float'], {}), '(np.float)\n', (14658, 14668), True, 'import numpy as np\n'), ((14695, 14714), 'numpy.dtype', 'np.dtype', (['np.double'], {}), '(np.double)\n', (14703, 14714), True, 'import numpy as np\n'), ((1131, 1168), 'random.choice', 'random.choice', (['string.ascii_lowercase'], {}), '(string.ascii_lowercase)\n', (1144, 1168), False, 'import random\n'), ((3402, 3435), 'graphscope.proto.data_types_pb2.BoolValue', 'data_types_pb2.BoolValue', ([], {'value': 'v'}), '(value=v)\n', (3426, 3435), False, 'from graphscope.proto import data_types_pb2\n'), ((5395, 5409), 'numpy.prod', 'np.prod', (['shape'], {}), '(shape)\n', (5402, 5409), True, 'import numpy as np\n'), ((6339, 6371), 'numpy.array', 'np.array', (['data_copy'], {'dtype': 'dtype'}), '(data_copy, dtype=dtype)\n', (6347, 6371), True, 'import numpy as np\n'), ((3485, 3519), 'graphscope.proto.data_types_pb2.Int64Value', 'data_types_pb2.Int64Value', ([], {'value': 'v'}), '(value=v)\n', (3510, 3519), False, 'from graphscope.proto import data_types_pb2\n'), ((3571, 3606), 'graphscope.proto.data_types_pb2.DoubleValue', 'data_types_pb2.DoubleValue', ([], {'value': 'v'}), '(value=v)\n', (3597, 3606), False, 'from graphscope.proto import data_types_pb2\n'), ((3656, 3691), 'graphscope.proto.data_types_pb2.StringValue', 'data_types_pb2.StringValue', ([], {'value': 'v'}), '(value=v)\n', (3682, 3691), False, 'from graphscope.proto import data_types_pb2\n'), ((3743, 3777), 'graphscope.proto.data_types_pb2.BytesValue', 'data_types_pb2.BytesValue', ([], {'value': 'v'}), '(value=v)\n', (3768, 3777), False, 'from graphscope.proto import data_types_pb2\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file digraph.py is referred and derived from project NetworkX,
#
# https://github.com/networkx/networkx/blob/master/networkx/classes/digraph.py
#
# which has the following license:
#
# Copyright (C) 2004-2020, NetworkX Developers
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# All rights reserved.
#
# This file is part of NetworkX.
#
# NetworkX is distributed under a BSD license; see LICENSE.txt for more
# information.
#
from copy import deepcopy
from networkx import freeze
from networkx.classes.coreviews import AdjacencyView
from networkx.classes.digraph import DiGraph as RefDiGraph
from networkx.classes.reportviews import DiDegreeView
from networkx.classes.reportviews import InDegreeView
from networkx.classes.reportviews import OutDegreeView
from graphscope.client.session import get_session_by_id
from graphscope.framework import dag_utils
from graphscope.framework.dag_utils import copy_graph
from graphscope.framework.errors import check_argument
from graphscope.framework.graph_schema import GraphSchema
from graphscope.nx import NetworkXError
from graphscope.nx.classes.graph import Graph
from graphscope.nx.classes.reportviews import InEdgeView
from graphscope.nx.classes.reportviews import OutEdgeView
from graphscope.nx.convert import to_networkx_graph
from graphscope.nx.utils.compat import patch_docstring
from graphscope.nx.utils.misc import clear_cache
from graphscope.nx.utils.misc import empty_graph_in_engine
from graphscope.proto import types_pb2
class DiGraph(Graph):
"""
Base class for directed graphs.
A DiGraph that holds the metadata of a graph, and provides NetworkX-like DiGraph APIs.
It is worth noticing that the graph is actually stored by the Analytical Engine backend.
In other words, the Graph object holds nothing but metadata of a graph
DiGraph support nodes and edges with optional data, or attributes.
DiGraphs support directed edges. Self loops are allowed but multiple
(parallel) edges are not.
Nodes can be arbitrary int/str/float/bool objects with optional
key/value attributes.
Edges are represented as links between nodes with optional
key/value attributes.
DiGraph support node label if it's created from a GraphScope graph object.
nodes are identified by `(label, id)` tuple.
Parameters
----------
incoming_graph_data : input graph (optional, default: None)
Data to initialize graph. If None (default) an empty
graph is created. The data can be any format that is supported
by the to_networkx_graph() function, currently including edge list,
dict of dicts, dict of lists, NetworkX graph, NumPy matrix
or 2d ndarray, Pandas DataFrame, SciPy sparse matrix, or a GraphScope
graph object.
default_label : default node label (optional, default: None)
if incoming_graph_data is a GraphScope graph object, default label means
the nodes of the label can be identified by id directly, other label nodes
need to use `(label, id)` to identify.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to graph as key=value pairs.
See Also
--------
Graph
Examples
--------
Create an empty graph structure (a "null graph") with no nodes and
no edges.
>>> G = nx.DiGraph()
G can be grown in several ways.
**Nodes:**
Add one node at a time:
>>> G.add_node(1)
Add the nodes from any container (a list, dict, set or
even the lines from a file or the nodes from another graph).
>>> G.add_nodes_from([2, 3])
>>> G.add_nodes_from(range(100, 110))
>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
In addition integers, strings can represent a node.
>>> G.add_node('a node')
**Edges:**
G can also be grown by adding edges.
Add one edge,
>>> G.add_edge(1, 2)
a list of edges,
>>> G.add_edges_from([(1, 2), (1, 3)])
or a collection of edges,
>>> G.add_edges_from(H.edges)
If some edges connect nodes not yet in the graph, the nodes
are added automatically. There are no errors when adding
nodes or edges that already exist.
**Attributes:**
Each graph, node, and edge can hold key/value attribute pairs
in an associated attribute dictionary (the keys must be hashable).
By default these are empty, but can be added or changed using
add_edge, add_node or direct manipulation of the attribute
dictionaries named graph, node and edge respectively.
>>> G = nx.DiGraph(day="Friday")
>>> G.graph
{'day': 'Friday'}
Add node attributes using add_node(), add_nodes_from() or G.nodes
>>> G.add_node(1, time='5pm')
>>> G.add_nodes_from([3], time='2pm')
>>> G.nodes[1]
{'time': '5pm'}
>>> G.nodes[1]['room'] = 714
>>> del G.nodes[1]['room'] # remove attribute
>>> list(G.nodes(data=True))
[(1, {'time': '5pm'}), (3, {'time': '2pm'})]
Add edge attributes using add_edge(), add_edges_from(), subscript
notation, or G.edges.
>>> G.add_edge(1, 2, weight=4.7 )
>>> G.add_edges_from([(3, 4), (4, 5)], color='red')
>>> G.add_edges_from([(1, 2, {'color':'blue'}), (2, 3, {'weight':8})])
>>> G[1][2]['weight'] = 4.7
>>> G.edges[1, 2]['weight'] = 4
Warning: we protect the graph data structure by making `G.edges[1, 2]` a
read-only dict-like structure. However, you can assign to attributes
in e.g. `G.edges[1, 2]`. Thus, use 2 sets of brackets to add/change
data attributes: `G.edges[1, 2]['weight'] = 4`
(For multigraphs: `MG.edges[u, v, key][name] = value`).
**Shortcuts:**
Many common graph features allow python syntax to speed reporting.
>>> 1 in G # check if node in graph
True
>>> [n for n in G if n < 3] # iterate through nodes
[1, 2]
>>> len(G) # number of nodes in graph
5
Often the best way to traverse all edges of a graph is via the neighbors.
The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`
>>> for n, nbrsdict in G.adjacency():
... for nbr, eattr in nbrsdict.items():
... if 'weight' in eattr:
... # Do something useful with the edges
... pass
But the edges reporting object is often more convenient:
>>> for u, v, weight in G.edges(data='weight'):
... if weight is not None:
... # Do something useful with the edges
... pass
**Transformation**
Create a graph with GraphScope graph object. First we init a GraphScope graph
with two node labels: person and comment`
>>> g = graphscope.g(directed=True).add_vertice("persion.csv", label="person").add_vertice("comment.csv", label="comment")
create a graph with g, set default_label to 'person'
>>> G = nx.DiGraph(g, default_label="person")
`person` label nodes can be identified by id directly, for `comment` label,
we has to use tuple `("comment", id)` identify. Like, add a person label
node and a comment label node
>>> G.add_node(0, type="person")
>>> G.add_node(("comment", 0), type="comment")
print property of two nodes
>>> G.nodes[0]
{"type", "person"}
>>> G.nodes[("comment", 0)]
{"type", "comment"}
**Reporting:**
Simple graph information is obtained using object-attributes and methods.
Reporting usually provides views instead of containers to reduce memory
usage. The views update as the graph is updated similarly to dict-views.
The objects `nodes, `edges` and `adj` provide access to data attributes
via lookup (e.g. `nodes[n], `edges[u, v]`, `adj[u][v]`) and iteration
(e.g. `nodes.items()`, `nodes.data('color')`,
`nodes.data('color', default='blue')` and similarly for `edges`)
Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
For details on these and other miscellaneous methods, see below.
"""
@patch_docstring(Graph.__init__)
def __init__(self, incoming_graph_data=None, default_label=None, **attr):
self.graph_attr_dict_factory = self.graph_attr_dict_factory
self.node_dict_factory = self.node_dict_factory
self.adjlist_dict_factory = self.adjlist_dict_factory
self.graph = self.graph_attr_dict_factory()
self._node = self.node_dict_factory(self)
self._adj = self.adjlist_dict_factory(self)
self._pred = self.adjlist_dict_factory(self, types_pb2.PREDS_BY_NODE)
self._succ = self._adj
self._key = None
self._op = None
self._session_id = None
self._graph_type = self._graph_type
self._schema = GraphSchema()
self._schema.init_nx_schema()
# cache for add_node and add_edge
self._add_node_cache = []
self._add_edge_cache = []
self._remove_node_cache = []
self._remove_edge_cache = []
create_empty_in_engine = attr.pop(
"create_empty_in_engine", True
) # a hidden parameter
self._distributed = attr.pop("dist", False)
if incoming_graph_data is not None and self._is_gs_graph(incoming_graph_data):
# convert from gs graph always use distributed mode
self._distributed = True
if self._session is None:
self._session = get_session_by_id(incoming_graph_data.session_id)
self._default_label = default_label
if self._session is None:
self._try_to_get_default_session()
if not self._is_gs_graph(incoming_graph_data) and create_empty_in_engine:
graph_def = empty_graph_in_engine(
self, self.is_directed(), self._distributed
)
self._key = graph_def.key
# attempt to load graph with data
if incoming_graph_data is not None:
if self._is_gs_graph(incoming_graph_data):
self._init_with_arrow_property_graph(incoming_graph_data)
else:
g = to_networkx_graph(incoming_graph_data, create_using=self)
check_argument(isinstance(g, Graph))
# load graph attributes (must be after to_networkx_graph)
self.graph.update(attr)
self._saved_signature = self.signature
@property
@clear_cache
@patch_docstring(RefDiGraph.adj)
def adj(self):
return AdjacencyView(self._succ)
succ = adj
@property
@clear_cache
@patch_docstring(RefDiGraph.pred)
def pred(self):
return AdjacencyView(self._pred)
@clear_cache
@patch_docstring(RefDiGraph.has_predecessor)
def has_successor(self, u, v):
return self.has_edge(u, v)
@clear_cache
@patch_docstring(RefDiGraph.has_predecessor)
def has_predecessor(self, u, v):
return self.has_edge(v, u)
@clear_cache
@patch_docstring(RefDiGraph.successors)
def successors(self, n):
try:
return iter(self._succ[n])
except KeyError:
raise NetworkXError("The node %s is not in the digraph." % (n,))
# digraph definitions
neighbors = successors
@clear_cache
@patch_docstring(RefDiGraph.predecessors)
def predecessors(self, n):
try:
return iter(self._pred[n])
except KeyError:
raise NetworkXError("The node %s is not in the digraph." % (n,))
@property
@clear_cache
def edges(self):
"""An OutEdgeView of the DiGraph as G.edges or G.edges().
edges(self, nbunch=None, data=False, default=None)
The OutEdgeView provides set-like operations on the edge-tuples
as well as edge attribute lookup. When called, it also provides
an EdgeDataView object which allows control of access to edge
attributes (but does not provide set-like operations).
Hence, `G.edges[u, v]['color']` provides the value of the color
attribute for edge `(u, v)` while
`for (u, v, c) in G.edges.data('color', default='red'):`
iterates through all the edges yielding the color attribute
with default `'red'` if no color attribute exists.
Parameters
----------
nbunch : single node, container, or all nodes (default= all nodes)
The view will only report edges incident to these nodes.
data : string or bool, optional (default=False)
The edge attribute returned in 3-tuple (u, v, ddict[data]).
If True, return edge attribute dict in 3-tuple (u, v, ddict).
If False, return 2-tuple (u, v).
default : value, optional (default=None)
Value used for edges that don't have the requested attribute.
Only relevant if data is not True or False.
Returns
-------
edges : OutEdgeView
A view of edge attributes, usually it iterates over (u, v)
or (u, v, d) tuples of edges, but can also be used for
attribute lookup as `edges[u, v]['foo']`.
See Also
--------
in_edges, out_edges
Notes
-----
Nodes in nbunch that are not in the graph will be (quietly) ignored.
For directed graphs this returns the out-edges.
Examples
--------
>>> G = nx.DiGraph()
>>> nx.add_path(G, [0, 1, 2])
>>> G.add_edge(2, 3, weight=5)
>>> [e for e in G.edges]
[(0, 1), (1, 2), (2, 3)]
>>> G.edges.data() # default data is {} (empty dict)
OutEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
>>> G.edges.data("weight", default=1)
OutEdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
>>> G.edges([0, 2]) # only edges incident to these nodes
OutEdgeDataView([(0, 1), (2, 3)])
>>> G.edges(0) # only edges incident to a single node (use G.adj[0]?)
OutEdgeDataView([(0, 1)])
"""
return OutEdgeView(self)
# alias out_edges to edges
out_edges = edges
@property
@clear_cache
@patch_docstring(RefDiGraph.in_edges)
def in_edges(self):
return InEdgeView(self)
@property
@clear_cache
def degree(self):
"""A DegreeView for the Graph as G.degree or G.degree().
The node degree is the number of edges adjacent to the node.
The weighted node degree is the sum of the edge weights for
edges incident to that node.
This object provides an iterator for (node, degree) as well as
lookup for the degree for a single node.
Parameters
----------
nbunch : single node, container, or all nodes (default= all nodes)
The view will only report edges incident to these nodes.
weight : string or None, optional (default=None)
The name of an edge attribute that holds the numerical value used
as a weight. If None, then each edge has weight 1.
The degree is the sum of the edge weights adjacent to the node.
Returns
-------
If a single node is requested
deg : int
Degree of the node
OR if multiple nodes are requested
nd_iter : iterator
The iterator returns two-tuples of (node, degree).
See Also
--------
in_degree, out_degree
Examples
--------
>>> G = nx.DiGraph()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.degree(0) # node 0 with degree 1
1
>>> list(G.degree([0, 1, 2]))
[(0, 1), (1, 2), (2, 2)]
"""
return DiDegreeView(self)
@property
@clear_cache
@patch_docstring(RefDiGraph.in_degree)
def in_degree(self):
return InDegreeView(self)
@property
@clear_cache
@patch_docstring(RefDiGraph.out_degree)
def out_degree(self):
return OutDegreeView(self)
@patch_docstring(RefDiGraph.is_directed)
def is_directed(self):
return True
@patch_docstring(RefDiGraph.is_multigraph)
def is_multigraph(self):
return False
@clear_cache
@patch_docstring(RefDiGraph.reverse)
def reverse(self, copy=True):
self._convert_arrow_to_dynamic()
if not copy:
g = self.__class__(create_empty_in_engine=False)
g.graph.update(self.graph)
op = dag_utils.create_graph_view(self, "reversed")
g._op = op
graph_def = op.eval()
g._key = graph_def.key
g._schema = deepcopy(self._schema)
g._graph = self
g._is_client_view = False
g = freeze(g)
else:
g = self.__class__(create_empty_in_engine=False)
g.graph = self.graph
g.name = self.name
op = copy_graph(self, "reverse")
g._op = op
graph_def = op.eval()
g._key = graph_def.key
g._schema = deepcopy(self._schema)
g._session = self._session
return g
|
[
"graphscope.framework.dag_utils.create_graph_view",
"graphscope.framework.graph_schema.GraphSchema",
"networkx.classes.reportviews.DiDegreeView",
"copy.deepcopy",
"networkx.classes.reportviews.InDegreeView",
"graphscope.client.session.get_session_by_id",
"graphscope.nx.classes.reportviews.OutEdgeView",
"networkx.freeze",
"graphscope.framework.dag_utils.copy_graph",
"networkx.classes.coreviews.AdjacencyView",
"graphscope.nx.convert.to_networkx_graph",
"graphscope.nx.NetworkXError",
"networkx.classes.reportviews.OutDegreeView",
"graphscope.nx.utils.compat.patch_docstring",
"graphscope.nx.classes.reportviews.InEdgeView"
] |
[((8037, 8068), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['Graph.__init__'], {}), '(Graph.__init__)\n', (8052, 8068), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((10379, 10410), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['RefDiGraph.adj'], {}), '(RefDiGraph.adj)\n', (10394, 10410), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((10524, 10556), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['RefDiGraph.pred'], {}), '(RefDiGraph.pred)\n', (10539, 10556), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((10641, 10684), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['RefDiGraph.has_predecessor'], {}), '(RefDiGraph.has_predecessor)\n', (10656, 10684), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((10778, 10821), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['RefDiGraph.has_predecessor'], {}), '(RefDiGraph.has_predecessor)\n', (10793, 10821), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((10917, 10955), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['RefDiGraph.successors'], {}), '(RefDiGraph.successors)\n', (10932, 10955), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((11216, 11256), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['RefDiGraph.predecessors'], {}), '(RefDiGraph.predecessors)\n', (11231, 11256), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((14097, 14133), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['RefDiGraph.in_edges'], {}), '(RefDiGraph.in_edges)\n', (14112, 14133), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((15697, 15734), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['RefDiGraph.in_degree'], {}), '(RefDiGraph.in_degree)\n', (15712, 15734), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((15831, 15869), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['RefDiGraph.out_degree'], {}), '(RefDiGraph.out_degree)\n', (15846, 15869), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((15937, 15976), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['RefDiGraph.is_directed'], {}), '(RefDiGraph.is_directed)\n', (15952, 15976), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((16030, 16071), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['RefDiGraph.is_multigraph'], {}), '(RefDiGraph.is_multigraph)\n', (16045, 16071), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((16145, 16180), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['RefDiGraph.reverse'], {}), '(RefDiGraph.reverse)\n', (16160, 16180), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((8747, 8760), 'graphscope.framework.graph_schema.GraphSchema', 'GraphSchema', ([], {}), '()\n', (8758, 8760), False, 'from graphscope.framework.graph_schema import GraphSchema\n'), ((10445, 10470), 'networkx.classes.coreviews.AdjacencyView', 'AdjacencyView', (['self._succ'], {}), '(self._succ)\n', (10458, 10470), False, 'from networkx.classes.coreviews import AdjacencyView\n'), ((10592, 10617), 'networkx.classes.coreviews.AdjacencyView', 'AdjacencyView', (['self._pred'], {}), '(self._pred)\n', (10605, 10617), False, 'from networkx.classes.coreviews import AdjacencyView\n'), ((13988, 14005), 'graphscope.nx.classes.reportviews.OutEdgeView', 'OutEdgeView', (['self'], {}), '(self)\n', (13999, 14005), False, 'from graphscope.nx.classes.reportviews import OutEdgeView\n'), ((14173, 14189), 'graphscope.nx.classes.reportviews.InEdgeView', 'InEdgeView', (['self'], {}), '(self)\n', (14183, 14189), False, 'from graphscope.nx.classes.reportviews import InEdgeView\n'), ((15641, 15659), 'networkx.classes.reportviews.DiDegreeView', 'DiDegreeView', (['self'], {}), '(self)\n', (15653, 15659), False, 'from networkx.classes.reportviews import DiDegreeView\n'), ((15775, 15793), 'networkx.classes.reportviews.InDegreeView', 'InDegreeView', (['self'], {}), '(self)\n', (15787, 15793), False, 'from networkx.classes.reportviews import InDegreeView\n'), ((15911, 15930), 'networkx.classes.reportviews.OutDegreeView', 'OutDegreeView', (['self'], {}), '(self)\n', (15924, 15930), False, 'from networkx.classes.reportviews import OutDegreeView\n'), ((16395, 16440), 'graphscope.framework.dag_utils.create_graph_view', 'dag_utils.create_graph_view', (['self', '"""reversed"""'], {}), "(self, 'reversed')\n", (16422, 16440), False, 'from graphscope.framework import dag_utils\n'), ((16557, 16579), 'copy.deepcopy', 'deepcopy', (['self._schema'], {}), '(self._schema)\n', (16565, 16579), False, 'from copy import deepcopy\n'), ((16662, 16671), 'networkx.freeze', 'freeze', (['g'], {}), '(g)\n', (16668, 16671), False, 'from networkx import freeze\n'), ((16828, 16855), 'graphscope.framework.dag_utils.copy_graph', 'copy_graph', (['self', '"""reverse"""'], {}), "(self, 'reverse')\n", (16838, 16855), False, 'from graphscope.framework.dag_utils import copy_graph\n'), ((16972, 16994), 'copy.deepcopy', 'deepcopy', (['self._schema'], {}), '(self._schema)\n', (16980, 16994), False, 'from copy import deepcopy\n'), ((9413, 9462), 'graphscope.client.session.get_session_by_id', 'get_session_by_id', (['incoming_graph_data.session_id'], {}), '(incoming_graph_data.session_id)\n', (9430, 9462), False, 'from graphscope.client.session import get_session_by_id\n'), ((10085, 10142), 'graphscope.nx.convert.to_networkx_graph', 'to_networkx_graph', (['incoming_graph_data'], {'create_using': 'self'}), '(incoming_graph_data, create_using=self)\n', (10102, 10142), False, 'from graphscope.nx.convert import to_networkx_graph\n'), ((11080, 11138), 'graphscope.nx.NetworkXError', 'NetworkXError', (["('The node %s is not in the digraph.' % (n,))"], {}), "('The node %s is not in the digraph.' % (n,))\n", (11093, 11138), False, 'from graphscope.nx import NetworkXError\n'), ((11383, 11441), 'graphscope.nx.NetworkXError', 'NetworkXError', (["('The node %s is not in the digraph.' % (n,))"], {}), "('The node %s is not in the digraph.' % (n,))\n", (11396, 11441), False, 'from graphscope.nx import NetworkXError\n')]
|
import networkx.algorithms.tests.test_euler
import pytest
from graphscope.nx.utils.compat import import_as_graphscope_nx
from graphscope.nx.utils.compat import with_graphscope_nx_context
import_as_graphscope_nx(networkx.algorithms.tests.test_euler,
decorators=pytest.mark.usefixtures("graphscope_session"))
from networkx.algorithms.tests.test_euler import TestHasEulerianPath
from networkx.algorithms.tests.test_euler import TestIsEulerian
from networkx.algorithms.tests.test_euler import TestIsSemiEulerian
@pytest.mark.usefixtures("graphscope_session")
@with_graphscope_nx_context(TestIsEulerian)
class TestIsEulerian:
# NB: graphscope.nx does not support hypercube_graph(which use tuple as node),
# remove it
def test_is_eulerian(self):
assert nx.is_eulerian(nx.complete_graph(5))
assert nx.is_eulerian(nx.complete_graph(7))
assert not nx.is_eulerian(nx.complete_graph(4))
assert not nx.is_eulerian(nx.complete_graph(6))
assert not nx.is_eulerian(nx.petersen_graph())
assert not nx.is_eulerian(nx.path_graph(4))
@pytest.mark.usefixtures("graphscope_session")
@with_graphscope_nx_context(TestHasEulerianPath)
class TestHasEulerianPath:
# NB: graphscope.nx does not support hypercube_graph(which use tuple as node),
# remove it
def test_has_eulerian_path_cyclic(self):
# Test graphs with Eulerian cycles return True.
assert nx.has_eulerian_path(nx.complete_graph(5))
assert nx.has_eulerian_path(nx.complete_graph(7))
@pytest.mark.usefixtures("graphscope_session")
@with_graphscope_nx_context(TestIsSemiEulerian)
class TestIsSemiEulerian:
# NB: graphscope.nx does not support hypercube_graph(which use tuple as node),
# remove it
def test_is_semieulerian(self):
# Test graphs with Eulerian paths but no cycles return True.
assert nx.is_semieulerian(nx.path_graph(4))
G = nx.path_graph(6, create_using=nx.DiGraph)
assert nx.is_semieulerian(G)
# Test graphs with Eulerian cycles return False.
assert not nx.is_semieulerian(nx.complete_graph(5))
assert not nx.is_semieulerian(nx.complete_graph(7))
|
[
"graphscope.nx.utils.compat.with_graphscope_nx_context",
"pytest.mark.usefixtures"
] |
[((538, 583), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (561, 583), False, 'import pytest\n'), ((585, 627), 'graphscope.nx.utils.compat.with_graphscope_nx_context', 'with_graphscope_nx_context', (['TestIsEulerian'], {}), '(TestIsEulerian)\n', (611, 627), False, 'from graphscope.nx.utils.compat import with_graphscope_nx_context\n'), ((1109, 1154), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (1132, 1154), False, 'import pytest\n'), ((1156, 1203), 'graphscope.nx.utils.compat.with_graphscope_nx_context', 'with_graphscope_nx_context', (['TestHasEulerianPath'], {}), '(TestHasEulerianPath)\n', (1182, 1203), False, 'from graphscope.nx.utils.compat import with_graphscope_nx_context\n'), ((1550, 1595), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (1573, 1595), False, 'import pytest\n'), ((1597, 1643), 'graphscope.nx.utils.compat.with_graphscope_nx_context', 'with_graphscope_nx_context', (['TestIsSemiEulerian'], {}), '(TestIsSemiEulerian)\n', (1623, 1643), False, 'from graphscope.nx.utils.compat import with_graphscope_nx_context\n'), ((286, 331), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (309, 331), False, 'import pytest\n')]
|
import pytest
from networkx.generators.tests.test_atlas import TestAtlasGraph
from networkx.generators.tests.test_atlas import TestAtlasGraphG
import graphscope.nx as nx
from graphscope.nx import graph_atlas
from graphscope.nx import graph_atlas_g
from graphscope.nx.utils.compat import with_graphscope_nx_context
@pytest.mark.usefixtures("graphscope_session")
@with_graphscope_nx_context(TestAtlasGraph)
class TestAtlasGraph:
pass
@pytest.mark.usefixtures("graphscope_session")
@with_graphscope_nx_context(TestAtlasGraphG)
class TestAtlasGraphG:
pass
|
[
"graphscope.nx.utils.compat.with_graphscope_nx_context",
"pytest.mark.usefixtures"
] |
[((318, 363), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (341, 363), False, 'import pytest\n'), ((365, 407), 'graphscope.nx.utils.compat.with_graphscope_nx_context', 'with_graphscope_nx_context', (['TestAtlasGraph'], {}), '(TestAtlasGraph)\n', (391, 407), False, 'from graphscope.nx.utils.compat import with_graphscope_nx_context\n'), ((442, 487), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (465, 487), False, 'import pytest\n'), ((489, 532), 'graphscope.nx.utils.compat.with_graphscope_nx_context', 'with_graphscope_nx_context', (['TestAtlasGraphG'], {}), '(TestAtlasGraphG)\n', (515, 532), False, 'from graphscope.nx.utils.compat import with_graphscope_nx_context\n')]
|
import networkx.algorithms.shortest_paths.tests.test_astar
import pytest
from graphscope.experimental.nx.utils.compat import import_as_graphscope_nx
from graphscope.experimental.nx.utils.compat import with_graphscope_nx_context
import_as_graphscope_nx(networkx.algorithms.shortest_paths.tests.test_astar,
decorators=pytest.mark.usefixtures("graphscope_session"))
from networkx.algorithms.shortest_paths.tests.test_astar import TestAStar
@pytest.mark.usefixtures("graphscope_session")
@with_graphscope_nx_context(TestAStar)
class TestAStar():
@pytest.mark.skip(reason="not support multigraph")
def test_astar_multigraph():
pass
@pytest.mark.skip(reason="not support class object as node")
def test_unorderable_nodes():
pass
|
[
"graphscope.experimental.nx.utils.compat.with_graphscope_nx_context",
"pytest.mark.skip",
"pytest.mark.usefixtures"
] |
[((467, 512), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (490, 512), False, 'import pytest\n'), ((514, 551), 'graphscope.experimental.nx.utils.compat.with_graphscope_nx_context', 'with_graphscope_nx_context', (['TestAStar'], {}), '(TestAStar)\n', (540, 551), False, 'from graphscope.experimental.nx.utils.compat import with_graphscope_nx_context\n'), ((576, 625), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""not support multigraph"""'}), "(reason='not support multigraph')\n", (592, 625), False, 'import pytest\n'), ((678, 737), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""not support class object as node"""'}), "(reason='not support class object as node')\n", (694, 737), False, 'import pytest\n'), ((342, 387), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (365, 387), False, 'import pytest\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import networkx.algorithms as nxa
import graphscope
from graphscope.experimental import nx
from graphscope.experimental.nx.utils.compat import patch_docstring
from graphscope.framework.app import AppAssets
@patch_docstring(nxa.pagerank)
def pagerank(G, alpha=0.85, max_iter=100, tol=1.0e-6):
raise NotImplementedError
@patch_docstring(nxa.hits)
def hits(G, max_iter=100, tol=1.0e-8, normalized=True):
pg = G.project_to_simple()
ctx = graphscope.hits(pg, tol, max_iter, normalized)
return ctx.to_dataframe({"node": "v.id", "auth": "r.auth", "hub": "r.hub"})
@patch_docstring(nxa.degree_centrality)
def degree_centrality(G):
pg = G.project_to_simple()
ctx = graphscope.degree_centrality(pg, centrality_type="both")
return ctx.to_dataframe({"node": "v.id", "result": "r"})
@patch_docstring(nxa.in_degree_centrality)
def in_degree_centrality(G):
pg = G.project_to_simple()
ctx = graphscope.degree_centrality(pg, centrality_type="in")
return ctx.to_dataframe({"node": "v.id", "result": "r"})
@patch_docstring(nxa.out_degree_centrality)
def out_degree_centrality(G):
pg = G.project_to_simple()
ctx = graphscope.degree_centrality(pg, centrality_type="out")
return ctx.to_dataframe({"node": "v.id", "result": "r"})
@patch_docstring(nxa.eigenvector_centrality)
def eigenvector_centrality(G, max_iter=100, tol=1e-06, weight=None):
if weight is None:
weight = "weight"
pg = G.project_to_simple(e_prop=weight)
ctx = graphscope.eigenvector_centrality(pg, tolerance=tol, max_round=max_iter)
return ctx.to_dataframe({"node": "v.id", "result": "r"})
@patch_docstring(nxa.katz_centrality)
def katz_centrality(
G,
alpha=0.1,
beta=1.0,
max_iter=100,
tol=1e-06,
nstart=None,
normalized=True,
weight=None,
):
# FIXME: nstart not support.
if weight is None:
weight = "weight"
pg = G.project_to_simple(e_prop=weight)
ctx = graphscope.katz_centrality(
pg,
alpha=alpha,
beta=beta,
tolerance=tol,
max_round=max_iter,
normalized=normalized,
)
return ctx.to_dataframe({"node": "v.id", "result": "r"})
@patch_docstring(nxa.has_path)
def has_path(G, source, target):
pg = G.project_to_simple()
return AppAssets(algo="sssp_has_path")(pg, source, target)
@patch_docstring(nxa.shortest_path)
def shortest_path(G, source=None, target=None, weight=None):
# FIXME: target and method not support.
if weight is None:
weight = "weight"
default = False
else:
default = True
pg = G.project_to_simple(e_prop=weight)
return AppAssets(algo="sssp_path")(pg, source, weight=default)
@patch_docstring(nxa.single_source_dijkstra_path_length)
def single_source_dijkstra_path_length(G, source, weight=None):
if weight is None:
weight = "weight"
pg = G.project_to_simple(e_prop=weight)
ctx = AppAssets(algo="sssp_projected")(pg, source)
return ctx.to_dataframe({"node": "v.id", "result": "r"})
@patch_docstring(nxa.average_shortest_path_length)
def average_shortest_path_length(G, weight=None):
pg = G.project_to_simple(e_prop=weight)
ctx = AppAssets(algo="sssp_average_length")(pg, weight=True)
return ctx.to_numpy("r", axis=0)[0]
@patch_docstring(nxa.bfs_edges)
def bfs_edges(G, source, reverse=False, depth_limit=None):
# FIXME: reverse not support.
pg = G.project_to_simple()
ctx = AppAssets(algo="bfs_generic")(pg, source, depth_limit, format="edges")
return ctx.to_numpy("r", axis=0).tolist()
@patch_docstring(nxa.bfs_predecessors)
def bfs_predecessors(G, source, depth_limit=None):
pg = G.project_to_simple()
return AppAssets(algo="bfs_generic")(pg, source, depth_limit, format="predecessors")
@patch_docstring(nxa.bfs_successors)
def bfs_successors(G, source, depth_limit=None):
pg = G.project_to_simple()
return AppAssets(algo="bfs_generic")(pg, source, depth_limit, format="successors")
@patch_docstring(nxa.bfs_tree)
def bfs_tree(G, source, reverse=False, depth_limit=None):
T = nx.DiGraph()
T.add_node(source)
edges_gen = bfs_edges(G, source, reverse=reverse, depth_limit=depth_limit)
T.add_edges_from(edges_gen)
return T
@patch_docstring(nxa.k_core)
def k_core(G, k=None, core_number=None):
# FIXME: core number not support.
pg = G.project_to_simple()
return graphscope.k_core(pg, k)
@patch_docstring(nxa.clustering)
def clustering(G, nodes=None, weight=None):
# FIXME(weibin): clustering now only correct in directed graph.
# FIXME: nodes and weight not support.
pg = G.project_to_simple()
ctx = graphscope.clustering(pg)
return ctx.to_dataframe({"node": "v.id", "result": "r"})
@patch_docstring(nxa.triangles)
def triangles(G, nodes=None):
# FIXME: nodes not support.
pg = G.project_to_simple()
ctx = graphscope.triangles(pg)
return ctx.to_dataframe({"node": "v.id", "result": "r"})
@patch_docstring(nxa.transitivity)
def transitivity(G):
# FIXME: nodes not support.
pg = G.project_to_simple()
return AppAssets(algo="transitivity")(pg)
@patch_docstring(nxa.average_clustering)
def average_clustering(G, nodes=None, weight=None, count_zeros=True):
# FIXME: nodes, weight, count_zeros not support.
pg = G.project_to_simple()
ctx = AppAssets(algo="avg_clustering")(pg)
return ctx.to_numpy("r")[0]
@patch_docstring(nxa.weakly_connected_components)
def weakly_connected_components(G):
pg = G.project_to_simple()
return AppAssets(algo="wcc_projected")(pg)
|
[
"graphscope.framework.app.AppAssets",
"graphscope.eigenvector_centrality",
"graphscope.experimental.nx.utils.compat.patch_docstring",
"graphscope.k_core",
"graphscope.clustering",
"graphscope.degree_centrality",
"graphscope.experimental.nx.DiGraph",
"graphscope.triangles",
"graphscope.katz_centrality",
"graphscope.hits"
] |
[((877, 906), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.pagerank'], {}), '(nxa.pagerank)\n', (892, 906), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((995, 1020), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.hits'], {}), '(nxa.hits)\n', (1010, 1020), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((1248, 1286), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.degree_centrality'], {}), '(nxa.degree_centrality)\n', (1263, 1286), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((1475, 1516), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.in_degree_centrality'], {}), '(nxa.in_degree_centrality)\n', (1490, 1516), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((1706, 1748), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.out_degree_centrality'], {}), '(nxa.out_degree_centrality)\n', (1721, 1748), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((1940, 1983), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.eigenvector_centrality'], {}), '(nxa.eigenvector_centrality)\n', (1955, 1983), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((2293, 2329), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.katz_centrality'], {}), '(nxa.katz_centrality)\n', (2308, 2329), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((2846, 2875), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.has_path'], {}), '(nxa.has_path)\n', (2861, 2875), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((3006, 3040), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.shortest_path'], {}), '(nxa.shortest_path)\n', (3021, 3040), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((3366, 3421), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.single_source_dijkstra_path_length'], {}), '(nxa.single_source_dijkstra_path_length)\n', (3381, 3421), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((3698, 3747), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.average_shortest_path_length'], {}), '(nxa.average_shortest_path_length)\n', (3713, 3747), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((3950, 3980), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.bfs_edges'], {}), '(nxa.bfs_edges)\n', (3965, 3980), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((4235, 4272), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.bfs_predecessors'], {}), '(nxa.bfs_predecessors)\n', (4250, 4272), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((4447, 4482), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.bfs_successors'], {}), '(nxa.bfs_successors)\n', (4462, 4482), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((4653, 4682), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.bfs_tree'], {}), '(nxa.bfs_tree)\n', (4668, 4682), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((4912, 4939), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.k_core'], {}), '(nxa.k_core)\n', (4927, 4939), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((5089, 5120), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.clustering'], {}), '(nxa.clustering)\n', (5104, 5120), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((5407, 5437), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.triangles'], {}), '(nxa.triangles)\n', (5422, 5437), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((5630, 5663), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.transitivity'], {}), '(nxa.transitivity)\n', (5645, 5663), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((5797, 5836), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.average_clustering'], {}), '(nxa.average_clustering)\n', (5812, 5836), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((6073, 6121), 'graphscope.experimental.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.weakly_connected_components'], {}), '(nxa.weakly_connected_components)\n', (6088, 6121), False, 'from graphscope.experimental.nx.utils.compat import patch_docstring\n'), ((1118, 1164), 'graphscope.hits', 'graphscope.hits', (['pg', 'tol', 'max_iter', 'normalized'], {}), '(pg, tol, max_iter, normalized)\n', (1133, 1164), False, 'import graphscope\n'), ((1354, 1410), 'graphscope.degree_centrality', 'graphscope.degree_centrality', (['pg'], {'centrality_type': '"""both"""'}), "(pg, centrality_type='both')\n", (1382, 1410), False, 'import graphscope\n'), ((1587, 1641), 'graphscope.degree_centrality', 'graphscope.degree_centrality', (['pg'], {'centrality_type': '"""in"""'}), "(pg, centrality_type='in')\n", (1615, 1641), False, 'import graphscope\n'), ((1820, 1875), 'graphscope.degree_centrality', 'graphscope.degree_centrality', (['pg'], {'centrality_type': '"""out"""'}), "(pg, centrality_type='out')\n", (1848, 1875), False, 'import graphscope\n'), ((2156, 2228), 'graphscope.eigenvector_centrality', 'graphscope.eigenvector_centrality', (['pg'], {'tolerance': 'tol', 'max_round': 'max_iter'}), '(pg, tolerance=tol, max_round=max_iter)\n', (2189, 2228), False, 'import graphscope\n'), ((2614, 2730), 'graphscope.katz_centrality', 'graphscope.katz_centrality', (['pg'], {'alpha': 'alpha', 'beta': 'beta', 'tolerance': 'tol', 'max_round': 'max_iter', 'normalized': 'normalized'}), '(pg, alpha=alpha, beta=beta, tolerance=tol,\n max_round=max_iter, normalized=normalized)\n', (2640, 2730), False, 'import graphscope\n'), ((4749, 4761), 'graphscope.experimental.nx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (4759, 4761), False, 'from graphscope.experimental import nx\n'), ((5061, 5085), 'graphscope.k_core', 'graphscope.k_core', (['pg', 'k'], {}), '(pg, k)\n', (5078, 5085), False, 'import graphscope\n'), ((5317, 5342), 'graphscope.clustering', 'graphscope.clustering', (['pg'], {}), '(pg)\n', (5338, 5342), False, 'import graphscope\n'), ((5541, 5565), 'graphscope.triangles', 'graphscope.triangles', (['pg'], {}), '(pg)\n', (5561, 5565), False, 'import graphscope\n'), ((2951, 2982), 'graphscope.framework.app.AppAssets', 'AppAssets', ([], {'algo': '"""sssp_has_path"""'}), "(algo='sssp_has_path')\n", (2960, 2982), False, 'from graphscope.framework.app import AppAssets\n'), ((3307, 3334), 'graphscope.framework.app.AppAssets', 'AppAssets', ([], {'algo': '"""sssp_path"""'}), "(algo='sssp_path')\n", (3316, 3334), False, 'from graphscope.framework.app import AppAssets\n'), ((3589, 3621), 'graphscope.framework.app.AppAssets', 'AppAssets', ([], {'algo': '"""sssp_projected"""'}), "(algo='sssp_projected')\n", (3598, 3621), False, 'from graphscope.framework.app import AppAssets\n'), ((3852, 3889), 'graphscope.framework.app.AppAssets', 'AppAssets', ([], {'algo': '"""sssp_average_length"""'}), "(algo='sssp_average_length')\n", (3861, 3889), False, 'from graphscope.framework.app import AppAssets\n'), ((4115, 4144), 'graphscope.framework.app.AppAssets', 'AppAssets', ([], {'algo': '"""bfs_generic"""'}), "(algo='bfs_generic')\n", (4124, 4144), False, 'from graphscope.framework.app import AppAssets\n'), ((4366, 4395), 'graphscope.framework.app.AppAssets', 'AppAssets', ([], {'algo': '"""bfs_generic"""'}), "(algo='bfs_generic')\n", (4375, 4395), False, 'from graphscope.framework.app import AppAssets\n'), ((4574, 4603), 'graphscope.framework.app.AppAssets', 'AppAssets', ([], {'algo': '"""bfs_generic"""'}), "(algo='bfs_generic')\n", (4583, 4603), False, 'from graphscope.framework.app import AppAssets\n'), ((5759, 5789), 'graphscope.framework.app.AppAssets', 'AppAssets', ([], {'algo': '"""transitivity"""'}), "(algo='transitivity')\n", (5768, 5789), False, 'from graphscope.framework.app import AppAssets\n'), ((6001, 6033), 'graphscope.framework.app.AppAssets', 'AppAssets', ([], {'algo': '"""avg_clustering"""'}), "(algo='avg_clustering')\n", (6010, 6033), False, 'from graphscope.framework.app import AppAssets\n'), ((6200, 6231), 'graphscope.framework.app.AppAssets', 'AppAssets', ([], {'algo': '"""wcc_projected"""'}), "(algo='wcc_projected')\n", (6209, 6231), False, 'from graphscope.framework.app import AppAssets\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from typing import Any
from typing import Mapping
from typing import Sequence
from typing import Tuple
from typing import Union
import numpy as np
import pandas as pd
try:
import vineyard
except ImportError:
vineyard = None
from graphscope.framework import utils
from graphscope.framework.errors import check_argument
from graphscope.framework.loader import Loader
from graphscope.proto import attr_value_pb2
from graphscope.proto import types_pb2
if vineyard is not None:
VineyardObjectTypes = (vineyard.Object, vineyard.ObjectID, vineyard.ObjectName)
LoaderVariants = Union[
Loader,
str,
Sequence[np.ndarray],
pd.DataFrame,
vineyard.Object,
vineyard.ObjectID,
vineyard.ObjectName,
]
else:
VineyardObjectTypes = ()
LoaderVariants = Union[
Loader,
str,
Sequence[np.ndarray],
pd.DataFrame,
]
class VertexLabel(object):
"""Holds meta informations about a single vertex label."""
def __init__(
self,
label: str,
loader: Any,
properties: Sequence = None,
vid_field: Union[str, int] = 0,
session_id=None,
id_type: str = "int64_t",
):
self.label = label
# loader to take various data source
if isinstance(loader, Loader):
self.loader = loader
else:
self.loader = Loader(loader)
# raw properties passed by user parameters
self.raw_properties = properties
# finally properties for constructing graph
self.properties = []
# column index or property name used as id field
self.vid_field = vid_field
# type of vertex original id
# should be consistent with the original graph
self.id_type = id_type
self._session_id = session_id
# normalize properties
# add vid to property list
self.add_property(str(self.vid_field), self.id_type)
if self.raw_properties:
self.add_properties(self.raw_properties)
elif self.loader.deduced_properties:
self.add_properties(self.loader.deduced_properties)
# set selected columns to loader
self.loader.select_columns(
self.properties, include_all=bool(self.raw_properties is None)
)
def __str__(self) -> str:
s = "\ntype: VertexLabel"
s += "\nlabel: " + self.label
s += "\nproperties: " + str(self.properties)
s += "\nvid: " + str(self.vid_field)
s += "\nid_type: " + self.id_type
s += "\nloader: " + repr(self.loader)
return s
def __repr__(self) -> str:
return self.__str__()
def add_property(self, prop: str, dtype=None) -> None:
"""prop is a str, representing name. It can optionally have a type."""
self.properties.append((prop, utils.unify_type(dtype)))
def add_properties(self, properties: Sequence) -> None:
for prop in properties:
if isinstance(prop, str):
self.add_property(prop)
else:
self.add_property(prop[0], prop[1])
def attr(self) -> attr_value_pb2.NameAttrList:
attr_list = attr_value_pb2.NameAttrList()
attr_list.name = "vertex"
attr_list.attr[types_pb2.LABEL].CopyFrom(utils.s_to_attr(self.label))
attr_list.attr[types_pb2.VID].CopyFrom(utils.s_to_attr(str(self.vid_field)))
props = []
for prop in self.properties[1:]:
prop_attr = attr_value_pb2.NameAttrList()
prop_attr.name = prop[0]
prop_attr.attr[0].CopyFrom(utils.type_to_attr(prop[1]))
props.append(prop_attr)
attr_list.attr[types_pb2.PROPERTIES].list.func.extend(props)
attr_list.attr[types_pb2.LOADER].CopyFrom(self.loader.get_attr())
return attr_list
class EdgeSubLabel(object):
"""Hold meta informations of a single relationship.
i.e. src_label -> edge_label -> dst_label
"""
def __init__(
self,
loader,
properties=None,
src_label: str = "_",
dst_label: str = "_",
src_field: Union[str, int] = 0,
dst_field: Union[str, int] = 1,
load_strategy="both_out_in",
id_type: str = "int64_t",
):
if isinstance(loader, Loader):
self.loader = loader
else:
self.loader = Loader(loader)
# raw properties passed by user parameters
self.raw_properties = properties
# finally properties for constructing graph
self.properties = []
# type of vertex original id
# should be consistent with the original graph
self.id_type = id_type
self.src_label = src_label
self.dst_label = dst_label
self.src_field = src_field
self.dst_field = dst_field
# check avaiable
check_argument(
load_strategy in ("only_out", "only_in", "both_out_in"),
"invalid load strategy: " + load_strategy,
)
self.load_strategy = load_strategy
if (isinstance(self.src_field, int) and isinstance(self.dst_field, str)) or (
isinstance(self.src_field, str) and isinstance(self.dst_field, int)
):
print("src field", self.src_field, "dst_field", self.dst_field)
raise SyntaxError(
"Source vid and destination vid must have same formats, both use name or both use index"
)
# normalize properties
# add src/dst to property list
self.add_property(str(self.src_field), self.id_type)
self.add_property(str(self.dst_field), self.id_type)
if self.raw_properties:
self.add_properties(self.raw_properties)
elif self.loader.deduced_properties:
self.add_properties(self.loader.deduced_properties)
# set selected columns to loader
self.loader.select_columns(
self.properties, include_all=bool(self.raw_properties is None)
)
def __str__(self) -> str:
s = "\ntype: EdgeSubLabel"
s += "\nsource_label: " + self.src_label
s += "\ndestination_label: " + self.dst_label
s += "\nproperties: " + str(self.properties)
s += "\nloader: " + repr(self.loader)
return s
def __repr__(self) -> str:
return self.__str__()
def add_property(self, prop: str, dtype=None) -> None:
"""prop is a str, representing name. It can optionally have a type."""
self.properties.append((prop, utils.unify_type(dtype)))
def add_properties(self, properties: Sequence) -> None:
for prop in properties:
if isinstance(prop, str):
self.add_property(prop)
else:
self.add_property(prop[0], prop[1])
def get_attr(self):
attr_list = attr_value_pb2.NameAttrList()
attr_list.name = "{}_{}".format(self.src_label, self.dst_label)
attr_list.attr[types_pb2.SRC_LABEL].CopyFrom(utils.s_to_attr(self.src_label))
attr_list.attr[types_pb2.DST_LABEL].CopyFrom(utils.s_to_attr(self.dst_label))
attr_list.attr[types_pb2.LOAD_STRATEGY].CopyFrom(
utils.s_to_attr(self.load_strategy)
)
attr_list.attr[types_pb2.SRC_VID].CopyFrom(utils.s_to_attr(str(self.src_field)))
attr_list.attr[types_pb2.DST_VID].CopyFrom(utils.s_to_attr(str(self.dst_field)))
attr_list.attr[types_pb2.LOADER].CopyFrom(self.loader.get_attr())
props = []
for prop in self.properties[2:]:
prop_attr = attr_value_pb2.NameAttrList()
prop_attr.name = prop[0]
prop_attr.attr[0].CopyFrom(utils.type_to_attr(prop[1]))
props.append(prop_attr)
attr_list.attr[types_pb2.PROPERTIES].list.func.extend(props)
return attr_list
class EdgeLabel(object):
"""Hold meta informations of an edge label.
An Edge label may be consist of a few `EdgeSubLabel`s.
i.e. src_label1 -> edge_label -> dst_label1
src_label2 -> edge_label -> dst_label2
src_label3 -> edge_label -> dst_label3
"""
def __init__(self, label: str, id_type: str, session_id=None):
self.label = label
# type of vertex original id
# should be consistent with the original graph
self.id_type = id_type
self.sub_labels = {}
self._session_id = session_id
def __str__(self):
s = "\ntype: EdgeLabel"
s += "\nlabel: " + self.label
s += "\nsub_labels: "
for sub_label in self.sub_labels.values():
s += "\n"
s += str(sub_label)
return s
def __repr__(self):
return self.__str__()
def add_sub_label(self, sub_label):
src = sub_label.src_label
dst = sub_label.dst_label
if (src, dst) in self.sub_labels:
raise ValueError(
f"The relationship {src} -> {self.label} <- {dst} already existed in graph."
)
self.sub_labels[(src, dst)] = sub_label
def attr(self) -> attr_value_pb2.NameAttrList:
attr_list = attr_value_pb2.NameAttrList()
attr_list.name = "edge"
attr_list.attr[types_pb2.LABEL].CopyFrom(utils.s_to_attr(self.label))
sub_label_attr = [
sub_label.get_attr() for sub_label in self.sub_labels.values()
]
attr_list.attr[types_pb2.SUB_LABEL].list.func.extend(sub_label_attr)
return attr_list
def _convert_array_to_deprecated_form(items):
compat_items = []
# for i in range(len(items)):
for i, item in enumerate(items):
if i < 2:
compat_items.append(item)
elif i == 2:
if isinstance(item, (int, str)) and isinstance(items[i + 1], (int, str)):
compat_items.append("_")
compat_items.append("_")
compat_items.append(item)
compat_items.append(items[i + 1])
else:
assert len(item) == 2 and len(items[i + 1]) == 2
compat_items.append(item[1])
compat_items.append(items[i + 1][1])
compat_items.append(item[0])
compat_items.append(items[i + 1][0])
elif i == 3:
pass
else:
compat_items.append(item)
return compat_items
def _convert_dict_to_compat_form(items):
if "source" in items:
if isinstance(items["source"], (int, str)):
items["src_label"] = "_"
items["src_field"] = items["source"]
else:
assert len(items["source"]) == 2
items["src_label"] = items["source"][1]
items["src_field"] = items["source"][0]
items.pop("source")
if "destination" in items:
if isinstance(items["destination"], (int, str)):
items["dst_label"] = "_"
items["dst_field"] = items["destination"]
else:
assert len(items["destination"]) == 2
items["dst_label"] = items["destination"][1]
items["dst_field"] = items["destination"][0]
items.pop("destination")
return items
def normalize_parameter_edges(
edges: Union[
Mapping[str, Union[Sequence, LoaderVariants, Mapping]], Tuple, LoaderVariants
],
id_type: str,
):
"""Normalize parameters user passed in. Since parameters are very flexible, we need to be
careful about it.
Args:
edges (Union[ Mapping[str, Union[Sequence, LoaderVariants, Mapping]], Tuple, LoaderVariants ]):
Edges definition.
id_type (str): Type of vertex original id.
"""
def process_sub_label(items):
if isinstance(items, (Loader, str, pd.DataFrame, *VineyardObjectTypes)):
return EdgeSubLabel(items, None, "_", "_", 0, 1, id_type=id_type)
elif isinstance(items, Sequence):
if all([isinstance(item, np.ndarray) for item in items]):
return EdgeSubLabel(items, None, "_", "_", 0, 1, id_type=id_type)
else:
check_argument(len(items) < 6, "Too many arguments for a edge label")
compat_items = _convert_array_to_deprecated_form(items)
return EdgeSubLabel(*compat_items, id_type=id_type)
elif isinstance(items, Mapping):
items = _convert_dict_to_compat_form(items)
return EdgeSubLabel(**items, id_type=id_type)
else:
raise SyntaxError("Wrong format of e sub label: " + str(items))
def process_label(label, items):
e_label = EdgeLabel(label, id_type)
if isinstance(items, (Loader, str, pd.DataFrame, *VineyardObjectTypes)):
e_label.add_sub_label(process_sub_label(items))
elif isinstance(items, Sequence):
if isinstance(
items[0], (Loader, str, pd.DataFrame, *VineyardObjectTypes, np.ndarray)
):
e_label.add_sub_label(process_sub_label(items))
else:
for item in items:
e_label.add_sub_label(process_sub_label(item))
elif isinstance(items, Mapping):
e_label.add_sub_label(process_sub_label(items))
else:
raise SyntaxError("Wrong format of e label: " + str(items))
return e_label
e_labels = []
if edges is None:
raise ValueError("Edges should be None")
if isinstance(edges, Mapping):
for label, attr in edges.items():
e_labels.append(process_label(label, attr))
else:
e_labels.append(process_label("_", edges))
return e_labels
def normalize_parameter_vertices(
vertices: Union[
Mapping[str, Union[Sequence, LoaderVariants, Mapping]],
Tuple,
LoaderVariants,
None,
],
id_type: str,
):
"""Normalize parameters user passed in. Since parameters are very flexible, we need to be
careful about it.
Args:
vertices (Union[ Mapping[str, Union[Sequence, LoaderVariants, Mapping]], Tuple, LoaderVariants, None, ]):
Vertices definition.
id_type (str): Type of vertex original id.
"""
def process_label(label, items):
if isinstance(items, (Loader, str, pd.DataFrame, *VineyardObjectTypes)):
return VertexLabel(label=label, id_type=id_type, loader=items)
elif isinstance(items, Sequence):
if all([isinstance(item, np.ndarray) for item in items]):
return VertexLabel(label=label, id_type=id_type, loader=items)
else:
check_argument(len(items) < 4, "Too many arguments for a vertex label")
return VertexLabel(label, *items, id_type=id_type)
elif isinstance(items, Mapping):
if "vid" in items:
items["vid_field"] = items["vid"]
items.pop("vid")
return VertexLabel(label, id_type=id_type, **items)
else:
raise RuntimeError("Wrong format of v label: " + str(items))
v_labels = []
if vertices is None:
return v_labels
if isinstance(vertices, Mapping):
for label, attr in vertices.items():
v_labels.append(process_label(label, attr))
else:
v_labels.append(process_label("_", vertices))
return v_labels
|
[
"graphscope.framework.errors.check_argument",
"graphscope.proto.attr_value_pb2.NameAttrList",
"graphscope.framework.utils.unify_type",
"graphscope.framework.utils.s_to_attr",
"graphscope.framework.utils.type_to_attr",
"graphscope.framework.loader.Loader"
] |
[((3883, 3912), 'graphscope.proto.attr_value_pb2.NameAttrList', 'attr_value_pb2.NameAttrList', ([], {}), '()\n', (3910, 3912), False, 'from graphscope.proto import attr_value_pb2\n'), ((5561, 5680), 'graphscope.framework.errors.check_argument', 'check_argument', (["(load_strategy in ('only_out', 'only_in', 'both_out_in'))", "('invalid load strategy: ' + load_strategy)"], {}), "(load_strategy in ('only_out', 'only_in', 'both_out_in'), \n 'invalid load strategy: ' + load_strategy)\n", (5575, 5680), False, 'from graphscope.framework.errors import check_argument\n'), ((7541, 7570), 'graphscope.proto.attr_value_pb2.NameAttrList', 'attr_value_pb2.NameAttrList', ([], {}), '()\n', (7568, 7570), False, 'from graphscope.proto import attr_value_pb2\n'), ((9814, 9843), 'graphscope.proto.attr_value_pb2.NameAttrList', 'attr_value_pb2.NameAttrList', ([], {}), '()\n', (9841, 9843), False, 'from graphscope.proto import attr_value_pb2\n'), ((2075, 2089), 'graphscope.framework.loader.Loader', 'Loader', (['loader'], {}), '(loader)\n', (2081, 2089), False, 'from graphscope.framework.loader import Loader\n'), ((3996, 4023), 'graphscope.framework.utils.s_to_attr', 'utils.s_to_attr', (['self.label'], {}), '(self.label)\n', (4011, 4023), False, 'from graphscope.framework import utils\n'), ((4194, 4223), 'graphscope.proto.attr_value_pb2.NameAttrList', 'attr_value_pb2.NameAttrList', ([], {}), '()\n', (4221, 4223), False, 'from graphscope.proto import attr_value_pb2\n'), ((5077, 5091), 'graphscope.framework.loader.Loader', 'Loader', (['loader'], {}), '(loader)\n', (5083, 5091), False, 'from graphscope.framework.loader import Loader\n'), ((7696, 7727), 'graphscope.framework.utils.s_to_attr', 'utils.s_to_attr', (['self.src_label'], {}), '(self.src_label)\n', (7711, 7727), False, 'from graphscope.framework import utils\n'), ((7782, 7813), 'graphscope.framework.utils.s_to_attr', 'utils.s_to_attr', (['self.dst_label'], {}), '(self.dst_label)\n', (7797, 7813), False, 'from graphscope.framework import utils\n'), ((7885, 7920), 'graphscope.framework.utils.s_to_attr', 'utils.s_to_attr', (['self.load_strategy'], {}), '(self.load_strategy)\n', (7900, 7920), False, 'from graphscope.framework import utils\n'), ((8269, 8298), 'graphscope.proto.attr_value_pb2.NameAttrList', 'attr_value_pb2.NameAttrList', ([], {}), '()\n', (8296, 8298), False, 'from graphscope.proto import attr_value_pb2\n'), ((9925, 9952), 'graphscope.framework.utils.s_to_attr', 'utils.s_to_attr', (['self.label'], {}), '(self.label)\n', (9940, 9952), False, 'from graphscope.framework import utils\n'), ((3544, 3567), 'graphscope.framework.utils.unify_type', 'utils.unify_type', (['dtype'], {}), '(dtype)\n', (3560, 3567), False, 'from graphscope.framework import utils\n'), ((4300, 4327), 'graphscope.framework.utils.type_to_attr', 'utils.type_to_attr', (['prop[1]'], {}), '(prop[1])\n', (4318, 4327), False, 'from graphscope.framework import utils\n'), ((7229, 7252), 'graphscope.framework.utils.unify_type', 'utils.unify_type', (['dtype'], {}), '(dtype)\n', (7245, 7252), False, 'from graphscope.framework import utils\n'), ((8375, 8402), 'graphscope.framework.utils.type_to_attr', 'utils.type_to_attr', (['prop[1]'], {}), '(prop[1])\n', (8393, 8402), False, 'from graphscope.framework import utils\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
import numpy as np
import pytest
import graphscope
import graphscope.nx as nx
from graphscope import property_sssp
from graphscope import sssp
from graphscope.client.session import default_session
from graphscope.dataset import load_ldbc
from graphscope.dataset import load_modern_graph
from graphscope.framework.graph import Graph
from graphscope.framework.loader import Loader
@pytest.fixture(scope="module")
def graphscope_session():
graphscope.set_option(show_log=True)
graphscope.set_option(initializing_interactive_engine=False)
sess = graphscope.session(cluster_type="hosts")
yield sess
sess.close()
test_repo_dir = os.path.expandvars("${GS_TEST_DIR}")
new_property_dir = os.path.join(test_repo_dir, "new_property", "v2_e2")
property_dir = os.path.join(test_repo_dir, "property")
@pytest.fixture(scope="module")
def arrow_modern_graph(graphscope_session):
graph = load_modern_graph(
graphscope_session, prefix="{}/modern_graph".format(test_repo_dir)
)
yield graph
graph.unload()
@pytest.fixture(scope="module")
def modern_person():
return "{}/modern_graph/person.csv".format(test_repo_dir)
@pytest.fixture(scope="module")
def modern_software():
return "{}/modern_graph/software.csv".format(test_repo_dir)
@pytest.fixture(scope="module")
def twitter_v_0():
return "{}/twitter_v_0".format(new_property_dir)
@pytest.fixture(scope="module")
def modern_graph():
return "{}/modern_graph".format(test_repo_dir)
@pytest.fixture(scope="module")
def ldbc_sample():
return "{}/ldbc_sample".format(test_repo_dir)
@pytest.fixture(scope="module")
def p2p_property():
return "{}/property".format(test_repo_dir)
@pytest.fixture(scope="module")
def ogbn_mag_small():
return "{}/ogbn_mag_small".format(test_repo_dir)
@pytest.fixture(scope="module")
def twitter_v_1():
return "{}/twitter_v_1".format(new_property_dir)
@pytest.fixture(scope="module")
def twitter_e_0_0_0():
return "{}/twitter_e_0_0_0".format(new_property_dir)
@pytest.fixture(scope="module")
def twitter_e_0_1_0():
return "{}/twitter_e_0_1_0".format(new_property_dir)
@pytest.fixture(scope="module")
def twitter_e_1_0_0():
return "{}/twitter_e_1_0_0".format(new_property_dir)
@pytest.fixture(scope="module")
def twitter_e_1_1_0():
return "{}/twitter_e_1_1_0".format(new_property_dir)
@pytest.fixture(scope="module")
def twitter_e_0_0_1():
return "{}/twitter_e_0_0_1".format(new_property_dir)
@pytest.fixture(scope="module")
def twitter_e_0_1_1():
return "{}/twitter_e_0_1_1".format(new_property_dir)
@pytest.fixture(scope="module")
def twitter_e_1_0_1():
return "{}/twitter_e_1_0_1".format(new_property_dir)
@pytest.fixture(scope="module")
def twitter_e_1_1_1():
return "{}/twitter_e_1_1_1".format(new_property_dir)
@pytest.fixture(scope="module")
def arrow_property_graph(graphscope_session):
g = graphscope_session.load_from(
edges={
"e0": [
(
Loader(
"{}/twitter_e_0_0_0".format(new_property_dir),
header_row=True,
delimiter=",",
),
["weight"],
("src", "v0"),
("dst", "v0"),
),
(
Loader(
"{}/twitter_e_0_1_0".format(new_property_dir),
header_row=True,
delimiter=",",
),
["weight"],
("src", "v0"),
("dst", "v1"),
),
(
Loader(
"{}/twitter_e_1_0_0".format(new_property_dir),
header_row=True,
delimiter=",",
),
["weight"],
("src", "v1"),
("dst", "v0"),
),
(
Loader(
"{}/twitter_e_1_1_0".format(new_property_dir),
header_row=True,
delimiter=",",
),
["weight"],
("src", "v1"),
("dst", "v1"),
),
],
"e1": [
(
Loader(
"{}/twitter_e_0_0_1".format(new_property_dir),
header_row=True,
delimiter=",",
),
["weight"],
("src", "v0"),
("dst", "v0"),
),
(
Loader(
"{}/twitter_e_0_1_1".format(new_property_dir),
header_row=True,
delimiter=",",
),
["weight"],
("src", "v0"),
("dst", "v1"),
),
(
Loader(
"{}/twitter_e_1_0_1".format(new_property_dir),
header_row=True,
delimiter=",",
),
["weight"],
("src", "v1"),
("dst", "v0"),
),
(
Loader(
"{}/twitter_e_1_1_1".format(new_property_dir),
header_row=True,
delimiter=",",
),
["weight"],
("src", "v1"),
("dst", "v1"),
),
],
},
vertices={
"v0": Loader("{}/twitter_v_0".format(new_property_dir), header_row=True),
"v1": Loader("{}/twitter_v_1".format(new_property_dir), header_row=True),
},
generate_eid=False,
)
yield g
g.unload()
@pytest.fixture(scope="module")
def arrow_property_graph_only_from_efile(graphscope_session):
g = graphscope_session.load_from(
edges={
"e0": [
(
Loader(
"{}/twitter_e_0_0_0".format(new_property_dir),
header_row=True,
delimiter=",",
),
["weight"],
("src", "v0"),
("dst", "v0"),
),
(
Loader(
"{}/twitter_e_0_1_0".format(new_property_dir),
header_row=True,
delimiter=",",
),
["weight"],
("src", "v0"),
("dst", "v1"),
),
(
Loader(
"{}/twitter_e_1_0_0".format(new_property_dir),
header_row=True,
delimiter=",",
),
["weight"],
("src", "v1"),
("dst", "v0"),
),
(
Loader(
"{}/twitter_e_1_1_0".format(new_property_dir),
header_row=True,
delimiter=",",
),
["weight"],
("src", "v1"),
("dst", "v1"),
),
],
"e1": [
(
Loader(
"{}/twitter_e_0_0_1".format(new_property_dir),
header_row=True,
delimiter=",",
),
["weight"],
("src", "v0"),
("dst", "v0"),
),
(
Loader(
"{}/twitter_e_0_1_1".format(new_property_dir),
header_row=True,
delimiter=",",
),
["weight"],
("src", "v0"),
("dst", "v1"),
),
(
Loader(
"{}/twitter_e_1_0_1".format(new_property_dir),
header_row=True,
delimiter=",",
),
["weight"],
("src", "v1"),
("dst", "v0"),
),
(
Loader(
"{}/twitter_e_1_1_1".format(new_property_dir),
header_row=True,
delimiter=",",
),
["weight"],
("src", "v1"),
("dst", "v1"),
),
],
},
generate_eid=False,
)
yield g
g.unload()
# @pytest.fixture(scope="module")
# def arrow_property_graph(graphscope_session):
# g = graphscope_session.g(generate_eid=False)
# g = g.add_vertices(f"{new_property_dir}/twitter_v_0", "v0")
# g = g.add_vertices(f"{new_property_dir}/twitter_v_1", "v1")
# g = g.add_edges(f"{new_property_dir}/twitter_e_0_0_0", "e0", ["weight"], "v0", "v0")
# g = g.add_edges(f"{new_property_dir}/twitter_e_0_1_0", "e0", ["weight"], "v0", "v1")
# g = g.add_edges(f"{new_property_dir}/twitter_e_1_0_0", "e0", ["weight"], "v1", "v0")
# g = g.add_edges(f"{new_property_dir}/twitter_e_1_1_0", "e0", ["weight"], "v1", "v1")
# g = g.add_edges(f"{new_property_dir}/twitter_e_0_0_1", "e1", ["weight"], "v0", "v0")
# g = g.add_edges(f"{new_property_dir}/twitter_e_0_1_1", "e1", ["weight"], "v0", "v1")
# g = g.add_edges(f"{new_property_dir}/twitter_e_1_0_1", "e1", ["weight"], "v1", "v0")
# g = g.add_edges(f"{new_property_dir}/twitter_e_1_1_1", "e1", ["weight"], "v1", "v1")
# yield g
# g.unload()
# @pytest.fixture(scope="module")
# def arrow_property_graph_only_from_efile(graphscope_session):
# g = graphscope_session.g(generate_eid=False)
# g = g.add_edges(f"{new_property_dir}/twitter_e_0_0_0", "e0", ["weight"], "v0", "v0")
# g = g.add_edges(f"{new_property_dir}/twitter_e_0_1_0", "e0", ["weight"], "v0", "v1")
# g = g.add_edges(f"{new_property_dir}/twitter_e_1_0_0", "e0", ["weight"], "v1", "v0")
# g = g.add_edges(f"{new_property_dir}/twitter_e_1_1_0", "e0", ["weight"], "v1", "v1")
# g = g.add_edges(f"{new_property_dir}/twitter_e_0_0_1", "e1", ["weight"], "v0", "v0")
# g = g.add_edges(f"{new_property_dir}/twitter_e_0_1_1", "e1", ["weight"], "v0", "v1")
# g = g.add_edges(f"{new_property_dir}/twitter_e_1_0_1", "e1", ["weight"], "v1", "v0")
# g = g.add_edges(f"{new_property_dir}/twitter_e_1_1_1", "e1", ["weight"], "v1", "v1")
# yield g
# g.unload()
@pytest.fixture(scope="module")
def arrow_property_graph_undirected(graphscope_session):
g = graphscope_session.g(directed=False, generate_eid=False)
g = g.add_vertices(f"{new_property_dir}/twitter_v_0", "v0")
g = g.add_vertices(f"{new_property_dir}/twitter_v_1", "v1")
g = g.add_edges(f"{new_property_dir}/twitter_e_0_0_0", "e0", ["weight"], "v0", "v0")
g = g.add_edges(f"{new_property_dir}/twitter_e_0_1_0", "e0", ["weight"], "v0", "v1")
g = g.add_edges(f"{new_property_dir}/twitter_e_1_0_0", "e0", ["weight"], "v1", "v0")
g = g.add_edges(f"{new_property_dir}/twitter_e_1_1_0", "e0", ["weight"], "v1", "v1")
g = g.add_edges(f"{new_property_dir}/twitter_e_0_0_1", "e1", ["weight"], "v0", "v0")
g = g.add_edges(f"{new_property_dir}/twitter_e_0_1_1", "e1", ["weight"], "v0", "v1")
g = g.add_edges(f"{new_property_dir}/twitter_e_1_0_1", "e1", ["weight"], "v1", "v0")
g = g.add_edges(f"{new_property_dir}/twitter_e_1_1_1", "e1", ["weight"], "v1", "v1")
yield g
g.unload()
@pytest.fixture(scope="module")
def arrow_property_graph_lpa(graphscope_session):
g = graphscope_session.g(generate_eid=False)
g = g.add_vertices(f"{property_dir}/lpa_dataset/lpa_3000_v_0", "v0")
g = g.add_vertices(f"{property_dir}/lpa_dataset/lpa_3000_v_1", "v1")
g = g.add_edges(
f"{property_dir}/lpa_dataset/lpa_3000_e_0", "e0", ["weight"], "v0", "v1"
)
yield g
g.unload()
@pytest.fixture(scope="module")
def arrow_project_graph(arrow_property_graph):
pg = arrow_property_graph.project(vertices={"v0": ["id"]}, edges={"e0": ["weight"]})
yield pg
@pytest.fixture(scope="module")
def arrow_project_undirected_graph(arrow_property_graph_undirected):
pg = arrow_property_graph_undirected.project(
vertices={"v0": ["id"]}, edges={"e0": ["weight"]}
)
yield pg
@pytest.fixture(scope="module")
def p2p_property_graph(graphscope_session):
g = graphscope_session.g(generate_eid=False)
g = g.add_vertices(f"{property_dir}/p2p-31_property_v_0", "person")
g = g.add_edges(
f"{property_dir}/p2p-31_property_e_0",
label="knows",
src_label="person",
dst_label="person",
)
yield g
g.unload()
@pytest.fixture(scope="module")
def p2p_property_graph_string(graphscope_session):
g = graphscope_session.g(oid_type="string", generate_eid=False)
g = g.add_vertices(f"{property_dir}/p2p-31_property_v_0", "person")
g = g.add_edges(
f"{property_dir}/p2p-31_property_e_0",
label="knows",
src_label="person",
dst_label="person",
)
yield g
g.unload()
@pytest.fixture(scope="module")
def p2p_property_graph_undirected(graphscope_session):
g = graphscope_session.g(directed=False, generate_eid=False)
g = g.add_vertices(f"{property_dir}/p2p-31_property_v_0", "person")
g = g.add_edges(
f"{property_dir}/p2p-31_property_e_0",
label="knows",
src_label="person",
dst_label="person",
)
yield g
g.unload()
@pytest.fixture(scope="module")
def p2p_project_directed_graph(p2p_property_graph):
pg = p2p_property_graph.project(
vertices={"person": ["weight"]}, edges={"knows": ["dist"]}
)
yield pg
@pytest.fixture(scope="module")
def p2p_project_undirected_graph(p2p_property_graph_undirected):
pg = p2p_property_graph_undirected.project(
vertices={"person": ["weight"]}, edges={"knows": ["dist"]}
)
yield pg
@pytest.fixture(scope="module")
def p2p_project_directed_graph_string(p2p_property_graph_string):
pg = p2p_property_graph_string.project(
vertices={"person": ["weight"]}, edges={"knows": ["dist"]}
)
yield pg
@pytest.fixture(scope="module")
def projected_pg_no_edge_data(arrow_property_graph):
pg = arrow_property_graph.project(vertices={"v0": []}, edges={"e0": []})
yield pg
@pytest.fixture(scope="module")
def dynamic_property_graph(graphscope_session):
with default_session(graphscope_session):
g = nx.Graph()
g.add_edges_from([(1, 2), (2, 3)], weight=3)
yield g
@pytest.fixture(scope="module")
def dynamic_project_graph(graphscope_session):
with default_session(graphscope_session):
g = nx.Graph()
g.add_edges_from([(1, 2), (2, 3)], weight=3)
pg = g.project_to_simple(e_prop="weight")
yield pg
@pytest.fixture(scope="module")
def arrow_empty_graph(property_dir=os.path.expandvars("${GS_TEST_DIR}/property")):
return None
@pytest.fixture(scope="module")
def append_only_graph():
return None
@pytest.fixture(scope="module")
def sssp_result():
ret = {}
ret["directed"] = np.loadtxt(
"{}/ldbc/p2p-31-SSSP-directed".format(property_dir), dtype=float
)
ret["undirected"] = np.loadtxt(
"{}/ldbc/p2p-31-SSSP".format(property_dir), dtype=float
)
yield ret
@pytest.fixture(scope="module")
def wcc_result():
ret = np.loadtxt("{}/../p2p-31-wcc_auto".format(property_dir), dtype=int)
yield ret
@pytest.fixture(scope="module")
def kshell_result():
ret = np.loadtxt("{}/../p2p-31-kshell-3".format(property_dir), dtype=int)
yield ret
@pytest.fixture(scope="module")
def pagerank_result():
ret = {}
ret["directed"] = np.loadtxt(
"{}/ldbc/p2p-31-PR-directed".format(property_dir), dtype=float
)
ret["undirected"] = np.loadtxt(
"{}/ldbc/p2p-31-PR".format(property_dir), dtype=float
)
yield ret
@pytest.fixture(scope="module")
def bfs_result():
ret = {}
ret["directed"] = np.loadtxt(
"{}/ldbc/p2p-31-BFS-directed".format(property_dir), dtype=int
)
ret["undirected"] = np.loadtxt("{}/ldbc/p2p-31-BFS".format(property_dir), dtype=int)
yield ret
@pytest.fixture(scope="module")
def cdlp_result():
ret = np.loadtxt("{}/ldbc/p2p-31-CDLP".format(property_dir), dtype=int)
yield ret
@pytest.fixture(scope="module")
def clustering_result():
ret = np.fromfile(
"{}/results/twitter_property_clustering_ndarray".format(property_dir), sep="\n"
)
yield ret
@pytest.fixture(scope="module")
def dc_result():
ret = np.fromfile(
"{}/results/twitter_property_dc_ndarray".format(property_dir), sep="\n"
)
yield ret
@pytest.fixture(scope="module")
def ev_result():
ret = np.fromfile(
"{}/results/twitter_property_ev_ndarray".format(property_dir), sep="\n"
)
yield ret
@pytest.fixture(scope="module")
def katz_result():
ret = np.fromfile(
"{}/results/twitter_property_katz_ndarray".format(property_dir), sep="\n"
)
yield ret
@pytest.fixture(scope="module")
def triangles_result():
ret = np.fromfile(
"{}/results/twitter_property_triangles_ndarray".format(property_dir),
dtype=np.int64,
sep="\n",
)
yield ret
@pytest.fixture(scope="module")
def property_context(arrow_property_graph):
return property_sssp(arrow_property_graph, 20)
@pytest.fixture(scope="module")
def simple_context(arrow_property_graph):
sg = arrow_property_graph.project(vertices={"v0": ["id"]}, edges={"e0": ["weight"]})
return sssp(sg, 20)
@pytest.fixture(scope="module")
def ldbc_graph(graphscope_session):
graph = load_ldbc(graphscope_session, prefix="{}/ldbc_sample".format(test_repo_dir))
yield graph
graph.unload()
@pytest.fixture(scope="module")
def modern_scripts():
queries = [
"g.V().has('name','marko').count()",
"g.V().has('person','name','marko').count()",
"g.V().has('person','name','marko').outE('created').count()",
"g.V().has('person','name','marko').outE('created').inV().count()",
"g.V().has('person','name','marko').out('created').count()",
"g.V().has('person','name','marko').out('created').values('name').count()",
]
return queries
@pytest.fixture(scope="module")
def modern_bytecode():
def func(g):
from gremlin_python.process.traversal import Order
from gremlin_python.process.traversal import P
assert g.V().has("name", "marko").count().toList()[0] == 1
assert g.V().has("person", "name", "marko").count().toList()[0] == 1
assert (
g.V().has("person", "name", "marko").outE("created").count().toList()[0]
== 1
)
assert (
g.V()
.has("person", "name", "marko")
.outE("created")
.inV()
.count()
.toList()[0]
== 1
)
assert (
g.V().has("person", "name", "marko").out("created").count().toList()[0] == 1
)
assert (
g.V()
.has("person", "name", "marko")
.out("created")
.values("name")
.count()
.toList()[0]
== 1
)
assert (
g.V()
.hasLabel("person")
.has("age", P.gt(30))
.order()
.by("age", Order.desc)
.count()
.toList()[0]
== 2
)
return func
|
[
"graphscope.set_option",
"graphscope.session",
"graphscope.client.session.default_session",
"pytest.fixture",
"gremlin_python.process.traversal.P.gt",
"graphscope.nx.Graph",
"os.path.expandvars",
"os.path.join",
"graphscope.sssp",
"graphscope.property_sssp"
] |
[((1061, 1091), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1075, 1091), False, 'import pytest\n'), ((1326, 1362), 'os.path.expandvars', 'os.path.expandvars', (['"""${GS_TEST_DIR}"""'], {}), "('${GS_TEST_DIR}')\n", (1344, 1362), False, 'import os\n'), ((1382, 1434), 'os.path.join', 'os.path.join', (['test_repo_dir', '"""new_property"""', '"""v2_e2"""'], {}), "(test_repo_dir, 'new_property', 'v2_e2')\n", (1394, 1434), False, 'import os\n'), ((1450, 1489), 'os.path.join', 'os.path.join', (['test_repo_dir', '"""property"""'], {}), "(test_repo_dir, 'property')\n", (1462, 1489), False, 'import os\n'), ((1493, 1523), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1507, 1523), False, 'import pytest\n'), ((1718, 1748), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1732, 1748), False, 'import pytest\n'), ((1835, 1865), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1849, 1865), False, 'import pytest\n'), ((1956, 1986), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1970, 1986), False, 'import pytest\n'), ((2062, 2092), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (2076, 2092), False, 'import pytest\n'), ((2167, 2197), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (2181, 2197), False, 'import pytest\n'), ((2270, 2300), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (2284, 2300), False, 'import pytest\n'), ((2371, 2401), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (2385, 2401), False, 'import pytest\n'), ((2480, 2510), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (2494, 2510), False, 'import pytest\n'), ((2586, 2616), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (2600, 2616), False, 'import pytest\n'), ((2700, 2730), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (2714, 2730), False, 'import pytest\n'), ((2814, 2844), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (2828, 2844), False, 'import pytest\n'), ((2928, 2958), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (2942, 2958), False, 'import pytest\n'), ((3042, 3072), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (3056, 3072), False, 'import pytest\n'), ((3156, 3186), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (3170, 3186), False, 'import pytest\n'), ((3270, 3300), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (3284, 3300), False, 'import pytest\n'), ((3384, 3414), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (3398, 3414), False, 'import pytest\n'), ((3498, 3528), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (3512, 3528), False, 'import pytest\n'), ((6704, 6734), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (6718, 6734), False, 'import pytest\n'), ((11566, 11596), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (11580, 11596), False, 'import pytest\n'), ((12590, 12620), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (12604, 12620), False, 'import pytest\n'), ((13004, 13034), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (13018, 13034), False, 'import pytest\n'), ((13187, 13217), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (13201, 13217), False, 'import pytest\n'), ((13417, 13447), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (13431, 13447), False, 'import pytest\n'), ((13796, 13826), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (13810, 13826), False, 'import pytest\n'), ((14201, 14231), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (14215, 14231), False, 'import pytest\n'), ((14607, 14637), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (14621, 14637), False, 'import pytest\n'), ((14816, 14846), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (14830, 14846), False, 'import pytest\n'), ((15049, 15079), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (15063, 15079), False, 'import pytest\n'), ((15279, 15309), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (15293, 15309), False, 'import pytest\n'), ((15456, 15486), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (15470, 15486), False, 'import pytest\n'), ((15668, 15698), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (15682, 15698), False, 'import pytest\n'), ((15926, 15956), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (15940, 15956), False, 'import pytest\n'), ((16059, 16089), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (16073, 16089), False, 'import pytest\n'), ((16134, 16164), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (16148, 16164), False, 'import pytest\n'), ((16433, 16463), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (16447, 16463), False, 'import pytest\n'), ((16577, 16607), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (16591, 16607), False, 'import pytest\n'), ((16724, 16754), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (16738, 16754), False, 'import pytest\n'), ((17023, 17053), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (17037, 17053), False, 'import pytest\n'), ((17301, 17331), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (17315, 17331), False, 'import pytest\n'), ((17444, 17474), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (17458, 17474), False, 'import pytest\n'), ((17634, 17664), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (17648, 17664), False, 'import pytest\n'), ((17808, 17838), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (17822, 17838), False, 'import pytest\n'), ((17982, 18012), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (17996, 18012), False, 'import pytest\n'), ((18160, 18190), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (18174, 18190), False, 'import pytest\n'), ((18381, 18411), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (18395, 18411), False, 'import pytest\n'), ((18510, 18540), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (18524, 18540), False, 'import pytest\n'), ((18699, 18729), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (18713, 18729), False, 'import pytest\n'), ((18893, 18923), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (18907, 18923), False, 'import pytest\n'), ((19388, 19418), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (19402, 19418), False, 'import pytest\n'), ((1122, 1158), 'graphscope.set_option', 'graphscope.set_option', ([], {'show_log': '(True)'}), '(show_log=True)\n', (1143, 1158), False, 'import graphscope\n'), ((1163, 1223), 'graphscope.set_option', 'graphscope.set_option', ([], {'initializing_interactive_engine': '(False)'}), '(initializing_interactive_engine=False)\n', (1184, 1223), False, 'import graphscope\n'), ((1235, 1275), 'graphscope.session', 'graphscope.session', ([], {'cluster_type': '"""hosts"""'}), "(cluster_type='hosts')\n", (1253, 1275), False, 'import graphscope\n'), ((15992, 16037), 'os.path.expandvars', 'os.path.expandvars', (['"""${GS_TEST_DIR}/property"""'], {}), "('${GS_TEST_DIR}/property')\n", (16010, 16037), False, 'import os\n'), ((18467, 18506), 'graphscope.property_sssp', 'property_sssp', (['arrow_property_graph', '(20)'], {}), '(arrow_property_graph, 20)\n', (18480, 18506), False, 'from graphscope import property_sssp\n'), ((18683, 18695), 'graphscope.sssp', 'sssp', (['sg', '(20)'], {}), '(sg, 20)\n', (18687, 18695), False, 'from graphscope import sssp\n'), ((15544, 15579), 'graphscope.client.session.default_session', 'default_session', (['graphscope_session'], {}), '(graphscope_session)\n', (15559, 15579), False, 'from graphscope.client.session import default_session\n'), ((15593, 15603), 'graphscope.nx.Graph', 'nx.Graph', ([], {}), '()\n', (15601, 15603), True, 'import graphscope.nx as nx\n'), ((15755, 15790), 'graphscope.client.session.default_session', 'default_session', (['graphscope_session'], {}), '(graphscope_session)\n', (15770, 15790), False, 'from graphscope.client.session import default_session\n'), ((15804, 15814), 'graphscope.nx.Graph', 'nx.Graph', ([], {}), '()\n', (15812, 15814), True, 'import graphscope.nx as nx\n'), ((20462, 20470), 'gremlin_python.process.traversal.P.gt', 'P.gt', (['(30)'], {}), '(30)\n', (20466, 20470), False, 'from gremlin_python.process.traversal import P\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from graphscope.framework.app import AppAssets
from graphscope.framework.app import not_compatible_for
__all__ = [
"property_dump",
]
@not_compatible_for("dynamic_property", "arrow_projected", "dynamic_projected")
def property_dump(graph, out_prefix="/tmp/dump_graph", write_eid=False):
"""Compute single source shortest path on graph G.
Args:
graph (Graph): a property graph.
src (int, optional): the source. Defaults to 0.
Returns:
:class:`graphscope.framework.context.LabeledVertexDataContext`:
A context with each vertex assigned with the shortest distance from the src, evaluated in eager mode.
"""
return AppAssets(algo="property_dump", context="labeled_vertex_data")(graph, out_prefix, write_eid)
|
[
"graphscope.framework.app.AppAssets",
"graphscope.framework.app.not_compatible_for"
] |
[((809, 887), 'graphscope.framework.app.not_compatible_for', 'not_compatible_for', (['"""dynamic_property"""', '"""arrow_projected"""', '"""dynamic_projected"""'], {}), "('dynamic_property', 'arrow_projected', 'dynamic_projected')\n", (827, 887), False, 'from graphscope.framework.app import not_compatible_for\n'), ((1343, 1405), 'graphscope.framework.app.AppAssets', 'AppAssets', ([], {'algo': '"""property_dump"""', 'context': '"""labeled_vertex_data"""'}), "(algo='property_dump', context='labeled_vertex_data')\n", (1352, 1405), False, 'from graphscope.framework.app import AppAssets\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# fmt: off
import pytest
from networkx import adjacency_matrix
from networkx.generators.tests.test_expanders import test_chordal_cycle_graph
from networkx.generators.tests.test_expanders import test_margulis_gabber_galil_graph
from networkx.generators.tests.test_expanders import \
test_margulis_gabber_galil_graph_badinput
#fmt: off
try:
from networkx.generators.tests.test_expanders import test_paley_graph
except ImportError:
# NetworkX<=2.4 not contains paley_graph
test_paley_graph = lambda: None
import graphscope.nx as nx
from graphscope.nx import number_of_nodes
from graphscope.nx.generators.expanders import chordal_cycle_graph
from graphscope.nx.generators.expanders import margulis_gabber_galil_graph
from graphscope.nx.utils.compat import with_graphscope_nx_context
try:
from graphscope.nx.generators.expanders import paley_graph
except ImportError:
# NetworkX <= 2.4
pass
@pytest.mark.usefixtures("graphscope_session")
def test_margulis_gabber_galil_graph():
for n in 2, 3, 5, 6, 10:
g = margulis_gabber_galil_graph(n)
assert number_of_nodes(g) == n * n
for node in g:
assert g.degree(node) == 8
assert len(node) == 2
for i in node:
assert int(i) == i
assert 0 <= i < n
np = pytest.importorskip("numpy")
# scipy submodule has to import explicitly
linalg = pytest.importorskip("scipy.linalg")
# Eigenvalues are already sorted using the scipy eigvalsh,
# but the implementation in numpy does not guarantee order.
w = sorted(linalg.eigvalsh(adjacency_matrix(g).A))
assert w[-2] < 5 * np.sqrt(2)
@pytest.mark.usefixtures("graphscope_session")
@with_graphscope_nx_context(test_chordal_cycle_graph)
def test_chordal_cycle_graph():
pass
@pytest.mark.usefixtures("graphscope_session")
@with_graphscope_nx_context(test_margulis_gabber_galil_graph_badinput)
def test_margulis_gabber_galil_graph_badinput():
pass
@pytest.mark.usefixtures("graphscope_session")
@with_graphscope_nx_context(test_paley_graph)
def test_paley_graph():
pass
|
[
"networkx.adjacency_matrix",
"graphscope.nx.generators.expanders.margulis_gabber_galil_graph",
"pytest.importorskip",
"graphscope.nx.utils.compat.with_graphscope_nx_context",
"graphscope.nx.number_of_nodes",
"pytest.mark.usefixtures"
] |
[((1589, 1634), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (1612, 1634), False, 'import pytest\n'), ((2336, 2381), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (2359, 2381), False, 'import pytest\n'), ((2383, 2435), 'graphscope.nx.utils.compat.with_graphscope_nx_context', 'with_graphscope_nx_context', (['test_chordal_cycle_graph'], {}), '(test_chordal_cycle_graph)\n', (2409, 2435), False, 'from graphscope.nx.utils.compat import with_graphscope_nx_context\n'), ((2480, 2525), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (2503, 2525), False, 'import pytest\n'), ((2527, 2596), 'graphscope.nx.utils.compat.with_graphscope_nx_context', 'with_graphscope_nx_context', (['test_margulis_gabber_galil_graph_badinput'], {}), '(test_margulis_gabber_galil_graph_badinput)\n', (2553, 2596), False, 'from graphscope.nx.utils.compat import with_graphscope_nx_context\n'), ((2658, 2703), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (2681, 2703), False, 'import pytest\n'), ((2705, 2749), 'graphscope.nx.utils.compat.with_graphscope_nx_context', 'with_graphscope_nx_context', (['test_paley_graph'], {}), '(test_paley_graph)\n', (2731, 2749), False, 'from graphscope.nx.utils.compat import with_graphscope_nx_context\n'), ((1992, 2020), 'pytest.importorskip', 'pytest.importorskip', (['"""numpy"""'], {}), "('numpy')\n", (2011, 2020), False, 'import pytest\n'), ((2081, 2116), 'pytest.importorskip', 'pytest.importorskip', (['"""scipy.linalg"""'], {}), "('scipy.linalg')\n", (2100, 2116), False, 'import pytest\n'), ((1716, 1746), 'graphscope.nx.generators.expanders.margulis_gabber_galil_graph', 'margulis_gabber_galil_graph', (['n'], {}), '(n)\n', (1743, 1746), False, 'from graphscope.nx.generators.expanders import margulis_gabber_galil_graph\n'), ((1762, 1780), 'graphscope.nx.number_of_nodes', 'number_of_nodes', (['g'], {}), '(g)\n', (1777, 1780), False, 'from graphscope.nx import number_of_nodes\n'), ((2275, 2294), 'networkx.adjacency_matrix', 'adjacency_matrix', (['g'], {}), '(g)\n', (2291, 2294), False, 'from networkx import adjacency_matrix\n')]
|
# -*- coding: utf-8 -*-
#
# This file random_graphs.py is referred and derived from project NetworkX,
#
# https://github.com/networkx/networkx/blob/master/networkx/generators/random_graphs.py
#
# which has the following license:
#
# Copyright (C) 2004-2020, NetworkX Developers
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# All rights reserved.
#
# This file is part of NetworkX.
#
# NetworkX is distributed under a BSD license; see LICENSE.txt for more
# information.
#
"""
Generators for random graphs.
"""
import itertools
import math
from collections import defaultdict
import networkx as nxa
from networkx.utils import powerlaw_sequence
from networkx.utils import py_random_state
from graphscope import nx
from graphscope.nx.generators.classic import complete_graph
from graphscope.nx.generators.classic import empty_graph
from graphscope.nx.generators.classic import path_graph
from graphscope.nx.generators.degree_seq import degree_sequence_tree
from graphscope.nx.utils.compat import patch_docstring
__all__ = [
"fast_gnp_random_graph",
"gnp_random_graph",
"dense_gnm_random_graph",
"gnm_random_graph",
"erdos_renyi_graph",
"binomial_graph",
"newman_watts_strogatz_graph",
"watts_strogatz_graph",
"connected_watts_strogatz_graph",
"random_regular_graph",
"barabasi_albert_graph",
"dual_barabasi_albert_graph",
"extended_barabasi_albert_graph",
"powerlaw_cluster_graph",
"random_lobster",
"random_shell_graph",
"random_powerlaw_tree",
"random_powerlaw_tree_sequence",
"random_kernel_graph",
]
# -------------------------------------------------------------------------
# Some Famous Random Graphs
# -------------------------------------------------------------------------
@patch_docstring(nxa.fast_gnp_random_graph)
@py_random_state(2)
def fast_gnp_random_graph(n, p, seed=None, directed=False):
G = empty_graph(n)
if p <= 0 or p >= 1:
return nx.gnp_random_graph(n, p, seed=seed, directed=directed)
w = -1
lp = math.log(1.0 - p)
if directed:
G = nx.DiGraph(G)
# Nodes in graph are from 0,n-1 (start with v as the first node index).
v = 0
while v < n:
lr = math.log(1.0 - seed.random())
w = w + 1 + int(lr / lp)
if v == w: # avoid self loops
w = w + 1
while v < n <= w:
w = w - n
v = v + 1
if v == w: # avoid self loops
w = w + 1
if v < n:
G.add_edge(v, w)
else:
# Nodes in graph are from 0,n-1 (start with v as the second node index).
v = 1
while v < n:
lr = math.log(1.0 - seed.random())
w = w + 1 + int(lr / lp)
while w >= v and v < n:
w = w - v
v = v + 1
if v < n:
G.add_edge(v, w)
return G
@patch_docstring(nxa.gnp_random_graph)
@py_random_state(2)
def gnp_random_graph(n, p, seed=None, directed=False):
if directed:
edges = itertools.permutations(range(n), 2)
G = nx.DiGraph()
else:
edges = itertools.combinations(range(n), 2)
G = nx.Graph()
G.add_nodes_from(range(n))
if p <= 0:
return G
if p >= 1:
return complete_graph(n, create_using=G)
for e in edges:
if seed.random() < p:
G.add_edge(*e)
return G
# add some aliases to common names
binomial_graph = gnp_random_graph
erdos_renyi_graph = gnp_random_graph
@patch_docstring(nxa.dense_gnm_random_graph)
@py_random_state(2)
def dense_gnm_random_graph(n, m, seed=None):
mmax = n * (n - 1) / 2
if m >= mmax:
G = complete_graph(n)
else:
G = empty_graph(n)
if n == 1 or m >= mmax:
return G
u = 0
v = 1
t = 0
k = 0
while True:
if seed.randrange(mmax - t) < m - k:
G.add_edge(u, v)
k += 1
if k == m:
return G
t += 1
v += 1
if v == n: # go to next row of adjacency matrix
u += 1
v = u + 1
@patch_docstring(nxa.gnm_random_graph)
@py_random_state(2)
def gnm_random_graph(n, m, seed=None, directed=False):
if directed:
G = nx.DiGraph()
else:
G = nx.Graph()
G.add_nodes_from(range(n))
if n == 1:
return G
max_edges = n * (n - 1)
if not directed:
max_edges /= 2.0
if m >= max_edges:
return complete_graph(n, create_using=G)
nlist = list(G)
edge_count = 0
while edge_count < m:
# generate random edge,u,v
u = seed.choice(nlist)
v = seed.choice(nlist)
if u == v:
continue
else:
G.add_edge(u, v)
edge_count = edge_count + 1
return G
@patch_docstring(nxa.newman_watts_strogatz_graph)
@py_random_state(3)
def newman_watts_strogatz_graph(n, k, p, seed=None):
if k > n:
raise nx.NetworkXError("k>=n, choose smaller k or larger n")
# If k == n the graph return is a complete graph
if k == n:
return nx.complete_graph(n)
G = empty_graph(n)
nlist = list(G.nodes())
fromv = nlist
# connect the k/2 neighbors
for j in range(1, k // 2 + 1):
tov = fromv[j:] + fromv[0:j] # the first j are now last
for i, value in enumerate(fromv):
G.add_edge(value, tov[i])
# for each edge u-v, with probability p, randomly select existing
# node w and add new edge u-w
e = list(G.edges())
for (u, v) in e:
if seed.random() < p:
w = seed.choice(nlist)
# no self-loops and reject if edge u-w exists
# is that the correct NWS model?
while w == u or G.has_edge(u, w):
w = seed.choice(nlist)
if G.degree(u) >= n - 1:
break # skip this rewiring
else:
G.add_edge(u, w)
return G
@patch_docstring(nxa.watts_strogatz_graph)
@py_random_state(3)
def watts_strogatz_graph(n, k, p, seed=None):
if k > n:
raise nx.NetworkXError("k>n, choose smaller k or larger n")
# If k == n, the graph is complete not Watts-Strogatz
if k == n:
return nx.complete_graph(n)
G = nx.Graph()
nodes = list(range(n)) # nodes are labeled 0 to n-1
# connect each node to k/2 neighbors
for j in range(1, k // 2 + 1):
targets = nodes[j:] + nodes[0:j] # first j nodes are now last in list
G.add_edges_from(zip(nodes, targets))
# rewire edges from each node
# loop over all nodes in order (label) and neighbors in order (distance)
# no self loops or multiple edges allowed
for j in range(1, k // 2 + 1): # outer loop is neighbors
targets = nodes[j:] + nodes[0:j] # first j nodes are now last in list
# inner loop in node order
for u, v in zip(nodes, targets):
if seed.random() < p:
w = seed.choice(nodes)
# Enforce no self-loops or multiple edges
while w == u or G.has_edge(u, w):
w = seed.choice(nodes)
if G.degree(u) >= n - 1:
break # skip this rewiring
else:
G.remove_edge(u, v)
G.add_edge(u, w)
return G
@patch_docstring(nxa.connected_watts_strogatz_graph)
@py_random_state(4)
def connected_watts_strogatz_graph(n, k, p, tries=100, seed=None):
for i in range(tries):
# seed is an RNG so should change sequence each call
G = watts_strogatz_graph(n, k, p, seed)
if nx.is_connected(G):
return G
raise nx.NetworkXError("Maximum number of tries exceeded")
@patch_docstring(nxa.random_regular_graph)
@py_random_state(2)
def random_regular_graph(d, n, seed=None):
if (n * d) % 2 != 0:
raise nx.NetworkXError("n * d must be even")
if not 0 <= d < n:
raise nx.NetworkXError("the 0 <= d < n inequality must be satisfied")
if d == 0:
return empty_graph(n)
def _suitable(edges, potential_edges):
# Helper subroutine to check if there are suitable edges remaining
# If False, the generation of the graph has failed
if not potential_edges:
return True
for s1 in potential_edges:
for s2 in potential_edges:
# Two iterators on the same dictionary are guaranteed
# to visit it in the same order if there are no
# intervening modifications.
if s1 == s2:
# Only need to consider s1-s2 pair one time
break
if s1 > s2:
s1, s2 = s2, s1
if (s1, s2) not in edges:
return True
return False
def _try_creation():
# Attempt to create an edge set
edges = set()
stubs = list(range(n)) * d
while stubs:
potential_edges = defaultdict(lambda: 0)
seed.shuffle(stubs)
stubiter = iter(stubs)
for s1, s2 in zip(stubiter, stubiter):
if s1 > s2:
s1, s2 = s2, s1
if s1 != s2 and ((s1, s2) not in edges):
edges.add((s1, s2))
else:
potential_edges[s1] += 1
potential_edges[s2] += 1
if not _suitable(edges, potential_edges):
return None # failed to find suitable edge set
stubs = [
node
for node, potential in potential_edges.items()
for _ in range(potential)
]
return edges
# Even though a suitable edge set exists,
# the generation of such a set is not guaranteed.
# Try repeatedly to find one.
edges = _try_creation()
while edges is None:
edges = _try_creation()
G = nx.Graph()
G.add_edges_from(edges)
return G
def _random_subset(seq, m, rng):
"""Return m unique elements from seq.
This differs from random.sample which can return repeated
elements if seq holds repeated elements.
Note: rng is a random.Random or numpy.random.RandomState instance.
"""
targets = set()
while len(targets) < m:
x = rng.choice(seq)
targets.add(x)
return targets
@patch_docstring(nxa.barabasi_albert_graph)
@py_random_state(2)
def barabasi_albert_graph(n, m, seed=None, initial_graph=None):
if m < 1 or m >= n:
raise nx.NetworkXError(
"Barabási–Albert network must have m >= 1"
" and m < n, m = %d, n = %d" % (m, n)
)
if initial_graph is None:
# Default initial graph : star graph on (m + 1) nodes
G = nx.star_graph(m)
else:
if len(initial_graph) < m or len(initial_graph) > n:
raise nx.NetworkXError(
f"Barabási–Albert initial graph needs between m={m} and n={n} nodes"
)
G = initial_graph.copy()
# List of existing nodes, with nodes repeated once for each adjacent edge
repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
# Start adding the other n - m0 nodes.
source = len(G)
while source < n:
# Now choose m unique nodes from the existing nodes
# Pick uniformly from repeated_nodes (preferential attachment)
targets = _random_subset(repeated_nodes, m, seed)
# Add edges to m nodes from the source.
G.add_edges_from(zip([source] * m, targets))
# Add one node to the list for each new edge just created.
repeated_nodes.extend(targets)
# And the new node "source" has m edges to add to the list.
repeated_nodes.extend([source] * m)
source += 1
return G
@patch_docstring(nxa.dual_barabasi_albert_graph)
@py_random_state(4)
def dual_barabasi_albert_graph(n, m1, m2, p, seed=None, initial_graph=None):
if m1 < 1 or m1 >= n:
raise nx.NetworkXError(
"Dual Barabási–Albert network must have m1 >= 1"
" and m1 < n, m1 = %d, n = %d" % (m1, n)
)
if m2 < 1 or m2 >= n:
raise nx.NetworkXError(
"Dual Barabási–Albert network must have m2 >= 1"
" and m2 < n, m2 = %d, n = %d" % (m2, n)
)
if p < 0 or p > 1:
raise nx.NetworkXError(
"Dual Barabási–Albert network must have 0 <= p <= 1," "p = %f" % p
)
# For simplicity, if p == 0 or 1, just return BA
if p == 1:
return barabasi_albert_graph(n, m1, seed)
if p == 0:
return barabasi_albert_graph(n, m2, seed)
if initial_graph is None:
# Default initial graph : empty graph on max(m1, m2) nodes
G = nx.star_graph(max(m1, m2))
else:
if len(initial_graph) < max(m1, m2) or len(initial_graph) > n:
raise nx.NetworkXError(
f"Barabási–Albert initial graph must have between "
f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes"
)
G = initial_graph.copy()
# Target nodes for new edges
targets = list(G)
# List of existing nodes, with nodes repeated once for each adjacent edge
repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
# Start adding the remaining nodes.
source = len(G)
while source < n:
# Pick which m to use (m1 or m2)
if seed.random() < p:
m = m1
else:
m = m2
# Now choose m unique nodes from the existing nodes
# Pick uniformly from repeated_nodes (preferential attachment)
targets = _random_subset(repeated_nodes, m, seed)
# Add edges to m nodes from the source.
G.add_edges_from(zip([source] * m, targets))
# Add one node to the list for each new edge just created.
repeated_nodes.extend(targets)
# And the new node "source" has m edges to add to the list.
repeated_nodes.extend([source] * m)
source += 1
return G
@patch_docstring(nxa.extended_barabasi_albert_graph)
@py_random_state(4)
def extended_barabasi_albert_graph(n, m, p, q, seed=None):
if m < 1 or m >= n:
msg = "Extended Barabasi-Albert network needs m>=1 and m<n, m=%d, n=%d"
raise nx.NetworkXError(msg % (m, n))
if p + q >= 1:
msg = "Extended Barabasi-Albert network needs p + q <= 1, p=%d, q=%d"
raise nx.NetworkXError(msg % (p, q))
# Add m initial nodes (m0 in barabasi-speak)
G = empty_graph(m)
# List of nodes to represent the preferential attachment random selection.
# At the creation of the graph, all nodes are added to the list
# so that even nodes that are not connected have a chance to get selected,
# for rewiring and adding of edges.
# With each new edge, nodes at the ends of the edge are added to the list.
attachment_preference = []
attachment_preference.extend(range(m))
# Start adding the other n-m nodes. The first node is m.
new_node = m
while new_node < n:
a_probability = seed.random()
# Total number of edges of a Clique of all the nodes
clique_degree = len(G) - 1
clique_size = (len(G) * clique_degree) / 2
# Adding m new edges, if there is room to add them
if a_probability < p and G.size() <= clique_size - m:
# Select the nodes where an edge can be added
elligible_nodes = [nd for nd, deg in G.degree() if deg < clique_degree]
for i in range(m):
# Choosing a random source node from elligible_nodes
src_node = seed.choice(elligible_nodes)
# Picking a possible node that is not 'src_node' or
# neighbor with 'src_node', with preferential attachment
prohibited_nodes = list(G[src_node])
prohibited_nodes.append(src_node)
# This will raise an exception if the sequence is empty
dest_node = seed.choice(
[nd for nd in attachment_preference if nd not in prohibited_nodes]
)
# Adding the new edge
G.add_edge(src_node, dest_node)
# Appending both nodes to add to their preferential attachment
attachment_preference.append(src_node)
attachment_preference.append(dest_node)
# Adjusting the elligible nodes. Degree may be saturated.
if G.degree(src_node) == clique_degree:
elligible_nodes.remove(src_node)
if (
G.degree(dest_node) == clique_degree
and dest_node in elligible_nodes
):
elligible_nodes.remove(dest_node)
# Rewiring m edges, if there are enough edges
elif p <= a_probability < (p + q) and m <= G.size() < clique_size:
# Selecting nodes that have at least 1 edge but that are not
# fully connected to ALL other nodes (center of star).
# These nodes are the pivot nodes of the edges to rewire
elligible_nodes = [nd for nd, deg in G.degree() if 0 < deg < clique_degree]
for i in range(m):
# Choosing a random source node
node = seed.choice(elligible_nodes)
# The available nodes do have a neighbor at least.
neighbor_nodes = list(G[node])
# Choosing the other end that will get dettached
src_node = seed.choice(neighbor_nodes)
# Picking a target node that is not 'node' or
# neighbor with 'node', with preferential attachment
neighbor_nodes.append(node)
dest_node = seed.choice(
[nd for nd in attachment_preference if nd not in neighbor_nodes]
)
# Rewire
G.remove_edge(node, src_node)
G.add_edge(node, dest_node)
# Adjusting the preferential attachment list
attachment_preference.remove(src_node)
attachment_preference.append(dest_node)
# Adjusting the elligible nodes.
# nodes may be saturated or isolated.
if G.degree(src_node) == 0 and src_node in elligible_nodes:
elligible_nodes.remove(src_node)
if dest_node in elligible_nodes:
if G.degree(dest_node) == clique_degree:
elligible_nodes.remove(dest_node)
else:
if G.degree(dest_node) == 1:
elligible_nodes.append(dest_node)
# Adding new node with m edges
else:
# Select the edges' nodes by preferential attachment
targets = _random_subset(attachment_preference, m, seed)
G.add_edges_from(zip([new_node] * m, targets))
# Add one node to the list for each new edge just created.
attachment_preference.extend(targets)
# The new node has m edges to it, plus itself: m + 1
attachment_preference.extend([new_node] * (m + 1))
new_node += 1
return G
@patch_docstring(nxa.powerlaw_cluster_graph)
@py_random_state(3)
def powerlaw_cluster_graph(n, m, p, seed=None):
if m < 1 or n < m:
raise nx.NetworkXError(
"NetworkXError must have m>1 and m<n, m=%d,n=%d" % (m, n)
)
if p > 1 or p < 0:
raise nx.NetworkXError("NetworkXError p must be in [0,1], p=%f" % (p))
G = empty_graph(m) # add m initial nodes (m0 in barabasi-speak)
repeated_nodes = list(G.nodes()) # list of existing nodes to sample from
# with nodes repeated once for each adjacent edge
source = m # next node is m
while source < n: # Now add the other n-1 nodes
possible_targets = _random_subset(repeated_nodes, m, seed)
# do one preferential attachment for new node
target = possible_targets.pop()
G.add_edge(source, target)
repeated_nodes.append(target) # add one node to list for each new link
count = 1
while count < m: # add m-1 more new links
if seed.random() < p: # clustering step: add triangle
neighborhood = [
nbr
for nbr in G.neighbors(target)
if not G.has_edge(source, nbr) and not nbr == source
]
if neighborhood: # if there is a neighbor without a link
nbr = seed.choice(neighborhood)
G.add_edge(source, nbr) # add triangle
repeated_nodes.append(nbr)
count = count + 1
continue # go to top of while loop
# else do preferential attachment step if above fails
target = possible_targets.pop()
G.add_edge(source, target)
repeated_nodes.append(target)
count = count + 1
repeated_nodes.extend([source] * m) # add source node to list m times
source += 1
return G
@patch_docstring(nxa.random_lobster)
@py_random_state(3)
def random_lobster(n, p1, p2, seed=None):
# a necessary ingredient in any self-respecting graph library
llen = int(2 * seed.random() * n + 0.5)
L = path_graph(llen)
# build caterpillar: add edges to path graph with probability p1
current_node = llen - 1
for n in range(llen):
if seed.random() < p1: # add fuzzy caterpillar parts
current_node += 1
L.add_edge(n, current_node)
if seed.random() < p2: # add crunchy lobster bits
current_node += 1
L.add_edge(current_node - 1, current_node)
return L # voila, un lobster!
@patch_docstring(nxa.random_shell_graph)
@py_random_state(1)
def random_shell_graph(constructor, seed=None):
G = empty_graph(0)
glist = []
intra_edges = []
nnodes = 0
# create gnm graphs for each shell
for (n, m, d) in constructor:
inter_edges = int(m * d)
intra_edges.append(m - inter_edges)
g = nx.convert_node_labels_to_integers(
gnm_random_graph(n, inter_edges, seed=seed), first_label=nnodes
)
glist.append(g)
nnodes += n
G = nx.operators.union(G, g)
# connect the shells randomly
for gi in range(len(glist) - 1):
nlist1 = list(glist[gi])
nlist2 = list(glist[gi + 1])
total_edges = intra_edges[gi]
edge_count = 0
while edge_count < total_edges:
u = seed.choice(nlist1)
v = seed.choice(nlist2)
if u == v or G.has_edge(u, v):
continue
else:
G.add_edge(u, v)
edge_count = edge_count + 1
return G
@patch_docstring(nxa.random_powerlaw_tree)
@py_random_state(2)
def random_powerlaw_tree(n, gamma=3, seed=None, tries=100):
# This call may raise a NetworkXError if the number of tries is succeeded.
seq = random_powerlaw_tree_sequence(n, gamma=gamma, seed=seed, tries=tries)
G = degree_sequence_tree(seq)
return G
@patch_docstring(nxa.random_powerlaw_tree_sequence)
@py_random_state(2)
def random_powerlaw_tree_sequence(n, gamma=3, seed=None, tries=100):
# get trial sequence
z = powerlaw_sequence(n, exponent=gamma, seed=seed)
# round to integer values in the range [0,n]
zseq = [min(n, max(int(round(s)), 0)) for s in z]
# another sequence to swap values from
z = powerlaw_sequence(tries, exponent=gamma, seed=seed)
# round to integer values in the range [0,n]
swap = [min(n, max(int(round(s)), 0)) for s in z]
for deg in swap:
# If this degree sequence can be the degree sequence of a tree, return
# it. It can be a tree if the number of edges is one fewer than the
# number of nodes, or in other words, `n - sum(zseq) / 2 == 1`. We
# use an equivalent condition below that avoids floating point
# operations.
if 2 * n - sum(zseq) == 2:
return zseq
index = seed.randint(0, n - 1)
zseq[index] = swap.pop()
raise nx.NetworkXError(
"Exceeded max (%d) attempts for a valid tree" " sequence." % tries
)
@patch_docstring(nxa.random_kernel_graph)
@py_random_state(3)
def random_kernel_graph(n, kernel_integral, kernel_root=None, seed=None):
if kernel_root is None:
import scipy.optimize as optimize
def kernel_root(y, a, r):
def my_function(b):
return kernel_integral(y, a, b) - r
return optimize.brentq(my_function, a, 1)
graph = nx.Graph()
graph.add_nodes_from(range(n))
(i, j) = (1, 1)
while i < n:
r = -math.log(1 - seed.random()) # (1-seed.random()) in (0, 1]
if kernel_integral(i / n, j / n, 1) <= r:
i, j = i + 1, i + 1
else:
j = int(math.ceil(n * kernel_root(i / n, j / n, r)))
graph.add_edge(i - 1, j - 1)
return graph
|
[
"graphscope.nx.DiGraph",
"networkx.utils.py_random_state",
"graphscope.nx.generators.classic.complete_graph",
"networkx.utils.powerlaw_sequence",
"scipy.optimize.brentq",
"graphscope.nx.generators.degree_seq.degree_sequence_tree",
"graphscope.nx.operators.union",
"graphscope.nx.generators.classic.path_graph",
"graphscope.nx.gnp_random_graph",
"graphscope.nx.Graph",
"graphscope.nx.complete_graph",
"graphscope.nx.is_connected",
"graphscope.nx.star_graph",
"collections.defaultdict",
"graphscope.nx.NetworkXError",
"math.log",
"graphscope.nx.utils.compat.patch_docstring",
"graphscope.nx.generators.classic.empty_graph"
] |
[((1780, 1822), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.fast_gnp_random_graph'], {}), '(nxa.fast_gnp_random_graph)\n', (1795, 1822), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((1824, 1842), 'networkx.utils.py_random_state', 'py_random_state', (['(2)'], {}), '(2)\n', (1839, 1842), False, 'from networkx.utils import py_random_state\n'), ((2957, 2994), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.gnp_random_graph'], {}), '(nxa.gnp_random_graph)\n', (2972, 2994), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((2996, 3014), 'networkx.utils.py_random_state', 'py_random_state', (['(2)'], {}), '(2)\n', (3011, 3014), False, 'from networkx.utils import py_random_state\n'), ((3578, 3621), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.dense_gnm_random_graph'], {}), '(nxa.dense_gnm_random_graph)\n', (3593, 3621), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((3623, 3641), 'networkx.utils.py_random_state', 'py_random_state', (['(2)'], {}), '(2)\n', (3638, 3641), False, 'from networkx.utils import py_random_state\n'), ((4174, 4211), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.gnm_random_graph'], {}), '(nxa.gnm_random_graph)\n', (4189, 4211), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((4213, 4231), 'networkx.utils.py_random_state', 'py_random_state', (['(2)'], {}), '(2)\n', (4228, 4231), False, 'from networkx.utils import py_random_state\n'), ((4874, 4922), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.newman_watts_strogatz_graph'], {}), '(nxa.newman_watts_strogatz_graph)\n', (4889, 4922), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((4924, 4942), 'networkx.utils.py_random_state', 'py_random_state', (['(3)'], {}), '(3)\n', (4939, 4942), False, 'from networkx.utils import py_random_state\n'), ((6024, 6065), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.watts_strogatz_graph'], {}), '(nxa.watts_strogatz_graph)\n', (6039, 6065), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((6067, 6085), 'networkx.utils.py_random_state', 'py_random_state', (['(3)'], {}), '(3)\n', (6082, 6085), False, 'from networkx.utils import py_random_state\n'), ((7412, 7463), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.connected_watts_strogatz_graph'], {}), '(nxa.connected_watts_strogatz_graph)\n', (7427, 7463), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((7465, 7483), 'networkx.utils.py_random_state', 'py_random_state', (['(4)'], {}), '(4)\n', (7480, 7483), False, 'from networkx.utils import py_random_state\n'), ((7805, 7846), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.random_regular_graph'], {}), '(nxa.random_regular_graph)\n', (7820, 7846), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((7848, 7866), 'networkx.utils.py_random_state', 'py_random_state', (['(2)'], {}), '(2)\n', (7863, 7866), False, 'from networkx.utils import py_random_state\n'), ((10462, 10504), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.barabasi_albert_graph'], {}), '(nxa.barabasi_albert_graph)\n', (10477, 10504), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((10506, 10524), 'networkx.utils.py_random_state', 'py_random_state', (['(2)'], {}), '(2)\n', (10521, 10524), False, 'from networkx.utils import py_random_state\n'), ((11896, 11943), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.dual_barabasi_albert_graph'], {}), '(nxa.dual_barabasi_albert_graph)\n', (11911, 11943), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((11945, 11963), 'networkx.utils.py_random_state', 'py_random_state', (['(4)'], {}), '(4)\n', (11960, 11963), False, 'from networkx.utils import py_random_state\n'), ((14117, 14168), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.extended_barabasi_albert_graph'], {}), '(nxa.extended_barabasi_albert_graph)\n', (14132, 14168), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((14170, 14188), 'networkx.utils.py_random_state', 'py_random_state', (['(4)'], {}), '(4)\n', (14185, 14188), False, 'from networkx.utils import py_random_state\n'), ((19340, 19383), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.powerlaw_cluster_graph'], {}), '(nxa.powerlaw_cluster_graph)\n', (19355, 19383), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((19385, 19403), 'networkx.utils.py_random_state', 'py_random_state', (['(3)'], {}), '(3)\n', (19400, 19403), False, 'from networkx.utils import py_random_state\n'), ((21253, 21288), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.random_lobster'], {}), '(nxa.random_lobster)\n', (21268, 21288), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((21290, 21308), 'networkx.utils.py_random_state', 'py_random_state', (['(3)'], {}), '(3)\n', (21305, 21308), False, 'from networkx.utils import py_random_state\n'), ((21935, 21974), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.random_shell_graph'], {}), '(nxa.random_shell_graph)\n', (21950, 21974), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((21976, 21994), 'networkx.utils.py_random_state', 'py_random_state', (['(1)'], {}), '(1)\n', (21991, 21994), False, 'from networkx.utils import py_random_state\n'), ((22977, 23018), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.random_powerlaw_tree'], {}), '(nxa.random_powerlaw_tree)\n', (22992, 23018), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((23020, 23038), 'networkx.utils.py_random_state', 'py_random_state', (['(2)'], {}), '(2)\n', (23035, 23038), False, 'from networkx.utils import py_random_state\n'), ((23308, 23358), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.random_powerlaw_tree_sequence'], {}), '(nxa.random_powerlaw_tree_sequence)\n', (23323, 23358), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((23360, 23378), 'networkx.utils.py_random_state', 'py_random_state', (['(2)'], {}), '(2)\n', (23375, 23378), False, 'from networkx.utils import py_random_state\n'), ((24428, 24468), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['nxa.random_kernel_graph'], {}), '(nxa.random_kernel_graph)\n', (24443, 24468), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((24470, 24488), 'networkx.utils.py_random_state', 'py_random_state', (['(3)'], {}), '(3)\n', (24485, 24488), False, 'from networkx.utils import py_random_state\n'), ((1911, 1925), 'graphscope.nx.generators.classic.empty_graph', 'empty_graph', (['n'], {}), '(n)\n', (1922, 1925), False, 'from graphscope.nx.generators.classic import empty_graph\n'), ((2044, 2061), 'math.log', 'math.log', (['(1.0 - p)'], {}), '(1.0 - p)\n', (2052, 2061), False, 'import math\n'), ((5193, 5207), 'graphscope.nx.generators.classic.empty_graph', 'empty_graph', (['n'], {}), '(n)\n', (5204, 5207), False, 'from graphscope.nx.generators.classic import empty_graph\n'), ((6333, 6343), 'graphscope.nx.Graph', 'nx.Graph', ([], {}), '()\n', (6341, 6343), False, 'from graphscope import nx\n'), ((7749, 7801), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (['"""Maximum number of tries exceeded"""'], {}), "('Maximum number of tries exceeded')\n", (7765, 7801), False, 'from graphscope import nx\n'), ((10023, 10033), 'graphscope.nx.Graph', 'nx.Graph', ([], {}), '()\n', (10031, 10033), False, 'from graphscope import nx\n'), ((14597, 14611), 'graphscope.nx.generators.classic.empty_graph', 'empty_graph', (['m'], {}), '(m)\n', (14608, 14611), False, 'from graphscope.nx.generators.classic import empty_graph\n'), ((19699, 19713), 'graphscope.nx.generators.classic.empty_graph', 'empty_graph', (['m'], {}), '(m)\n', (19710, 19713), False, 'from graphscope.nx.generators.classic import empty_graph\n'), ((21469, 21485), 'graphscope.nx.generators.classic.path_graph', 'path_graph', (['llen'], {}), '(llen)\n', (21479, 21485), False, 'from graphscope.nx.generators.classic import path_graph\n'), ((22051, 22065), 'graphscope.nx.generators.classic.empty_graph', 'empty_graph', (['(0)'], {}), '(0)\n', (22062, 22065), False, 'from graphscope.nx.generators.classic import empty_graph\n'), ((23266, 23291), 'graphscope.nx.generators.degree_seq.degree_sequence_tree', 'degree_sequence_tree', (['seq'], {}), '(seq)\n', (23286, 23291), False, 'from graphscope.nx.generators.degree_seq import degree_sequence_tree\n'), ((23481, 23528), 'networkx.utils.powerlaw_sequence', 'powerlaw_sequence', (['n'], {'exponent': 'gamma', 'seed': 'seed'}), '(n, exponent=gamma, seed=seed)\n', (23498, 23528), False, 'from networkx.utils import powerlaw_sequence\n'), ((23684, 23735), 'networkx.utils.powerlaw_sequence', 'powerlaw_sequence', (['tries'], {'exponent': 'gamma', 'seed': 'seed'}), '(tries, exponent=gamma, seed=seed)\n', (23701, 23735), False, 'from networkx.utils import powerlaw_sequence\n'), ((24326, 24411), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (["('Exceeded max (%d) attempts for a valid tree sequence.' % tries)"], {}), "('Exceeded max (%d) attempts for a valid tree sequence.' %\n tries)\n", (24342, 24411), False, 'from graphscope import nx\n'), ((24820, 24830), 'graphscope.nx.Graph', 'nx.Graph', ([], {}), '()\n', (24828, 24830), False, 'from graphscope import nx\n'), ((1967, 2022), 'graphscope.nx.gnp_random_graph', 'nx.gnp_random_graph', (['n', 'p'], {'seed': 'seed', 'directed': 'directed'}), '(n, p, seed=seed, directed=directed)\n', (1986, 2022), False, 'from graphscope import nx\n'), ((2092, 2105), 'graphscope.nx.DiGraph', 'nx.DiGraph', (['G'], {}), '(G)\n', (2102, 2105), False, 'from graphscope import nx\n'), ((3151, 3163), 'graphscope.nx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (3161, 3163), False, 'from graphscope import nx\n'), ((3238, 3248), 'graphscope.nx.Graph', 'nx.Graph', ([], {}), '()\n', (3246, 3248), False, 'from graphscope import nx\n'), ((3342, 3375), 'graphscope.nx.generators.classic.complete_graph', 'complete_graph', (['n'], {'create_using': 'G'}), '(n, create_using=G)\n', (3356, 3375), False, 'from graphscope.nx.generators.classic import complete_graph\n'), ((3744, 3761), 'graphscope.nx.generators.classic.complete_graph', 'complete_graph', (['n'], {}), '(n)\n', (3758, 3761), False, 'from graphscope.nx.generators.classic import complete_graph\n'), ((3784, 3798), 'graphscope.nx.generators.classic.empty_graph', 'empty_graph', (['n'], {}), '(n)\n', (3795, 3798), False, 'from graphscope.nx.generators.classic import empty_graph\n'), ((4316, 4328), 'graphscope.nx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (4326, 4328), False, 'from graphscope import nx\n'), ((4351, 4361), 'graphscope.nx.Graph', 'nx.Graph', ([], {}), '()\n', (4359, 4361), False, 'from graphscope import nx\n'), ((4538, 4571), 'graphscope.nx.generators.classic.complete_graph', 'complete_graph', (['n'], {'create_using': 'G'}), '(n, create_using=G)\n', (4552, 4571), False, 'from graphscope.nx.generators.classic import complete_graph\n'), ((5024, 5078), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (['"""k>=n, choose smaller k or larger n"""'], {}), "('k>=n, choose smaller k or larger n')\n", (5040, 5078), False, 'from graphscope import nx\n'), ((5163, 5183), 'graphscope.nx.complete_graph', 'nx.complete_graph', (['n'], {}), '(n)\n', (5180, 5183), False, 'from graphscope import nx\n'), ((6160, 6213), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (['"""k>n, choose smaller k or larger n"""'], {}), "('k>n, choose smaller k or larger n')\n", (6176, 6213), False, 'from graphscope import nx\n'), ((6303, 6323), 'graphscope.nx.complete_graph', 'nx.complete_graph', (['n'], {}), '(n)\n', (6320, 6323), False, 'from graphscope import nx\n'), ((7698, 7716), 'graphscope.nx.is_connected', 'nx.is_connected', (['G'], {}), '(G)\n', (7713, 7716), False, 'from graphscope import nx\n'), ((7949, 7987), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (['"""n * d must be even"""'], {}), "('n * d must be even')\n", (7965, 7987), False, 'from graphscope import nx\n'), ((8026, 8089), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (['"""the 0 <= d < n inequality must be satisfied"""'], {}), "('the 0 <= d < n inequality must be satisfied')\n", (8042, 8089), False, 'from graphscope import nx\n'), ((8121, 8135), 'graphscope.nx.generators.classic.empty_graph', 'empty_graph', (['n'], {}), '(n)\n', (8132, 8135), False, 'from graphscope.nx.generators.classic import empty_graph\n'), ((10627, 10731), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (["('Barabási–Albert network must have m >= 1 and m < n, m = %d, n = %d' % (m, n))"], {}), "(\n 'Barabási–Albert network must have m >= 1 and m < n, m = %d, n = %d' %\n (m, n))\n", (10643, 10731), False, 'from graphscope import nx\n'), ((10865, 10881), 'graphscope.nx.star_graph', 'nx.star_graph', (['m'], {}), '(m)\n', (10878, 10881), False, 'from graphscope import nx\n'), ((12081, 12195), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (["('Dual Barabási–Albert network must have m1 >= 1 and m1 < n, m1 = %d, n = %d' %\n (m1, n))"], {}), "(\n 'Dual Barabási–Albert network must have m1 >= 1 and m1 < n, m1 = %d, n = %d'\n % (m1, n))\n", (12097, 12195), False, 'from graphscope import nx\n'), ((12263, 12377), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (["('Dual Barabási–Albert network must have m2 >= 1 and m2 < n, m2 = %d, n = %d' %\n (m2, n))"], {}), "(\n 'Dual Barabási–Albert network must have m2 >= 1 and m2 < n, m2 = %d, n = %d'\n % (m2, n))\n", (12279, 12377), False, 'from graphscope import nx\n'), ((12442, 12528), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (["('Dual Barabási–Albert network must have 0 <= p <= 1,p = %f' % p)"], {}), "(\n 'Dual Barabási–Albert network must have 0 <= p <= 1,p = %f' % p)\n", (12458, 12528), False, 'from graphscope import nx\n'), ((14366, 14396), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (['(msg % (m, n))'], {}), '(msg % (m, n))\n', (14382, 14396), False, 'from graphscope import nx\n'), ((14508, 14538), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (['(msg % (p, q))'], {}), '(msg % (p, q))\n', (14524, 14538), False, 'from graphscope import nx\n'), ((19489, 19564), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (["('NetworkXError must have m>1 and m<n, m=%d,n=%d' % (m, n))"], {}), "('NetworkXError must have m>1 and m<n, m=%d,n=%d' % (m, n))\n", (19505, 19564), False, 'from graphscope import nx\n'), ((19625, 19687), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (["('NetworkXError p must be in [0,1], p=%f' % p)"], {}), "('NetworkXError p must be in [0,1], p=%f' % p)\n", (19641, 19687), False, 'from graphscope import nx\n'), ((22458, 22482), 'graphscope.nx.operators.union', 'nx.operators.union', (['G', 'g'], {}), '(G, g)\n', (22476, 22482), False, 'from graphscope import nx\n'), ((9077, 9100), 'collections.defaultdict', 'defaultdict', (['(lambda : 0)'], {}), '(lambda : 0)\n', (9088, 9100), False, 'from collections import defaultdict\n'), ((10971, 11062), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (['f"""Barabási–Albert initial graph needs between m={m} and n={n} nodes"""'], {}), "(\n f'Barabási–Albert initial graph needs between m={m} and n={n} nodes')\n", (10987, 11062), False, 'from graphscope import nx\n'), ((24772, 24806), 'scipy.optimize.brentq', 'optimize.brentq', (['my_function', 'a', '(1)'], {}), '(my_function, a, 1)\n', (24787, 24806), True, 'import scipy.optimize as optimize\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file is referred and derived from project NetworkX
#
# which has the following license:
#
# Copyright (C) 2004-2020, NetworkX Developers
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# All rights reserved.
#
# This file is part of NetworkX.
#
# NetworkX is distributed under a BSD license; see LICENSE.txt for more
# information.
#
import networkx.readwrite.tests.test_sparse6
import pytest
from networkx.readwrite.tests.test_sparse6 import TestWriteSparse6
from graphscope.nx.utils.compat import import_as_graphscope_nx
from graphscope.nx.utils.compat import with_graphscope_nx_context
import_as_graphscope_nx(
networkx.readwrite.tests.test_sparse6,
decorators=pytest.mark.usefixtures("graphscope_session"),
)
@pytest.mark.usefixtures("graphscope_session")
@with_graphscope_nx_context(TestWriteSparse6)
class TestWriteSparse6:
@pytest.mark.slow
def test_very_large_empty_graph(self):
G = nx.empty_graph(258049)
result = BytesIO()
nx.write_sparse6(G, result)
assert result.getvalue() == b">>sparse6<<:~~???~?@\n"
|
[
"graphscope.nx.utils.compat.with_graphscope_nx_context",
"pytest.mark.usefixtures"
] |
[((792, 837), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (815, 837), False, 'import pytest\n'), ((839, 883), 'graphscope.nx.utils.compat.with_graphscope_nx_context', 'with_graphscope_nx_context', (['TestWriteSparse6'], {}), '(TestWriteSparse6)\n', (865, 883), False, 'from graphscope.nx.utils.compat import with_graphscope_nx_context\n'), ((740, 785), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (763, 785), False, 'import pytest\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import yaml
from graphscope.analytical.udf.compile import GRAPECompiler
from graphscope.analytical.udf.utils import InMemoryZip
from graphscope.analytical.udf.utils import LinesWrapper
from graphscope.analytical.udf.utils import ProgramModel
from graphscope.framework.app import load_app
from graphscope.framework.utils import get_timestamp
def wrap_init(
algo, program_model, pyx_header, pyx_body, vd_type, md_type, pregel_combine
):
"""Wrapper :code:`__init__` function in algo."""
algo_name = getattr(algo, "__name__")
module_name = algo_name + "_" + get_timestamp(with_milliseconds=False)
pyx_code = "\n\n".join(pyx_header.dump() + pyx_body.dump())
gs_config = {
"app": [
{
"algo": module_name,
"context_type": "labeled_vertex_data",
"type": "cython_pie"
if program_model == ProgramModel.PIE
else "cython_pregel",
"class_name": "gs::PregelPropertyAppBase",
"compatible_graph": ["vineyard::ArrowFragment"],
"vd_type": vd_type,
"md_type": md_type,
"pregel_combine": pregel_combine,
}
]
}
garfile = InMemoryZip()
garfile.append("{}.pyx".format(module_name), pyx_code)
garfile.append(".gs_conf.yaml", yaml.dump(gs_config))
def init(self):
pass
def call(self, graph, **kwargs):
app_assets = load_app(algo=module_name, gar=garfile.read_bytes())
return app_assets(graph, **kwargs)
setattr(algo, "__decorated__", True) # can't decorate on a decorated class
setattr(algo, "_gar", garfile.read_bytes().getvalue())
setattr(algo, "__init__", init)
setattr(algo, "__call__", call)
def pyx_codegen(
algo,
defs,
program_model,
pyx_header,
vd_type=None,
md_type=None,
pregel_combine=False,
):
"""Transfer python to cython code with :code:`grape.GRAPECompiler`.
Args:
algo: class defination of algorithm.
defs: list of function to be transfer.
program_model: ProgramModel, 'Pregel' or 'PIE'.
pyx_header: LinesWrapper, list of pyx source code.
vd_type (str): vertex data type.
md_type (str): message type.
pregel_combine (bool): combinator in pregel model.
"""
class_name = getattr(algo, "__name__")
compiler = GRAPECompiler(class_name, vd_type, md_type, program_model)
pyx_body = LinesWrapper()
for func_name in defs.keys():
func = getattr(algo, func_name)
cycode = compiler.run(func, pyx_header)
pyx_body.putline(cycode)
# append code body
# pyx_wrapper['pyx_code_body'].extend(pyx_code_body)
wrap_init(
algo, program_model, pyx_header, pyx_body, vd_type, md_type, pregel_combine
)
|
[
"graphscope.analytical.udf.utils.InMemoryZip",
"yaml.dump",
"graphscope.analytical.udf.compile.GRAPECompiler",
"graphscope.analytical.udf.utils.LinesWrapper",
"graphscope.framework.utils.get_timestamp"
] |
[((1904, 1917), 'graphscope.analytical.udf.utils.InMemoryZip', 'InMemoryZip', ([], {}), '()\n', (1915, 1917), False, 'from graphscope.analytical.udf.utils import InMemoryZip\n'), ((3056, 3114), 'graphscope.analytical.udf.compile.GRAPECompiler', 'GRAPECompiler', (['class_name', 'vd_type', 'md_type', 'program_model'], {}), '(class_name, vd_type, md_type, program_model)\n', (3069, 3114), False, 'from graphscope.analytical.udf.compile import GRAPECompiler\n'), ((3131, 3145), 'graphscope.analytical.udf.utils.LinesWrapper', 'LinesWrapper', ([], {}), '()\n', (3143, 3145), False, 'from graphscope.analytical.udf.utils import LinesWrapper\n'), ((1240, 1278), 'graphscope.framework.utils.get_timestamp', 'get_timestamp', ([], {'with_milliseconds': '(False)'}), '(with_milliseconds=False)\n', (1253, 1278), False, 'from graphscope.framework.utils import get_timestamp\n'), ((2013, 2033), 'yaml.dump', 'yaml.dump', (['gs_config'], {}), '(gs_config)\n', (2022, 2033), False, 'import yaml\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from typing import Mapping
from typing import Sequence
from typing import Union
try:
import vineyard
except ImportError:
vineyard = None
from graphscope.client.session import get_default_session
from graphscope.framework import dag_utils
from graphscope.framework import utils
from graphscope.framework.graph import Graph
from graphscope.framework.graph_utils import LoaderVariants
from graphscope.framework.graph_utils import VineyardObjectTypes
from graphscope.framework.graph_utils import normalize_parameter_edges
from graphscope.framework.graph_utils import normalize_parameter_vertices
from graphscope.proto import graph_def_pb2
from graphscope.proto import types_pb2
__all__ = ["load_from"]
def load_from(
edges: Union[
Mapping[str, Union[LoaderVariants, Sequence, Mapping]], LoaderVariants, Sequence
],
vertices: Union[
Mapping[str, Union[LoaderVariants, Sequence, Mapping]],
LoaderVariants,
Sequence,
None,
] = None,
directed=True,
oid_type="int64_t",
generate_eid=True,
) -> Graph:
"""Load a Arrow property graph using a list of vertex/edge specifications.
.. deprecated:: version 0.3
Use :class:`graphscope.Graph()` instead.
- Use Dict of tuples to setup a graph.
We can use a dict to set vertex and edge configurations,
which can be used to build graphs.
Examples:
.. code:: ipython
g = graphscope_session.load_from(
edges={
"group": [
(
"file:///home/admin/group.e",
["group_id", "member_size"],
("leader_student_id", "student"),
("member_student_id", "student"),
),
(
"file:///home/admin/group_for_teacher_student.e",
["group_id", "group_name", "establish_date"],
("teacher_in_charge_id", "teacher"),
("member_student_id", "student"),
),
]
},
vertices={
"student": (
"file:///home/admin/student.v",
["name", "lesson_nums", "avg_score"],
"student_id",
),
"teacher": (
"file:///home/admin/teacher.v",
["name", "salary", "age"],
"teacher_id",
),
},
)
'e' is the label of edges, and 'v' is the label for vertices, edges are stored in the 'both_in_out' format
edges with label 'e' linking from 'v' to 'v'.
- Use Dict of dict to setup a graph.
We can also give each element inside the tuple a meaningful name,
makes it more understandable.
Examples:
.. code:: ipython
g = graphscope_session.load_from(
edges={
"group": [
{
"loader": "file:///home/admin/group.e",
"properties": ["group_id", "member_size"],
"source": ("leader_student_id", "student"),
"destination": ("member_student_id", "student"),
},
{
"loader": "file:///home/admin/group_for_teacher_student.e",
"properties": ["group_id", "group_name", "establish_date"],
"source": ("teacher_in_charge_id", "teacher"),
"destination": ("member_student_id", "student"),
},
]
},
vertices={
"student": {
"loader": "file:///home/admin/student.v",
"properties": ["name", "lesson_nums", "avg_score"],
"vid": "student_id",
},
"teacher": {
"loader": "file:///home/admin/teacher.v",
"properties": ["name", "salary", "age"],
"vid": "teacher_id",
},
},
)
Args:
edges: Edge configuration of the graph
vertices (optional): Vertices configurations of the graph. Defaults to None.
If None, we assume all edge's src_label and dst_label are deduced and unambiguous.
directed (bool, optional): Indicate whether the graph
should be treated as directed or undirected.
oid_type (str, optional): ID type of graph. Can be "int64_t" or "string". Defaults to "int64_t".
generate_eid (bool, optional): Whether to generate a unique edge id for each edge. Generated eid will be placed
in third column. This feature is for cooperating with interactive engine.
If you only need to work with analytical engine, set it to False. Defaults to False.
"""
# Don't import the :code:`nx` in top-level statments to improve the
# performance of :code:`import graphscope`.
from graphscope import nx
sess = get_default_session()
if sess is None:
raise ValueError("No default session found.")
if isinstance(edges, (Graph, nx.Graph, *VineyardObjectTypes)):
return sess.g(edges)
oid_type = utils.normalize_data_type_str(oid_type)
if oid_type not in ("int64_t", "std::string"):
raise ValueError("oid_type can only be int64_t or string.")
v_labels = normalize_parameter_vertices(vertices, oid_type)
e_labels = normalize_parameter_edges(edges, oid_type)
# generate and add a loader op to dag
loader_op = dag_utils.create_loader(v_labels + e_labels)
sess.dag.add_op(loader_op)
# construct create graph op
config = {
types_pb2.DIRECTED: utils.b_to_attr(directed),
types_pb2.OID_TYPE: utils.s_to_attr(oid_type),
types_pb2.GENERATE_EID: utils.b_to_attr(generate_eid),
types_pb2.VID_TYPE: utils.s_to_attr("uint64_t"),
types_pb2.IS_FROM_VINEYARD_ID: utils.b_to_attr(False),
}
op = dag_utils.create_graph(
sess.session_id, graph_def_pb2.ARROW_PROPERTY, inputs=[loader_op], attrs=config
)
graph = sess.g(op)
return graph
|
[
"graphscope.framework.utils.b_to_attr",
"graphscope.framework.dag_utils.create_graph",
"graphscope.framework.graph_utils.normalize_parameter_vertices",
"graphscope.framework.utils.normalize_data_type_str",
"graphscope.framework.dag_utils.create_loader",
"graphscope.framework.utils.s_to_attr",
"graphscope.client.session.get_default_session",
"graphscope.framework.graph_utils.normalize_parameter_edges"
] |
[((6044, 6065), 'graphscope.client.session.get_default_session', 'get_default_session', ([], {}), '()\n', (6063, 6065), False, 'from graphscope.client.session import get_default_session\n'), ((6252, 6291), 'graphscope.framework.utils.normalize_data_type_str', 'utils.normalize_data_type_str', (['oid_type'], {}), '(oid_type)\n', (6281, 6291), False, 'from graphscope.framework import utils\n'), ((6426, 6474), 'graphscope.framework.graph_utils.normalize_parameter_vertices', 'normalize_parameter_vertices', (['vertices', 'oid_type'], {}), '(vertices, oid_type)\n', (6454, 6474), False, 'from graphscope.framework.graph_utils import normalize_parameter_vertices\n'), ((6490, 6532), 'graphscope.framework.graph_utils.normalize_parameter_edges', 'normalize_parameter_edges', (['edges', 'oid_type'], {}), '(edges, oid_type)\n', (6515, 6532), False, 'from graphscope.framework.graph_utils import normalize_parameter_edges\n'), ((6591, 6635), 'graphscope.framework.dag_utils.create_loader', 'dag_utils.create_loader', (['(v_labels + e_labels)'], {}), '(v_labels + e_labels)\n', (6614, 6635), False, 'from graphscope.framework import dag_utils\n'), ((7022, 7129), 'graphscope.framework.dag_utils.create_graph', 'dag_utils.create_graph', (['sess.session_id', 'graph_def_pb2.ARROW_PROPERTY'], {'inputs': '[loader_op]', 'attrs': 'config'}), '(sess.session_id, graph_def_pb2.ARROW_PROPERTY,\n inputs=[loader_op], attrs=config)\n', (7044, 7129), False, 'from graphscope.framework import dag_utils\n'), ((6742, 6767), 'graphscope.framework.utils.b_to_attr', 'utils.b_to_attr', (['directed'], {}), '(directed)\n', (6757, 6767), False, 'from graphscope.framework import utils\n'), ((6797, 6822), 'graphscope.framework.utils.s_to_attr', 'utils.s_to_attr', (['oid_type'], {}), '(oid_type)\n', (6812, 6822), False, 'from graphscope.framework import utils\n'), ((6856, 6885), 'graphscope.framework.utils.b_to_attr', 'utils.b_to_attr', (['generate_eid'], {}), '(generate_eid)\n', (6871, 6885), False, 'from graphscope.framework import utils\n'), ((6915, 6942), 'graphscope.framework.utils.s_to_attr', 'utils.s_to_attr', (['"""uint64_t"""'], {}), "('uint64_t')\n", (6930, 6942), False, 'from graphscope.framework import utils\n'), ((6983, 7005), 'graphscope.framework.utils.b_to_attr', 'utils.b_to_attr', (['(False)'], {}), '(False)\n', (6998, 7005), False, 'from graphscope.framework import utils\n')]
|
import networkx.algorithms.tests.test_lowest_common_ancestors
import pytest
from graphscope.nx.utils.compat import import_as_graphscope_nx
from graphscope.nx.utils.compat import with_graphscope_nx_context
import_as_graphscope_nx(networkx.algorithms.tests.test_lowest_common_ancestors,
decorators=pytest.mark.usefixtures("graphscope_session"))
from networkx.algorithms.tests.test_lowest_common_ancestors import TestDAGLCA
from networkx.algorithms.tests.test_lowest_common_ancestors import TestTreeLCA
@pytest.mark.usefixtures("graphscope_session")
@with_graphscope_nx_context(TestDAGLCA)
class TestDAGLCA:
@pytest.mark.skip(reason="not support None object as node")
def test_all_pairs_lowest_common_ancestor10(self):
pass
@pytest.mark.skip(reason="assert 2 == 3")
def test_all_pairs_lowest_common_ancestor1(self):
pass
@pytest.mark.skip(reason="assert 2 == 3")
def test_all_pairs_lowest_common_ancestor2(self):
pass
@pytest.mark.skip(reason="assert 2 == 3")
def test_all_pairs_lowest_common_ancestor3(self):
pass
@pytest.mark.skip(reason="assert 3 == 4")
def test_all_pairs_lowest_common_ancestor4(self):
pass
@pytest.mark.usefixtures("graphscope_session")
@with_graphscope_nx_context(TestTreeLCA)
class TestTreeLCA:
@pytest.mark.skip(reason="not support None object as node")
def test_tree_all_pairs_lowest_common_ancestor11(self):
pass
|
[
"pytest.mark.skip",
"graphscope.nx.utils.compat.with_graphscope_nx_context",
"pytest.mark.usefixtures"
] |
[((530, 575), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (553, 575), False, 'import pytest\n'), ((577, 615), 'graphscope.nx.utils.compat.with_graphscope_nx_context', 'with_graphscope_nx_context', (['TestDAGLCA'], {}), '(TestDAGLCA)\n', (603, 615), False, 'from graphscope.nx.utils.compat import with_graphscope_nx_context\n'), ((1225, 1270), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (1248, 1270), False, 'import pytest\n'), ((1272, 1311), 'graphscope.nx.utils.compat.with_graphscope_nx_context', 'with_graphscope_nx_context', (['TestTreeLCA'], {}), '(TestTreeLCA)\n', (1298, 1311), False, 'from graphscope.nx.utils.compat import with_graphscope_nx_context\n'), ((639, 697), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""not support None object as node"""'}), "(reason='not support None object as node')\n", (655, 697), False, 'import pytest\n'), ((772, 812), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""assert 2 == 3"""'}), "(reason='assert 2 == 3')\n", (788, 812), False, 'import pytest\n'), ((886, 926), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""assert 2 == 3"""'}), "(reason='assert 2 == 3')\n", (902, 926), False, 'import pytest\n'), ((1000, 1040), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""assert 2 == 3"""'}), "(reason='assert 2 == 3')\n", (1016, 1040), False, 'import pytest\n'), ((1114, 1154), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""assert 3 == 4"""'}), "(reason='assert 3 == 4')\n", (1130, 1154), False, 'import pytest\n'), ((1336, 1394), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""not support None object as node"""'}), "(reason='not support None object as node')\n", (1352, 1394), False, 'import pytest\n'), ((322, 367), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (345, 367), False, 'import pytest\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file convert_matrix.py is referred and derived from project NetworkX,
#
# https://github.com/networkx/networkx/blob/master/networkx/convert_matrix.py
#
# which has the following license:
#
# Copyright (C) 2004-2020, NetworkX Developers
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# All rights reserved.
#
# This file is part of NetworkX.
#
# NetworkX is distributed under a BSD license; see LICENSE.txt for more
# information.
#
import networkx.convert_matrix
from networkx.convert_matrix import from_pandas_edgelist as _from_pandas_edgelist
from graphscope import nx
from graphscope.nx.utils.compat import import_as_graphscope_nx
from graphscope.nx.utils.compat import patch_docstring
import_as_graphscope_nx(networkx.convert_matrix)
@patch_docstring(_from_pandas_edgelist)
def from_pandas_edgelist(
df,
source="source",
target="target",
edge_attr=None,
create_using=None,
edge_key=None,
):
g = nx.empty_graph(0, create_using)
if edge_attr is None:
g.add_edges_from(zip(df[source], df[target]))
return g
reserved_columns = [source, target]
# Additional columns requested
attr_col_headings = []
attribute_data = []
if edge_attr is True:
attr_col_headings = [c for c in df.columns if c not in reserved_columns]
elif isinstance(edge_attr, (list, tuple)):
attr_col_headings = edge_attr
else:
attr_col_headings = [edge_attr]
if len(attr_col_headings) == 0:
raise nx.NetworkXError(
f"Invalid edge_attr argument: No columns found with name: {attr_col_headings}"
)
try:
attribute_data = zip(*[df[col] for col in attr_col_headings])
except (KeyError, TypeError) as e:
msg = f"Invalid edge_attr argument: {edge_attr}"
raise nx.NetworkXError(msg) from e
if g.is_multigraph():
# => append the edge keys from the df to the bundled data
if edge_key is not None:
try:
multigraph_edge_keys = df[edge_key]
attribute_data = zip(attribute_data, multigraph_edge_keys)
except (KeyError, TypeError) as e:
msg = f"Invalid edge_key argument: {edge_key}"
raise nx.NetworkXError(msg) from e
for s, t, attrs in zip(df[source], df[target], attribute_data):
if edge_key is not None:
attrs, multigraph_edge_key = attrs
key = g.add_edge(s, t, key=multigraph_edge_key)
else:
key = g.add_edge(s, t)
g[s][t][key].update(zip(attr_col_headings, attrs))
else:
edges = []
for s, t, attrs in zip(df[source], df[target], attribute_data):
edges.append((s, t, zip(attr_col_headings, attrs)))
g.add_edges_from(edges)
return g
|
[
"graphscope.nx.empty_graph",
"graphscope.nx.NetworkXError",
"graphscope.nx.utils.compat.patch_docstring",
"graphscope.nx.utils.compat.import_as_graphscope_nx"
] |
[((759, 807), 'graphscope.nx.utils.compat.import_as_graphscope_nx', 'import_as_graphscope_nx', (['networkx.convert_matrix'], {}), '(networkx.convert_matrix)\n', (782, 807), False, 'from graphscope.nx.utils.compat import import_as_graphscope_nx\n'), ((811, 849), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['_from_pandas_edgelist'], {}), '(_from_pandas_edgelist)\n', (826, 849), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((999, 1030), 'graphscope.nx.empty_graph', 'nx.empty_graph', (['(0)', 'create_using'], {}), '(0, create_using)\n', (1013, 1030), False, 'from graphscope import nx\n'), ((1549, 1655), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (['f"""Invalid edge_attr argument: No columns found with name: {attr_col_headings}"""'], {}), "(\n f'Invalid edge_attr argument: No columns found with name: {attr_col_headings}'\n )\n", (1565, 1655), False, 'from graphscope import nx\n'), ((1858, 1879), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (['msg'], {}), '(msg)\n', (1874, 1879), False, 'from graphscope import nx\n'), ((2289, 2310), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (['msg'], {}), '(msg)\n', (2305, 2310), False, 'from graphscope import nx\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file referred and derived from project NetworkX,
#
# https://github.com/networkx/networkx/blob/master/networkx/generators/cograph.py
#
# which has the following license:
#
# Copyright (C) 2004-2020, NetworkX Developers
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# All rights reserved.
#
# This file is part of NetworkX.
#
# NetworkX is distributed under a BSD license; see LICENSE.txt for more
# information.
#
from networkx.generators import random_cograph as _random_cograph
from networkx.utils import py_random_state
import graphscope.nx as nx
from graphscope.nx.utils.compat import patch_docstring
__all__ = ["random_cograph"]
@py_random_state(1)
@patch_docstring(_random_cograph)
def random_cograph(n, seed=None):
R = nx.empty_graph(1)
for i in range(n):
RR = nx.relabel_nodes(R.copy(), lambda x: x + len(R))
if seed.randint(0, 1) == 0:
R = full_join(R, RR)
else:
R = disjoint_union(R, RR)
return R
def union(G, H, rename=(None, None), name=None):
if not G.is_multigraph() == H.is_multigraph():
raise nx.NetworkXError("G and H must both be graphs or multigraphs.")
# Union is the same type as G
R = G.__class__()
# add graph attributes, H attributes take precedent over G attributes
R.graph.update(G.graph)
R.graph.update(H.graph)
# rename graph to obtain disjoint node labels
def add_prefix(graph, prefix):
if prefix is None:
return graph
def label(x):
if isinstance(x, str):
name = prefix + x
else:
name = prefix + repr(x)
return name
return nx.relabel_nodes(graph, label)
G = add_prefix(G, rename[0])
H = add_prefix(H, rename[1])
if set(G) & set(H):
raise nx.NetworkXError(
"The node sets of G and H are not disjoint.",
"Use appropriate rename=(Gprefix,Hprefix)" "or use disjoint_union(G,H).",
)
if G.is_multigraph():
G_edges = G.edges(keys=True, data=True)
else:
G_edges = G.edges(data=True)
if H.is_multigraph():
H_edges = H.edges(keys=True, data=True)
else:
H_edges = H.edges(data=True)
# add nodes
R.add_nodes_from(G)
R.add_nodes_from(H)
# add edges
R.add_edges_from(G_edges)
R.add_edges_from(H_edges)
# add node attributes
for n in G:
R.nodes[n].update(G.nodes[n])
for n in H:
R.nodes[n].update(H.nodes[n])
return R
def disjoint_union(G, H):
R1 = nx.convert_node_labels_to_integers(G)
R2 = nx.convert_node_labels_to_integers(H, first_label=len(R1))
R = union(R1, R2)
R.graph.update(G.graph)
R.graph.update(H.graph)
return R
def full_join(G, H, rename=(None, None)):
R = union(G, H, rename)
def add_prefix(graph, prefix):
if prefix is None:
return graph
def label(x):
if isinstance(x, str):
name = prefix + x
else:
name = prefix + repr(x)
return name
return nx.relabel_nodes(graph, label)
G = add_prefix(G, rename[0])
H = add_prefix(H, rename[1])
for i in G:
for j in H:
R.add_edge(i, j)
if R.is_directed():
for i in H:
for j in G:
R.add_edge(i, j)
return R
|
[
"graphscope.nx.empty_graph",
"networkx.utils.py_random_state",
"graphscope.nx.NetworkXError",
"graphscope.nx.relabel_nodes",
"graphscope.nx.utils.compat.patch_docstring",
"graphscope.nx.convert_node_labels_to_integers"
] |
[((708, 726), 'networkx.utils.py_random_state', 'py_random_state', (['(1)'], {}), '(1)\n', (723, 726), False, 'from networkx.utils import py_random_state\n'), ((728, 760), 'graphscope.nx.utils.compat.patch_docstring', 'patch_docstring', (['_random_cograph'], {}), '(_random_cograph)\n', (743, 760), False, 'from graphscope.nx.utils.compat import patch_docstring\n'), ((803, 820), 'graphscope.nx.empty_graph', 'nx.empty_graph', (['(1)'], {}), '(1)\n', (817, 820), True, 'import graphscope.nx as nx\n'), ((2613, 2650), 'graphscope.nx.convert_node_labels_to_integers', 'nx.convert_node_labels_to_integers', (['G'], {}), '(G)\n', (2647, 2650), True, 'import graphscope.nx as nx\n'), ((1159, 1222), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (['"""G and H must both be graphs or multigraphs."""'], {}), "('G and H must both be graphs or multigraphs.')\n", (1175, 1222), True, 'import graphscope.nx as nx\n'), ((1737, 1767), 'graphscope.nx.relabel_nodes', 'nx.relabel_nodes', (['graph', 'label'], {}), '(graph, label)\n', (1753, 1767), True, 'import graphscope.nx as nx\n'), ((1873, 2010), 'graphscope.nx.NetworkXError', 'nx.NetworkXError', (['"""The node sets of G and H are not disjoint."""', '"""Use appropriate rename=(Gprefix,Hprefix)or use disjoint_union(G,H)."""'], {}), "('The node sets of G and H are not disjoint.',\n 'Use appropriate rename=(Gprefix,Hprefix)or use disjoint_union(G,H).')\n", (1889, 2010), True, 'import graphscope.nx as nx\n'), ((3160, 3190), 'graphscope.nx.relabel_nodes', 'nx.relabel_nodes', (['graph', 'label'], {}), '(graph, label)\n', (3176, 3190), True, 'import graphscope.nx as nx\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import logging
import os
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from graphscope import JavaApp
@pytest.fixture(scope="module")
def not_exist_jar():
path = os.path.join("not_exist_dir", "not_exist.jar")
return path
@pytest.fixture(scope="module")
def not_jar_file():
return os.path.expandvars("${GS_TEST_DIR}/p2p-31.e")
@pytest.fixture(scope="module")
def a_gar_file():
return os.path.expandvars("${GS_TEST_DIR}/gars/sssp_pie.gar")
@pytest.fixture(scope="module")
def empty_jar():
return os.path.expandvars("${GS_TEST_DIR}/jars/empty.jar")
@pytest.fixture(scope="module")
def demo_jar():
return os.path.expandvars("${USER_JAR_PATH}")
@pytest.fixture(scope="module")
def property_graph_sssp_vertex_property_class():
return "com.alibaba.graphscope.example.property.sssp.PropertySSSPVertexProperty"
@pytest.fixture(scope="module")
def property_graph_sssp_vertex_data_class():
return "com.alibaba.graphscope.example.property.sssp.PropertySSSPVertexData"
@pytest.fixture(scope="module")
def non_exist_java_class():
return "com.alibaba.graphscope.example.non.existing.java.class"
@pytest.mark.skipif(
os.environ.get("RUN_JAVA_TESTS") != "ON",
reason="Java SDK is disabled, skip this test.",
)
def test_load_non_existing_jar(
not_exist_jar, property_graph_sssp_vertex_data_class, non_exist_java_class
):
with pytest.raises(FileNotFoundError):
sssp = JavaApp(not_exist_jar, property_graph_sssp_vertex_data_class)
with pytest.raises(FileNotFoundError):
sssp = JavaApp(not_exist_jar, non_exist_java_class)
@pytest.mark.skipif(
os.environ.get("RUN_JAVA_TESTS") != "ON",
reason="Java SDK is disabled, skip this test.",
)
def test_load_not_a_jar(
not_jar_file, property_graph_sssp_vertex_data_class, non_exist_java_class
):
with pytest.raises(KeyError):
sssp = JavaApp(not_jar_file, property_graph_sssp_vertex_data_class)
with pytest.raises(KeyError):
sssp = JavaApp(not_jar_file, non_exist_java_class)
@pytest.mark.skipif(
os.environ.get("RUN_JAVA_TESTS") != "ON",
reason="Java SDK is disabled, skip this test.",
)
def test_load_gar_file(
a_gar_file, property_graph_sssp_vertex_data_class, non_exist_java_class
):
with pytest.raises(KeyError):
sssp = JavaApp(a_gar_file, property_graph_sssp_vertex_data_class)
with pytest.raises(KeyError):
sssp = JavaApp(a_gar_file, non_exist_java_class)
@pytest.mark.skipif(
os.environ.get("RUN_JAVA_TESTS") != "ON",
reason="Java SDK is disabled, skip this test.",
)
def test_load_empty_jar(
empty_jar, property_graph_sssp_vertex_data_class, non_exist_java_class
):
with pytest.raises(KeyError):
sssp = JavaApp(empty_jar, property_graph_sssp_vertex_data_class)
with pytest.raises(KeyError):
sssp = JavaApp(empty_jar, non_exist_java_class)
@pytest.mark.skipif(
os.environ.get("RUN_JAVA_TESTS") != "ON",
reason="Java SDK is disabled, skip this test.",
)
def test_load_correct_jar(property_graph_sssp_vertex_data_class, demo_jar):
sssp = JavaApp(demo_jar, property_graph_sssp_vertex_data_class)
@pytest.mark.skipif(
os.environ.get("RUN_JAVA_TESTS") != "ON",
reason="Java SDK is disabled, skip this test.",
)
def test_sssp_property_vertex_data(
demo_jar,
graphscope_session,
p2p_property_graph,
property_graph_sssp_vertex_data_class,
):
sssp = JavaApp(
full_jar_path=demo_jar, java_app_class=property_graph_sssp_vertex_data_class
)
sssp(p2p_property_graph, src=6)
@pytest.mark.skipif(
os.environ.get("RUN_JAVA_TESTS") != "ON",
reason="Java SDK is disabled, skip this test.",
)
def test_sssp_property_vertex_property(
demo_jar,
graphscope_session,
p2p_property_graph,
property_graph_sssp_vertex_property_class,
):
sssp = JavaApp(
full_jar_path=demo_jar, java_app_class=property_graph_sssp_vertex_property_class
)
sssp(p2p_property_graph, src=6)
|
[
"pytest.fixture",
"os.environ.get",
"os.path.expandvars",
"pytest.raises",
"graphscope.JavaApp",
"os.path.join"
] |
[((806, 836), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (820, 836), False, 'import pytest\n'), ((935, 965), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (949, 965), False, 'import pytest\n'), ((1046, 1076), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1060, 1076), False, 'import pytest\n'), ((1164, 1194), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1178, 1194), False, 'import pytest\n'), ((1278, 1308), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1292, 1308), False, 'import pytest\n'), ((1378, 1408), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1392, 1408), False, 'import pytest\n'), ((1546, 1576), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1560, 1576), False, 'import pytest\n'), ((1706, 1736), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1720, 1736), False, 'import pytest\n'), ((869, 915), 'os.path.join', 'os.path.join', (['"""not_exist_dir"""', '"""not_exist.jar"""'], {}), "('not_exist_dir', 'not_exist.jar')\n", (881, 915), False, 'import os\n'), ((997, 1042), 'os.path.expandvars', 'os.path.expandvars', (['"""${GS_TEST_DIR}/p2p-31.e"""'], {}), "('${GS_TEST_DIR}/p2p-31.e')\n", (1015, 1042), False, 'import os\n'), ((1106, 1160), 'os.path.expandvars', 'os.path.expandvars', (['"""${GS_TEST_DIR}/gars/sssp_pie.gar"""'], {}), "('${GS_TEST_DIR}/gars/sssp_pie.gar')\n", (1124, 1160), False, 'import os\n'), ((1223, 1274), 'os.path.expandvars', 'os.path.expandvars', (['"""${GS_TEST_DIR}/jars/empty.jar"""'], {}), "('${GS_TEST_DIR}/jars/empty.jar')\n", (1241, 1274), False, 'import os\n'), ((1336, 1374), 'os.path.expandvars', 'os.path.expandvars', (['"""${USER_JAR_PATH}"""'], {}), "('${USER_JAR_PATH}')\n", (1354, 1374), False, 'import os\n'), ((3783, 3839), 'graphscope.JavaApp', 'JavaApp', (['demo_jar', 'property_graph_sssp_vertex_data_class'], {}), '(demo_jar, property_graph_sssp_vertex_data_class)\n', (3790, 3839), False, 'from graphscope import JavaApp\n'), ((4118, 4208), 'graphscope.JavaApp', 'JavaApp', ([], {'full_jar_path': 'demo_jar', 'java_app_class': 'property_graph_sssp_vertex_data_class'}), '(full_jar_path=demo_jar, java_app_class=\n property_graph_sssp_vertex_data_class)\n', (4125, 4208), False, 'from graphscope import JavaApp\n'), ((4540, 4634), 'graphscope.JavaApp', 'JavaApp', ([], {'full_jar_path': 'demo_jar', 'java_app_class': 'property_graph_sssp_vertex_property_class'}), '(full_jar_path=demo_jar, java_app_class=\n property_graph_sssp_vertex_property_class)\n', (4547, 4634), False, 'from graphscope import JavaApp\n'), ((2079, 2111), 'pytest.raises', 'pytest.raises', (['FileNotFoundError'], {}), '(FileNotFoundError)\n', (2092, 2111), False, 'import pytest\n'), ((2128, 2189), 'graphscope.JavaApp', 'JavaApp', (['not_exist_jar', 'property_graph_sssp_vertex_data_class'], {}), '(not_exist_jar, property_graph_sssp_vertex_data_class)\n', (2135, 2189), False, 'from graphscope import JavaApp\n'), ((2199, 2231), 'pytest.raises', 'pytest.raises', (['FileNotFoundError'], {}), '(FileNotFoundError)\n', (2212, 2231), False, 'import pytest\n'), ((2248, 2292), 'graphscope.JavaApp', 'JavaApp', (['not_exist_jar', 'non_exist_java_class'], {}), '(not_exist_jar, non_exist_java_class)\n', (2255, 2292), False, 'from graphscope import JavaApp\n'), ((1860, 1892), 'os.environ.get', 'os.environ.get', (['"""RUN_JAVA_TESTS"""'], {}), "('RUN_JAVA_TESTS')\n", (1874, 1892), False, 'import os\n'), ((2531, 2554), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (2544, 2554), False, 'import pytest\n'), ((2571, 2631), 'graphscope.JavaApp', 'JavaApp', (['not_jar_file', 'property_graph_sssp_vertex_data_class'], {}), '(not_jar_file, property_graph_sssp_vertex_data_class)\n', (2578, 2631), False, 'from graphscope import JavaApp\n'), ((2641, 2664), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (2654, 2664), False, 'import pytest\n'), ((2681, 2724), 'graphscope.JavaApp', 'JavaApp', (['not_jar_file', 'non_exist_java_class'], {}), '(not_jar_file, non_exist_java_class)\n', (2688, 2724), False, 'from graphscope import JavaApp\n'), ((2320, 2352), 'os.environ.get', 'os.environ.get', (['"""RUN_JAVA_TESTS"""'], {}), "('RUN_JAVA_TESTS')\n", (2334, 2352), False, 'import os\n'), ((2960, 2983), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (2973, 2983), False, 'import pytest\n'), ((3000, 3058), 'graphscope.JavaApp', 'JavaApp', (['a_gar_file', 'property_graph_sssp_vertex_data_class'], {}), '(a_gar_file, property_graph_sssp_vertex_data_class)\n', (3007, 3058), False, 'from graphscope import JavaApp\n'), ((3068, 3091), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (3081, 3091), False, 'import pytest\n'), ((3108, 3149), 'graphscope.JavaApp', 'JavaApp', (['a_gar_file', 'non_exist_java_class'], {}), '(a_gar_file, non_exist_java_class)\n', (3115, 3149), False, 'from graphscope import JavaApp\n'), ((2752, 2784), 'os.environ.get', 'os.environ.get', (['"""RUN_JAVA_TESTS"""'], {}), "('RUN_JAVA_TESTS')\n", (2766, 2784), False, 'import os\n'), ((3385, 3408), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (3398, 3408), False, 'import pytest\n'), ((3425, 3482), 'graphscope.JavaApp', 'JavaApp', (['empty_jar', 'property_graph_sssp_vertex_data_class'], {}), '(empty_jar, property_graph_sssp_vertex_data_class)\n', (3432, 3482), False, 'from graphscope import JavaApp\n'), ((3492, 3515), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (3505, 3515), False, 'import pytest\n'), ((3532, 3572), 'graphscope.JavaApp', 'JavaApp', (['empty_jar', 'non_exist_java_class'], {}), '(empty_jar, non_exist_java_class)\n', (3539, 3572), False, 'from graphscope import JavaApp\n'), ((3177, 3209), 'os.environ.get', 'os.environ.get', (['"""RUN_JAVA_TESTS"""'], {}), "('RUN_JAVA_TESTS')\n", (3191, 3209), False, 'import os\n'), ((3600, 3632), 'os.environ.get', 'os.environ.get', (['"""RUN_JAVA_TESTS"""'], {}), "('RUN_JAVA_TESTS')\n", (3614, 3632), False, 'import os\n'), ((3867, 3899), 'os.environ.get', 'os.environ.get', (['"""RUN_JAVA_TESTS"""'], {}), "('RUN_JAVA_TESTS')\n", (3881, 3899), False, 'import os\n'), ((4281, 4313), 'os.environ.get', 'os.environ.get', (['"""RUN_JAVA_TESTS"""'], {}), "('RUN_JAVA_TESTS')\n", (4295, 4313), False, 'import os\n')]
|
#
# This file is referred and derived from project NetworkX
#
# which has the following license:
#
# Copyright (C) 2004-2020, NetworkX Developers
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# All rights reserved.
#
# This file is part of NetworkX.
#
# NetworkX is distributed under a BSD license; see LICENSE.txt for more
# information.
#
import networkx
import pytest
from networkx.classes.tests import test_graphviews as test_gvs
from graphscope.experimental import nx
from graphscope.experimental.nx.tests.utils import assert_edges_equal
from graphscope.experimental.nx.tests.utils import assert_nodes_equal
# Note: SubGraph views are not tested here. They have their own testing file
@pytest.mark.usefixtures("graphscope_session")
class TestReverseView(test_gvs.TestReverseView):
def setup_method(self):
self.G = nx.path_graph(9, create_using=nx.DiGraph())
self.rv = nx.reverse_view(self.G)
def test_exceptions(self):
nxg = networkx.graphviews
pytest.raises(nx.NetworkXNotImplemented, nxg.reverse_view, nx.Graph())
def test_subclass(self):
class MyGraph(nx.DiGraph):
def my_method(self):
return "me"
def to_directed_class(self):
return MyGraph()
M = MyGraph()
M.add_edge(1, 2)
RM = nx.reverse_view(M)
print("RM class", RM.__class__)
# RMC = RM.copy()
RMC = RM.copy(as_view=True)
print("RMC class", RMC.__class__)
print(RMC.edges)
assert RMC.has_edge(2, 1)
assert RMC.my_method() == "me"
class TestToDirected(test_gvs.TestToDirected):
def setup_method(self):
self.G = nx.path_graph(9)
self.dv = nx.to_directed(self.G)
def test_pickle(self):
pass
def test_already_directed(self):
pass
def test_already_directed(self):
dd = nx.to_directed(self.dv)
assert_edges_equal(dd.edges, self.dv.edges)
class TestToUndirected(test_gvs.TestToUndirected):
def setup_method(self):
self.DG = nx.path_graph(9, create_using=nx.DiGraph())
self.uv = nx.to_undirected(self.DG)
def test_pickle(self):
pass
def test_already_directed(self):
uu = nx.to_undirected(self.uv)
assert_edges_equal(uu.edges, self.uv.edges)
class TestChainsOfViews(test_gvs.TestChainsOfViews):
@classmethod
def setup_class(cls):
cls.G = nx.path_graph(9)
cls.DG = nx.path_graph(9, create_using=nx.DiGraph())
cls.Gv = nx.to_undirected(cls.DG)
cls.DGv = nx.to_directed(cls.G)
cls.Rv = cls.DG.reverse()
cls.graphs = [cls.G, cls.DG, cls.Gv, cls.DGv, cls.Rv]
for G in cls.graphs:
G.edges, G.nodes, G.degree
def test_pickle(self):
pass
def test_subgraph_of_subgraph(self):
SGv = nx.subgraph(self.G, range(3, 7))
SDGv = nx.subgraph(self.DG, range(3, 7))
for G in self.graphs + [SGv, SDGv]:
SG = nx.induced_subgraph(G, [4, 5, 6])
assert list(SG) == [4, 5, 6]
SSG = SG.subgraph([6, 7])
assert list(SSG) == [6]
# subgraph-subgraph chain is short-cut in base class method
assert SSG._graph is G
def test_restricted_induced_subgraph_chains(self):
"""Test subgraph chains that both restrict and show nodes/edges.
A restricted_view subgraph should allow induced subgraphs using
G.subgraph that automagically without a chain (meaning the result
is a subgraph view of the original graph not a subgraph-of-subgraph.
"""
hide_nodes = [3, 4, 5]
hide_edges = [(6, 7)]
RG = nx.restricted_view(self.G, hide_nodes, hide_edges)
nodes = [4, 5, 6, 7, 8]
SG = nx.induced_subgraph(RG, nodes)
SSG = RG.subgraph(nodes)
assert RG._graph is self.G
assert SSG._graph is self.G
assert SG._graph is RG
assert_edges_equal(SG.edges, SSG.edges)
# should be same as morphing the graph
CG = self.G.copy()
CG.remove_nodes_from(hide_nodes)
CG.remove_edges_from(hide_edges)
assert_edges_equal(CG.edges(nodes), SSG.edges)
CG.remove_nodes_from([0, 1, 2, 3])
assert_edges_equal(CG.edges, SSG.edges)
# switch order: subgraph first, then restricted view
SSSG = self.G.subgraph(nodes)
RSG = nx.restricted_view(SSSG, hide_nodes, hide_edges)
assert RSG._graph is not self.G
assert_edges_equal(RSG.edges, CG.edges)
@pytest.mark.skip(reason="not support order-like graph")
def test_subgraph_copy(self):
for origG in self.graphs:
G = nx.OrderedGraph(origG)
SG = G.subgraph([4, 5, 6])
H = SG.copy()
assert type(G) == type(H)
def test_subgraph_toundirected(self):
SG = nx.induced_subgraph(self.G, [4, 5, 6])
# FIXME: not match like networkx.
SSG = SG.to_undirected(as_view=True)
assert list(SSG) == [4, 5, 6]
assert sorted(SSG.edges) == [(4, 5), (5, 6)]
def test_reverse_subgraph_toundirected(self):
G = self.DG.reverse(copy=False)
SG = G.subgraph([4, 5, 6])
# FIXME: not match like networkx.
SSG = SG.to_undirected(as_view=True)
assert list(SSG) == [4, 5, 6]
assert sorted(SSG.edges) == [(4, 5), (5, 6)]
def test_reverse_reverse_copy(self):
G = self.DG.reverse(copy=False)
# FIXME: not match networkx
# H = G.reverse(copy=True)
H = G.reverse(copy=False)
assert H.nodes == self.DG.nodes
assert H.edges == self.DG.edges
def test_subgraph_edgesubgraph_toundirected(self):
G = self.G.copy()
SG = G.subgraph([4, 5, 6])
SSG = SG.edge_subgraph([(4, 5), (5, 4)])
USSG = SSG.to_undirected(as_view=True)
assert list(USSG) == [4, 5]
assert sorted(USSG.edges) == [(4, 5)]
def test_copy_multidisubgraph(self):
pass
def test_copy_multisubgraph(self):
pass
@pytest.mark.skip(reason="not support order-like graph")
def test_copy_of_view(self):
G = nx.OrderedMultiGraph(self.MGv)
assert G.__class__.__name__ == "OrderedMultiGraph"
G = G.copy(as_view=True)
assert G.__class__.__name__ == "OrderedMultiGraph"
@pytest.mark.skip(reason="subgraph now is fallback with networkx, not view")
def test_subgraph_of_subgraph(self):
pass
@pytest.mark.skip(reason="subgraph now is fallback with networkx, not view")
def test_restricted_induced_subgraph_chains(self):
pass
|
[
"graphscope.experimental.nx.OrderedGraph",
"graphscope.experimental.nx.path_graph",
"graphscope.experimental.nx.OrderedMultiGraph",
"graphscope.experimental.nx.tests.utils.assert_edges_equal",
"graphscope.experimental.nx.to_undirected",
"graphscope.experimental.nx.induced_subgraph",
"graphscope.experimental.nx.DiGraph",
"graphscope.experimental.nx.reverse_view",
"graphscope.experimental.nx.restricted_view",
"pytest.mark.skip",
"graphscope.experimental.nx.to_directed",
"graphscope.experimental.nx.Graph",
"pytest.mark.usefixtures"
] |
[((706, 751), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (729, 751), False, 'import pytest\n'), ((4569, 4624), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""not support order-like graph"""'}), "(reason='not support order-like graph')\n", (4585, 4624), False, 'import pytest\n'), ((6088, 6143), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""not support order-like graph"""'}), "(reason='not support order-like graph')\n", (6104, 6143), False, 'import pytest\n'), ((6377, 6452), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""subgraph now is fallback with networkx, not view"""'}), "(reason='subgraph now is fallback with networkx, not view')\n", (6393, 6452), False, 'import pytest\n'), ((6513, 6588), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""subgraph now is fallback with networkx, not view"""'}), "(reason='subgraph now is fallback with networkx, not view')\n", (6529, 6588), False, 'import pytest\n'), ((908, 931), 'graphscope.experimental.nx.reverse_view', 'nx.reverse_view', (['self.G'], {}), '(self.G)\n', (923, 931), False, 'from graphscope.experimental import nx\n'), ((1339, 1357), 'graphscope.experimental.nx.reverse_view', 'nx.reverse_view', (['M'], {}), '(M)\n', (1354, 1357), False, 'from graphscope.experimental import nx\n'), ((1694, 1710), 'graphscope.experimental.nx.path_graph', 'nx.path_graph', (['(9)'], {}), '(9)\n', (1707, 1710), False, 'from graphscope.experimental import nx\n'), ((1729, 1751), 'graphscope.experimental.nx.to_directed', 'nx.to_directed', (['self.G'], {}), '(self.G)\n', (1743, 1751), False, 'from graphscope.experimental import nx\n'), ((1895, 1918), 'graphscope.experimental.nx.to_directed', 'nx.to_directed', (['self.dv'], {}), '(self.dv)\n', (1909, 1918), False, 'from graphscope.experimental import nx\n'), ((1927, 1970), 'graphscope.experimental.nx.tests.utils.assert_edges_equal', 'assert_edges_equal', (['dd.edges', 'self.dv.edges'], {}), '(dd.edges, self.dv.edges)\n', (1945, 1970), False, 'from graphscope.experimental.nx.tests.utils import assert_edges_equal\n'), ((2132, 2157), 'graphscope.experimental.nx.to_undirected', 'nx.to_undirected', (['self.DG'], {}), '(self.DG)\n', (2148, 2157), False, 'from graphscope.experimental import nx\n'), ((2250, 2275), 'graphscope.experimental.nx.to_undirected', 'nx.to_undirected', (['self.uv'], {}), '(self.uv)\n', (2266, 2275), False, 'from graphscope.experimental import nx\n'), ((2284, 2327), 'graphscope.experimental.nx.tests.utils.assert_edges_equal', 'assert_edges_equal', (['uu.edges', 'self.uv.edges'], {}), '(uu.edges, self.uv.edges)\n', (2302, 2327), False, 'from graphscope.experimental.nx.tests.utils import assert_edges_equal\n'), ((2442, 2458), 'graphscope.experimental.nx.path_graph', 'nx.path_graph', (['(9)'], {}), '(9)\n', (2455, 2458), False, 'from graphscope.experimental import nx\n'), ((2537, 2561), 'graphscope.experimental.nx.to_undirected', 'nx.to_undirected', (['cls.DG'], {}), '(cls.DG)\n', (2553, 2561), False, 'from graphscope.experimental import nx\n'), ((2580, 2601), 'graphscope.experimental.nx.to_directed', 'nx.to_directed', (['cls.G'], {}), '(cls.G)\n', (2594, 2601), False, 'from graphscope.experimental import nx\n'), ((3701, 3751), 'graphscope.experimental.nx.restricted_view', 'nx.restricted_view', (['self.G', 'hide_nodes', 'hide_edges'], {}), '(self.G, hide_nodes, hide_edges)\n', (3719, 3751), False, 'from graphscope.experimental import nx\n'), ((3797, 3827), 'graphscope.experimental.nx.induced_subgraph', 'nx.induced_subgraph', (['RG', 'nodes'], {}), '(RG, nodes)\n', (3816, 3827), False, 'from graphscope.experimental import nx\n'), ((3971, 4010), 'graphscope.experimental.nx.tests.utils.assert_edges_equal', 'assert_edges_equal', (['SG.edges', 'SSG.edges'], {}), '(SG.edges, SSG.edges)\n', (3989, 4010), False, 'from graphscope.experimental.nx.tests.utils import assert_edges_equal\n'), ((4273, 4312), 'graphscope.experimental.nx.tests.utils.assert_edges_equal', 'assert_edges_equal', (['CG.edges', 'SSG.edges'], {}), '(CG.edges, SSG.edges)\n', (4291, 4312), False, 'from graphscope.experimental.nx.tests.utils import assert_edges_equal\n'), ((4426, 4474), 'graphscope.experimental.nx.restricted_view', 'nx.restricted_view', (['SSSG', 'hide_nodes', 'hide_edges'], {}), '(SSSG, hide_nodes, hide_edges)\n', (4444, 4474), False, 'from graphscope.experimental import nx\n'), ((4523, 4562), 'graphscope.experimental.nx.tests.utils.assert_edges_equal', 'assert_edges_equal', (['RSG.edges', 'CG.edges'], {}), '(RSG.edges, CG.edges)\n', (4541, 4562), False, 'from graphscope.experimental.nx.tests.utils import assert_edges_equal\n'), ((4891, 4929), 'graphscope.experimental.nx.induced_subgraph', 'nx.induced_subgraph', (['self.G', '[4, 5, 6]'], {}), '(self.G, [4, 5, 6])\n', (4910, 4929), False, 'from graphscope.experimental import nx\n'), ((6189, 6219), 'graphscope.experimental.nx.OrderedMultiGraph', 'nx.OrderedMultiGraph', (['self.MGv'], {}), '(self.MGv)\n', (6209, 6219), False, 'from graphscope.experimental import nx\n'), ((1065, 1075), 'graphscope.experimental.nx.Graph', 'nx.Graph', ([], {}), '()\n', (1073, 1075), False, 'from graphscope.experimental import nx\n'), ((3006, 3039), 'graphscope.experimental.nx.induced_subgraph', 'nx.induced_subgraph', (['G', '[4, 5, 6]'], {}), '(G, [4, 5, 6])\n', (3025, 3039), False, 'from graphscope.experimental import nx\n'), ((4709, 4731), 'graphscope.experimental.nx.OrderedGraph', 'nx.OrderedGraph', (['origG'], {}), '(origG)\n', (4724, 4731), False, 'from graphscope.experimental import nx\n'), ((876, 888), 'graphscope.experimental.nx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (886, 888), False, 'from graphscope.experimental import nx\n'), ((2100, 2112), 'graphscope.experimental.nx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (2110, 2112), False, 'from graphscope.experimental import nx\n'), ((2506, 2518), 'graphscope.experimental.nx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (2516, 2518), False, 'from graphscope.experimental import nx\n')]
|
import networkx.algorithms.tests.test_threshold
import pytest
from graphscope.nx.utils.compat import import_as_graphscope_nx
from graphscope.nx.utils.compat import with_graphscope_nx_context
import_as_graphscope_nx(networkx.algorithms.tests.test_threshold,
decorators=pytest.mark.usefixtures("graphscope_session"))
from networkx.algorithms.tests.test_threshold import TestGeneratorThreshold
@pytest.mark.usefixtures("graphscope_session")
@with_graphscope_nx_context(TestGeneratorThreshold)
class TestGeneratorThreshold:
def test_eigenvectors(self):
np = pytest.importorskip('numpy')
eigenval = np.linalg.eigvals
scipy = pytest.importorskip('scipy')
cs = 'ddiiddid'
G = nxt.threshold_graph(cs)
(tgeval, tgevec) = nxt.eigenvectors(cs)
dot = np.dot
assert [abs(dot(lv, lv) - 1.0) < 1e-9 for lv in tgevec] == [True] * 8
def test_create_using(self):
cs = 'ddiiddid'
G = nxt.threshold_graph(cs)
assert pytest.raises(nx.exception.NetworkXError,
nxt.threshold_graph,
cs,
create_using=nx.DiGraph())
|
[
"pytest.importorskip",
"graphscope.nx.utils.compat.with_graphscope_nx_context",
"pytest.mark.usefixtures"
] |
[((421, 466), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (444, 466), False, 'import pytest\n'), ((468, 518), 'graphscope.nx.utils.compat.with_graphscope_nx_context', 'with_graphscope_nx_context', (['TestGeneratorThreshold'], {}), '(TestGeneratorThreshold)\n', (494, 518), False, 'from graphscope.nx.utils.compat import with_graphscope_nx_context\n'), ((294, 339), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (317, 339), False, 'import pytest\n'), ((595, 623), 'pytest.importorskip', 'pytest.importorskip', (['"""numpy"""'], {}), "('numpy')\n", (614, 623), False, 'import pytest\n'), ((677, 705), 'pytest.importorskip', 'pytest.importorskip', (['"""scipy"""'], {}), "('scipy')\n", (696, 705), False, 'import pytest\n')]
|
import networkx.algorithms.tests.test_triads
import pytest
from graphscope.nx.utils.compat import import_as_graphscope_nx
import_as_graphscope_nx(networkx.algorithms.tests.test_triads,
decorators=pytest.mark.usefixtures("graphscope_session"))
from collections import defaultdict
from itertools import permutations
from random import sample
import graphscope.nx as nx
# FIXME(@weibin): forward is_triad does not replace networkx with graphscope.nx correctly.
def is_triad(G):
"""Returns True if the graph G is a triad, else False.
Parameters
----------
G : graph
A NetworkX Graph
Returns
-------
istriad : boolean
Whether G is a valid triad
"""
if isinstance(G, nx.Graph):
if G.order() == 3 and nx.is_directed(G):
if not any((n, n) in G.edges() for n in G.nodes()):
return True
return False
# FIXME(@weibin): forward is_triad does not replace networkx with graphscope.nx correctly.
def triad_type(G):
if not is_triad(G):
raise nx.NetworkXAlgorithmError("G is not a triad (order-3 DiGraph)")
num_edges = len(G.edges())
if num_edges == 0:
return "003"
if num_edges == 1:
return "012"
if num_edges == 2:
e1, e2 = G.edges()
if set(e1) == set(e2):
return "102"
if e1[0] == e2[0]:
return "021D"
if e1[1] == e2[1]:
return "021U"
if e1[1] == e2[0] or e2[1] == e1[0]:
return "021C"
if num_edges == 3:
for (e1, e2, e3) in permutations(G.edges(), 3):
if set(e1) == set(e2):
if e3[0] in e1:
return "111U"
# e3[1] in e1:
return "111D"
if set(e1).symmetric_difference(set(e2)) == set(e3):
if {e1[0], e2[0], e3[0]} == {e1[0], e2[0], e3[0]} == set(G.nodes()):
return "030C"
# e3 == (e1[0], e2[1]) and e2 == (e1[1], e3[1]):
return "030T"
if num_edges == 4:
for (e1, e2, e3, e4) in permutations(G.edges(), 4):
if set(e1) == set(e2):
# identify pair of symmetric edges (which necessarily exists)
if set(e3) == set(e4):
return "201"
if {e3[0]} == {e4[0]} == set(e3).intersection(set(e4)):
return "120D"
if {e3[1]} == {e4[1]} == set(e3).intersection(set(e4)):
return "120U"
if e3[1] == e4[0]:
return "120C"
if num_edges == 5:
return "210"
if num_edges == 6:
return "300"
def triads_by_type(G):
"""Returns a list of all triads for each triad type in a directed graph.
Parameters
----------
G : digraph
A NetworkX DiGraph
Returns
-------
tri_by_type : dict
Dictionary with triad types as keys and lists of triads as values.
"""
# num_triads = o * (o - 1) * (o - 2) // 6
# if num_triads > TRIAD_LIMIT: print(WARNING)
all_tri = nx.all_triads(G)
tri_by_type = defaultdict(list)
for triad in all_tri:
name = triad_type(triad)
tri_by_type[name].append(triad)
return tri_by_type
@pytest.mark.usefixtures("graphscope_session")
def test_is_triad():
"""Tests the is_triad function"""
G = nx.karate_club_graph()
G = G.to_directed()
for i in range(100):
nodes = sample(G.nodes(), 3)
G2 = G.subgraph(nodes)
assert is_triad(G2)
@pytest.mark.usefixtures("graphscope_session")
def test_triad_type():
"""Tests the triad_type function."""
# 0 edges (1 type)
G = nx.DiGraph({0: [], 1: [], 2: []})
assert triad_type(G) == "003"
# 1 edge (1 type)
G = nx.DiGraph({0: [1], 1: [], 2: []})
assert triad_type(G) == "012"
# 2 edges (4 types)
G = nx.DiGraph([(0, 1), (0, 2)])
assert triad_type(G) == "021D"
G = nx.DiGraph({0: [1], 1: [0], 2: []})
assert triad_type(G) == "102"
G = nx.DiGraph([(0, 1), (2, 1)])
assert triad_type(G) == "021U"
G = nx.DiGraph([(0, 1), (1, 2)])
assert triad_type(G) == "021C"
# 3 edges (4 types)
G = nx.DiGraph([(0, 1), (1, 0), (2, 1)])
assert triad_type(G) == "111D"
G = nx.DiGraph([(0, 1), (1, 0), (1, 2)])
assert triad_type(G) == "111U"
G = nx.DiGraph([(0, 1), (1, 2), (0, 2)])
assert triad_type(G) == "030T"
G = nx.DiGraph([(0, 1), (1, 2), (2, 0)])
assert triad_type(G) == "030C"
# 4 edges (4 types)
G = nx.DiGraph([(0, 1), (1, 0), (2, 0), (0, 2)])
assert triad_type(G) == "201"
G = nx.DiGraph([(0, 1), (1, 0), (2, 0), (2, 1)])
assert triad_type(G) == "120D"
G = nx.DiGraph([(0, 1), (1, 0), (0, 2), (1, 2)])
assert triad_type(G) == "120U"
G = nx.DiGraph([(0, 1), (1, 0), (0, 2), (2, 1)])
assert triad_type(G) == "120C"
# 5 edges (1 type)
G = nx.DiGraph([(0, 1), (1, 0), (2, 1), (1, 2), (0, 2)])
assert triad_type(G) == "210"
# 6 edges (1 type)
G = nx.DiGraph([(0, 1), (1, 0), (1, 2), (2, 1), (0, 2), (2, 0)])
assert triad_type(G) == "300"
@pytest.mark.usefixtures("graphscope_session")
def test_triads_by_type():
"""Tests the all_triplets function."""
G = nx.DiGraph()
G.add_edges_from(["01", "02", "03", "04", "05", "12", "16", "51", "56", "65"])
all_triads = nx.all_triads(G)
expected = defaultdict(list)
for triad in all_triads:
name = triad_type(triad)
expected[name].append(triad)
actual = triads_by_type(G)
assert set(actual.keys()) == set(expected.keys())
for tri_type, actual_Gs in actual.items():
expected_Gs = expected[tri_type]
for a in actual_Gs:
assert any(nx.is_isomorphic(a, e) for e in expected_Gs)
@pytest.mark.usefixtures("graphscope_session")
def test_random_triad():
"""Tests the random_triad function"""
G = nx.karate_club_graph()
G = G.to_directed()
for i in range(100):
assert is_triad(nx.random_triad(G))
|
[
"graphscope.nx.is_isomorphic",
"graphscope.nx.DiGraph",
"graphscope.nx.is_directed",
"graphscope.nx.random_triad",
"collections.defaultdict",
"graphscope.nx.karate_club_graph",
"graphscope.nx.all_triads",
"pytest.mark.usefixtures",
"graphscope.nx.NetworkXAlgorithmError"
] |
[((3278, 3323), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (3301, 3323), False, 'import pytest\n'), ((3562, 3607), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (3585, 3607), False, 'import pytest\n'), ((5154, 5199), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (5177, 5199), False, 'import pytest\n'), ((5812, 5857), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (5835, 5857), False, 'import pytest\n'), ((3100, 3116), 'graphscope.nx.all_triads', 'nx.all_triads', (['G'], {}), '(G)\n', (3113, 3116), True, 'import graphscope.nx as nx\n'), ((3135, 3152), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (3146, 3152), False, 'from collections import defaultdict\n'), ((3391, 3413), 'graphscope.nx.karate_club_graph', 'nx.karate_club_graph', ([], {}), '()\n', (3411, 3413), True, 'import graphscope.nx as nx\n'), ((3703, 3742), 'graphscope.nx.DiGraph', 'nx.DiGraph', (['{(0): [], (1): [], (2): []}'], {}), '({(0): [], (1): [], (2): []})\n', (3713, 3742), True, 'import graphscope.nx as nx\n'), ((3801, 3841), 'graphscope.nx.DiGraph', 'nx.DiGraph', (['{(0): [1], (1): [], (2): []}'], {}), '({(0): [1], (1): [], (2): []})\n', (3811, 3841), True, 'import graphscope.nx as nx\n'), ((3902, 3930), 'graphscope.nx.DiGraph', 'nx.DiGraph', (['[(0, 1), (0, 2)]'], {}), '([(0, 1), (0, 2)])\n', (3912, 3930), True, 'import graphscope.nx as nx\n'), ((3974, 4015), 'graphscope.nx.DiGraph', 'nx.DiGraph', (['{(0): [1], (1): [0], (2): []}'], {}), '({(0): [1], (1): [0], (2): []})\n', (3984, 4015), True, 'import graphscope.nx as nx\n'), ((4052, 4080), 'graphscope.nx.DiGraph', 'nx.DiGraph', (['[(0, 1), (2, 1)]'], {}), '([(0, 1), (2, 1)])\n', (4062, 4080), True, 'import graphscope.nx as nx\n'), ((4124, 4152), 'graphscope.nx.DiGraph', 'nx.DiGraph', (['[(0, 1), (1, 2)]'], {}), '([(0, 1), (1, 2)])\n', (4134, 4152), True, 'import graphscope.nx as nx\n'), ((4220, 4256), 'graphscope.nx.DiGraph', 'nx.DiGraph', (['[(0, 1), (1, 0), (2, 1)]'], {}), '([(0, 1), (1, 0), (2, 1)])\n', (4230, 4256), True, 'import graphscope.nx as nx\n'), ((4300, 4336), 'graphscope.nx.DiGraph', 'nx.DiGraph', (['[(0, 1), (1, 0), (1, 2)]'], {}), '([(0, 1), (1, 0), (1, 2)])\n', (4310, 4336), True, 'import graphscope.nx as nx\n'), ((4380, 4416), 'graphscope.nx.DiGraph', 'nx.DiGraph', (['[(0, 1), (1, 2), (0, 2)]'], {}), '([(0, 1), (1, 2), (0, 2)])\n', (4390, 4416), True, 'import graphscope.nx as nx\n'), ((4460, 4496), 'graphscope.nx.DiGraph', 'nx.DiGraph', (['[(0, 1), (1, 2), (2, 0)]'], {}), '([(0, 1), (1, 2), (2, 0)])\n', (4470, 4496), True, 'import graphscope.nx as nx\n'), ((4564, 4608), 'graphscope.nx.DiGraph', 'nx.DiGraph', (['[(0, 1), (1, 0), (2, 0), (0, 2)]'], {}), '([(0, 1), (1, 0), (2, 0), (0, 2)])\n', (4574, 4608), True, 'import graphscope.nx as nx\n'), ((4651, 4695), 'graphscope.nx.DiGraph', 'nx.DiGraph', (['[(0, 1), (1, 0), (2, 0), (2, 1)]'], {}), '([(0, 1), (1, 0), (2, 0), (2, 1)])\n', (4661, 4695), True, 'import graphscope.nx as nx\n'), ((4739, 4783), 'graphscope.nx.DiGraph', 'nx.DiGraph', (['[(0, 1), (1, 0), (0, 2), (1, 2)]'], {}), '([(0, 1), (1, 0), (0, 2), (1, 2)])\n', (4749, 4783), True, 'import graphscope.nx as nx\n'), ((4827, 4871), 'graphscope.nx.DiGraph', 'nx.DiGraph', (['[(0, 1), (1, 0), (0, 2), (2, 1)]'], {}), '([(0, 1), (1, 0), (0, 2), (2, 1)])\n', (4837, 4871), True, 'import graphscope.nx as nx\n'), ((4938, 4990), 'graphscope.nx.DiGraph', 'nx.DiGraph', (['[(0, 1), (1, 0), (2, 1), (1, 2), (0, 2)]'], {}), '([(0, 1), (1, 0), (2, 1), (1, 2), (0, 2)])\n', (4948, 4990), True, 'import graphscope.nx as nx\n'), ((5056, 5116), 'graphscope.nx.DiGraph', 'nx.DiGraph', (['[(0, 1), (1, 0), (1, 2), (2, 1), (0, 2), (2, 0)]'], {}), '([(0, 1), (1, 0), (1, 2), (2, 1), (0, 2), (2, 0)])\n', (5066, 5116), True, 'import graphscope.nx as nx\n'), ((5278, 5290), 'graphscope.nx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (5288, 5290), True, 'import graphscope.nx as nx\n'), ((5391, 5407), 'graphscope.nx.all_triads', 'nx.all_triads', (['G'], {}), '(G)\n', (5404, 5407), True, 'import graphscope.nx as nx\n'), ((5423, 5440), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (5434, 5440), False, 'from collections import defaultdict\n'), ((5933, 5955), 'graphscope.nx.karate_club_graph', 'nx.karate_club_graph', ([], {}), '()\n', (5953, 5955), True, 'import graphscope.nx as nx\n'), ((222, 267), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""graphscope_session"""'], {}), "('graphscope_session')\n", (245, 267), False, 'import pytest\n'), ((1062, 1125), 'graphscope.nx.NetworkXAlgorithmError', 'nx.NetworkXAlgorithmError', (['"""G is not a triad (order-3 DiGraph)"""'], {}), "('G is not a triad (order-3 DiGraph)')\n", (1087, 1125), True, 'import graphscope.nx as nx\n'), ((784, 801), 'graphscope.nx.is_directed', 'nx.is_directed', (['G'], {}), '(G)\n', (798, 801), True, 'import graphscope.nx as nx\n'), ((6029, 6047), 'graphscope.nx.random_triad', 'nx.random_triad', (['G'], {}), '(G)\n', (6044, 6047), True, 'import graphscope.nx as nx\n'), ((5764, 5786), 'graphscope.nx.is_isomorphic', 'nx.is_isomorphic', (['a', 'e'], {}), '(a, e)\n', (5780, 5786), True, 'import graphscope.nx as nx\n')]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.