repo_id
stringlengths
21
96
file_path
stringlengths
31
155
content
stringlengths
1
92.9M
__index_level_0__
int64
0
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/louvain.pyx
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) from pylibcugraph._cugraph_c.community_algorithms cimport ( cugraph_hierarchical_clustering_result_t, cugraph_louvain, cugraph_hierarchical_clustering_result_get_vertices, cugraph_hierarchical_clustering_result_get_clusters, cugraph_hierarchical_clustering_result_get_modularity, cugraph_hierarchical_clustering_result_free, ) from pylibcugraph.resource_handle cimport ( ResourceHandle, ) from pylibcugraph.graphs cimport ( _GPUGraph, ) from pylibcugraph.utils cimport ( assert_success, copy_to_cupy_array, ) def louvain(ResourceHandle resource_handle, _GPUGraph graph, size_t max_level, float threshold, float resolution, bool_t do_expensive_check): """ Compute the modularity optimizing partition of the input graph using the Louvain method. Parameters ---------- resource_handle : ResourceHandle Handle to the underlying device resources needed for referencing data and running algorithms. graph : SGGraph or MGGraph The input graph. max_level: size_t This controls the maximum number of levels/iterations of the Louvain algorithm. When specified the algorithm will terminate after no more than the specified number of iterations. No error occurs when the algorithm terminates early in this manner. threshold: float Modularity gain threshold for each level. If the gain of modularity between 2 levels of the algorithm is less than the given threshold then the algorithm stops and returns the resulting communities. resolution: float Called gamma in the modularity formula, this changes the size of the communities. Higher resolutions lead to more smaller communities, lower resolutions lead to fewer larger communities. do_expensive_check : bool_t If True, performs more extensive tests on the inputs to ensure validitity, at the expense of increased run time. Returns ------- A tuple containing the hierarchical clustering vertices, clusters and modularity score Examples -------- >>> import pylibcugraph, cupy, numpy >>> srcs = cupy.asarray([0, 1, 2], dtype=numpy.int32) >>> dsts = cupy.asarray([1, 2, 0], dtype=numpy.int32) >>> weights = cupy.asarray([1.0, 1.0, 1.0], dtype=numpy.float32) >>> resource_handle = pylibcugraph.ResourceHandle() >>> graph_props = pylibcugraph.GraphProperties( ... is_symmetric=True, is_multigraph=False) >>> G = pylibcugraph.SGGraph( ... resource_handle, graph_props, srcs, dsts, weights, ... store_transposed=True, renumber=False, do_expensive_check=False) >>> (vertices, clusters, modularity) = pylibcugraph.louvain( resource_handle, G, 100, 1e-7, 1., False) >>> vertices [0, 1, 2] >>> clusters [0, 0, 0] >>> modularity 0.0 """ cdef cugraph_resource_handle_t* c_resource_handle_ptr = \ resource_handle.c_resource_handle_ptr cdef cugraph_graph_t* c_graph_ptr = graph.c_graph_ptr cdef cugraph_hierarchical_clustering_result_t* result_ptr cdef cugraph_error_code_t error_code cdef cugraph_error_t* error_ptr error_code = cugraph_louvain(c_resource_handle_ptr, c_graph_ptr, max_level, threshold, resolution, do_expensive_check, &result_ptr, &error_ptr) assert_success(error_code, error_ptr, "cugraph_louvain") # Extract individual device array pointers from result and copy to cupy # arrays for returning. cdef cugraph_type_erased_device_array_view_t* vertices_ptr = \ cugraph_hierarchical_clustering_result_get_vertices(result_ptr) cdef cugraph_type_erased_device_array_view_t* clusters_ptr = \ cugraph_hierarchical_clustering_result_get_clusters(result_ptr) cdef double modularity = \ cugraph_hierarchical_clustering_result_get_modularity(result_ptr) cupy_vertices = copy_to_cupy_array(c_resource_handle_ptr, vertices_ptr) cupy_clusters = copy_to_cupy_array(c_resource_handle_ptr, clusters_ptr) cugraph_hierarchical_clustering_result_free(result_ptr) return (cupy_vertices, cupy_clusters, modularity)
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/_version.py
# Copyright (c) 2023, NVIDIA CORPORATION. # # 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 importlib.resources # Read VERSION file from the module that is symlinked to VERSION file # in the root of the repo at build time or copied to the moudle at # installation. VERSION is a separate file that allows CI build-time scripts # to update version info (including commit hashes) without modifying # source files. __version__ = ( importlib.resources.files("pylibcugraph").joinpath("VERSION").read_text().strip() ) __git_commit__ = ""
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/sssp.pyx
# Copyright (c) 2022, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, data_type_id_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) from pylibcugraph._cugraph_c.algorithms cimport ( cugraph_sssp, cugraph_paths_result_t, cugraph_paths_result_get_vertices, cugraph_paths_result_get_distances, cugraph_paths_result_get_predecessors, cugraph_paths_result_free, ) from pylibcugraph.resource_handle cimport ( ResourceHandle, ) from pylibcugraph.graphs cimport ( _GPUGraph, ) from pylibcugraph.utils cimport ( assert_success, copy_to_cupy_array, ) def sssp(ResourceHandle resource_handle, _GPUGraph graph, size_t source, double cutoff, bool_t compute_predecessors, bool_t do_expensive_check): """ Compute the distance and predecessors for shortest paths from the specified source to all the vertices in the graph. The returned distances array will contain the distance from the source to each vertex in the returned vertex array at the same index. The returned predecessors array will contain the previous vertex in the shortest path for each vertex in the vertex array at the same index. Vertices that are unreachable will have a distance of infinity denoted by the maximum value of the data type and the predecessor set as -1. The source vertex predecessor will be set to -1. Graphs with negative weight cycles are not supported. Parameters ---------- resource_handle : ResourceHandle Handle to the underlying device resources needed for referencing data and running algorithms. graph : SGGraph or MGGraph The input graph, for either Single or Multi-GPU operations. source : The vertex identifier of the source vertex. cutoff : Maximum edge weight sum to consider. compute_predecessors : bool This parameter must be set to True for this release. do_expensive_check : bool If True, performs more extensive tests on the inputs to ensure validitity, at the expense of increased run time. Returns ------- A 3-tuple, where the first item in the tuple is a device array containing the vertex identifiers, the second item is a device array containing the distance for each vertex from the source vertex, and the third item is a device array containing the vertex identifier of the preceding vertex in the path for that vertex. For example, the vertex identifier at the ith element of the vertex array has a distance from the source vertex of the ith element in the distance array, and the preceding vertex in the path is the ith element in the predecessor array. Examples -------- >>> import pylibcugraph, cupy, numpy >>> srcs = cupy.asarray([0, 1, 2], dtype=numpy.int32) >>> dsts = cupy.asarray([1, 2, 3], dtype=numpy.int32) >>> weights = cupy.asarray([1.0, 1.0, 1.0], dtype=numpy.float32) >>> resource_handle = pylibcugraph.ResourceHandle() >>> graph_props = pylibcugraph.GraphProperties( ... is_symmetric=False, is_multigraph=False) >>> G = pylibcugraph.SGGraph( ... resource_handle, graph_props, srcs, dsts, weights, ... store_transposed=False, renumber=False, do_expensive_check=False) >>> (vertices, distances, predecessors) = pylibcugraph.sssp( ... resource_handle, G, source=1, cutoff=999, ... compute_predecessors=True, do_expensive_check=False) >>> vertices array([0, 1, 2, 3], dtype=int32) >>> distances array([3.4028235e+38, 0.0000000e+00, 1.0000000e+00, 2.0000000e+00], dtype=float32) >>> predecessors array([-1, -1, 1, 2], dtype=int32) """ # FIXME: import these modules here for now until a better pattern can be # used for optional imports (perhaps 'import_optional()' from cugraph), or # these are made hard dependencies. try: import cupy except ModuleNotFoundError: raise RuntimeError("sssp requires the cupy package, which could not " "be imported") try: import numpy except ModuleNotFoundError: raise RuntimeError("sssp requires the numpy package, which could not " "be imported") if compute_predecessors is False: raise ValueError("compute_predecessors must be True for the current " "release.") cdef cugraph_resource_handle_t* c_resource_handle_ptr = \ resource_handle.c_resource_handle_ptr cdef cugraph_graph_t* c_graph_ptr = graph.c_graph_ptr cdef cugraph_paths_result_t* result_ptr cdef cugraph_error_code_t error_code cdef cugraph_error_t* error_ptr error_code = cugraph_sssp(c_resource_handle_ptr, c_graph_ptr, source, cutoff, compute_predecessors, do_expensive_check, &result_ptr, &error_ptr) assert_success(error_code, error_ptr, "cugraph_sssp") # Extract individual device array pointers from result and copy to cupy # arrays for returning. cdef cugraph_type_erased_device_array_view_t* vertices_ptr = \ cugraph_paths_result_get_vertices(result_ptr) cdef cugraph_type_erased_device_array_view_t* distances_ptr = \ cugraph_paths_result_get_distances(result_ptr) cdef cugraph_type_erased_device_array_view_t* predecessors_ptr = \ cugraph_paths_result_get_predecessors(result_ptr) cupy_vertices = copy_to_cupy_array(c_resource_handle_ptr, vertices_ptr) cupy_distances = copy_to_cupy_array(c_resource_handle_ptr, distances_ptr) cupy_predecessors = copy_to_cupy_array(c_resource_handle_ptr, predecessors_ptr) cugraph_paths_result_free(result_ptr) return (cupy_vertices, cupy_distances, cupy_predecessors)
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/egonet.pyx
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from libc.stdint cimport uintptr_t from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, data_type_id_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) from pylibcugraph._cugraph_c.graph_functions cimport ( cugraph_induced_subgraph_result_t, cugraph_induced_subgraph_get_sources, cugraph_induced_subgraph_get_destinations, cugraph_induced_subgraph_get_edge_weights, cugraph_induced_subgraph_get_subgraph_offsets, cugraph_induced_subgraph_result_free, ) from pylibcugraph._cugraph_c.community_algorithms cimport ( cugraph_extract_ego, ) from pylibcugraph.resource_handle cimport ( ResourceHandle, ) from pylibcugraph.graphs cimport ( _GPUGraph, ) from pylibcugraph.utils cimport ( assert_success, copy_to_cupy_array, create_cugraph_type_erased_device_array_view_from_py_obj, ) def ego_graph(ResourceHandle resource_handle, _GPUGraph graph, source_vertices, size_t radius, bool_t do_expensive_check): """ Compute the induced subgraph of neighbors centered at nodes source_vertices, within a given radius. Parameters ---------- resource_handle : ResourceHandle Handle to the underlying device resources needed for referencing data and running algorithms. graph : SGGraph or MGGraph The input graph. source_vertices : cupy array The centered nodes from which the induced subgraph will be extracted radius: size_t The number of hops to go out from each source vertex do_expensive_check : bool_t If True, performs more extensive tests on the inputs to ensure validitity, at the expense of increased run time. Returns ------- A tuple of device arrays containing the sources, destinations, edge_weights and the subgraph_offsets(if there are more than one seeds) Examples -------- >>> import pylibcugraph, cupy, numpy >>> srcs = cupy.asarray([0, 1, 1, 2, 2, 2, 3, 3, 4], dtype=numpy.int32) >>> dsts = cupy.asarray([1, 3, 4, 0, 1, 3, 4, 5, 5], dtype=numpy.int32) >>> weights = cupy.asarray( ... [0.1, 2.1, 1.1, 5.1, 3.1, 4.1, 7.2, 3.2, 6.1], dtype=numpy.float32) >>> source_vertices = cupy.asarray([0, 1], dtype=numpy.int32) >>> resource_handle = pylibcugraph.ResourceHandle() >>> graph_props = pylibcugraph.GraphProperties( ... is_symmetric=False, is_multigraph=False) >>> G = pylibcugraph.SGGraph( ... resource_handle, graph_props, srcs, dsts, weights, ... store_transposed=False, renumber=False, do_expensive_check=False) >>> (sources, destinations, edge_weights, subgraph_offsets) = ... pylibcugraph.ego_graph(resource_handle, G, source_vertices, 2, False) # FIXME: update results >>> sources [0, 1, 1, 3, 1, 1, 3, 3, 4] >>> destinations [1, 3, 4, 4, 3, 4, 4, 5, 5] >>> edge_weights [0.1, 2.1, 1.1, 7.2, 2.1, 1.1, 7.2, 3.2, 6.1] >>> subgraph_offsets [0, 4, 9] """ cdef cugraph_resource_handle_t* c_resource_handle_ptr = \ resource_handle.c_resource_handle_ptr cdef cugraph_graph_t* c_graph_ptr = graph.c_graph_ptr cdef cugraph_induced_subgraph_result_t* result_ptr cdef cugraph_error_code_t error_code cdef cugraph_error_t* error_ptr cdef cugraph_type_erased_device_array_view_t* \ source_vertices_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj( source_vertices) error_code = cugraph_extract_ego(c_resource_handle_ptr, c_graph_ptr, source_vertices_view_ptr, radius, do_expensive_check, &result_ptr, &error_ptr) assert_success(error_code, error_ptr, "cugraph_extract_ego") # Extract individual device array pointers from result and copy to cupy # arrays for returning. cdef cugraph_type_erased_device_array_view_t* sources_ptr = \ cugraph_induced_subgraph_get_sources(result_ptr) cdef cugraph_type_erased_device_array_view_t* destinations_ptr = \ cugraph_induced_subgraph_get_destinations(result_ptr) cdef cugraph_type_erased_device_array_view_t* edge_weights_ptr = \ cugraph_induced_subgraph_get_edge_weights(result_ptr) cdef cugraph_type_erased_device_array_view_t* subgraph_offsets_ptr = \ cugraph_induced_subgraph_get_subgraph_offsets(result_ptr) # FIXME: Get ownership of the result data instead of performing a copy # for perfomance improvement cupy_sources = copy_to_cupy_array( c_resource_handle_ptr, sources_ptr) cupy_destinations = copy_to_cupy_array( c_resource_handle_ptr, destinations_ptr) if edge_weights_ptr is not NULL: cupy_edge_weights = copy_to_cupy_array( c_resource_handle_ptr, edge_weights_ptr) else: cupy_edge_weights = None cupy_subgraph_offsets = copy_to_cupy_array( c_resource_handle_ptr, subgraph_offsets_ptr) # Free pointer cugraph_induced_subgraph_result_free(result_ptr) return (cupy_sources, cupy_destinations, cupy_edge_weights, cupy_subgraph_offsets)
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/select_random_vertices.pyx
# Copyright (c) 2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, ) from pylibcugraph._cugraph_c.graph_functions cimport ( cugraph_two_hop_neighbors, cugraph_vertex_pairs_t, cugraph_vertex_pairs_get_first, cugraph_vertex_pairs_get_second, cugraph_vertex_pairs_free, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) from pylibcugraph.resource_handle cimport ( ResourceHandle, ) from pylibcugraph.graphs cimport ( _GPUGraph, ) from pylibcugraph.utils cimport ( assert_success, copy_to_cupy_array, ) from pylibcugraph._cugraph_c.random cimport ( cugraph_rng_state_t ) from pylibcugraph.random cimport ( CuGraphRandomState ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_t, cugraph_type_erased_device_array_view ) from pylibcugraph._cugraph_c.sampling_algorithms cimport ( cugraph_select_random_vertices ) def select_random_vertices(ResourceHandle resource_handle, _GPUGraph graph, random_state, size_t num_vertices, ): """ Select random vertices from the graph Parameters ---------- resource_handle : ResourceHandle Handle to the underlying device resources needed for referencing data and running algorithms. graph : SGGraph or MGGraph The input graph, for either Single or Multi-GPU operations. random_state : int , optional Random state to use when generating samples. Optional argument, defaults to a hash of process id, time, and hostname. (See pylibcugraph.random.CuGraphRandomState) num_vertices : size_t , optional Number of vertices to sample. Optional argument, defaults to the total number of vertices. Returns ------- return random vertices from the graph """ cdef cugraph_resource_handle_t* c_resource_handle_ptr = \ resource_handle.c_resource_handle_ptr cdef cugraph_graph_t* c_graph_ptr = graph.c_graph_ptr cdef cugraph_type_erased_device_array_t* vertices_ptr cdef cugraph_error_code_t error_code cdef cugraph_error_t* error_ptr cg_rng_state = CuGraphRandomState(resource_handle, random_state) cdef cugraph_rng_state_t* rng_state_ptr = \ cg_rng_state.rng_state_ptr error_code = cugraph_select_random_vertices(c_resource_handle_ptr, c_graph_ptr, rng_state_ptr, num_vertices, &vertices_ptr, &error_ptr) assert_success(error_code, error_ptr, "select_random_vertices") cdef cugraph_type_erased_device_array_view_t* \ vertices_view_ptr = \ cugraph_type_erased_device_array_view( vertices_ptr) cupy_vertices = copy_to_cupy_array(c_resource_handle_ptr, vertices_view_ptr) return cupy_vertices
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/utils.pyx
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from libc.stdint cimport uintptr_t import numpy import cupy from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_size, cugraph_type_erased_device_array_view_type, cugraph_type_erased_device_array_view_pointer, cugraph_type_erased_device_array_view_create, cugraph_type_erased_device_array_view_copy, cugraph_type_erased_device_array_view_free, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_message, cugraph_error_free ) # FIXME: add tests for this cdef assert_success(cugraph_error_code_t code, cugraph_error_t* err, api_name): if code != cugraph_error_code_t.CUGRAPH_SUCCESS: c_error = cugraph_error_message(err) if isinstance(c_error, bytes): c_error = c_error.decode() else: c_error = str(c_error) cugraph_error_free(err) if code == cugraph_error_code_t.CUGRAPH_UNKNOWN_ERROR: code_str = "CUGRAPH_UNKNOWN_ERROR" error_msg = f"non-success value returned from {api_name}: {code_str} "\ f"{c_error}" raise RuntimeError(error_msg) elif code == cugraph_error_code_t.CUGRAPH_INVALID_HANDLE: code_str = "CUGRAPH_INVALID_HANDLE" error_msg = f"non-success value returned from {api_name}: {code_str} "\ f"{c_error}" raise ValueError(error_msg) elif code == cugraph_error_code_t.CUGRAPH_ALLOC_ERROR: code_str = "CUGRAPH_ALLOC_ERROR" error_msg = f"non-success value returned from {api_name}: {code_str} "\ f"{c_error}" raise MemoryError(error_msg) elif code == cugraph_error_code_t.CUGRAPH_INVALID_INPUT: code_str = "CUGRAPH_INVALID_INPUT" error_msg = f"non-success value returned from {api_name}: {code_str} "\ f"{c_error}" raise ValueError(error_msg) elif code == cugraph_error_code_t.CUGRAPH_NOT_IMPLEMENTED: code_str = "CUGRAPH_NOT_IMPLEMENTED" error_msg = f"non-success value returned from {api_name}: {code_str}\ "\ f"{c_error}" raise NotImplementedError(error_msg) elif code == cugraph_error_code_t.CUGRAPH_UNSUPPORTED_TYPE_COMBINATION: code_str = "CUGRAPH_UNSUPPORTED_TYPE_COMBINATION" error_msg = f"non-success value returned from {api_name}: {code_str} "\ f"{c_error}" raise ValueError(error_msg) else: code_str = "unknown error code" error_msg = f"non-success value returned from {api_name}: {code_str} "\ f"{c_error}" raise RuntimeError(error_msg) cdef assert_CAI_type(obj, var_name, allow_None=False): if allow_None: if obj is None: return msg = f"{var_name} must be None or support __cuda_array_interface__" else: msg = f"{var_name} does not support __cuda_array_interface__" if not(hasattr(obj, "__cuda_array_interface__")): raise TypeError(msg) cdef assert_AI_type(obj, var_name, allow_None=False): if allow_None: if obj is None: return msg = f"{var_name} must be None or support __array_interface__" else: msg = f"{var_name} does not support __array_interface__" if not(hasattr(obj, "__array_interface__")): raise TypeError(msg) cdef get_numpy_type_from_c_type(data_type_id_t c_type): if c_type == data_type_id_t.INT32: return numpy.int32 elif c_type == data_type_id_t.INT64: return numpy.int64 elif c_type == data_type_id_t.FLOAT32: return numpy.float32 elif c_type == data_type_id_t.FLOAT64: return numpy.float64 elif c_type == data_type_id_t.SIZE_T: return numpy.int64 else: raise RuntimeError("Internal error: got invalid data type enum value " f"from C: {c_type}") cdef get_c_type_from_numpy_type(numpy_type): dt = numpy.dtype(numpy_type) if dt == numpy.int32: return data_type_id_t.INT32 elif dt == numpy.int64: return data_type_id_t.INT64 elif dt == numpy.float32: return data_type_id_t.FLOAT32 elif dt == numpy.float64: return data_type_id_t.FLOAT64 else: raise RuntimeError("Internal error: got invalid data type enum value " f"from Numpy: {numpy_type}") cdef get_c_weight_type_from_numpy_edge_ids_type(numpy_type): if numpy_type == numpy.int32: return data_type_id_t.FLOAT32 else: return data_type_id_t.FLOAT64 cdef get_numpy_edge_ids_type_from_c_weight_type(data_type_id_t c_weight_type): if c_weight_type == data_type_id_t.FLOAT32: return numpy.int32 else: return numpy.int64 cdef copy_to_cupy_array( cugraph_resource_handle_t* c_resource_handle_ptr, cugraph_type_erased_device_array_view_t* device_array_view_ptr): """ Copy the contents from a device array view as returned by various cugraph_* APIs to a new cupy device array, typically intended to be used as a return value from pylibcugraph APIs. """ cdef c_type = cugraph_type_erased_device_array_view_type( device_array_view_ptr) array_size = cugraph_type_erased_device_array_view_size( device_array_view_ptr) cupy_array = cupy.zeros( array_size, dtype=get_numpy_type_from_c_type(c_type)) cdef uintptr_t cupy_array_ptr = \ cupy_array.__cuda_array_interface__["data"][0] cdef cugraph_type_erased_device_array_view_t* cupy_array_view_ptr = \ cugraph_type_erased_device_array_view_create( <void*>cupy_array_ptr, array_size, c_type) cdef cugraph_error_t* error_ptr error_code = cugraph_type_erased_device_array_view_copy( c_resource_handle_ptr, cupy_array_view_ptr, device_array_view_ptr, &error_ptr) assert_success(error_code, error_ptr, "cugraph_type_erased_device_array_view_copy") cugraph_type_erased_device_array_view_free(device_array_view_ptr) return cupy_array cdef copy_to_cupy_array_ids( cugraph_resource_handle_t* c_resource_handle_ptr, cugraph_type_erased_device_array_view_t* device_array_view_ptr): """ Copy the contents from a device array view as returned by various cugraph_* APIs to a new cupy device array, typically intended to be used as a return value from pylibcugraph APIs then convert float to int """ cdef c_type = cugraph_type_erased_device_array_view_type( device_array_view_ptr) array_size = cugraph_type_erased_device_array_view_size( device_array_view_ptr) cupy_array = cupy.zeros( array_size, dtype=get_numpy_edge_ids_type_from_c_weight_type(c_type)) cdef uintptr_t cupy_array_ptr = \ cupy_array.__cuda_array_interface__["data"][0] cdef cugraph_type_erased_device_array_view_t* cupy_array_view_ptr = \ cugraph_type_erased_device_array_view_create( <void*>cupy_array_ptr, array_size, get_c_type_from_numpy_type(cupy_array.dtype)) cdef cugraph_error_t* error_ptr error_code = cugraph_type_erased_device_array_view_copy( c_resource_handle_ptr, cupy_array_view_ptr, device_array_view_ptr, &error_ptr) assert_success(error_code, error_ptr, "cugraph_type_erased_device_array_view_copy") cugraph_type_erased_device_array_view_free(device_array_view_ptr) return cupy_array cdef cugraph_type_erased_device_array_view_t* \ create_cugraph_type_erased_device_array_view_from_py_obj(python_obj): cdef uintptr_t cai_ptr = <uintptr_t>NULL cdef cugraph_type_erased_device_array_view_t* view_ptr = NULL if python_obj is not None: cai_ptr = python_obj.__cuda_array_interface__["data"][0] view_ptr = cugraph_type_erased_device_array_view_create( <void*>cai_ptr, len(python_obj), get_c_type_from_numpy_type(python_obj.dtype)) return view_ptr cdef create_cupy_array_view_for_device_ptr( cugraph_type_erased_device_array_view_t* device_array_view_ptr, owning_py_object): if device_array_view_ptr == NULL: raise ValueError("device_array_view_ptr cannot be NULL") cdef c_type = cugraph_type_erased_device_array_view_type( device_array_view_ptr) array_size = cugraph_type_erased_device_array_view_size( device_array_view_ptr) dtype = get_numpy_type_from_c_type(c_type) cdef uintptr_t ptr_value = \ <uintptr_t> cugraph_type_erased_device_array_view_pointer(device_array_view_ptr) if ptr_value == <uintptr_t> NULL: # For the case of a NULL ptr, just create a new empty ndarray of the # appropriate type. This will not be associated with the # owning_py_object, but will still be garbage collected correctly. cupy_array = cupy.ndarray(0, dtype=dtype) else: # cupy.cuda.UnownedMemory takes a reference to an owning python object # which is used to increment the refcount on the owning python object. # This prevents the owning python object from being garbage collected # and having the memory freed when there are instances of the # cupy_array still in use that need the memory. When the cupy_array # instance returned here is deleted, it will decrement the refcount on # the owning python object, and when that refcount reaches zero the # owning python object will be garbage collected and the memory freed. cpmem = cupy.cuda.UnownedMemory(ptr_value, array_size, owning_py_object) cpmem_ptr = cupy.cuda.MemoryPointer(cpmem, 0) cupy_array = cupy.ndarray( array_size, dtype=dtype, memptr=cpmem_ptr) return cupy_array
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/pagerank.pyx
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_device_array_view_free ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) from pylibcugraph._cugraph_c.centrality_algorithms cimport ( cugraph_centrality_result_t, cugraph_pagerank_allow_nonconvergence, cugraph_centrality_result_converged, cugraph_centrality_result_get_vertices, cugraph_centrality_result_get_values, cugraph_centrality_result_free, ) from pylibcugraph.resource_handle cimport ( ResourceHandle, ) from pylibcugraph.graphs cimport ( _GPUGraph, ) from pylibcugraph.utils cimport ( assert_success, copy_to_cupy_array, create_cugraph_type_erased_device_array_view_from_py_obj, ) from pylibcugraph.exceptions import FailedToConvergeError def pagerank(ResourceHandle resource_handle, _GPUGraph graph, precomputed_vertex_out_weight_vertices, precomputed_vertex_out_weight_sums, initial_guess_vertices, initial_guess_values, double alpha, double epsilon, size_t max_iterations, bool_t do_expensive_check, fail_on_nonconvergence=True): """ Find the PageRank score for every vertex in a graph by computing an approximation of the Pagerank eigenvector using the power method. The number of iterations depends on the properties of the network itself; it increases when the tolerance descreases and/or alpha increases toward the limiting value of 1. Parameters ---------- resource_handle : ResourceHandle Handle to the underlying device resources needed for referencing data and running algorithms. graph : SGGraph or MGGraph The input graph, for either Single or Multi-GPU operations. precomputed_vertex_out_weight_vertices: device array type Subset of vertices of graph for precomputed_vertex_out_weight (a performance optimization) precomputed_vertex_out_weight_sums : device array type Corresponding precomputed sum of outgoing vertices weight (a performance optimization) initial_guess_vertices : device array type Subset of vertices of graph for initial guess for pagerank values (a performance optimization) initial_guess_values : device array type Pagerank values for vertices (a performance optimization) alpha : double The damping factor alpha represents the probability to follow an outgoing edge, standard value is 0.85. Thus, 1.0-alpha is the probability to “teleport” to a random vertex. Alpha should be greater than 0.0 and strictly lower than 1.0. epsilon : double Set the tolerance the approximation, this parameter should be a small magnitude value. The lower the tolerance the better the approximation. If this value is 0.0f, cuGraph will use the default value which is 1.0E-5. Setting too small a tolerance can lead to non-convergence due to numerical roundoff. Usually values between 0.01 and 0.00001 are acceptable. max_iterations : size_t The maximum number of iterations before an answer is returned. This can be used to limit the execution time and do an early exit before the solver reaches the convergence tolerance. If this value is lower or equal to 0 cuGraph will use the default value, which is 100. do_expensive_check : bool_t If True, performs more extensive tests on the inputs to ensure validitity, at the expense of increased run time. fail_on_nonconvergence : bool (default=True) If the solver does not reach convergence, raise an exception if fail_on_nonconvergence is True. If fail_on_nonconvergence is False, the return value is a tuple of (pagerank, converged) where pagerank is a cudf.DataFrame as described below, and converged is a boolean indicating if the solver converged (True) or not (False). Returns ------- The return value varies based on the value of the fail_on_nonconvergence paramter. If fail_on_nonconvergence is True: A tuple of device arrays, where the first item in the tuple is a device array containing the vertex identifiers, and the second item is a device array containing the pagerank values for the corresponding vertices. For example, the vertex identifier at the ith element of the vertex array has the pagerank value of the ith element in the pagerank array. If fail_on_nonconvergence is False: A three-tuple where the first two items are the device arrays described above, and the third is a bool indicating if the solver converged (True) or not (False). Examples -------- >>> import pylibcugraph, cupy, numpy >>> srcs = cupy.asarray([0, 1, 2], dtype=numpy.int32) >>> dsts = cupy.asarray([1, 2, 3], dtype=numpy.int32) >>> weights = cupy.asarray([1.0, 1.0, 1.0], dtype=numpy.float32) >>> resource_handle = pylibcugraph.ResourceHandle() >>> graph_props = pylibcugraph.GraphProperties( ... is_symmetric=False, is_multigraph=False) >>> G = pylibcugraph.SGGraph( ... resource_handle, graph_props, srcs, dsts, weights, ... store_transposed=True, renumber=False, do_expensive_check=False) >>> (vertices, pageranks) = pylibcugraph.pagerank( ... resource_handle, G, None, None, None, None, alpha=0.85, ... epsilon=1.0e-6, max_iterations=500, do_expensive_check=False) >>> vertices array([0, 1, 2, 3], dtype=int32) >>> pageranks array([0.11615585, 0.21488841, 0.2988108 , 0.3701449 ], dtype=float32) """ # FIXME: import these modules here for now until a better pattern can be # used for optional imports (perhaps 'import_optional()' from cugraph), or # these are made hard dependencies. try: import cupy except ModuleNotFoundError: raise RuntimeError("pagerank requires the cupy package, which could " "not be imported") try: import numpy except ModuleNotFoundError: raise RuntimeError("pagerank requires the numpy package, which could " "not be imported") cdef cugraph_type_erased_device_array_view_t* \ initial_guess_vertices_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj( initial_guess_vertices) cdef cugraph_type_erased_device_array_view_t* \ initial_guess_values_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj( initial_guess_values) cdef cugraph_resource_handle_t* c_resource_handle_ptr = \ resource_handle.c_resource_handle_ptr cdef cugraph_graph_t* c_graph_ptr = graph.c_graph_ptr cdef cugraph_type_erased_device_array_view_t* \ precomputed_vertex_out_weight_vertices_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj( precomputed_vertex_out_weight_vertices) # FIXME: assert that precomputed_vertex_out_weight_sums # type == weight type cdef cugraph_type_erased_device_array_view_t* \ precomputed_vertex_out_weight_sums_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj( precomputed_vertex_out_weight_sums) cdef cugraph_centrality_result_t* result_ptr cdef cugraph_error_code_t error_code cdef cugraph_error_t* error_ptr cdef bool_t converged cdef cugraph_type_erased_device_array_view_t* vertices_ptr cdef cugraph_type_erased_device_array_view_t* pageranks_ptr error_code = cugraph_pagerank_allow_nonconvergence( c_resource_handle_ptr, c_graph_ptr, precomputed_vertex_out_weight_vertices_view_ptr, precomputed_vertex_out_weight_sums_view_ptr, initial_guess_vertices_view_ptr, initial_guess_values_view_ptr, alpha, epsilon, max_iterations, do_expensive_check, &result_ptr, &error_ptr) assert_success(error_code, error_ptr, "cugraph_pagerank_allow_nonconvergence") converged = cugraph_centrality_result_converged(result_ptr) # Only extract results if necessary if (fail_on_nonconvergence is False) or (converged is True): # Extract individual device array pointers from result and copy to cupy # arrays for returning. vertices_ptr = cugraph_centrality_result_get_vertices(result_ptr) pageranks_ptr = cugraph_centrality_result_get_values(result_ptr) cupy_vertices = copy_to_cupy_array(c_resource_handle_ptr, vertices_ptr) cupy_pageranks = copy_to_cupy_array(c_resource_handle_ptr, pageranks_ptr) # Free all pointers cugraph_centrality_result_free(result_ptr) if initial_guess_vertices is not None: cugraph_type_erased_device_array_view_free(initial_guess_vertices_view_ptr) if initial_guess_values is not None: cugraph_type_erased_device_array_view_free(initial_guess_values_view_ptr) if precomputed_vertex_out_weight_vertices is not None: cugraph_type_erased_device_array_view_free(precomputed_vertex_out_weight_vertices_view_ptr) if precomputed_vertex_out_weight_sums is not None: cugraph_type_erased_device_array_view_free(precomputed_vertex_out_weight_sums_view_ptr) if fail_on_nonconvergence is False: return (cupy_vertices, cupy_pageranks, bool(converged)) else: if converged is True: return (cupy_vertices, cupy_pageranks) else: raise FailedToConvergeError
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/uniform_random_walks.pyx
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from libc.stdint cimport uintptr_t from pylibcugraph._cugraph_c.resource_handle cimport ( cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_device_array_view_create, cugraph_type_erased_device_array_view_free, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) from pylibcugraph._cugraph_c.algorithms cimport ( cugraph_uniform_random_walks, cugraph_random_walk_result_t, cugraph_random_walk_result_get_paths, cugraph_random_walk_result_get_weights, cugraph_random_walk_result_get_max_path_length, cugraph_random_walk_result_free, ) from pylibcugraph.resource_handle cimport ( ResourceHandle, ) from pylibcugraph.graphs cimport ( _GPUGraph, ) from pylibcugraph.utils cimport ( assert_success, copy_to_cupy_array, assert_CAI_type, get_c_type_from_numpy_type, ) def uniform_random_walks(ResourceHandle resource_handle, _GPUGraph input_graph, start_vertices, size_t max_length): """ Compute uniform random walks for each nodes in 'start_vertices' Parameters ---------- resource_handle: ResourceHandle Handle to the underlying device and host resources needed for referencing data and running algorithms. input_graph : SGGraph or MGGraph The input graph, for either Single or Multi-GPU operations. start_vertices: device array type Device array containing the list of starting vertices from which to run the uniform random walk max_length: size_t The maximum depth of the uniform random walks Returns ------- A tuple containing two device arrays and an size_t which are respectively the vertices path, the edge path weights and the maximum path length """ cdef cugraph_resource_handle_t* c_resource_handle_ptr = \ resource_handle.c_resource_handle_ptr cdef cugraph_graph_t* c_graph_ptr = input_graph.c_graph_ptr assert_CAI_type(start_vertices, "start_vertices") cdef cugraph_random_walk_result_t* result_ptr cdef cugraph_error_code_t error_code cdef cugraph_error_t* error_ptr cdef uintptr_t cai_start_ptr = \ start_vertices.__cuda_array_interface__["data"][0] cdef cugraph_type_erased_device_array_view_t* weights_ptr cdef cugraph_type_erased_device_array_view_t* start_ptr = \ cugraph_type_erased_device_array_view_create( <void*>cai_start_ptr, len(start_vertices), get_c_type_from_numpy_type(start_vertices.dtype)) error_code = cugraph_uniform_random_walks( c_resource_handle_ptr, c_graph_ptr, start_ptr, max_length, &result_ptr, &error_ptr) assert_success(error_code, error_ptr, "cugraph_uniform_random_walks") cdef cugraph_type_erased_device_array_view_t* path_ptr = \ cugraph_random_walk_result_get_paths(result_ptr) if input_graph.weights_view_ptr is NULL: cupy_weights = None else: weights_ptr = cugraph_random_walk_result_get_weights(result_ptr) cupy_weights = copy_to_cupy_array(c_resource_handle_ptr, weights_ptr) max_path_length = \ cugraph_random_walk_result_get_max_path_length(result_ptr) cupy_paths = copy_to_cupy_array(c_resource_handle_ptr, path_ptr) cugraph_random_walk_result_free(result_ptr) cugraph_type_erased_device_array_view_free(start_ptr) return (cupy_paths, cupy_weights, max_path_length)
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/replicate_edgelist.pyx
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_device_array_view_free, ) from pylibcugraph._cugraph_c.graph_functions cimport ( cugraph_allgather, cugraph_induced_subgraph_result_t, cugraph_induced_subgraph_get_sources, cugraph_induced_subgraph_get_destinations, cugraph_induced_subgraph_get_edge_weights, cugraph_induced_subgraph_get_edge_ids, cugraph_induced_subgraph_get_edge_type_ids, cugraph_induced_subgraph_get_subgraph_offsets, cugraph_induced_subgraph_result_free, ) from pylibcugraph.resource_handle cimport ( ResourceHandle, ) from pylibcugraph.utils cimport ( assert_success, assert_CAI_type, copy_to_cupy_array, create_cugraph_type_erased_device_array_view_from_py_obj ) def replicate_edgelist(ResourceHandle resource_handle, src_array, dst_array, weight_array, edge_id_array, edge_type_id_array): """ Replicate edges across all GPUs Parameters ---------- resource_handle : ResourceHandle Handle to the underlying device resources needed for referencing data and running algorithms. src_array : device array type, optional Device array containing the vertex identifiers of the source of each directed edge. The order of the array corresponds to the ordering of the dst_array, where the ith item in src_array and the ith item in dst_array define the ith edge of the graph. dst_array : device array type, optional Device array containing the vertex identifiers of the destination of each directed edge. The order of the array corresponds to the ordering of the src_array, where the ith item in src_array and the ith item in dst_array define the ith edge of the graph. weight_array : device array type, optional Device array containing the weight values of each directed edge. The order of the array corresponds to the ordering of the src_array and dst_array arrays, where the ith item in weight_array is the weight value of the ith edge of the graph. edge_id_array : device array type, optional Device array containing the edge id values of each directed edge. The order of the array corresponds to the ordering of the src_array and dst_array arrays, where the ith item in edge_id_array is the id value of the ith edge of the graph. edge_type_id_array : device array type, optional Device array containing the edge type id values of each directed edge. The order of the array corresponds to the ordering of the src_array and dst_array arrays, where the ith item in edge_type_id_array is the type id value of the ith edge of the graph. Returns ------- return cupy arrays of 'src' and/or 'dst' and/or 'weight'and/or 'edge_id' and/or 'edge_type_id'. """ assert_CAI_type(src_array, "src_array", True) assert_CAI_type(dst_array, "dst_array", True) assert_CAI_type(weight_array, "weight_array", True) assert_CAI_type(edge_id_array, "edge_id_array", True) assert_CAI_type(edge_type_id_array, "edge_type_id_array", True) cdef cugraph_resource_handle_t* c_resource_handle_ptr = \ resource_handle.c_resource_handle_ptr cdef cugraph_induced_subgraph_result_t* result_ptr cdef cugraph_error_code_t error_code cdef cugraph_error_t* error_ptr cdef cugraph_type_erased_device_array_view_t* srcs_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj(src_array) cdef cugraph_type_erased_device_array_view_t* dsts_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj(dst_array) cdef cugraph_type_erased_device_array_view_t* weights_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj(weight_array) cdef cugraph_type_erased_device_array_view_t* edge_ids_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj(edge_id_array) cdef cugraph_type_erased_device_array_view_t* edge_type_ids_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj(edge_type_id_array) error_code = cugraph_allgather(c_resource_handle_ptr, srcs_view_ptr, dsts_view_ptr, weights_view_ptr, edge_ids_view_ptr, edge_type_ids_view_ptr, &result_ptr, &error_ptr) assert_success(error_code, error_ptr, "replicate_edgelist") # Extract individual device array pointers from result and copy to cupy # arrays for returning. cdef cugraph_type_erased_device_array_view_t* sources_ptr if src_array is not None: sources_ptr = cugraph_induced_subgraph_get_sources(result_ptr) cdef cugraph_type_erased_device_array_view_t* destinations_ptr if dst_array is not None: destinations_ptr = cugraph_induced_subgraph_get_destinations(result_ptr) cdef cugraph_type_erased_device_array_view_t* edge_weights_ptr = \ cugraph_induced_subgraph_get_edge_weights(result_ptr) cdef cugraph_type_erased_device_array_view_t* edge_ids_ptr = \ cugraph_induced_subgraph_get_edge_ids(result_ptr) cdef cugraph_type_erased_device_array_view_t* edge_type_ids_ptr = \ cugraph_induced_subgraph_get_edge_type_ids(result_ptr) cdef cugraph_type_erased_device_array_view_t* subgraph_offsets_ptr = \ cugraph_induced_subgraph_get_subgraph_offsets(result_ptr) # FIXME: Get ownership of the result data instead of performing a copy # for perfomance improvement cupy_sources = None cupy_destinations = None cupy_edge_weights = None cupy_edge_ids = None cupy_edge_type_ids = None if src_array is not None: cupy_sources = copy_to_cupy_array( c_resource_handle_ptr, sources_ptr) if dst_array is not None: cupy_destinations = copy_to_cupy_array( c_resource_handle_ptr, destinations_ptr) if weight_array is not None: cupy_edge_weights = copy_to_cupy_array( c_resource_handle_ptr, edge_weights_ptr) if edge_id_array is not None: cupy_edge_ids = copy_to_cupy_array( c_resource_handle_ptr, edge_ids_ptr) if edge_type_id_array is not None: cupy_edge_type_ids = copy_to_cupy_array( c_resource_handle_ptr, edge_type_ids_ptr) cupy_subgraph_offsets = copy_to_cupy_array( c_resource_handle_ptr, subgraph_offsets_ptr) # Free pointer cugraph_induced_subgraph_result_free(result_ptr) if src_array is not None: cugraph_type_erased_device_array_view_free(srcs_view_ptr) if dst_array is not None: cugraph_type_erased_device_array_view_free(dsts_view_ptr) if weight_array is not None: cugraph_type_erased_device_array_view_free(weights_view_ptr) if edge_id_array is not None: cugraph_type_erased_device_array_view_free(edge_ids_view_ptr) if edge_type_id_array is not None: cugraph_type_erased_device_array_view_free(edge_type_ids_view_ptr) return (cupy_sources, cupy_destinations, cupy_edge_weights, cupy_edge_ids, cupy_edge_type_ids, cupy_subgraph_offsets)
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/graphs.pyx
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_device_array_view_free, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_sg_graph_create, cugraph_mg_graph_create, cugraph_sg_graph_create_from_csr, cugraph_sg_graph_free, cugraph_mg_graph_free, ) from pylibcugraph.resource_handle cimport ( ResourceHandle, ) from pylibcugraph.graph_properties cimport ( GraphProperties, ) from pylibcugraph.utils cimport ( assert_success, assert_CAI_type, create_cugraph_type_erased_device_array_view_from_py_obj, ) cdef class SGGraph(_GPUGraph): """ RAII-stye Graph class for use with single-GPU APIs that manages the individual create/free calls and the corresponding cugraph_graph_t pointer. Parameters ---------- resource_handle : ResourceHandle Handle to the underlying device resources needed for referencing data and running algorithms. graph_properties : GraphProperties Object defining intended properties for the graph. src_or_offset_array : device array type Device array containing either the vertex identifiers of the source of each directed edge if represented in COO format or the offset if CSR format. In the case of a COO, the order of the array corresponds to the ordering of the dst_or_index_array, where the ith item in src_offset_array and the ith item in dst_index_array define the ith edge of the graph. dst_or_index_array : device array type Device array containing the vertex identifiers of the destination of each directed edge if represented in COO format or the index if CSR format. In the case of a COO, The order of the array corresponds to the ordering of the src_offset_array, where the ith item in src_offset_array and the ith item in dst_index_array define the ith edge of the graph. weight_array : device array type Device array containing the weight values of each directed edge. The order of the array corresponds to the ordering of the src_array and dst_array arrays, where the ith item in weight_array is the weight value of the ith edge of the graph. store_transposed : bool Set to True if the graph should be transposed. This is required for some algorithms, such as pagerank. renumber : bool Set to True to indicate the vertices used in src_array and dst_array are not appropriate for use as internal array indices, and should be mapped to continuous integers starting from 0. do_expensive_check : bool If True, performs more extensive tests on the inputs to ensure validitity, at the expense of increased run time. edge_id_array : device array type Device array containing the edge ids of each directed edge. Must match the ordering of the src/dst arrays. Optional (may be null). If provided, edge_type_array must also be provided. edge_type_array : device array type Device array containing the edge types of each directed edge. Must match the ordering of the src/dst/edge_id arrays. Optional (may be null). If provided, edge_id_array must be provided. input_array_format: str, optional (default='COO') Input representation used to construct a graph COO: arrays represent src_array and dst_array CSR: arrays represent offset_array and index_array Examples --------- >>> import pylibcugraph, cupy, numpy >>> srcs = cupy.asarray([0, 1, 2], dtype=numpy.int32) >>> dsts = cupy.asarray([1, 2, 3], dtype=numpy.int32) >>> seeds = cupy.asarray([0, 0, 1], dtype=numpy.int32) >>> weights = cupy.asarray([1.0, 1.0, 1.0], dtype=numpy.float32) >>> resource_handle = pylibcugraph.ResourceHandle() >>> graph_props = pylibcugraph.GraphProperties( ... is_symmetric=False, is_multigraph=False) >>> G = pylibcugraph.SGGraph( ... resource_handle, graph_props, srcs, dsts, weights, ... store_transposed=False, renumber=False, do_expensive_check=False) """ def __cinit__(self, ResourceHandle resource_handle, GraphProperties graph_properties, src_or_offset_array, dst_or_index_array, weight_array=None, store_transposed=False, renumber=False, do_expensive_check=False, edge_id_array=None, edge_type_array=None, input_array_format="COO"): # FIXME: add tests for these if not(isinstance(store_transposed, (int, bool))): raise TypeError("expected int or bool for store_transposed, got " f"{type(store_transposed)}") if not(isinstance(renumber, (int, bool))): raise TypeError("expected int or bool for renumber, got " f"{type(renumber)}") if not(isinstance(do_expensive_check, (int, bool))): raise TypeError("expected int or bool for do_expensive_check, got " f"{type(do_expensive_check)}") assert_CAI_type(src_or_offset_array, "src_or_offset_array") assert_CAI_type(dst_or_index_array, "dst_or_index_array") assert_CAI_type(weight_array, "weight_array", True) if edge_id_array is not None: assert_CAI_type(edge_id_array, "edge_id_array") if edge_type_array is not None: assert_CAI_type(edge_type_array, "edge_type_array") # FIXME: assert that src_or_offset_array and dst_or_index_array have the same type cdef cugraph_error_t* error_ptr cdef cugraph_error_code_t error_code cdef cugraph_type_erased_device_array_view_t* srcs_or_offsets_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj( src_or_offset_array ) cdef cugraph_type_erased_device_array_view_t* dsts_or_indices_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj( dst_or_index_array ) self.weights_view_ptr = create_cugraph_type_erased_device_array_view_from_py_obj( weight_array ) self.edge_id_view_ptr = create_cugraph_type_erased_device_array_view_from_py_obj( edge_id_array ) cdef cugraph_type_erased_device_array_view_t* edge_type_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj( edge_type_array ) if input_array_format == "COO": error_code = cugraph_sg_graph_create( resource_handle.c_resource_handle_ptr, &(graph_properties.c_graph_properties), srcs_or_offsets_view_ptr, dsts_or_indices_view_ptr, self.weights_view_ptr, self.edge_id_view_ptr, edge_type_view_ptr, store_transposed, renumber, do_expensive_check, &(self.c_graph_ptr), &error_ptr) assert_success(error_code, error_ptr, "cugraph_sg_graph_create()") elif input_array_format == "CSR": error_code = cugraph_sg_graph_create_from_csr( resource_handle.c_resource_handle_ptr, &(graph_properties.c_graph_properties), srcs_or_offsets_view_ptr, dsts_or_indices_view_ptr, self.weights_view_ptr, self.edge_id_view_ptr, edge_type_view_ptr, store_transposed, renumber, do_expensive_check, &(self.c_graph_ptr), &error_ptr) assert_success(error_code, error_ptr, "cugraph_sg_graph_create_from_csr()") else: raise ValueError("invalid 'input_array_format'. Only " "'COO' and 'CSR' format are supported." ) cugraph_type_erased_device_array_view_free(srcs_or_offsets_view_ptr) cugraph_type_erased_device_array_view_free(dsts_or_indices_view_ptr) cugraph_type_erased_device_array_view_free(self.weights_view_ptr) if self.edge_id_view_ptr is not NULL: cugraph_type_erased_device_array_view_free(self.edge_id_view_ptr) if edge_type_view_ptr is not NULL: cugraph_type_erased_device_array_view_free(edge_type_view_ptr) def __dealloc__(self): if self.c_graph_ptr is not NULL: cugraph_sg_graph_free(self.c_graph_ptr) cdef class MGGraph(_GPUGraph): """ RAII-stye Graph class for use with multi-GPU APIs that manages the individual create/free calls and the corresponding cugraph_graph_t pointer. Parameters ---------- resource_handle : ResourceHandle Handle to the underlying device resources needed for referencing data and running algorithms. graph_properties : GraphProperties Object defining intended properties for the graph. src_array : device array type Device array containing the vertex identifiers of the source of each directed edge. The order of the array corresponds to the ordering of the dst_array, where the ith item in src_array and the ith item in dst_array define the ith edge of the graph. dst_array : device array type Device array containing the vertex identifiers of the destination of each directed edge. The order of the array corresponds to the ordering of the src_array, where the ith item in src_array and the ith item in dst_array define the ith edge of the graph. weight_array : device array type Device array containing the weight values of each directed edge. The order of the array corresponds to the ordering of the src_array and dst_array arrays, where the ith item in weight_array is the weight value of the ith edge of the graph. store_transposed : bool Set to True if the graph should be transposed. This is required for some algorithms, such as pagerank. num_edges : int Number of edges do_expensive_check : bool If True, performs more extensive tests on the inputs to ensure validitity, at the expense of increased run time. edge_id_array : device array type Device array containing the edge ids of each directed edge. Must match the ordering of the src/dst arrays. Optional (may be null). If provided, edge_type_array must also be provided. edge_type_array : device array type Device array containing the edge types of each directed edge. Must match the ordering of the src/dst/edge_id arrays. Optional (may be null). If provided, edge_id_array must be provided. """ def __cinit__(self, ResourceHandle resource_handle, GraphProperties graph_properties, src_array, dst_array, weight_array=None, store_transposed=False, num_edges=-1, do_expensive_check=False, edge_id_array=None, edge_type_array=None): # FIXME: add tests for these if not(isinstance(store_transposed, (int, bool))): raise TypeError("expected int or bool for store_transposed, got " f"{type(store_transposed)}") if not(isinstance(num_edges, (int))): raise TypeError("expected int for num_edges, got " f"{type(num_edges)}") if num_edges < 0: raise TypeError("num_edges must be > 0") if not(isinstance(do_expensive_check, (int, bool))): raise TypeError("expected int or bool for do_expensive_check, got " f"{type(do_expensive_check)}") assert_CAI_type(src_array, "src_array") assert_CAI_type(dst_array, "dst_array") assert_CAI_type(weight_array, "weight_array", True) assert_CAI_type(edge_id_array, "edge_id_array", True) if edge_id_array is not None and len(edge_id_array) != len(src_array): raise ValueError('Edge id array must be same length as edgelist') assert_CAI_type(edge_type_array, "edge_type_array", True) if edge_type_array is not None and len(edge_type_array) != len(src_array): raise ValueError('Edge type array must be same length as edgelist') # FIXME: assert that src_array and dst_array have the same type cdef cugraph_error_t* error_ptr cdef cugraph_error_code_t error_code cdef cugraph_type_erased_device_array_view_t* srcs_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj( src_array ) cdef cugraph_type_erased_device_array_view_t* dsts_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj( dst_array ) self.weights_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj( weight_array ) self.edge_id_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj( edge_id_array ) cdef cugraph_type_erased_device_array_view_t* edge_type_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj( edge_type_array ) error_code = cugraph_mg_graph_create( resource_handle.c_resource_handle_ptr, &(graph_properties.c_graph_properties), srcs_view_ptr, dsts_view_ptr, self.weights_view_ptr, self.edge_id_view_ptr, edge_type_view_ptr, store_transposed, num_edges, do_expensive_check, &(self.c_graph_ptr), &error_ptr) assert_success(error_code, error_ptr, "cugraph_mg_graph_create()") cugraph_type_erased_device_array_view_free(srcs_view_ptr) cugraph_type_erased_device_array_view_free(dsts_view_ptr) cugraph_type_erased_device_array_view_free(self.weights_view_ptr) if self.edge_id_view_ptr is not NULL: cugraph_type_erased_device_array_view_free(self.edge_id_view_ptr) if edge_type_view_ptr is not NULL: cugraph_type_erased_device_array_view_free(edge_type_view_ptr) def __dealloc__(self): if self.c_graph_ptr is not NULL: cugraph_mg_graph_free(self.c_graph_ptr)
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/graph_properties.pxd
# Copyright (c) 2022, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_properties_t, ) cdef class GraphProperties: cdef cugraph_graph_properties_t c_graph_properties
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/triangle_count.pyx
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from libc.stdint cimport uintptr_t from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_device_array_view_create, cugraph_type_erased_device_array_view_free, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) from pylibcugraph._cugraph_c.community_algorithms cimport ( cugraph_triangle_count_result_t, cugraph_triangle_count, cugraph_triangle_count_result_get_vertices, cugraph_triangle_count_result_get_counts, cugraph_triangle_count_result_free, ) from pylibcugraph.resource_handle cimport ( ResourceHandle, ) from pylibcugraph.graphs cimport ( _GPUGraph, ) from pylibcugraph.utils cimport ( assert_success, copy_to_cupy_array, assert_CAI_type, get_c_type_from_numpy_type, ) def triangle_count(ResourceHandle resource_handle, _GPUGraph graph, start_list, bool_t do_expensive_check): """ Computes the number of triangles (cycles of length three) and the number per vertex in the input graph. Parameters ---------- resource_handle: ResourceHandle Handle to the underlying device and host resources needed for referencing data and running algorithms. graph : SGGraph or MGGraph The input graph, for either Single or Multi-GPU operations. start_list: device array type Device array containing the list of vertices for triangle counting. If 'None' the entire set of vertices in the graph is processed do_expensive_check: bool If True, performs more extensive tests on the inputs to ensure validitity, at the expense of increased run time. Returns ------- A tuple of device arrays, where the first item in the tuple is a device array containing the vertex identifiers and the second item contains the triangle counting counts Examples -------- # FIXME: No example yet """ cdef cugraph_resource_handle_t* c_resource_handle_ptr = \ resource_handle.c_resource_handle_ptr cdef cugraph_graph_t* c_graph_ptr = graph.c_graph_ptr assert_CAI_type(start_list, "start_list", allow_None=True) cdef cugraph_triangle_count_result_t* result_ptr cdef cugraph_error_code_t error_code cdef cugraph_error_t* error_ptr cdef uintptr_t cai_start_ptr cdef cugraph_type_erased_device_array_view_t* start_ptr if start_list is not None: cai_start_ptr = start_list.__cuda_array_interface__["data"][0] start_ptr = \ cugraph_type_erased_device_array_view_create( <void*>cai_start_ptr, len(start_list), get_c_type_from_numpy_type(start_list.dtype)) else: start_ptr = NULL error_code = cugraph_triangle_count(c_resource_handle_ptr, c_graph_ptr, start_ptr, do_expensive_check, &result_ptr, &error_ptr) assert_success(error_code, error_ptr, "triangle_count") cdef cugraph_type_erased_device_array_view_t* vertices_ptr = \ cugraph_triangle_count_result_get_vertices(result_ptr) cdef cugraph_type_erased_device_array_view_t* counts_ptr = \ cugraph_triangle_count_result_get_counts(result_ptr) cupy_vertices = copy_to_cupy_array(c_resource_handle_ptr, vertices_ptr) cupy_counts = copy_to_cupy_array(c_resource_handle_ptr, counts_ptr) cugraph_triangle_count_result_free(result_ptr) if start_list is not None: cugraph_type_erased_device_array_view_free(start_ptr) return (cupy_vertices, cupy_counts)
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/edge_betweenness_centrality.pyx
# Copyright (c) 2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_device_array_view_free, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) from pylibcugraph._cugraph_c.centrality_algorithms cimport ( cugraph_edge_centrality_result_t, cugraph_edge_betweenness_centrality, cugraph_edge_centrality_result_get_src_vertices, cugraph_edge_centrality_result_get_dst_vertices, cugraph_edge_centrality_result_get_values, cugraph_edge_centrality_result_get_edge_ids, cugraph_edge_centrality_result_get_values, cugraph_edge_centrality_result_free, ) from pylibcugraph.resource_handle cimport ( ResourceHandle, ) from pylibcugraph.graphs cimport ( _GPUGraph, ) from pylibcugraph.utils cimport ( assert_success, copy_to_cupy_array, create_cugraph_type_erased_device_array_view_from_py_obj, ) from pylibcugraph.select_random_vertices import ( select_random_vertices ) def edge_betweenness_centrality(ResourceHandle resource_handle, _GPUGraph graph, k, random_state, bool_t normalized, bool_t do_expensive_check): """ Compute the edge betweenness centrality for all edges of the graph G. Betweenness centrality is a measure of the number of shortest paths that pass over an edge. An edge with a high betweenness centrality score has more paths passing over it and is therefore believed to be more important. Parameters ---------- resource_handle : ResourceHandle Handle to the underlying device resources needed for referencing data and running algorithms. graph : SGGraph or MGGraph The input graph, for either Single or Multi-GPU operations. k : int or device array type or None, optional (default=None) If k is not None, use k node samples to estimate the edge betweenness. Higher values give better approximation. If k is a device array type, the contents are assumed to be vertex identifiers to be used for estimation. If k is None (the default), all the vertices are used to estimate the edge betweenness. Vertices obtained through sampling or defined as a list will be used as sources for traversals inside the algorithm. random_state : int, optional (default=None) if k is specified and k is an integer, use random_state to initialize the random number generator. Using None defaults to a hash of process id, time, and hostname If k is either None or list or cudf objects: random_state parameter is ignored. normalized : bool_t Normalization will ensure that values are in [0, 1]. do_expensive_check : bool_t A flag to run expensive checks for input arguments if True. Returns ------- A tuple of device arrays corresponding to the sources, destinations, edge betweenness centrality scores and edge ids (if provided). array containing the vertices and the second item in the tuple is a device array containing the eigenvector centrality scores for the corresponding vertices. Examples -------- >>> import pylibcugraph, cupy, numpy >>> srcs = cupy.asarray([0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5], ... dtype=numpy.int32) >>> dsts = cupy.asarray([1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4], ... dtype=numpy.int32) >>> edge_ids = cupy.asarray( ... [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], ... dtype=numpy.int32) >>> resource_handle = pylibcugraph.ResourceHandle() >>> graph_props = pylibcugraph.GraphProperties( ... is_symmetric=False, is_multigraph=False) >>> G = pylibcugraph.SGGraph( ... resource_handle, graph_props, srcs, dsts, store_transposed=False, ... renumber=False, do_expensive_check=False, edge_id_array=edge_ids) >>> (srcs, dsts, values, edge_ids) = pylibcugraph.edge_betweenness_centrality( resource_handle, G, None, None, True, False) >>> srcs [0 0 1 1 1 1 2 2 2 3 3 3 4 4 5 5] >>> dsts [1 2 0 2 3 4 0 1 3 1 2 5 1 5 3 4] >>> values [0.10555556 0.06111111 0.10555556 0.06666667 0.09444445 0.14444445 0.06111111 0.06666667 0.09444445 0.09444445 0.09444445 0.12222222 0.14444445 0.07777778 0.12222222 0.07777778] >>> edge_ids [ 0 11 8 12 1 2 3 4 5 9 13 6 10 7 14 15] """ if isinstance(k, int): # randomly select vertices #'select_random_vertices' internally creates a # 'pylibcugraph.random.CuGraphRandomState' vertex_list = select_random_vertices( resource_handle, graph, random_state, k) else: # FiXME: Add CAPI check ensuring that k is a cuda array interface vertex_list = k cdef cugraph_resource_handle_t* c_resource_handle_ptr = \ resource_handle.c_resource_handle_ptr cdef cugraph_graph_t* c_graph_ptr = graph.c_graph_ptr cdef cugraph_edge_centrality_result_t* result_ptr cdef cugraph_error_code_t error_code cdef cugraph_error_t* error_ptr cdef cugraph_type_erased_device_array_view_t* \ vertex_list_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj( vertex_list) error_code = cugraph_edge_betweenness_centrality(c_resource_handle_ptr, c_graph_ptr, vertex_list_view_ptr, normalized, do_expensive_check, &result_ptr, &error_ptr) assert_success(error_code, error_ptr, "cugraph_edge_betweenness_centrality") # Extract individual device array pointers from result and copy to cupy # arrays for returning. cdef cugraph_type_erased_device_array_view_t* src_ptr = \ cugraph_edge_centrality_result_get_src_vertices(result_ptr) cdef cugraph_type_erased_device_array_view_t* dst_ptr = \ cugraph_edge_centrality_result_get_dst_vertices(result_ptr) cdef cugraph_type_erased_device_array_view_t* values_ptr = \ cugraph_edge_centrality_result_get_values(result_ptr) if graph.edge_id_view_ptr is NULL: cupy_edge_ids = None else: edge_ids_ptr = cugraph_edge_centrality_result_get_edge_ids(result_ptr) cupy_edge_ids = copy_to_cupy_array(c_resource_handle_ptr, edge_ids_ptr) cupy_src_vertices = copy_to_cupy_array(c_resource_handle_ptr, src_ptr) cupy_dst_vertices = copy_to_cupy_array(c_resource_handle_ptr, dst_ptr) cupy_values = copy_to_cupy_array(c_resource_handle_ptr, values_ptr) cugraph_edge_centrality_result_free(result_ptr) cugraph_type_erased_device_array_view_free(vertex_list_view_ptr) return (cupy_src_vertices, cupy_dst_vertices, cupy_values, cupy_edge_ids)
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/balanced_cut_clustering.pyx
# Copyright (c) 2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) from pylibcugraph._cugraph_c.community_algorithms cimport ( cugraph_clustering_result_t, cugraph_balanced_cut_clustering, cugraph_clustering_result_get_vertices, cugraph_clustering_result_get_clusters, cugraph_clustering_result_free, ) from pylibcugraph.resource_handle cimport ( ResourceHandle, ) from pylibcugraph.graphs cimport ( _GPUGraph, ) from pylibcugraph.utils cimport ( assert_success, copy_to_cupy_array, ) def balanced_cut_clustering(ResourceHandle resource_handle, _GPUGraph graph, num_clusters, num_eigen_vects, evs_tolerance, evs_max_iter, kmean_tolerance, kmean_max_iter, bool_t do_expensive_check ): """ Compute a clustering/partitioning of the given graph using the spectral balanced cut method. Parameters ---------- resource_handle : ResourceHandle Handle to the underlying device resources needed for referencing data and running algorithms. graph : SGGraph The input graph. num_clusters : size_t Specifies the number of clusters to find, must be greater than 1. num_eigen_vects : size_t Specifies the number of eigenvectors to use. Must be lower or equal to num_clusters. evs_tolerance: double Specifies the tolerance to use in the eigensolver. evs_max_iter: size_t Specifies the maximum number of iterations for the eigensolver. kmean_tolerance: double Specifies the tolerance to use in the k-means solver. kmean_max_iter: size_t Specifies the maximum number of iterations for the k-means solver. do_expensive_check : bool_t If True, performs more extensive tests on the inputs to ensure validitity, at the expense of increased run time. Returns ------- A tuple containing the clustering vertices, clusters Examples -------- >>> import pylibcugraph, cupy, numpy >>> srcs = cupy.asarray([0, 1, 2], dtype=numpy.int32) >>> dsts = cupy.asarray([1, 2, 0], dtype=numpy.int32) >>> weights = cupy.asarray([1.0, 1.0, 1.0], dtype=numpy.float32) >>> resource_handle = pylibcugraph.ResourceHandle() >>> graph_props = pylibcugraph.GraphProperties( ... is_symmetric=True, is_multigraph=False) >>> G = pylibcugraph.SGGraph( ... resource_handle, graph_props, srcs, dsts, weights, ... store_transposed=True, renumber=False, do_expensive_check=False) >>> (vertices, clusters) = pylibcugraph.balanced_cut_clustering( ... resource_handle, G, num_clusters=5, num_eigen_vects=2, evs_tolerance=0.00001 ... evs_max_iter=100, kmean_tolerance=0.00001, kmean_max_iter=100) # FIXME: Fix docstring results. >>> vertices ############ >>> clusters ############ """ cdef cugraph_resource_handle_t* c_resource_handle_ptr = \ resource_handle.c_resource_handle_ptr cdef cugraph_graph_t* c_graph_ptr = graph.c_graph_ptr cdef cugraph_clustering_result_t* result_ptr cdef cugraph_error_code_t error_code cdef cugraph_error_t* error_ptr error_code = cugraph_balanced_cut_clustering(c_resource_handle_ptr, c_graph_ptr, num_clusters, num_eigen_vects, evs_tolerance, evs_max_iter, kmean_tolerance, kmean_max_iter, do_expensive_check, &result_ptr, &error_ptr) assert_success(error_code, error_ptr, "cugraph_balanced_cut_clustering") # Extract individual device array pointers from result and copy to cupy # arrays for returning. cdef cugraph_type_erased_device_array_view_t* vertices_ptr = \ cugraph_clustering_result_get_vertices(result_ptr) cdef cugraph_type_erased_device_array_view_t* clusters_ptr = \ cugraph_clustering_result_get_clusters(result_ptr) cupy_vertices = copy_to_cupy_array(c_resource_handle_ptr, vertices_ptr) cupy_clusters = copy_to_cupy_array(c_resource_handle_ptr, clusters_ptr) cugraph_clustering_result_free(result_ptr) return (cupy_vertices, cupy_clusters)
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/resource_handle.pyx
# Copyright (c) 2022, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( cugraph_create_resource_handle, cugraph_free_resource_handle, ) #from cugraph.dask.traversal cimport mg_bfs as c_bfs from pylibcugraph cimport resource_handle as c_resource_handle cdef class ResourceHandle: """ RAII-stye resource handle class to manage individual create/free calls and the corresponding pointer to a cugraph_resource_handle_t """ def __cinit__(self, handle=None): cdef void* handle_ptr = NULL cdef size_t handle_size_t if handle is not None: # FIXME: rather than assume a RAFT handle here, consider something # like a factory function in cugraph (which already has a RAFT # dependency and makes RAFT assumptions) that takes a RAFT handle # and constructs/returns a ResourceHandle handle_size_t = <size_t>handle handle_ptr = <void*>handle_size_t self.c_resource_handle_ptr = cugraph_create_resource_handle(handle_ptr) # FIXME: check for error def __dealloc__(self): # FIXME: free only if handle is a valid pointer cugraph_free_resource_handle(self.c_resource_handle_ptr)
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/sorensen_coefficients.pyx
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from libc.stdint cimport uintptr_t from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_device_array_view_free ) from pylibcugraph._cugraph_c.graph_functions cimport ( cugraph_vertex_pairs_t, cugraph_vertex_pairs_get_first, cugraph_vertex_pairs_get_second, cugraph_vertex_pairs_free, cugraph_create_vertex_pairs ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) from pylibcugraph._cugraph_c.similarity_algorithms cimport ( cugraph_sorensen_coefficients, cugraph_similarity_result_t, cugraph_similarity_result_get_similarity, cugraph_similarity_result_free ) from pylibcugraph.resource_handle cimport ( ResourceHandle, ) from pylibcugraph.graphs cimport ( _GPUGraph, ) from pylibcugraph.utils cimport ( assert_success, copy_to_cupy_array, create_cugraph_type_erased_device_array_view_from_py_obj ) def sorensen_coefficients(ResourceHandle resource_handle, _GPUGraph graph, first, second, bool_t use_weight, bool_t do_expensive_check): """ Compute the Sorensen coefficients for the specified vertex_pairs. Note that Sorensen similarity must run on a symmetric graph. Parameters ---------- resource_handle : ResourceHandle Handle to the underlying device resources needed for referencing data and running algorithms. graph : SGGraph or MGGraph The input graph, for either Single or Multi-GPU operations. first : Source of the vertex pair. second : Destination of the vertex pair. use_weight : bool, optional If set to True, the compute weighted jaccard_coefficients( the input graph must be weighted in that case). Otherwise, computed un-weighted jaccard_coefficients do_expensive_check : bool If True, performs more extensive tests on the inputs to ensure validitity, at the expense of increased run time. Returns ------- A tuple of device arrays containing the vertex pairs with their corresponding Sorensen coefficient scores. Examples -------- # FIXME: No example yet """ cdef cugraph_vertex_pairs_t* vertex_pairs_ptr cdef cugraph_resource_handle_t* c_resource_handle_ptr = \ resource_handle.c_resource_handle_ptr cdef cugraph_graph_t* c_graph_ptr = graph.c_graph_ptr cdef cugraph_similarity_result_t* result_ptr cdef cugraph_error_code_t error_code cdef cugraph_error_t* error_ptr # 'first' is a required parameter cdef cugraph_type_erased_device_array_view_t* \ first_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj( first) # 'second' is a required parameter cdef cugraph_type_erased_device_array_view_t* \ second_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj( second) error_code = cugraph_create_vertex_pairs(c_resource_handle_ptr, c_graph_ptr, first_view_ptr, second_view_ptr, &vertex_pairs_ptr, &error_ptr) assert_success(error_code, error_ptr, "vertex_pairs") error_code = cugraph_sorensen_coefficients(c_resource_handle_ptr, c_graph_ptr, vertex_pairs_ptr, use_weight, do_expensive_check, &result_ptr, &error_ptr) assert_success(error_code, error_ptr, "cugraph_sorensen_coefficients") # Extract individual device array pointers from result and copy to cupy # arrays for returning. cdef cugraph_type_erased_device_array_view_t* similarity_ptr = \ cugraph_similarity_result_get_similarity(result_ptr) cupy_similarity = copy_to_cupy_array(c_resource_handle_ptr, similarity_ptr) cdef cugraph_type_erased_device_array_view_t* first_ptr = \ cugraph_vertex_pairs_get_first(vertex_pairs_ptr) cupy_first = copy_to_cupy_array(c_resource_handle_ptr, first_ptr) cdef cugraph_type_erased_device_array_view_t* second_ptr = \ cugraph_vertex_pairs_get_second(vertex_pairs_ptr) cupy_second = copy_to_cupy_array(c_resource_handle_ptr, second_ptr) # Free all pointers cugraph_similarity_result_free(result_ptr) cugraph_vertex_pairs_free(vertex_pairs_ptr) cugraph_type_erased_device_array_view_free(first_view_ptr) cugraph_type_erased_device_array_view_free(second_view_ptr) return cupy_first, cupy_second, cupy_similarity
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/overlap_coefficients.pyx
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from libc.stdint cimport uintptr_t from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_device_array_view_free ) from pylibcugraph._cugraph_c.graph_functions cimport ( cugraph_vertex_pairs_t, cugraph_vertex_pairs_get_first, cugraph_vertex_pairs_get_second, cugraph_vertex_pairs_free, cugraph_create_vertex_pairs ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) from pylibcugraph._cugraph_c.similarity_algorithms cimport ( cugraph_overlap_coefficients, cugraph_similarity_result_t, cugraph_similarity_result_get_similarity, cugraph_similarity_result_free ) from pylibcugraph.resource_handle cimport ( ResourceHandle, ) from pylibcugraph.graphs cimport ( _GPUGraph, ) from pylibcugraph.utils cimport ( assert_success, copy_to_cupy_array, create_cugraph_type_erased_device_array_view_from_py_obj ) def overlap_coefficients(ResourceHandle resource_handle, _GPUGraph graph, first, second, bool_t use_weight, bool_t do_expensive_check): """ Compute the Overlap coefficients for the specified vertex_pairs. Note that Overlap similarity must run on a symmetric graph. Parameters ---------- resource_handle : ResourceHandle Handle to the underlying device resources needed for referencing data and running algorithms. graph : SGGraph or MGGraph The input graph, for either Single or Multi-GPU operations. first : Source of the vertex pair. second : Destination of the vertex pair. use_weight : bool, optional If set to True, the compute weighted jaccard_coefficients( the input graph must be weighted in that case). Otherwise, computed un-weighted jaccard_coefficients do_expensive_check : bool If True, performs more extensive tests on the inputs to ensure validitity, at the expense of increased run time. Returns ------- A tuple of device arrays containing the vertex pairs with their corresponding Overlap coefficient scores. Examples -------- # FIXME: No example yet """ cdef cugraph_vertex_pairs_t* vertex_pairs_ptr cdef cugraph_resource_handle_t* c_resource_handle_ptr = \ resource_handle.c_resource_handle_ptr cdef cugraph_graph_t* c_graph_ptr = graph.c_graph_ptr cdef cugraph_similarity_result_t* result_ptr cdef cugraph_error_code_t error_code cdef cugraph_error_t* error_ptr # 'first' is a required parameter cdef cugraph_type_erased_device_array_view_t* \ first_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj( first) # 'second' is a required parameter cdef cugraph_type_erased_device_array_view_t* \ second_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj( second) error_code = cugraph_create_vertex_pairs(c_resource_handle_ptr, c_graph_ptr, first_view_ptr, second_view_ptr, &vertex_pairs_ptr, &error_ptr) assert_success(error_code, error_ptr, "vertex_pairs") error_code = cugraph_overlap_coefficients(c_resource_handle_ptr, c_graph_ptr, vertex_pairs_ptr, use_weight, do_expensive_check, &result_ptr, &error_ptr) assert_success(error_code, error_ptr, "cugraph_overlap_coefficients") # Extract individual device array pointers from result and copy to cupy # arrays for returning. cdef cugraph_type_erased_device_array_view_t* similarity_ptr = \ cugraph_similarity_result_get_similarity(result_ptr) cupy_similarity = copy_to_cupy_array(c_resource_handle_ptr, similarity_ptr) cdef cugraph_type_erased_device_array_view_t* first_ptr = \ cugraph_vertex_pairs_get_first(vertex_pairs_ptr) cupy_first = copy_to_cupy_array(c_resource_handle_ptr, first_ptr) cdef cugraph_type_erased_device_array_view_t* second_ptr = \ cugraph_vertex_pairs_get_second(vertex_pairs_ptr) cupy_second = copy_to_cupy_array(c_resource_handle_ptr, second_ptr) # Free all pointers cugraph_similarity_result_free(result_ptr) cugraph_vertex_pairs_free(vertex_pairs_ptr) cugraph_type_erased_device_array_view_free(first_view_ptr) cugraph_type_erased_device_array_view_free(second_view_ptr) return cupy_first, cupy_second, cupy_similarity
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/ecg.pyx
# Copyright (c) 2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) from pylibcugraph._cugraph_c.community_algorithms cimport ( cugraph_hierarchical_clustering_result_t, cugraph_ecg, cugraph_hierarchical_clustering_result_get_vertices, cugraph_hierarchical_clustering_result_get_clusters, cugraph_hierarchical_clustering_result_free, ) from pylibcugraph.resource_handle cimport ( ResourceHandle, ) from pylibcugraph.graphs cimport ( _GPUGraph, ) from pylibcugraph.utils cimport ( assert_success, copy_to_cupy_array, ) def ecg(ResourceHandle resource_handle, _GPUGraph graph, min_weight, size_t ensemble_size, bool_t do_expensive_check ): """ Compute the Ensemble Clustering for Graphs (ECG) partition of the input graph. ECG runs truncated Louvain on an ensemble of permutations of the input graph, then uses the ensemble partitions to determine weights for the input graph. The final result is found by running full Louvain on the input graph using the determined weights. See https://arxiv.org/abs/1809.05578 for further information. Parameters ---------- resource_handle : ResourceHandle Handle to the underlying device resources needed for referencing data and running algorithms. graph : SGGraph The input graph. min_weight : double, optional (default=0.5) The minimum value to assign as an edgeweight in the ECG algorithm. It should be a value in the range [0,1] usually left as the default value of .05 ensemble_size : size_t, optional (default=16) The number of graph permutations to use for the ensemble. The default value is 16, larger values may produce higher quality partitions for some graphs. do_expensive_check : bool_t If True, performs more extensive tests on the inputs to ensure validitity, at the expense of increased run time. Returns ------- A tuple containing the hierarchical clustering vertices, clusters Examples -------- >>> import pylibcugraph, cupy, numpy >>> srcs = cupy.asarray([0, 1, 2], dtype=numpy.int32) >>> dsts = cupy.asarray([1, 2, 0], dtype=numpy.int32) >>> weights = cupy.asarray([1.0, 1.0, 1.0], dtype=numpy.float32) >>> resource_handle = pylibcugraph.ResourceHandle() >>> graph_props = pylibcugraph.GraphProperties( ... is_symmetric=True, is_multigraph=False) >>> G = pylibcugraph.SGGraph( ... resource_handle, graph_props, srcs, dsts, weights, ... store_transposed=True, renumber=False, do_expensive_check=False) >>> (vertices, clusters) = pylibcugraph.ecg(resource_handle, G) # FIXME: Check this docstring example >>> vertices [0, 1, 2] >>> clusters [0, 0, 0] """ if min_weight is None: min_weight = 0.5 if ensemble_size is None: ensemble_size = 16 cdef cugraph_resource_handle_t* c_resource_handle_ptr = \ resource_handle.c_resource_handle_ptr cdef cugraph_graph_t* c_graph_ptr = graph.c_graph_ptr cdef cugraph_hierarchical_clustering_result_t* result_ptr cdef cugraph_error_code_t error_code cdef cugraph_error_t* error_ptr error_code = cugraph_ecg(c_resource_handle_ptr, c_graph_ptr, min_weight, ensemble_size, do_expensive_check, &result_ptr, &error_ptr) assert_success(error_code, error_ptr, "cugraph_ecg") # Extract individual device array pointers from result and copy to cupy # arrays for returning. cdef cugraph_type_erased_device_array_view_t* vertices_ptr = \ cugraph_hierarchical_clustering_result_get_vertices(result_ptr) cdef cugraph_type_erased_device_array_view_t* clusters_ptr = \ cugraph_hierarchical_clustering_result_get_clusters(result_ptr) cupy_vertices = copy_to_cupy_array(c_resource_handle_ptr, vertices_ptr) cupy_clusters = copy_to_cupy_array(c_resource_handle_ptr, clusters_ptr) cugraph_hierarchical_clustering_result_free(result_ptr) return (cupy_vertices, cupy_clusters)
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/__init__.py
# Copyright (c) 2021-2023, NVIDIA CORPORATION. # 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 pylibcugraph.components._connectivity import ( strongly_connected_components, ) from pylibcugraph import experimental from pylibcugraph.graphs import SGGraph, MGGraph from pylibcugraph.resource_handle import ResourceHandle from pylibcugraph.graph_properties import GraphProperties from pylibcugraph.eigenvector_centrality import eigenvector_centrality from pylibcugraph.katz_centrality import katz_centrality from pylibcugraph.pagerank import pagerank from pylibcugraph.personalized_pagerank import personalized_pagerank from pylibcugraph.sssp import sssp from pylibcugraph.hits import hits from pylibcugraph.node2vec import node2vec from pylibcugraph.bfs import bfs from pylibcugraph.uniform_neighbor_sample import uniform_neighbor_sample from pylibcugraph.core_number import core_number from pylibcugraph.k_core import k_core from pylibcugraph.two_hop_neighbors import get_two_hop_neighbors from pylibcugraph.louvain import louvain from pylibcugraph.triangle_count import triangle_count from pylibcugraph.egonet import ego_graph from pylibcugraph.weakly_connected_components import weakly_connected_components from pylibcugraph.uniform_random_walks import uniform_random_walks from pylibcugraph.betweenness_centrality import betweenness_centrality from pylibcugraph.induced_subgraph import induced_subgraph from pylibcugraph.ecg import ecg from pylibcugraph.balanced_cut_clustering import balanced_cut_clustering from pylibcugraph.spectral_modularity_maximization import ( spectral_modularity_maximization, ) from pylibcugraph.analyze_clustering_modularity import analyze_clustering_modularity from pylibcugraph.analyze_clustering_edge_cut import analyze_clustering_edge_cut from pylibcugraph.analyze_clustering_ratio_cut import analyze_clustering_ratio_cut from pylibcugraph.random import CuGraphRandomState from pylibcugraph.leiden import leiden from pylibcugraph.select_random_vertices import select_random_vertices from pylibcugraph.edge_betweenness_centrality import edge_betweenness_centrality from pylibcugraph.generate_rmat_edgelist import generate_rmat_edgelist from pylibcugraph.generate_rmat_edgelists import generate_rmat_edgelists from pylibcugraph.replicate_edgelist import replicate_edgelist from pylibcugraph.k_truss_subgraph import k_truss_subgraph from pylibcugraph.jaccard_coefficients import jaccard_coefficients from pylibcugraph.overlap_coefficients import overlap_coefficients from pylibcugraph.sorensen_coefficients import sorensen_coefficients from pylibcugraph import exceptions from pylibcugraph._version import __git_commit__, __version__
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/bfs.pyx
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from libc.stdint cimport uintptr_t from libc.stdint cimport int32_t from libc.limits cimport INT_MAX from pylibcugraph.resource_handle cimport ResourceHandle from pylibcugraph._cugraph_c.algorithms cimport ( cugraph_bfs, cugraph_paths_result_t, cugraph_paths_result_get_vertices, cugraph_paths_result_get_predecessors, cugraph_paths_result_get_distances, cugraph_paths_result_free, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_device_array_view_create, ) from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph.utils cimport ( assert_success, copy_to_cupy_array, assert_CAI_type, get_c_type_from_numpy_type, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) from pylibcugraph.graphs cimport ( _GPUGraph, ) def bfs(ResourceHandle handle, _GPUGraph graph, sources, bool_t direction_optimizing, int32_t depth_limit, bool_t compute_predecessors, bool_t do_expensive_check): """ Performs a Breadth-first search starting from the provided sources. Returns the distances, and predecessors if requested. Parameters ---------- handle: ResourceHandle The resource handle responsible for managing device resources that this algorithm will use graph: SGGraph or MGGraph The graph to operate upon sources: cudf.Series The vertices to start the breadth-first search from. Should match the numbering of the provided graph. All workers must have a unique set of sources. Empty sets are allowed as long as at least one worker has a source. direction_optimizing: bool_t Whether to treat the graph as undirected (should only be called on a symmetric graph) depth_limit: int32_t The depth limit at which the traversal will be stopped. If this is a negative number, the traversal will run without a depth limit. compute_predecessors: bool_t Whether to compute the predecessors. If left blank, -1 will be returned instead of the correct predecessor of each vertex. do_expensive_check : bool_t If True, performs more extensive tests on the inputs to ensure validitity, at the expense of increased run time. Returns ------- A tuple of device arrays (cupy arrays) of the form (distances, predecessors, vertices) Examples -------- >>> M = cudf.read_csv(datasets_path / 'karate.csv', delimiter=' ', >>> dtype=['int32', 'int32', 'float32'], header=None) >>> G = cugraph.Graph() >>> G.from_cudf_edgelist(M, source='0', destination='1', edge_attr='2') >>> >>> handle = ResourceHandle() >>> >>> srcs = G.edgelist.edgelist_df['src'] >>> dsts = G.edgelist.edgelist_df['dst'] >>> weights = G.edgelist.edgelist_df['weights'] >>> >>> sg = SGGraph( >>> resource_handle = handle, >>> graph_properties = GraphProperties(is_multigraph=G.is_multigraph()), >>> src_array = srcs, >>> dst_array = dsts, >>> weight_array = weights, >>> store_transposed=False, >>> renumber=False, >>> do_expensive_check=do_expensive_check >>> ) >>> >>> res = pylibcugraph_bfs( >>> handle, >>> sg, >>> cudf.Series([0], dtype='int32'), >>> False, >>> 10, >>> True, >>> False >>> ) >>> >>> distances, predecessors, vertices = res >>> f>>> inal_results = cudf.DataFrame({ >>> 'distance': cudf.Series(distances), >>> 'vertex': cudf.Series(vertices), >>> 'predecessor': cudf.Series(predecessors), >>> }) """ try: import cupy except ModuleNotFoundError: raise RuntimeError("bfs requires the cupy package, which could not " "be imported") assert_CAI_type(sources, "sources") if depth_limit <= 0: depth_limit = INT_MAX - 1 cdef cugraph_resource_handle_t* c_resource_handle_ptr = \ handle.c_resource_handle_ptr cdef cugraph_graph_t* c_graph_ptr = graph.c_graph_ptr cdef cugraph_error_code_t error_code cdef cugraph_error_t* error_ptr cdef uintptr_t cai_sources_ptr = \ sources.__cuda_array_interface__["data"][0] cdef cugraph_type_erased_device_array_view_t* sources_view_ptr = \ cugraph_type_erased_device_array_view_create( <void*>cai_sources_ptr, len(sources), get_c_type_from_numpy_type(sources.dtype)) cdef cugraph_paths_result_t* result_ptr error_code = cugraph_bfs( c_resource_handle_ptr, c_graph_ptr, sources_view_ptr, direction_optimizing, depth_limit, compute_predecessors, do_expensive_check, &result_ptr, &error_ptr ) assert_success(error_code, error_ptr, "cugraph_bfs") # Extract individual device array pointers from result cdef cugraph_type_erased_device_array_view_t* distances_ptr = \ cugraph_paths_result_get_distances(result_ptr) cdef cugraph_type_erased_device_array_view_t* predecessors_ptr = \ cugraph_paths_result_get_predecessors(result_ptr) cdef cugraph_type_erased_device_array_view_t* vertices_ptr = \ cugraph_paths_result_get_vertices(result_ptr) # copy to cupy arrays cupy_distances = copy_to_cupy_array(c_resource_handle_ptr, distances_ptr) cupy_predecessors = copy_to_cupy_array(c_resource_handle_ptr, predecessors_ptr) cupy_vertices = copy_to_cupy_array(c_resource_handle_ptr, vertices_ptr) # deallocate the no-longer needed result struct cugraph_paths_result_free(result_ptr) return (cupy_distances, cupy_predecessors, cupy_vertices)
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/eigenvector_centrality.pyx
# Copyright (c) 2022, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from libc.stdint cimport uintptr_t from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, data_type_id_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_device_array_view_create, cugraph_type_erased_device_array_view_free, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) from pylibcugraph._cugraph_c.centrality_algorithms cimport ( cugraph_centrality_result_t, cugraph_eigenvector_centrality, cugraph_centrality_result_get_vertices, cugraph_centrality_result_get_values, cugraph_centrality_result_free, ) from pylibcugraph.resource_handle cimport ( ResourceHandle, ) from pylibcugraph.graphs cimport ( _GPUGraph, ) from pylibcugraph.utils cimport ( assert_success, copy_to_cupy_array, assert_CAI_type, get_c_type_from_numpy_type, ) def eigenvector_centrality(ResourceHandle resource_handle, _GPUGraph graph, double epsilon, size_t max_iterations, bool_t do_expensive_check): """ Compute the Eigenvector centrality for the nodes of the graph. Parameters ---------- resource_handle : ResourceHandle Handle to the underlying device resources needed for referencing data and running algorithms. graph : SGGraph or MGGraph The input graph, for either Single or Multi-GPU operations. epsilon : double Error tolerance to check convergence max_iterations: size_t Maximum number of Eignevector Centrality iterations do_expensive_check : bool_t A flag to run expensive checks for input arguments if True. Returns ------- A tuple of device arrays, where the first item in the tuple is a device array containing the vertices and the second item in the tuple is a device array containing the eigenvector centrality scores for the corresponding vertices. Examples -------- >>> import pylibcugraph, cupy, numpy >>> srcs = cupy.asarray([0, 1, 2], dtype=numpy.int32) >>> dsts = cupy.asarray([1, 2, 3], dtype=numpy.int32) >>> weights = cupy.asarray([1.0, 1.0, 1.0], dtype=numpy.float32) >>> resource_handle = pylibcugraph.ResourceHandle() >>> graph_props = pylibcugraph.GraphProperties( ... is_symmetric=False, is_multigraph=False) >>> G = pylibcugraph.SGGraph( ... resource_handle, graph_props, srcs, dsts, weights, ... store_transposed=True, renumber=False, do_expensive_check=False) >>> (vertices, values) = pylibcugraph.eigenvector_centrality( resource_handle, G, 1e-6, 1000, False) """ cdef cugraph_resource_handle_t* c_resource_handle_ptr = \ resource_handle.c_resource_handle_ptr cdef cugraph_graph_t* c_graph_ptr = graph.c_graph_ptr cdef cugraph_centrality_result_t* result_ptr cdef cugraph_error_code_t error_code cdef cugraph_error_t* error_ptr error_code = cugraph_eigenvector_centrality(c_resource_handle_ptr, c_graph_ptr, epsilon, max_iterations, do_expensive_check, &result_ptr, &error_ptr) assert_success(error_code, error_ptr, "cugraph_eigenvector_centrality") # Extract individual device array pointers from result and copy to cupy # arrays for returning. cdef cugraph_type_erased_device_array_view_t* vertices_ptr = \ cugraph_centrality_result_get_vertices(result_ptr) cdef cugraph_type_erased_device_array_view_t* values_ptr = \ cugraph_centrality_result_get_values(result_ptr) cupy_vertices = copy_to_cupy_array(c_resource_handle_ptr, vertices_ptr) cupy_values = copy_to_cupy_array(c_resource_handle_ptr, values_ptr) cugraph_centrality_result_free(result_ptr) return (cupy_vertices, cupy_values)
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/VERSION
23.12.00
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/two_hop_neighbors.pyx
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( cugraph_resource_handle_t, bool_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_device_array_view_free, ) from pylibcugraph._cugraph_c.graph_functions cimport ( cugraph_two_hop_neighbors, cugraph_vertex_pairs_t, cugraph_vertex_pairs_get_first, cugraph_vertex_pairs_get_second, cugraph_vertex_pairs_free, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) from pylibcugraph.resource_handle cimport ( ResourceHandle, ) from pylibcugraph.graphs cimport ( _GPUGraph, ) from pylibcugraph.utils cimport ( assert_success, copy_to_cupy_array, create_cugraph_type_erased_device_array_view_from_py_obj ) def get_two_hop_neighbors(ResourceHandle resource_handle, _GPUGraph graph, start_vertices, bool_t do_expensive_check): """ Compute vertex pairs that are two hops apart. The resulting pairs are sorted before returning. Parameters ---------- resource_handle : ResourceHandle Handle to the underlying device resources needed for referencing data and running algorithms. graph : SGGraph or MGGraph The input graph, for either Single or Multi-GPU operations. start_vertices : Optional array of starting vertices If None use all, if specified compute two-hop neighbors for these starting vertices Returns ------- return a cupy arrays of 'first' and 'second' or a 'cugraph_vertex_pairs_t' which can be directly passed to the similarity algorithm? """ cdef cugraph_resource_handle_t* c_resource_handle_ptr = \ resource_handle.c_resource_handle_ptr cdef cugraph_graph_t* c_graph_ptr = graph.c_graph_ptr cdef cugraph_vertex_pairs_t* result_ptr cdef cugraph_error_code_t error_code cdef cugraph_error_t* error_ptr cdef cugraph_type_erased_device_array_view_t* start_vertices_ptr cdef cugraph_type_erased_device_array_view_t* \ start_vertices_view_ptr = \ create_cugraph_type_erased_device_array_view_from_py_obj( start_vertices) error_code = cugraph_two_hop_neighbors(c_resource_handle_ptr, c_graph_ptr, start_vertices_view_ptr, do_expensive_check, &result_ptr, &error_ptr) assert_success(error_code, error_ptr, "two_hop_neighbors") cdef cugraph_type_erased_device_array_view_t* first_ptr = \ cugraph_vertex_pairs_get_first(result_ptr) cdef cugraph_type_erased_device_array_view_t* second_ptr = \ cugraph_vertex_pairs_get_second(result_ptr) cupy_first = copy_to_cupy_array(c_resource_handle_ptr, first_ptr) cupy_second = copy_to_cupy_array(c_resource_handle_ptr, second_ptr) # Free all pointers cugraph_vertex_pairs_free(result_ptr) if start_vertices is not None: cugraph_type_erased_device_array_view_free(start_vertices_view_ptr) return cupy_first, cupy_second
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/leiden.pyx
# Copyright (c) 2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) from pylibcugraph._cugraph_c.community_algorithms cimport ( cugraph_hierarchical_clustering_result_t, cugraph_leiden, cugraph_hierarchical_clustering_result_get_vertices, cugraph_hierarchical_clustering_result_get_clusters, cugraph_hierarchical_clustering_result_get_modularity, cugraph_hierarchical_clustering_result_free, ) from pylibcugraph.resource_handle cimport ( ResourceHandle, ) from pylibcugraph.graphs cimport ( _GPUGraph, ) from pylibcugraph.utils cimport ( assert_success, copy_to_cupy_array, ) from pylibcugraph._cugraph_c.random cimport ( cugraph_rng_state_t ) from pylibcugraph.random cimport ( CuGraphRandomState ) def leiden(ResourceHandle resource_handle, random_state, _GPUGraph graph, size_t max_level, double resolution, double theta, bool_t do_expensive_check): """ Compute the modularity optimizing partition of the input graph using the Leiden method. Parameters ---------- resource_handle : ResourceHandle Handle to the underlying device resources needed for referencing data and running algorithms. random_state : int , optional Random state to use when generating samples. Optional argument, defaults to a hash of process id, time, and hostname. (See pylibcugraph.random.CuGraphRandomState) graph : SGGraph or MGGraph The input graph. max_level: size_t This controls the maximum number of levels/iterations of the leiden algorithm. When specified the algorithm will terminate after no more than the specified number of iterations. No error occurs when the algorithm terminates early in this manner. resolution: double Called gamma in the modularity formula, this changes the size of the communities. Higher resolutions lead to more smaller communities, lower resolutions lead to fewer larger communities. Defaults to 1. theta: double Called theta in the Leiden algorithm, this is used to scale modularity gain in Leiden refinement phase, to compute the probability of joining a random leiden community. do_expensive_check : bool_t If True, performs more extensive tests on the inputs to ensure validitity, at the expense of increased run time. Returns ------- A tuple containing the hierarchical clustering vertices, clusters and modularity score Examples -------- >>> import pylibcugraph, cupy, numpy >>> srcs = cupy.asarray([0, 1, 2], dtype=numpy.int32) >>> dsts = cupy.asarray([1, 2, 0], dtype=numpy.int32) >>> weights = cupy.asarray([1.0, 1.0, 1.0], dtype=numpy.float32) >>> resource_handle = pylibcugraph.ResourceHandle() >>> graph_props = pylibcugraph.GraphProperties( ... is_symmetric=True, is_multigraph=False) >>> G = pylibcugraph.SGGraph( ... resource_handle, graph_props, srcs, dsts, weights, ... store_transposed=True, renumber=False, do_expensive_check=False) >>> (vertices, clusters, modularity) = pylibcugraph.Leiden( resource_handle, G, 100, 1., False) >>> vertices [0, 1, 2] >>> clusters [0, 0, 0] >>> modularity 0.0 """ cdef cugraph_resource_handle_t* c_resource_handle_ptr = \ resource_handle.c_resource_handle_ptr cdef cugraph_graph_t* c_graph_ptr = graph.c_graph_ptr cdef cugraph_hierarchical_clustering_result_t* result_ptr cdef cugraph_error_code_t error_code cdef cugraph_error_t* error_ptr cg_rng_state = CuGraphRandomState(resource_handle, random_state) cdef cugraph_rng_state_t* rng_state_ptr = cg_rng_state.rng_state_ptr error_code = cugraph_leiden(c_resource_handle_ptr, rng_state_ptr, c_graph_ptr, max_level, resolution, theta, do_expensive_check, &result_ptr, &error_ptr) assert_success(error_code, error_ptr, "cugraph_leiden") # Extract individual device array pointers from result and copy to cupy # arrays for returning. cdef cugraph_type_erased_device_array_view_t* vertices_ptr = \ cugraph_hierarchical_clustering_result_get_vertices(result_ptr) cdef cugraph_type_erased_device_array_view_t* clusters_ptr = \ cugraph_hierarchical_clustering_result_get_clusters(result_ptr) cdef double modularity = \ cugraph_hierarchical_clustering_result_get_modularity(result_ptr) cupy_vertices = copy_to_cupy_array(c_resource_handle_ptr, vertices_ptr) cupy_clusters = copy_to_cupy_array(c_resource_handle_ptr, clusters_ptr) cugraph_hierarchical_clustering_result_free(result_ptr) return (cupy_vertices, cupy_clusters, modularity)
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/generate_rmat_edgelists.pyx
# Copyright (c) 2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( cugraph_resource_handle_t, bool_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, ) from pylibcugraph._cugraph_c.graph_generators cimport ( cugraph_generate_rmat_edgelists, cugraph_generate_edge_weights, cugraph_generate_edge_ids, cugraph_generate_edge_types, cugraph_coo_t, cugraph_coo_list_t, cugraph_generator_distribution_t, cugraph_coo_get_sources, cugraph_coo_get_destinations, cugraph_coo_get_edge_weights, cugraph_coo_get_edge_id, cugraph_coo_get_edge_type, cugraph_coo_list_size, cugraph_coo_list_element, cugraph_coo_free, cugraph_coo_list_free, ) from pylibcugraph.resource_handle cimport ( ResourceHandle, ) from pylibcugraph.utils cimport ( assert_success, copy_to_cupy_array, get_c_type_from_numpy_type, ) from pylibcugraph._cugraph_c.random cimport ( cugraph_rng_state_t ) from pylibcugraph.random cimport ( CuGraphRandomState ) def generate_rmat_edgelists(ResourceHandle resource_handle, random_state, size_t n_edgelists, size_t min_scale, size_t max_scale, size_t edge_factor, size_distribution, edge_distribution, bool_t clip_and_flip, bool_t scramble_vertex_ids, bool_t include_edge_weights, minimum_weight, maximum_weight, dtype, bool_t include_edge_ids, bool_t include_edge_types, min_edge_type_value, max_edge_type_value, bool_t multi_gpu, ): """ Generate multiple RMAT edge list Parameters ---------- resource_handle : ResourceHandle Handle to the underlying device resources needed for referencing data and running algorithms. random_state : int , optional Random state to use when generating samples. Optional argument, defaults to a hash of process id, time, and hostname. (See pylibcugraph.random.CuGraphRandomState) n_edgelists : size_t Number of edge lists (graphs) to generate min_scale : size_t Scale factor to set the minimum number of vertices in the graph max_scale : size_t Scale factor to set the maximum number of vertices in the graph edge_factor : size_t Average number of edges per vertex to generate size_distribution : int Distribution of the graph sizes, impacts the scale parameter of the R-MAT generator. '0' for POWER_LAW distribution and '1' for UNIFORM distribution edge_distribution : int Edges distribution for each graph, impacts how R-MAT parameters a,b,c,d, are set. '0' for POWER_LAW distribution and '1' for UNIFORM distribution clip_and_flip : bool Flag controlling whether to generate edges only in the lower triangular part (including the diagonal) of the graph adjacency matrix (if set to 'true') or not (if set to 'false') scramble_vertex_ids : bool Flag controlling whether to scramble vertex ID bits (if set to `true`) or not (if set to `false`); scrambling vertex ID bits breaks correlation between vertex ID values and vertex degrees. include_edge_weights : bool Flag controlling whether to generate edges with weights (if set to 'true') or not (if set to 'false'). minimum_weight : double Minimum weight value to generate (if 'include_edge_weights' is 'true') maximum_weight : double Maximum weight value to generate (if 'include_edge_weights' is 'true') dtype : string The type of weight to generate ("FLOAT32" or "FLOAT64"), ignored unless include_weights is true include_edge_ids : bool Flag controlling whether to generate edges with ids (if set to 'true') or not (if set to 'false'). include_edge_types : bool Flag controlling whether to generate edges with types (if set to 'true') or not (if set to 'false'). min_edge_type_value : int Minimum edge type to generate if 'include_edge_types' is 'true' otherwise, this parameter is ignored. max_edge_type_value : int Maximum edge type to generate if 'include_edge_types' is 'true' otherwise, this paramter is ignored. Returns ------- return a list of tuple containing the sources and destinations with their corresponding weights, ids and types if the flags 'include_edge_weights', 'include_edge_ids' and 'include_edge_types' are respectively set to 'true' """ cdef cugraph_resource_handle_t* c_resource_handle_ptr = \ resource_handle.c_resource_handle_ptr cdef cugraph_coo_list_t* result_coo_list_ptr cdef cugraph_error_code_t error_code cdef cugraph_error_t* error_ptr cg_rng_state = CuGraphRandomState(resource_handle, random_state) cdef cugraph_rng_state_t* rng_state_ptr = \ cg_rng_state.rng_state_ptr cdef cugraph_generator_distribution_t size_distribution_ cdef cugraph_generator_distribution_t edge_distribution_ if size_distribution == 0: size_distribution_ = cugraph_generator_distribution_t.POWER_LAW else: size_distribution_ = cugraph_generator_distribution_t.UNIFORM if edge_distribution == 0: edge_distribution_ = cugraph_generator_distribution_t.POWER_LAW else: edge_distribution_ = cugraph_generator_distribution_t.UNIFORM error_code = cugraph_generate_rmat_edgelists(c_resource_handle_ptr, rng_state_ptr, n_edgelists, min_scale, max_scale, edge_factor, size_distribution_, edge_distribution_, clip_and_flip, scramble_vertex_ids, &result_coo_list_ptr, &error_ptr) assert_success(error_code, error_ptr, "generate_rmat_edgelists") cdef size_t size = cugraph_coo_list_size(result_coo_list_ptr) cdef cugraph_coo_t* result_coo_ptr cdef cugraph_type_erased_device_array_view_t* sources_view_ptr cdef cugraph_type_erased_device_array_view_t* destinations_view_ptr cupy_edge_weights = None cupy_edge_ids = None cupy_edge_types = None edgelists = [] for index in range(size): result_coo_ptr = cugraph_coo_list_element(result_coo_list_ptr, index) sources_view_ptr = cugraph_coo_get_sources(result_coo_ptr) destinations_view_ptr = cugraph_coo_get_destinations(result_coo_ptr) cupy_sources = copy_to_cupy_array(c_resource_handle_ptr, sources_view_ptr) cupy_destinations = copy_to_cupy_array(c_resource_handle_ptr, destinations_view_ptr) if include_edge_weights: dtype = get_c_type_from_numpy_type(dtype) error_code = cugraph_generate_edge_weights(c_resource_handle_ptr, rng_state_ptr, result_coo_ptr, dtype, minimum_weight, maximum_weight, &error_ptr) assert_success(error_code, error_ptr, "generate_edge_weights") edge_weights_view_ptr = cugraph_coo_get_edge_weights(result_coo_ptr) cupy_edge_weights = copy_to_cupy_array(c_resource_handle_ptr, edge_weights_view_ptr) if include_edge_ids: error_code = cugraph_generate_edge_ids(c_resource_handle_ptr, result_coo_ptr, multi_gpu, &error_ptr) assert_success(error_code, error_ptr, "generate_edge_ids") edge_ids_view_ptr = cugraph_coo_get_edge_id(result_coo_ptr) cupy_edge_ids = copy_to_cupy_array(c_resource_handle_ptr, edge_ids_view_ptr) if include_edge_types: error_code = cugraph_generate_edge_types(c_resource_handle_ptr, rng_state_ptr, result_coo_ptr, min_edge_type_value, max_edge_type_value, &error_ptr) assert_success(error_code, error_ptr, "generate_edge_types") edge_type_view_ptr = cugraph_coo_get_edge_type(result_coo_ptr) cupy_edge_types = copy_to_cupy_array(c_resource_handle_ptr, edge_type_view_ptr) edgelists.append((cupy_sources, cupy_destinations, cupy_edge_weights, cupy_edge_ids, cupy_edge_types)) # FIXME: Does freeing 'result_coo_ptr' automatically free 'result_coo_list_ptr'? cugraph_coo_free(result_coo_ptr) return edgelists
0
rapidsai_public_repos/cugraph/python/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/resource_handle.pxd
# Copyright (c) 2022, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( cugraph_resource_handle_t, ) cdef class ResourceHandle: cdef cugraph_resource_handle_t* c_resource_handle_ptr
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/tests/test_louvain.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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 cupy as cp import numpy as np import cudf from pylibcugraph import ( SGGraph, ResourceHandle, GraphProperties, ) from pylibcugraph import louvain def check_results(d_vertices, d_clusters, modularity): expected_vertices = np.array([1, 2, 3, 0, 4, 5], dtype=np.int32) expected_clusters = np.array([0, 0, 0, 0, 1, 1], dtype=np.int32) expected_modularity = 0.125 h_vertices = d_vertices.get() h_clusters = d_clusters.get() assert np.array_equal(expected_vertices, h_vertices) assert np.array_equal(expected_clusters, h_clusters) assert expected_modularity == modularity # ============================================================================= # Pytest fixtures # ============================================================================= # fixtures used in this test module are defined in conftest.py # ============================================================================= # Tests # ============================================================================= def test_sg_louvain_cupy(): resource_handle = ResourceHandle() graph_props = GraphProperties(is_symmetric=True, is_multigraph=False) device_srcs = cp.asarray( [0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5], dtype=np.int32 ) device_dsts = cp.asarray( [1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4], dtype=np.int32 ) device_weights = cp.asarray( [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ], dtype=np.float32, ) max_level = 100 threshold = 0.0001 resolution = 1.0 sg = SGGraph( resource_handle, graph_props, device_srcs, device_dsts, device_weights, store_transposed=False, renumber=True, do_expensive_check=False, ) vertices, clusters, modularity = louvain( resource_handle, sg, max_level, threshold, resolution, do_expensive_check=False ) check_results(vertices, clusters, modularity) def test_sg_louvain_cudf(): resource_handle = ResourceHandle() graph_props = GraphProperties(is_symmetric=True, is_multigraph=False) device_srcs = cudf.Series( [0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5], dtype=np.int32 ) device_dsts = cudf.Series( [1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4], dtype=np.int32 ) device_weights = cudf.Series( [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ], dtype=np.float32, ) max_level = 100 threshold = 0.0001 resolution = 1.0 sg = SGGraph( resource_handle, graph_props, device_srcs, device_dsts, device_weights, store_transposed=False, renumber=True, do_expensive_check=False, ) vertices, clusters, modularity = louvain( resource_handle, sg, max_level, threshold, resolution, do_expensive_check=False ) check_results(vertices, clusters, modularity)
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/tests/test_katz_centrality.py
# Copyright (c) 2022, NVIDIA CORPORATION. # 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 pytest import cupy as cp import numpy as np from pylibcugraph import ResourceHandle, GraphProperties, SGGraph, katz_centrality from pylibcugraph.testing import utils TOY = utils.RAPIDS_DATASET_ROOT_DIR_PATH / "toy_graph_undirected.csv" # ============================================================================= # Test helpers # ============================================================================= def _get_param_args(param_name, param_values): """ Returns a tuple of (<param_name>, <pytest.param list>) which can be applied as the args to pytest.mark.parametrize(). The pytest.param list also contains param id string formed from the param name and values. """ return (param_name, [pytest.param(v, id=f"{param_name}={v}") for v in param_values]) def _generic_katz_test( src_arr, dst_arr, wgt_arr, result_arr, num_vertices, num_edges, store_transposed, alpha, beta, epsilon, max_iterations, ): """ Builds a graph from the input arrays and runs katz using the other args, similar to how katz is tested in libcugraph. """ resource_handle = ResourceHandle() graph_props = GraphProperties(is_symmetric=False, is_multigraph=False) G = SGGraph( resource_handle, graph_props, src_arr, dst_arr, wgt_arr, store_transposed=False, renumber=False, do_expensive_check=True, ) (vertices, centralities) = katz_centrality( resource_handle, G, None, alpha, beta, epsilon, max_iterations, do_expensive_check=False, ) result_arr = result_arr.get() vertices = vertices.get() centralities = centralities.get() for idx in range(num_vertices): vertex_id = vertices[idx] expected_result = result_arr[vertex_id] actual_result = centralities[idx] if pytest.approx(expected_result, 1e-4) != actual_result: raise ValueError( f"Vertex {idx} has centrality {actual_result}" f", should have been {expected_result}" ) def test_katz(): num_edges = 8 num_vertices = 6 graph_data = np.genfromtxt(TOY, delimiter=" ") src = cp.asarray(graph_data[:, 0], dtype=np.int32) dst = cp.asarray(graph_data[:, 1], dtype=np.int32) wgt = cp.asarray(graph_data[:, 2], dtype=np.float32) result = cp.asarray( [0.410614, 0.403211, 0.390689, 0.415175, 0.395125, 0.433226], dtype=np.float32 ) alpha = 0.01 beta = 1.0 epsilon = 0.000001 max_iterations = 1000 # Katz requires store_transposed to be True _generic_katz_test( src, dst, wgt, result, num_vertices, num_edges, True, alpha, beta, epsilon, max_iterations, )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/tests/test_rmat.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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 pytest import cupy as cp from pylibcugraph import ( ResourceHandle, ) from pylibcugraph import generate_rmat_edgelist # ============================================================================= # Pytest fixtures # ============================================================================= # fixtures used in this test module are defined in conftest.py # ============================================================================= # Tests # ============================================================================= def check_results( result, scale, num_edges, include_edge_ids, include_edge_weights, include_edge_types ): h_src_arr, h_dst_arr, h_wgt_arr, h_ids_arr, h_types_arr = result if include_edge_weights: assert h_wgt_arr is not None if include_edge_ids: assert h_ids_arr is not None if include_edge_types: assert h_types_arr is not None vertices = cp.union1d(h_src_arr, h_dst_arr) assert len(h_src_arr) == len(h_dst_arr) == num_edges assert len(vertices) <= 2**scale # TODO: Coverage for the MG implementation @pytest.mark.parametrize("scale", [2, 4, 8]) @pytest.mark.parametrize("num_edges", [4, 16, 32]) @pytest.mark.parametrize("clip_and_flip", [False, True]) @pytest.mark.parametrize("scramble_vertex_ids", [False, True]) @pytest.mark.parametrize("include_edge_weights", [False, True]) @pytest.mark.parametrize("include_edge_types", [False, True]) @pytest.mark.parametrize("include_edge_ids", [False, True]) def test_rmat( scale, num_edges, clip_and_flip, scramble_vertex_ids, include_edge_weights, include_edge_types, include_edge_ids, ): resource_handle = ResourceHandle() result = generate_rmat_edgelist( resource_handle=resource_handle, random_state=42, scale=scale, num_edges=num_edges, a=0.57, b=0.19, c=0.19, clip_and_flip=clip_and_flip, scramble_vertex_ids=scramble_vertex_ids, include_edge_weights=include_edge_weights, minimum_weight=0, maximum_weight=1, dtype=cp.float32, include_edge_ids=include_edge_ids, include_edge_types=include_edge_types, min_edge_type_value=2, max_edge_type_value=5, multi_gpu=False, ) check_results( result, scale, num_edges, include_edge_ids, include_edge_weights, include_edge_types, )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/tests/test_uniform_neighbor_sample.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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 gc import pytest import cupy as cp import numpy as np import cudf from pylibcugraph import ( SGGraph, ResourceHandle, GraphProperties, ) from pylibcugraph import uniform_neighbor_sample # Set to True to disable memory leak assertions. This may be necessary when # running in environments that share a GPU (pytest-xdist), are using memory # pools, or other reasons which may cause the memory leak assertions to # improperly fail. mem_leak_assert_disabled = True # ============================================================================= # Pytest fixtures # ============================================================================= # fixtures used in this test module are defined in conftest.py # ============================================================================= # Tests # ============================================================================= def check_edges(result, srcs, dsts, weights, num_verts, num_edges, num_seeds): result_srcs, result_dsts, result_indices = result h_src_arr = srcs h_dst_arr = dsts h_wgt_arr = weights if isinstance(h_src_arr, cp.ndarray): h_src_arr = h_src_arr.get() if isinstance(h_dst_arr, cp.ndarray): h_dst_arr = h_dst_arr.get() if isinstance(h_wgt_arr, cp.ndarray): h_wgt_arr = h_wgt_arr.get() h_result_srcs = result_srcs.get() h_result_dsts = result_dsts.get() h_result_indices = result_indices.get() # Following the C validation, we will check that all edges are part of the # graph M = np.zeros((num_verts, num_verts), dtype=np.float32) # Construct the adjacency matrix for idx in range(num_edges): M[h_dst_arr[idx]][h_src_arr[idx]] = h_wgt_arr[idx] for edge in range(len(h_result_indices)): assert M[h_result_dsts[edge]][h_result_srcs[edge]] == h_result_indices[edge] # TODO: Coverage for the MG implementation @pytest.mark.skipif(reason="skipping for testing purposes") @pytest.mark.parametrize("renumber", [True, False]) @pytest.mark.parametrize("store_transposed", [True, False]) @pytest.mark.parametrize("with_replacement", [True, False]) def test_neighborhood_sampling_cupy( sg_graph_objs, valid_graph_data, renumber, store_transposed, with_replacement ): resource_handle = ResourceHandle() graph_props = GraphProperties(is_symmetric=False, is_multigraph=False) device_srcs, device_dsts, device_weights, ds_name, is_valid = valid_graph_data start_list = cp.random.choice(device_srcs, size=3) fanout_vals = np.asarray([1, 2], dtype="int32") # FIXME cupy has no attribute cp.union1d vertices = np.union1d(cp.asnumpy(device_srcs), cp.asnumpy(device_dsts)) vertices = cp.asarray(vertices) num_verts = len(vertices) num_edges = max(len(device_srcs), len(device_dsts)) sg = SGGraph( resource_handle, graph_props, device_srcs, device_dsts, device_weights, store_transposed=store_transposed, renumber=renumber, do_expensive_check=False, ) result = uniform_neighbor_sample( resource_handle, sg, start_list, fanout_vals, with_replacement=with_replacement, do_expensive_check=False, ) check_edges( result, device_srcs, device_dsts, device_weights, num_verts, num_edges, len(start_list), ) # TODO: Coverage for the MG implementation @pytest.mark.skipif(reason="skipping for testing purposes") @pytest.mark.parametrize("renumber", [True, False]) @pytest.mark.parametrize("store_transposed", [True, False]) @pytest.mark.parametrize("with_replacement", [True, False]) def test_neighborhood_sampling_cudf( sg_graph_objs, valid_graph_data, renumber, store_transposed, with_replacement ): resource_handle = ResourceHandle() graph_props = GraphProperties(is_symmetric=False, is_multigraph=False) device_srcs, device_dsts, device_weights, ds_name, is_valid = valid_graph_data # FIXME cupy has no attribute cp.union1d vertices = np.union1d(cp.asnumpy(device_srcs), cp.asnumpy(device_dsts)) vertices = cp.asarray(vertices) device_srcs = cudf.Series(device_srcs, dtype=device_srcs.dtype) device_dsts = cudf.Series(device_dsts, dtype=device_dsts.dtype) device_weights = cudf.Series(device_weights, dtype=device_weights.dtype) start_list = cp.random.choice(device_srcs, size=3) fanout_vals = np.asarray([1, 2], dtype="int32") num_verts = len(vertices) num_edges = max(len(device_srcs), len(device_dsts)) sg = SGGraph( resource_handle, graph_props, device_srcs, device_dsts, device_weights, store_transposed=store_transposed, renumber=renumber, do_expensive_check=False, ) result = uniform_neighbor_sample( resource_handle, sg, start_list, fanout_vals, with_replacement=with_replacement, do_expensive_check=False, ) check_edges( result, device_srcs, device_dsts, device_weights, num_verts, num_edges, len(start_list), ) @pytest.mark.cugraph_ops def test_neighborhood_sampling_large_sg_graph(gpubenchmark): """ Use a large SG graph and set input args accordingly to test/benchmark returning a large result. """ resource_handle = ResourceHandle() graph_props = GraphProperties(is_symmetric=False, is_multigraph=False) # FIXME: this graph is just a line - consider a better graph that exercises # neighborhood sampling better/differently device_srcs = cp.arange(1e6, dtype=np.int32) device_dsts = cp.arange(1, 1e6 + 1, dtype=np.int32) device_weights = cp.asarray([1.0] * int(1e6), dtype=np.float32) # start_list == every vertex is intentionally excessive start_list = device_srcs fanout_vals = np.asarray([1, 2], dtype=np.int32) sg = SGGraph( resource_handle, graph_props, device_srcs, device_dsts, device_weights, store_transposed=True, renumber=False, do_expensive_check=False, ) # Ensure the only memory used after the algo call is for the result, so # take a snapshot here. # Assume GPU 0 will be used and the test has # exclusive access and nothing else can use its memory while the test is # running. gc.collect() device = cp.cuda.Device(0) free_memory_before = device.mem_info[0] result = gpubenchmark( uniform_neighbor_sample, resource_handle, sg, start_list, fanout_vals, with_replacement=True, do_expensive_check=False, ) assert type(result) is tuple assert isinstance(result[0], cp.ndarray) assert isinstance(result[1], cp.ndarray) assert isinstance(result[2], cp.ndarray) # Crude check that the results are accessible assert result[0][0].dtype == np.int32 assert result[1][0].dtype == np.int32 assert result[2][0].dtype == np.float32 # FIXME: this is to help debug a leak in uniform_neighbor_sample, remove # once leak is fixed free_before_cleanup = device.mem_info[0] print(f"{free_before_cleanup=}") result_bytes = (len(result[0]) + len(result[1]) + len(result[2])) * (32 // 8) # Cleanup the result - this should leave the memory used equal to the # amount prior to running the algo. del result gc.collect() # FIXME: this is to help debug a leak in uniform_neighbor_sample, remove # once leak is fixed free_after_cleanup = device.mem_info[0] print(f"{free_after_cleanup=}") actual_delta = free_after_cleanup - free_before_cleanup expected_delta = free_memory_before - free_before_cleanup leak = expected_delta - actual_delta print(f" {result_bytes=} {actual_delta=} {expected_delta=} {leak=}") assert (free_memory_before == device.mem_info[0]) or mem_leak_assert_disabled def test_sample_result(): """ Ensure the SampleResult class returns zero-copy cupy arrays and properly frees device memory when all references to it are gone and it's garbage collected. """ from pylibcugraph.testing.type_utils import create_sampling_result gc.collect() resource_handle = ResourceHandle() # Assume GPU 0 will be used and the test has exclusive access and nothing # else can use its memory while the test is running. device = cp.cuda.Device(0) free_memory_before = device.mem_info[0] # Use the testing utility to create a large sampling result. This API is # intended for testing only - SampleResult objects are normally only # created by running a sampling algo. sampling_result = create_sampling_result( resource_handle, device_sources=cp.arange(1e8, dtype="int32"), device_destinations=cp.arange(1, 1e8 + 1, dtype="int32"), device_weights=cp.arange(1e8 + 2, dtype="float32"), device_edge_id=cp.arange(1e8 + 3, dtype="int32"), device_edge_type=cp.arange(1e8 + 4, dtype="int32"), device_hop=cp.arange(1e8 + 5, dtype="int32"), device_batch_label=cp.arange(1e8 + 6, dtype="int32"), ) assert (free_memory_before > device.mem_info[0]) or mem_leak_assert_disabled sources = sampling_result.get_sources() destinations = sampling_result.get_destinations() indices = sampling_result.get_indices() assert isinstance(sources, cp.ndarray) assert isinstance(destinations, cp.ndarray) assert isinstance(indices, cp.ndarray) print("sources:", destinations) # Delete the SampleResult instance. This *should not* free the device # memory yet since the variables sources, destinations, and indices are # keeping the refcount >0. del sampling_result gc.collect() assert (free_memory_before > device.mem_info[0]) or mem_leak_assert_disabled # Check that the data is still valid assert sources[999] == 999 assert destinations[999] == 1000 assert indices[999] == 999 # Add yet another reference to the original data, which should prevent it # from being freed when the GC runs. sources2 = sources # delete the variables which should take the ref count on sampling_result # to 0, which will cause it to be garbage collected. del sources del destinations del indices gc.collect() # sources2 should be keeping the data alive assert sources2[999] == 999 assert (free_memory_before > device.mem_info[0]) or mem_leak_assert_disabled # All memory should be freed once the last reference is deleted del sources2 gc.collect() assert (free_memory_before == device.mem_info[0]) or mem_leak_assert_disabled
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/tests/test_eigenvector_centrality.py
# Copyright (c) 2022, NVIDIA CORPORATION. # 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 pytest import cupy as cp import numpy as np from pylibcugraph import ( ResourceHandle, GraphProperties, SGGraph, eigenvector_centrality, ) from pylibcugraph.testing import utils TOY = utils.RAPIDS_DATASET_ROOT_DIR_PATH / "toy_graph.csv" # ============================================================================= # Test helpers # ============================================================================= def _get_param_args(param_name, param_values): """ Returns a tuple of (<param_name>, <pytest.param list>) which can be applied as the args to pytest.mark.parametrize(). The pytest.param list also contains param id string formed from the param name and values. """ return (param_name, [pytest.param(v, id=f"{param_name}={v}") for v in param_values]) def _generic_eigenvector_test( src_arr, dst_arr, wgt_arr, result_arr, num_vertices, num_edges, store_transposed, epsilon, max_iterations, ): """ Builds a graph from the input arrays and runs eigen using the other args, similar to how eigen is tested in libcugraph. """ resource_handle = ResourceHandle() graph_props = GraphProperties(is_symmetric=False, is_multigraph=False) G = SGGraph( resource_handle, graph_props, src_arr, dst_arr, wgt_arr, store_transposed=False, renumber=False, do_expensive_check=True, ) (vertices, centralities) = eigenvector_centrality( resource_handle, G, epsilon, max_iterations, do_expensive_check=False ) result_arr = result_arr.get() vertices = vertices.get() centralities = centralities.get() for idx in range(num_vertices): vertex_id = vertices[idx] expected_result = result_arr[vertex_id] actual_result = centralities[idx] assert pytest.approx(expected_result, 1e-4) == actual_result, ( f"Vertex {idx} has centrality {actual_result}, should have" f" been {expected_result}" ) def test_eigenvector(): num_edges = 16 num_vertices = 6 graph_data = np.genfromtxt(TOY, delimiter=" ") src = cp.asarray(graph_data[:, 0], dtype=np.int32) dst = cp.asarray(graph_data[:, 1], dtype=np.int32) wgt = cp.asarray(graph_data[:, 2], dtype=np.float32) result = cp.asarray( [0.236325, 0.292055, 0.458457, 0.60533, 0.190498, 0.495942], dtype=np.float32 ) epsilon = 1e-6 max_iterations = 200 # Eigenvector requires store_transposed to be True? _generic_eigenvector_test( src, dst, wgt, result, num_vertices, num_edges, True, epsilon, max_iterations )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/tests/conftest.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. # 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 pandas as pd import cupy as cp import numpy as np import pytest from pylibcugraph.testing import utils # Spoof the gpubenchmark fixture if it's not available so that asvdb and # rapids-pytest-benchmark do not need to be installed to run tests. if "gpubenchmark" not in globals(): def benchmark_func(func, *args, **kwargs): return func(*args, **kwargs) @pytest.fixture def gpubenchmark(): return benchmark_func # ============================================================================= # Fixture parameters # ============================================================================= class COOTestGraphDeviceData: def __init__(self, srcs, dsts, weights, name): self.srcs = srcs self.dsts = dsts self.weights = weights self.name = name self.is_valid = not (name.startswith("Invalid")) InvalidNumWeights_1 = COOTestGraphDeviceData( srcs=cp.asarray([0, 1, 2], dtype=np.int32), dsts=cp.asarray([1, 2, 3], dtype=np.int32), weights=cp.asarray([1.0, 1.0, 1.0, 1.0], dtype=np.float32), name="InvalidNumWeights_1", ) InvalidNumVerts_1 = COOTestGraphDeviceData( srcs=cp.asarray([1, 2], dtype=np.int32), dsts=cp.asarray([1, 2, 3], dtype=np.int32), weights=cp.asarray([1.0, 1.0, 1.0], dtype=np.float32), name="InvalidNumVerts_1", ) Simple_1 = COOTestGraphDeviceData( srcs=cp.asarray([0, 1, 2], dtype=np.int32), dsts=cp.asarray([1, 2, 3], dtype=np.int32), weights=cp.asarray([1.0, 1.0, 1.0], dtype=np.float32), name="Simple_1", ) Simple_2 = COOTestGraphDeviceData( srcs=cp.asarray([0, 1, 1, 2, 2, 2, 3, 4], dtype=np.int32), dsts=cp.asarray([1, 3, 4, 0, 1, 3, 5, 5], dtype=np.int32), weights=cp.asarray([0.1, 2.1, 1.1, 5.1, 3.1, 4.1, 7.2, 3.2], dtype=np.float32), name="Simple_2", ) # The objects in these lists must have a "name" attr, since fixtures will # access that to pass to tests, which then may use the name to associate to # expected test results. The name attr is also used for the pytest test ID. valid_datasets = [ utils.RAPIDS_DATASET_ROOT_DIR_PATH / "karate.csv", utils.RAPIDS_DATASET_ROOT_DIR_PATH / "dolphins.csv", Simple_1, Simple_2, ] all_datasets = valid_datasets + [ InvalidNumWeights_1, InvalidNumVerts_1, ] # ============================================================================= # Helper functions # ============================================================================= def get_graph_data_for_dataset(ds, ds_name): """ Given an object representing either a path to a dataset on disk, or an object containing raw data, return a series of arrays that can be used to construct a graph object. The final value is a bool used to indicate if the data is valid or not (invalid to test error handling). """ if isinstance(ds, COOTestGraphDeviceData): device_srcs = ds.srcs device_dsts = ds.dsts device_weights = ds.weights is_valid = ds.is_valid else: pdf = pd.read_csv( ds, delimiter=" ", header=None, names=["0", "1", "weight"], dtype={"0": "int32", "1": "int32", "weight": "float32"}, ) device_srcs = cp.asarray(pdf["0"].to_numpy(), dtype=np.int32) device_dsts = cp.asarray(pdf["1"].to_numpy(), dtype=np.int32) device_weights = cp.asarray(pdf["weight"].to_numpy(), dtype=np.float32) # Assume all datasets on disk are valid is_valid = True return (device_srcs, device_dsts, device_weights, ds_name, is_valid) def create_SGGraph(device_srcs, device_dsts, device_weights, transposed=False): """ Creates and returns a SGGraph instance and the corresponding ResourceHandle using the parameters passed in. """ from pylibcugraph import ( SGGraph, ResourceHandle, GraphProperties, ) resource_handle = ResourceHandle() graph_props = GraphProperties(is_symmetric=False, is_multigraph=False) g = SGGraph( resource_handle, graph_props, device_srcs, device_dsts, device_weights, store_transposed=transposed, renumber=False, do_expensive_check=False, ) # FIXME: add coverage for renumber=True and do_expensive_check=True return (g, resource_handle) # ============================================================================= # Pytest fixtures # ============================================================================= @pytest.fixture( scope="package", params=[pytest.param(ds, id=ds.name) for ds in all_datasets] ) def graph_data(request): """ Return a series of cupy arrays that can be used to construct Graph objects. The parameterization includes invalid arrays which can be used to test error handling, so the final value returned indicated if the arrays are valid or not. """ return get_graph_data_for_dataset(request.param, request.param.name) @pytest.fixture( scope="package", params=[pytest.param(ds, id=ds.name) for ds in valid_datasets] ) def valid_graph_data(request): """ Return a series of cupy arrays that can be used to construct Graph objects, all of which are valid (last value in returned tuple is always True). """ return get_graph_data_for_dataset(request.param, request.param.name) @pytest.fixture(scope="package") def sg_graph_objs(valid_graph_data, request): """ Returns a tuple containing the SGGraph object constructed from parameterized values returned by the valid_graph_data fixture, the associated resource handle, and the name of the dataset used to construct the graph. """ (device_srcs, device_dsts, device_weights, ds_name, is_valid) = valid_graph_data if is_valid is False: pytest.exit("got invalid graph data - expecting only valid data") (g, resource_handle) = create_SGGraph( device_srcs, device_dsts, device_weights, transposed=False ) return (g, resource_handle, ds_name) @pytest.fixture(scope="package") def sg_transposed_graph_objs(valid_graph_data, request): """ Returns a tuple containing the SGGraph object constructed from parameterized values returned by the valid_graph_data fixture, the associated resource handle, and the name of the dataset used to construct the graph. The SGGraph object is created with the transposed arg set to True. """ (device_srcs, device_dsts, device_weights, ds_name, is_valid) = valid_graph_data if is_valid is False: pytest.exit("got invalid graph data - expecting only valid data") (g, resource_handle) = create_SGGraph( device_srcs, device_dsts, device_weights, transposed=True ) return (g, resource_handle, ds_name)
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/tests/test_edge_betweenness_centrality.py
# Copyright (c) 2023, NVIDIA CORPORATION. # 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 pytest import cupy as cp import numpy as np from pylibcugraph import ( ResourceHandle, GraphProperties, SGGraph, edge_betweenness_centrality, ) from pylibcugraph.testing import utils TOY = utils.RAPIDS_DATASET_ROOT_DIR_PATH / "toy_graph.csv" # ============================================================================= # Test helpers # ============================================================================= def _get_param_args(param_name, param_values): """ Returns a tuple of (<param_name>, <pytest.param list>) which can be applied as the args to pytest.mark.parametrize(). The pytest.param list also contains param id string formed from the param name and values. """ return (param_name, [pytest.param(v, id=f"{param_name}={v}") for v in param_values]) def _generic_edge_betweenness_centrality_test( src_arr, dst_arr, edge_id_arr, result_score_arr, result_edge_id_arr, num_edges, store_transposed, k, random_state, normalized, ): """ Builds a graph from the input arrays and runs edge bc using the other args, similar to how edge bc is tested in libcugraph. """ resource_handle = ResourceHandle() graph_props = GraphProperties(is_symmetric=False, is_multigraph=False) G = SGGraph( resource_handle, graph_props, src_arr, dst_arr, store_transposed=store_transposed, renumber=False, do_expensive_check=True, edge_id_array=edge_id_arr, ) (_, _, values, edge_ids) = edge_betweenness_centrality( resource_handle, G, k, random_state, normalized, do_expensive_check=False ) result_score_arr = result_score_arr.get() result_edge_id_arr = result_edge_id_arr.get() centralities = values.get() edge_ids = edge_ids.get() for idx in range(num_edges): expected_result_score = result_score_arr[idx] actual_result_score = centralities[idx] expected_result_edge_id = result_edge_id_arr[idx] actual_result_edge_id = edge_ids[idx] assert pytest.approx(expected_result_score, 1e-4) == actual_result_score, ( f"Edge {src_arr[idx]} {dst_arr[idx]} has centrality {actual_result_score}," f" should have been {expected_result_score}" ) assert pytest.approx(expected_result_edge_id, 1e-4) == actual_result_edge_id, ( f"Edge {src_arr[idx]} {dst_arr[idx]} has id {actual_result_edge_id}," f" should have been {expected_result_edge_id}" ) def test_edge_betweenness_centrality(): num_edges = 16 graph_data = np.genfromtxt(TOY, delimiter=" ") src = cp.asarray(graph_data[:, 0], dtype=np.int32) dst = cp.asarray(graph_data[:, 1], dtype=np.int32) edge_id = cp.array( [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], dtype=np.int32 ) result_score = cp.asarray( [ 0.10555556, 0.06111111, 0.10555556, 0.06666667, 0.09444445, 0.14444445, 0.06111111, 0.06666667, 0.09444445, 0.09444445, 0.09444445, 0.12222222, 0.14444445, 0.07777778, 0.12222222, 0.07777778, ], dtype=np.float32, ) result_edge_ids = cp.asarray([0, 11, 8, 12, 1, 2, 3, 4, 5, 9, 13, 6, 10, 7, 14, 15]) store_transposed = False k = None random_state = None normalized = True _generic_edge_betweenness_centrality_test( src, dst, edge_id, result_score, result_edge_ids, num_edges, store_transposed, k, random_state, normalized, )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/tests/test_triangle_count.py
# Copyright (c) 2022, NVIDIA CORPORATION. # 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 pytest import cupy as cp import numpy as np import cudf from pylibcugraph import ( SGGraph, MGGraph, ResourceHandle, GraphProperties, ) from pylibcugraph import triangle_count def check_results(d_result): expected_vertex_result = np.array([1, 2, 3, 0, 4, 5], dtype=np.int32) expected_counts_result = np.array([2, 2, 1, 1, 0, 0], dtype=np.int32) d_vertex_result, d_counts_result = d_result h_vertex_result = d_vertex_result.get() h_counts_result = d_counts_result.get() assert np.array_equal(expected_vertex_result, h_vertex_result) assert np.array_equal(expected_counts_result, h_counts_result) # ============================================================================= # Pytest fixtures # ============================================================================= # fixtures used in this test module are defined in conftest.py # ============================================================================= # Tests # ============================================================================= def test_sg_triangle_count_cupy(): resource_handle = ResourceHandle() graph_props = GraphProperties(is_symmetric=True, is_multigraph=False) device_srcs = cp.asarray( [0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5], dtype=np.int32 ) device_dsts = cp.asarray( [1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4], dtype=np.int32 ) device_weights = cp.asarray( [ 0.1, 2.1, 1.1, 5.1, 3.1, 4.1, 7.2, 3.2, 0.1, 2.1, 1.1, 5.1, 3.1, 4.1, 7.2, 3.2, ], dtype=np.float32, ) # FIXME: Disable the start_list parameter until it is working start_list = None sg = SGGraph( resource_handle, graph_props, device_srcs, device_dsts, device_weights, store_transposed=False, renumber=True, do_expensive_check=False, ) d_result = triangle_count(resource_handle, sg, start_list, do_expensive_check=True) check_results(d_result) def test_sg_triangle_count_cudf(): resource_handle = ResourceHandle() graph_props = GraphProperties(is_symmetric=True, is_multigraph=False) device_srcs = cudf.Series( [0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5], dtype=np.int32 ) device_dsts = cudf.Series( [1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4], dtype=np.int32 ) device_weights = cudf.Series( [ 0.1, 2.1, 1.1, 5.1, 3.1, 4.1, 7.2, 3.2, 0.1, 2.1, 1.1, 5.1, 3.1, 4.1, 7.2, 3.2, ], dtype=np.float32, ) # FIXME: Disable the start_list parameter until it is working start_list = None sg = SGGraph( resource_handle, graph_props, device_srcs, device_dsts, device_weights, store_transposed=False, renumber=True, do_expensive_check=False, ) d_result = triangle_count(resource_handle, sg, start_list, do_expensive_check=True) check_results(d_result) @pytest.mark.skip(reason="pylibcugraph MG test infra not complete") def test_mg_triangle_count(): resource_handle = ResourceHandle() graph_props = GraphProperties(is_symmetric=False, is_multigraph=False) device_srcs = cp.asarray( [0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5], dtype=np.int32 ) device_dsts = cp.asarray( [1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4], dtype=np.int32 ) device_weights = cp.asarray( [ 0.1, 2.1, 1.1, 5.1, 3.1, 4.1, 7.2, 3.2, 0.1, 2.1, 1.1, 5.1, 3.1, 4.1, 7.2, 3.2, ], dtype=np.float32, ) # FIXME: Disable the start_list parameter until it is working start_list = None mg = MGGraph( resource_handle, graph_props, device_srcs, device_dsts, device_weights, store_transposed=True, num_edges=16, do_expensive_check=False, ) d_result = triangle_count(resource_handle, mg, start_list, do_expensive_check=True) print(d_result)
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/tests/test_pagerank.py
# Copyright (c) 2022, NVIDIA CORPORATION. # 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 pytest import cupy as cp import numpy as np # ============================================================================= # Test data # ============================================================================= _alpha = 0.85 _epsilon = 1.0e-6 _max_iterations = 500 # Map the names of input data to expected pagerank output # The result names correspond to the datasets defined in conftest.py _test_data = { "karate.csv": ( cp.asarray(range(34), dtype=np.int32), cp.asarray( [ 0.096998, 0.052877, 0.057078, 0.035860, 0.021978, 0.029111, 0.029111, 0.024491, 0.029766, 0.014309, 0.021978, 0.009565, 0.014645, 0.029536, 0.014536, 0.014536, 0.016784, 0.014559, 0.014536, 0.019605, 0.014536, 0.014559, 0.014536, 0.031522, 0.021076, 0.021006, 0.015044, 0.025640, 0.019573, 0.026288, 0.024590, 0.037158, 0.071693, 0.100919, ], dtype=np.float32, ), ), "dolphins.csv": ( cp.asarray(range(62), dtype=np.int32), cp.asarray( [ 0.01696534, 0.02465084, 0.01333804, 0.00962903, 0.00507979, 0.01442816, 0.02005379, 0.01564308, 0.01709825, 0.02345867, 0.01510835, 0.00507979, 0.0048353, 0.02615709, 0.03214436, 0.01988301, 0.01662675, 0.03172837, 0.01939547, 0.01292825, 0.02464085, 0.01693892, 0.00541593, 0.00986347, 0.01690569, 0.01150429, 0.0112102, 0.01713019, 0.01484573, 0.02645844, 0.0153021, 0.00541593, 0.01330877, 0.02842296, 0.01591988, 0.00491821, 0.02061337, 0.02987523, 0.02393915, 0.00776477, 0.02196631, 0.01613769, 0.01761861, 0.02169104, 0.01283079, 0.02951408, 0.00882587, 0.01733948, 0.00526172, 0.00887672, 0.01923187, 0.03129924, 0.01207255, 0.00818102, 0.02165103, 0.00749415, 0.0083263, 0.0300956, 0.00496289, 0.01476788, 0.00619018, 0.01103916, ], dtype=np.float32, ), ), "Simple_1": ( cp.asarray(range(4), dtype=np.int32), cp.asarray([0.11615585, 0.21488841, 0.2988108, 0.3701449], dtype=np.float32), ), "Simple_2": ( cp.asarray(range(6), dtype=np.int32), cp.asarray( [ 0.09902544, 0.17307726, 0.0732199, 0.1905103, 0.12379099, 0.34037617, ], dtype=np.float32, ), ), } # ============================================================================= # Pytest fixtures # ============================================================================= # fixtures used in this test module are defined in conftest.py # ============================================================================= # Tests # ============================================================================= # FIXME: add tests for non-transposed graphs too, which should either work (via # auto-transposing in C) or raise the appropriate exception. def test_pagerank(sg_transposed_graph_objs): from pylibcugraph import pagerank (g, resource_handle, ds_name) = sg_transposed_graph_objs (expected_verts, expected_pageranks) = _test_data[ds_name] precomputed_vertex_out_weight_sums = None do_expensive_check = False precomputed_vertex_out_weight_vertices = None precomputed_vertex_out_weight_sums = None initial_guess_vertices = None initial_guess_values = None result = pagerank( resource_handle, g, precomputed_vertex_out_weight_vertices, precomputed_vertex_out_weight_sums, initial_guess_vertices, initial_guess_values, _alpha, _epsilon, _max_iterations, do_expensive_check, ) num_expected_verts = len(expected_verts) (actual_verts, actual_pageranks) = result # Do a simple check using the vertices as array indices. First, ensure # the test data vertices start from 0 with no gaps. assert sum(range(num_expected_verts)) == sum(expected_verts) assert actual_verts.dtype == expected_verts.dtype assert actual_pageranks.dtype == expected_pageranks.dtype actual_pageranks = actual_pageranks.tolist() actual_verts = actual_verts.tolist() expected_pageranks = expected_pageranks.tolist() for i in range(num_expected_verts): assert actual_pageranks[i] == pytest.approx( expected_pageranks[actual_verts[i]], 1e-4 ), f"actual != expected for result at index {i}"
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/tests/test_connected_components.py
# Copyright (c) 2021-2023, NVIDIA CORPORATION. # 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 pathlib import Path import pytest import numpy as np import pandas as pd import cupy as cp from scipy.sparse import coo_matrix, csr_matrix from pylibcugraph import ResourceHandle, GraphProperties, SGGraph from pylibcugraph.testing import utils # ============================================================================= # Test data # ============================================================================= _test_data = { "graph1": { # asymmetric "input": [ [0, 1, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, 0, 0, 0], ], "scc_comp_vertices": [ [0], [1], [2], [3], [4], ], "wcc_comp_vertices": [ [0, 1, 2], [3, 4], ], }, "graph2": { # symmetric "input": [ [0, 1, 1, 0, 0], [1, 0, 1, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, 0, 1, 0], ], "scc_comp_vertices": [ [0, 1, 2], [3, 4], ], "wcc_comp_vertices": [ [0, 1, 2], [3, 4], ], }, "karate-disjoint-sequential": { "input": utils.RAPIDS_DATASET_ROOT_DIR_PATH / "karate-disjoint-sequential.csv", "scc_comp_vertices": [ [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, ], [34], [35], [36], ], "wcc_comp_vertices": [ [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, ], [34, 35, 36], ], }, "dolphins": { # dolphins contains only one component "input": utils.RAPIDS_DATASET_ROOT_DIR_PATH / "dolphins.csv", "scc_comp_vertices": [ list(range(62)), ], "wcc_comp_vertices": [ list(range(62)), ], }, } # ============================================================================= # Pytest fixtures # ============================================================================= @pytest.fixture( scope="module", params=[pytest.param(value, id=key) for (key, value) in _test_data.items()], ) def input_and_expected_output(request): """ This fixture takes the above test data and converts it into everything needed to run a pylibcugraph CC algo for a specific input (either a adjacency matrix or a CSV edgelist file), and returns it along with the expected WCC and SCC result for each. """ d = request.param.copy() input = d.pop("input") expected_output_dict = d if isinstance(input, Path): pdf = pd.read_csv( input, delimiter=" ", header=None, names=["0", "1", "weight"], dtype={"0": "int32", "1": "int32", "weight": "float32"}, ) num_verts = len(set(pdf["0"].tolist() + pdf["1"].tolist())) num_edges = len(pdf) weights = np.ones(num_edges) coo = coo_matrix( (weights, (pdf["0"], pdf["1"])), shape=(num_verts, num_verts), dtype=np.float32, ) csr = coo.tocsr() else: csr = csr_matrix(input) num_verts = csr.get_shape()[0] num_edges = csr.nnz labels_to_populate = cp.zeros(num_verts, dtype=np.int32) return ( (csr, labels_to_populate, num_verts, num_edges), expected_output_dict, ) # ============================================================================= # Helper functions # ============================================================================= def _check_labels(vertex_ordered_labels, expected_vertex_comps): """ vertex_ordered_labels is a list of labels, ordered by the position of the vertex ID value, as returned by pylibcugraph.CC algos. For example: [9, 9, 7] means vertex 0 is labelled 9, vertex 1 is labelled 9, and vertex 2 is labelled 7. expected_vertex_comps is a list of components, where each component is a list of vertex IDs the component contains. Each component corresponds to some label For example: [[0, 1], [2]] is two components, the first containing vertices 0, 1, and the other 2. [0, 1] has the label 9 and [2] has the label 7. This asserts if the vertex_ordered_labels do not correspond to the expected_vertex_comps. """ # Group the vertex_ordered_labels list into components based on labels by # creating a dictionary of labels to lists of vertices with that label. d = {} for (vertex, label) in enumerate(vertex_ordered_labels): d.setdefault(label, []).append(vertex) assert len(d.keys()) == len( expected_vertex_comps ), "number of different labels does not match expected" # Compare the actual components (created from the dictionary above) to # expected. actual_vertex_comps = sorted(d.values()) assert actual_vertex_comps == sorted(expected_vertex_comps) # ============================================================================= # Tests # ============================================================================= def test_import(): """ Ensure pylibcugraph is importable. """ # suppress F401 (imported but never used) in flake8 import pylibcugraph # noqa: F401 def test_scc(input_and_expected_output): """ Tests strongly_connected_components() """ import pylibcugraph ( (csr, cupy_labels_to_populate, num_verts, num_edges), expected_output_dict, ) = input_and_expected_output cupy_offsets = cp.asarray(csr.indptr, dtype=np.int32) cupy_indices = cp.asarray(csr.indices, dtype=np.int32) pylibcugraph.strongly_connected_components( cupy_offsets, cupy_indices, None, num_verts, num_edges, cupy_labels_to_populate ) _check_labels( cupy_labels_to_populate.tolist(), expected_output_dict["scc_comp_vertices"] ) def test_wcc(input_and_expected_output): """ Tests weakly_connected_components() """ import pylibcugraph ( (csr, cupy_labels_to_populate, num_verts, num_edges), expected_output_dict, ) = input_and_expected_output # Symmetrize CSR matrix. WCC requires a symmetrized datasets rows, cols = csr.nonzero() csr[cols, rows] = csr[rows, cols] cupy_offsets = cp.asarray(csr.indptr, dtype=np.int32) cupy_indices = cp.asarray(csr.indices, dtype=np.int32) cupy_weights = cp.asarray(csr.data, dtype=np.float32) pylibcugraph.weakly_connected_components( None, None, cupy_offsets, cupy_indices, cupy_weights, cupy_labels_to_populate, False, ) _check_labels( cupy_labels_to_populate.tolist(), expected_output_dict["wcc_comp_vertices"] ) # FIXME: scc and wcc no longer have the same API (parameters in the # function definition): refactor this to consolidate both tests once the do @pytest.mark.parametrize("api_name", ["strongly_connected_components"]) def test_non_CAI_input_scc(api_name): """ Ensures that the *_connected_components() APIs only accepts instances of objects that have a __cuda_array_interface__ """ import pylibcugraph cupy_array = cp.ndarray(range(8)) python_list = list(range(8)) api = getattr(pylibcugraph, api_name) with pytest.raises(TypeError): api( src=cupy_array, dst=cupy_array, weights=cupy_array, # should raise, weights must be None num_verts=2, num_edges=8, labels=cupy_array, ) with pytest.raises(TypeError): api( src=cupy_array, dst=python_list, # should raise, no __cuda_array_interface__ weights=None, num_verts=2, num_edges=8, labels=cupy_array, ) with pytest.raises(TypeError): api( src=python_list, # should raise, no __cuda_array_interface__ dst=cupy_array, weights=None, num_verts=2, num_edges=8, labels=cupy_array, ) with pytest.raises(TypeError): api( src=cupy_array, dst=cupy_array, weights=None, num_verts=2, num_edges=8, labels=python_list, ) # should raise, no __cuda_array_interface__ # FIXME: scc and wcc no longer have the same API: # refactor this to consolidate both tests once they do @pytest.mark.parametrize("api_name", ["strongly_connected_components"]) def test_bad_dtypes_scc(api_name): """ Ensures that only supported dtypes are accepted. """ import pylibcugraph graph = [ [0, 1, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, 0, 0, 0], ] scipy_csr = csr_matrix(graph) num_verts = scipy_csr.get_shape()[0] num_edges = scipy_csr.nnz api = getattr(pylibcugraph, api_name) cp_offsets = cp.asarray(scipy_csr.indptr) cp_indices = cp.asarray(scipy_csr.indices) cp_labels = cp.zeros(num_verts, dtype=np.int64) # unsupported with pytest.raises(TypeError): api( offsets=cp_offsets, indices=cp_indices, weights=None, num_verts=num_verts, num_edges=num_edges, labels=cp_labels, ) cp_offsets = cp.asarray(scipy_csr.indptr, dtype=np.int64) # unsupported cp_indices = cp.asarray(scipy_csr.indices) cp_labels = cp.zeros(num_verts, dtype=np.int32) with pytest.raises(TypeError): api( offsets=cp_offsets, indices=cp_indices, weights=None, num_verts=num_verts, num_edges=num_edges, labels=cp_labels, ) cp_offsets = cp.asarray(scipy_csr.indptr) cp_indices = cp.asarray(scipy_csr.indices, dtype=np.float32) # unsupported cp_labels = cp.zeros(num_verts, dtype=np.int32) with pytest.raises(TypeError): api( offsets=cp_offsets, indices=cp_indices, weights=None, num_verts=num_verts, num_edges=num_edges, labels=cp_labels, ) def test_invalid_input_wcc(): """ Ensures that only supported dtypes are accepted. """ import pylibcugraph graph = [ [0, 1, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, 0, 0, 0], ] scipy_csr = csr_matrix(graph) sp_offsets = scipy_csr.indptr # unsupported sp_indices = scipy_csr.indices # unsupported resource_handle = ResourceHandle() graph_props = GraphProperties(is_symmetric=False, is_multigraph=False) with pytest.raises(TypeError): pylibcugraph.weakly_connected_components( resource_handle, None, sp_offsets, sp_indices, None, False ) resource_handle = ResourceHandle() cp_offsets = cp.asarray(scipy_csr.indptr) # unsupported cp_indices = cp.asarray(scipy_csr.indices) # unsupported G = SGGraph( resource_handle, graph_props, cp_offsets, cp_indices, None, store_transposed=False, renumber=False, do_expensive_check=True, input_array_format="CSR", ) # cannot set both a graph and csr arrays as input with pytest.raises(TypeError): pylibcugraph.weakly_connected_components( resource_handle, G, cp_offsets, cp_indices, None, True )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/tests/test_utils.py
# Copyright (c) 2022, NVIDIA CORPORATION. # 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 types import pytest def test_experimental_warning_wrapper_for_funcs(): from pylibcugraph.utilities.api_tools import experimental_warning_wrapper def EXPERIMENTAL__func(a, b): return a - b exp_func = experimental_warning_wrapper(EXPERIMENTAL__func) with pytest.warns(PendingDeprecationWarning): assert 1 == exp_func(3, 2) def test_experimental_warning_wrapper_for_classes(): from pylibcugraph.utilities.api_tools import experimental_warning_wrapper class EXPERIMENTAL__klass: def __init__(self, a, b): self.r = a - b exp_klass = experimental_warning_wrapper(EXPERIMENTAL__klass) with pytest.warns(PendingDeprecationWarning): k = exp_klass(3, 2) assert 1 == k.r assert isinstance(k, exp_klass) assert k.__class__.__name__ == "klass" def test_experimental_warning_wrapper_for_unsupported_type(): from pylibcugraph.utilities.api_tools import experimental_warning_wrapper # A module type should not be allowed to be wrapped mod = types.ModuleType("modname") with pytest.raises(TypeError): experimental_warning_wrapper(mod)
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/tests/test_sssp.py
# Copyright (c) 2022, NVIDIA CORPORATION. # 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 pytest import cupy as cp import numpy as np # ============================================================================= # Test data # ============================================================================= # Map the names of input data to expected pagerank output # The result names correspond to the datasets defined in conftest.py _test_data = { "karate.csv": { "start_vertex": 1, "vertex": cp.asarray(range(34), dtype=np.int32), "distance": cp.asarray( [ 1.0, 0.0, 1.0, 1.0, 2.0, 2.0, 2.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 1.0, 3.0, 3.0, 3.0, 1.0, 3.0, 1.0, 3.0, 1.0, 3.0, 3.0, 3.0, 3.0, 3.0, 2.0, 2.0, 3.0, 1.0, 2.0, 2.0, 2.0, ], dtype=np.float32, ), "predecessor": cp.asarray( [ 1, -1, 1, 1, 0, 0, 0, 1, 0, 2, 0, 0, 0, 1, 32, 32, 5, 1, 32, 1, 32, 1, 32, 32, 27, 31, 33, 2, 2, 32, 1, 0, 2, 13, ], dtype=np.int32, ), }, "dolphins.csv": { "start_vertex": 1, "vertex": cp.asarray(range(62), dtype=np.int32), "distance": cp.asarray( [ 3.0, 0.0, 4.0, 3.0, 4.0, 3.0, 2.0, 2.0, 2.0, 2.0, 3.0, 4.0, 4.0, 2.0, 3.0, 3.0, 3.0, 1.0, 3.0, 1.0, 2.0, 3.0, 2.0, 2.0, 4.0, 2.0, 1.0, 1.0, 1.0, 4.0, 2.0, 2.0, 3.0, 3.0, 3.0, 5.0, 1.0, 2.0, 3.0, 2.0, 2.0, 1.0, 3.0, 3.0, 3.0, 3.0, 4.0, 2.0, 3.0, 4.0, 3.0, 3.0, 3.0, 4.0, 1.0, 4.0, 3.0, 2.0, 4.0, 2.0, 4.0, 3.0, ], dtype=np.float32, ), "predecessor": cp.asarray( [ 40, -1, 10, 59, 51, 13, 54, 54, 28, 41, 47, 51, 33, 41, 37, 40, 37, 1, 20, 1, 28, 37, 17, 36, 45, 17, 1, 1, 1, 10, 19, 17, 9, 37, 37, 29, 1, 36, 20, 36, 36, 1, 30, 37, 20, 23, 43, 28, 57, 34, 20, 23, 40, 43, 1, 51, 6, 41, 38, 36, 32, 37, ], dtype=np.int32, ), }, "Simple_1": { "start_vertex": 1, "vertex": cp.asarray(range(4), dtype=np.int32), "distance": cp.asarray( [ 3.4028235e38, 0.0000000e00, 1.0000000e00, 2.0000000e00, ], dtype=np.float32, ), "predecessor": cp.asarray( [ -1, -1, 1, 2, ], dtype=np.int32, ), }, "Simple_2": { "start_vertex": 1, "vertex": cp.asarray(range(6), dtype=np.int32), "distance": cp.asarray( [ 3.4028235e38, 0.0000000e00, 3.4028235e38, 2.0999999e00, 1.1000000e00, 4.3000002e00, ], dtype=np.float32, ), "predecessor": cp.asarray( [ -1, -1, -1, 1, 1, 4, ], dtype=np.int32, ), }, } # ============================================================================= # Pytest fixtures # ============================================================================= # fixtures used in this test module are defined in conftest.py # ============================================================================= # Helper functions # ============================================================================= # ============================================================================= # Tests # ============================================================================= def test_sssp(sg_graph_objs): from pylibcugraph import sssp (g, resource_handle, ds_name) = sg_graph_objs (source, expected_verts, expected_distances, expected_predecessors) = _test_data[ ds_name ].values() cutoff = 999999999 # maximum edge weight sum to consider compute_predecessors = True do_expensive_check = False result = sssp( resource_handle, g, source, cutoff, compute_predecessors, do_expensive_check ) num_expected_verts = len(expected_verts) (actual_verts, actual_distances, actual_predecessors) = result # Do a simple check using the vertices as array indices. First, ensure # the test data vertices start from 0 with no gaps. assert sum(range(num_expected_verts)) == sum(expected_verts) assert actual_verts.dtype == expected_verts.dtype assert actual_distances.dtype == expected_distances.dtype assert actual_predecessors.dtype == expected_predecessors.dtype actual_verts = actual_verts.tolist() actual_distances = actual_distances.tolist() actual_predecessors = actual_predecessors.tolist() expected_distances = expected_distances.tolist() expected_predecessors = expected_predecessors.tolist() for i in range(num_expected_verts): actual_distance = actual_distances[i] expected_distance = expected_distances[actual_verts[i]] # The distance value will be a MAX value (2**128) if there is no # predecessor, so only do a closer compare if either the actual or # expected are not that MAX value. if (actual_distance <= 3.4e38) or (expected_distance <= 3.4e38): assert actual_distance == pytest.approx( expected_distance, 1e-4 ), f"actual != expected for distance result at index {i}" # The array of predecessors for graphs with multiple paths that are # equally short are non-deterministic, so skip those checks for # specific graph inputs. # FIXME: add a helper to verify paths are correct when results are # valid but non-deterministic if ds_name not in ["karate.csv", "dolphins.csv"]: assert actual_predecessors[i] == pytest.approx( expected_predecessors[actual_verts[i]], 1e-4 ), f"actual != expected for predecessor result at index {i}"
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/tests/test_node2vec.py
# Copyright (c) 2022, NVIDIA CORPORATION. # 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 pytest import cupy as cp import numpy as np from pylibcugraph import ResourceHandle, GraphProperties, SGGraph, node2vec from pylibcugraph.testing import utils COMPRESSED = [False, True] LINE = utils.RAPIDS_DATASET_ROOT_DIR_PATH / "small_line.csv" # ============================================================================= # Test data # ============================================================================= # The result names correspond to the datasets defined in conftest.py # Note: the only deterministic path(s) in the following datasets # are contained in Simple_1 _test_data = { "karate.csv": { "seeds": cp.asarray([0, 0], dtype=np.int32), "paths": cp.asarray([0, 8, 33, 29, 26, 0, 1, 3, 13, 33], dtype=np.int32), "weights": cp.asarray( [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], dtype=np.float32 ), "path_sizes": cp.asarray([5, 5], dtype=np.int32), "max_depth": 5, }, "dolphins.csv": { "seeds": cp.asarray([11], dtype=np.int32), "paths": cp.asarray([11, 51, 11, 51], dtype=np.int32), "weights": cp.asarray([1.0, 1.0, 1.0], dtype=np.float32), "path_sizes": cp.asarray([4], dtype=np.int32), "max_depth": 4, }, "Simple_1": { "seeds": cp.asarray([0, 3], dtype=np.int32), "paths": cp.asarray([0, 1, 2, 3], dtype=np.int32), "weights": cp.asarray([1.0, 1.0], dtype=np.float32), "path_sizes": cp.asarray([3, 1], dtype=np.int32), "max_depth": 3, }, "Simple_2": { "seeds": cp.asarray([0, 3], dtype=np.int32), "paths": cp.asarray([0, 1, 3, 5, 3, 5], dtype=np.int32), "weights": cp.asarray([0.1, 2.1, 7.2, 7.2], dtype=np.float32), "path_sizes": cp.asarray([4, 2], dtype=np.int32), "max_depth": 4, }, } # ============================================================================= # Test helpers # ============================================================================= def _get_param_args(param_name, param_values): """ Returns a tuple of (<param_name>, <pytest.param list>) which can be applied as the args to pytest.mark.parametrize(). The pytest.param list also contains param id string formed from teh param name and values. """ return (param_name, [pytest.param(v, id=f"{param_name}={v}") for v in param_values]) def _run_node2vec( src_arr, dst_arr, wgt_arr, seeds, num_vertices, num_edges, max_depth, compressed_result, p, q, renumbered, ): """ Builds a graph from the input arrays and runs node2vec using the other args to this function, then checks the output for validity. """ resource_handle = ResourceHandle() graph_props = GraphProperties(is_symmetric=False, is_multigraph=False) G = SGGraph( resource_handle, graph_props, src_arr, dst_arr, wgt_arr, store_transposed=False, renumber=renumbered, do_expensive_check=True, ) (paths, weights, sizes) = node2vec( resource_handle, G, seeds, max_depth, compressed_result, p, q ) num_seeds = len(seeds) # Validating results of node2vec by checking each path M = np.zeros((num_vertices, num_vertices), dtype=np.float64) h_src_arr = src_arr.get() h_dst_arr = dst_arr.get() h_wgt_arr = wgt_arr.get() h_paths = paths.get() h_weights = weights.get() for i in range(num_edges): M[h_src_arr[i]][h_dst_arr[i]] = h_wgt_arr[i] if compressed_result: path_offsets = np.zeros(num_seeds + 1, dtype=np.int32) path_offsets[0] = 0 for i in range(num_seeds): path_offsets[i + 1] = path_offsets[i] + sizes.get()[i] for i in range(num_seeds): for j in range(path_offsets[i], (path_offsets[i + 1] - 1)): actual_wgt = h_weights[j - i] expected_wgt = M[h_paths[j]][h_paths[j + 1]] if pytest.approx(expected_wgt, 1e-4) != actual_wgt: s = h_paths[j] d = h_paths[j + 1] raise ValueError( f"Edge ({s},{d}) has wgt {actual_wgt}, " f"should have been {expected_wgt}" ) else: max_path_length = int(len(paths) / num_seeds) for i in range(num_seeds): for j in range(max_path_length - 1): curr_idx = i * max_path_length + j next_idx = i * max_path_length + j + 1 if h_paths[next_idx] != num_vertices: actual_wgt = h_weights[i * (max_path_length - 1) + j] expected_wgt = M[h_paths[curr_idx]][h_paths[next_idx]] if pytest.approx(expected_wgt, 1e-4) != actual_wgt: s = h_paths[j] d = h_paths[j + 1] raise ValueError( f"Edge ({s},{d}) has wgt {actual_wgt}" f", should have been {expected_wgt}" ) # ============================================================================= # Pytest fixtures # ============================================================================= # fixtures used in this test module are defined in conftest.py # ============================================================================= # Tests adapted from libcugraph # ============================================================================= def test_node2vec_short(): num_edges = 8 num_vertices = 6 src = cp.asarray([0, 1, 1, 2, 2, 2, 3, 4], dtype=np.int32) dst = cp.asarray([1, 3, 4, 0, 1, 3, 5, 5], dtype=np.int32) wgt = cp.asarray([0.1, 2.1, 1.1, 5.1, 3.1, 4.1, 7.2, 3.2], dtype=np.float32) seeds = cp.asarray([0, 0], dtype=np.int32) max_depth = 4 _run_node2vec( src, dst, wgt, seeds, num_vertices, num_edges, max_depth, False, 0.8, 0.5, False ) def test_node2vec_short_dense(): num_edges = 8 num_vertices = 6 src = cp.asarray([0, 1, 1, 2, 2, 2, 3, 4], dtype=np.int32) dst = cp.asarray([1, 3, 4, 0, 1, 3, 5, 5], dtype=np.int32) wgt = cp.asarray([0.1, 2.1, 1.1, 5.1, 3.1, 4.1, 7.2, 3.2], dtype=np.float32) seeds = cp.asarray([2, 3], dtype=np.int32) max_depth = 4 _run_node2vec( src, dst, wgt, seeds, num_vertices, num_edges, max_depth, False, 0.8, 0.5, False ) def test_node2vec_short_sparse(): num_edges = 8 num_vertices = 6 src = cp.asarray([0, 1, 1, 2, 2, 2, 3, 4], dtype=np.int32) dst = cp.asarray([1, 3, 4, 0, 1, 3, 5, 5], dtype=np.int32) wgt = cp.asarray([0.1, 2.1, 1.1, 5.1, 3.1, 4.1, 7.2, 3.2], dtype=np.float32) seeds = cp.asarray([2, 3], dtype=np.int32) max_depth = 4 _run_node2vec( src, dst, wgt, seeds, num_vertices, num_edges, max_depth, True, 0.8, 0.5, False ) @pytest.mark.parametrize(*_get_param_args("compress_result", [True, False])) @pytest.mark.parametrize(*_get_param_args("renumbered", [True, False])) def test_node2vec_karate(compress_result, renumbered): num_edges = 156 num_vertices = 34 src = cp.asarray( [ 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 17, 19, 21, 31, 2, 3, 7, 13, 17, 19, 21, 30, 3, 7, 8, 9, 13, 27, 28, 32, 7, 12, 13, 6, 10, 6, 10, 16, 16, 30, 32, 33, 33, 33, 32, 33, 32, 33, 32, 33, 33, 32, 33, 32, 33, 25, 27, 29, 32, 33, 25, 27, 31, 31, 29, 33, 33, 31, 33, 32, 33, 32, 33, 32, 33, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 5, 6, 8, 8, 8, 9, 13, 14, 14, 15, 15, 18, 18, 19, 20, 20, 22, 22, 23, 23, 23, 23, 23, 24, 24, 24, 25, 26, 26, 27, 28, 28, 29, 29, 30, 30, 31, 31, 32, ], dtype=np.int32, ) dst = cp.asarray( [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 5, 6, 8, 8, 8, 9, 13, 14, 14, 15, 15, 18, 18, 19, 20, 20, 22, 22, 23, 23, 23, 23, 23, 24, 24, 24, 25, 26, 26, 27, 28, 28, 29, 29, 30, 30, 31, 31, 32, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 17, 19, 21, 31, 2, 3, 7, 13, 17, 19, 21, 30, 3, 7, 8, 9, 13, 27, 28, 32, 7, 12, 13, 6, 10, 6, 10, 16, 16, 30, 32, 33, 33, 33, 32, 33, 32, 33, 32, 33, 33, 32, 33, 32, 33, 25, 27, 29, 32, 33, 25, 27, 31, 31, 29, 33, 33, 31, 33, 32, 33, 32, 33, 32, 33, 33, ], dtype=np.int32, ) wgt = cp.asarray( [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ], dtype=np.float32, ) seeds = cp.asarray([12, 28, 20, 23, 15, 26], dtype=np.int32) max_depth = 5 _run_node2vec( src, dst, wgt, seeds, num_vertices, num_edges, max_depth, compress_result, 0.8, 0.5, renumbered, ) # ============================================================================= # Tests # ============================================================================= @pytest.mark.parametrize(*_get_param_args("compress_result", [True, False])) def test_node2vec(sg_graph_objs, compress_result): (g, resource_handle, ds_name) = sg_graph_objs ( seeds, expected_paths, expected_weights, expected_path_sizes, max_depth, ) = _test_data[ds_name].values() p = 0.8 q = 0.5 result = node2vec(resource_handle, g, seeds, max_depth, compress_result, p, q) (actual_paths, actual_weights, actual_path_sizes) = result num_paths = len(seeds) if compress_result: assert actual_paths.dtype == expected_paths.dtype assert actual_weights.dtype == expected_weights.dtype assert actual_path_sizes.dtype == expected_path_sizes.dtype actual_paths = actual_paths.tolist() actual_weights = actual_weights.tolist() actual_path_sizes = actual_path_sizes.tolist() exp_paths = expected_paths.tolist() exp_weights = expected_weights.tolist() exp_path_sizes = expected_path_sizes.tolist() # If compress_results is True, then also verify path lengths match # up with weights array assert len(actual_path_sizes) == num_paths expected_walks = sum(exp_path_sizes) - num_paths # Verify the number of walks was equal to path sizes - num paths assert len(actual_weights) == expected_walks else: assert actual_paths.dtype == expected_paths.dtype assert actual_weights.dtype == expected_weights.dtype actual_paths = actual_paths.tolist() actual_weights = actual_weights.tolist() exp_paths = expected_paths.tolist() exp_weights = expected_weights.tolist() # Verify exact walks chosen for linear graph Simple_1 if ds_name == "Simple_1": for i in range(len(exp_paths)): assert pytest.approx(actual_paths[i], 1e-4) == exp_paths[i] for i in range(len(exp_weights)): assert pytest.approx(actual_weights[i], 1e-4) == exp_weights[i] # Verify starting vertex of each path is the corresponding seed if compress_result: path_start = 0 for i in range(num_paths): assert actual_path_sizes[i] == exp_path_sizes[i] assert actual_paths[path_start] == seeds[i] path_start += actual_path_sizes[i] @pytest.mark.parametrize(*_get_param_args("graph_file", [LINE])) @pytest.mark.parametrize(*_get_param_args("renumber", COMPRESSED)) def test_node2vec_renumber_cupy(graph_file, renumber): import cupy as cp import numpy as np src_arr = cp.asarray([0, 1, 2, 3, 4, 5, 6, 7, 8], dtype=np.int32) dst_arr = cp.asarray([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=np.int32) wgt_arr = cp.asarray( [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], dtype=np.float32 ) seeds = cp.asarray([8, 0, 7, 1, 6, 2], dtype=np.int32) max_depth = 4 num_seeds = 6 resource_handle = ResourceHandle() graph_props = GraphProperties(is_symmetric=False, is_multigraph=False) G = SGGraph( resource_handle, graph_props, src_arr, dst_arr, wgt_arr, store_transposed=False, renumber=renumber, do_expensive_check=True, ) (paths, weights, sizes) = node2vec( resource_handle, G, seeds, max_depth, False, 0.8, 0.5 ) for i in range(num_seeds): if paths[i * max_depth] != seeds[i]: raise ValueError( "vertex_path {} start did not match seed \ vertex".format( paths ) )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/tests/test_graph_sg.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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 pytest # ============================================================================= # Pytest fixtures # ============================================================================= # fixtures used in this test module are defined in conftest.py # ============================================================================= # Tests # ============================================================================= def test_graph_properties(): from pylibcugraph import GraphProperties gp = GraphProperties() assert gp.is_symmetric is False assert gp.is_multigraph is False gp.is_symmetric = True assert gp.is_symmetric is True gp.is_symmetric = 0 assert gp.is_symmetric is False with pytest.raises(TypeError): gp.is_symmetric = "foo" gp.is_multigraph = True assert gp.is_multigraph is True gp.is_multigraph = 0 assert gp.is_multigraph is False with pytest.raises(TypeError): gp.is_multigraph = "foo" gp = GraphProperties(is_symmetric=True, is_multigraph=True) assert gp.is_symmetric is True assert gp.is_multigraph is True gp = GraphProperties(is_multigraph=True, is_symmetric=False) assert gp.is_symmetric is False assert gp.is_multigraph is True with pytest.raises(TypeError): gp = GraphProperties(is_symmetric="foo", is_multigraph=False) with pytest.raises(TypeError): gp = GraphProperties(is_multigraph=[]) def test_resource_handle(): from pylibcugraph import ResourceHandle # This type has no attributes and is just defined to pass a struct from C # back in to C. In the future it may take args to acquire specific # resources, but for now just make sure nothing crashes. rh = ResourceHandle() del rh def test_sg_graph(graph_data): from pylibcugraph import ( SGGraph, ResourceHandle, GraphProperties, ) # is_valid will only be True if the arrays are expected to produce a valid # graph. If False, ensure SGGraph() raises the proper exception. (device_srcs, device_dsts, device_weights, ds_name, is_valid) = graph_data graph_props = GraphProperties(is_symmetric=False, is_multigraph=False) resource_handle = ResourceHandle() if is_valid: g = SGGraph( # noqa:F841 resource_handle, graph_props, device_srcs, device_dsts, device_weights, store_transposed=False, renumber=False, do_expensive_check=False, ) # call SGGraph.__dealloc__() del g else: with pytest.raises(ValueError): SGGraph( resource_handle, graph_props, device_srcs, device_dsts, device_weights, store_transposed=False, renumber=False, do_expensive_check=False, ) def test_SGGraph_create_from_cudf(): """ Smoke test to ensure an SGGraph can be created from a cuDF DataFrame without raising exceptions, crashing, etc. This currently does not assert correctness of the graph in any way. """ # FIXME: other PLC tests are using cudf so this does not add a new dependency, # however, PLC tests should consider having fewer external dependencies, meaning # this and other tests would be changed to not use cudf. import cudf # Importing this cugraph class seems to cause a crash more reliably (2023-01-22) # from cugraph.structure.graph_implementation import simpleGraphImpl from pylibcugraph import ( ResourceHandle, GraphProperties, SGGraph, ) print("get edgelist...", end="", flush=True) edgelist = cudf.DataFrame( { "src": [0, 1, 2], "dst": [1, 2, 4], "wgt": [0.0, 0.1, 0.2], } ) print("edgelist = ", edgelist) print("done", flush=True) print("create Graph...", end="", flush=True) graph_props = GraphProperties(is_multigraph=False, is_symmetric=False) plc_graph = SGGraph( resource_handle=ResourceHandle(), graph_properties=graph_props, src_or_offset_array=edgelist["src"], dst_or_index_array=edgelist["dst"], weight_array=edgelist["wgt"], edge_id_array=None, edge_type_array=None, store_transposed=False, renumber=False, do_expensive_check=True, input_array_format="COO", ) print("done", flush=True) print(f"created SGGraph {plc_graph=}", flush=True)
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/components/CMakeLists.txt
# ============================================================================= # Copyright (c) 2022, NVIDIA CORPORATION. # # 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. # ============================================================================= set(cython_sources _connectivity.pyx ) set(linked_libraries cugraph::cugraph) rapids_cython_create_modules( CXX SOURCE_FILES "${cython_sources}" LINKED_LIBRARIES "${linked_libraries}" ASSOCIATED_TARGETS cugraph )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/components/_connectivity.pxd
# Copyright (c) 2019-2023, NVIDIA CORPORATION. # 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. # cython: profile=False # distutils: language = c++ # cython: embedsignature = True # cython: language_level = 3 from pylibcugraph.structure.graph_primtypes cimport * cdef extern from "cugraph/algorithms.hpp" namespace "cugraph": ctypedef enum cugraph_cc_t: CUGRAPH_STRONG "cugraph::cugraph_cc_t::CUGRAPH_STRONG" NUM_CONNECTIVITY_TYPES "cugraph::cugraph_cc_t::NUM_CONNECTIVITY_TYPES" cdef void connected_components[VT,ET,WT]( const GraphCSRView[VT,ET,WT] &graph, cugraph_cc_t connect_type, VT *labels) except +
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/components/__init__.py
# Copyright (c) 2021-2023, NVIDIA CORPORATION. # # 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.
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/components/_connectivity.pyx
# Copyright (c) 2021-2022, NVIDIA CORPORATION. # 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 libc.stdint cimport uintptr_t from libcpp.memory cimport unique_ptr from pylibcugraph.components._connectivity cimport * from pylibraft.common.handle cimport * def _ensure_arg_types(**kwargs): """ Ensure all args have a __cuda_array_interface__ attr """ for (arg_name, arg_val) in kwargs.items(): # FIXME: remove this special case when weights are supported: weights # can only be None if arg_name is "weights": if arg_val is not None: raise TypeError("weights are currently not supported and must " "be None") elif not(hasattr(arg_val, "__cuda_array_interface__")): raise TypeError(f"{arg_name} must support __cuda_array_interface__") if arg_name in ["offsets", "indices", "labels"]: typestr = arg_val.__cuda_array_interface__.get("typestr") if typestr != "<i4": raise TypeError(f"{arg_name} array must have a dtype of int32") def strongly_connected_components(offsets, indices, weights, num_verts, num_edges, labels): """ Generate the Strongly Connected Components and attach a component label to each vertex. Parameters ---------- offsets : object supporting a __cuda_array_interface__ interface Array containing the offsets values of a Compressed Sparse Row matrix that represents the graph. indices : object supporting a __cuda_array_interface__ interface Array containing the indices values of a Compressed Sparse Row matrix that represents the graph. weights : object supporting a __cuda_array_interface__ interface Array containing the weights values of a Compressed Sparse Row matrix that represents the graph. NOTE: weighted graphs are currently unsupported, and because of this the weights parameter can only be set to None. num_verts : int The number of vertices present in the graph represented by the CSR arrays above. num_edges : int The number of edges present in the graph represented by the CSR arrays above. labels : object supporting a __cuda_array_interface__ interface Array of size num_verts that will be populated with component label values. The component lables in the array are ordered based on the sorted vertex ID values of the graph. For example, labels [9, 9, 7] mean vertex 0 is labelled 9, vertex 1 is labelled 9, and vertex 2 is labelled 7. Returns ------- None Examples -------- >>> import cupy as cp >>> import numpy as np >>> from scipy.sparse import csr_matrix >>> >>> graph = [ ... [0, 1, 1, 0, 0], ... [0, 0, 1, 0, 0], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 1], ... [0, 0, 0, 0, 0], ... ] >>> scipy_csr = csr_matrix(graph) >>> num_verts = scipy_csr.get_shape()[0] >>> num_edges = scipy_csr.nnz >>> >>> cp_offsets = cp.asarray(scipy_csr.indptr) >>> cp_indices = cp.asarray(scipy_csr.indices, dtype=np.int32) >>> cp_labels = cp.asarray(np.zeros(num_verts, dtype=np.int32)) >>> >>> strongly_connected_components(offsets=cp_offsets, ... indices=cp_indices, ... weights=None, ... num_verts=num_verts, ... num_edges=num_edges, ... labels=cp_labels) >>> print(f"{len(set(cp_labels.tolist()))} - {cp_labels}") 5 - [0 1 2 3 4] """ _ensure_arg_types(offsets=offsets, indices=indices, weights=weights, labels=labels) cdef unique_ptr[handle_t] handle_ptr handle_ptr.reset(new handle_t()) handle_ = handle_ptr.get() cdef uintptr_t c_offsets = offsets.__cuda_array_interface__['data'][0] cdef uintptr_t c_indices = indices.__cuda_array_interface__['data'][0] cdef uintptr_t c_edge_weights = <uintptr_t>NULL cdef uintptr_t c_labels = labels.__cuda_array_interface__['data'][0] cdef GraphCSRView[int,int,float] g g = GraphCSRView[int,int,float](<int*>c_offsets, <int*>c_indices, <float*>NULL, num_verts, num_edges) cdef cugraph_cc_t connect_type=CUGRAPH_STRONG connected_components(g, <cugraph_cc_t>connect_type, <int *>c_labels)
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/testing/CMakeLists.txt
# ============================================================================= # Copyright (c) 2022, NVIDIA CORPORATION. # # 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. # ============================================================================= set(cython_sources type_utils.pyx ) set(linked_libraries cugraph::cugraph;cugraph::cugraph_c) rapids_cython_create_modules( CXX SOURCE_FILES "${cython_sources}" LINKED_LIBRARIES "${linked_libraries}" ASSOCIATED_TARGETS cugraph )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/testing/type_utils.pyx
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from libc.stdint cimport uintptr_t import cupy from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.resource_handle cimport ( cugraph_resource_handle_t, ) from pylibcugraph.internal_types.sampling_result cimport SamplingResult from pylibcugraph._cugraph_c.algorithms cimport ( cugraph_sample_result_t, cugraph_sample_result_free, ) from pylibcugraph._cugraph_c.sampling_algorithms cimport ( cugraph_test_uniform_neighborhood_sample_result_create, ) from pylibcugraph.resource_handle cimport ( ResourceHandle, ) from pylibcugraph.utils cimport ( assert_success, assert_CAI_type, get_c_type_from_numpy_type, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_device_array_view_create, cugraph_type_erased_device_array_view_free, ) def create_sampling_result(ResourceHandle resource_handle, device_sources, device_destinations, device_weights, device_edge_id, device_edge_type, device_hop, device_batch_label): """ Create a SamplingResult object from individual host arrays. This function is currently testing-only because the SamplingResult type is considered internal (ie. pylibcugraph users will not be exposed to it) and because SamplingResult instances will be created from a cugraph_sample_result_t pointer and not host arrays. """ assert_CAI_type(device_sources, "device_sources") assert_CAI_type(device_destinations, "device_destinations") if device_weights is not None: assert_CAI_type(device_weights, "device_weights") if device_edge_id is not None: assert_CAI_type(device_edge_id, "device_edge_id") if device_edge_type is not None: assert_CAI_type(device_edge_type, "device_edge_type") if device_weights is not None: assert_CAI_type(device_weights, "device_weights") if device_hop is not None: assert_CAI_type(device_hop, "device_hop") if device_batch_label is not None: assert_CAI_type(device_batch_label, "device_batch_label") cdef cugraph_resource_handle_t* c_resource_handle_ptr = \ resource_handle.c_resource_handle_ptr cdef cugraph_sample_result_t* result_ptr cdef cugraph_error_code_t error_code cdef cugraph_error_t* error_ptr cdef uintptr_t cai_srcs_ptr = \ device_sources.__cuda_array_interface__["data"][0] cdef uintptr_t cai_dsts_ptr = \ device_destinations.__cuda_array_interface__["data"][0] cdef uintptr_t cai_weights_ptr if device_weights is not None: cai_weights_ptr = device_weights.__cuda_array_interface__['data'][0] cdef uintptr_t cai_edge_ids_ptr if device_edge_id is not None: cai_edge_ids_ptr = device_edge_id.__cuda_array_interface__['data'][0] cdef uintptr_t cai_edge_types_ptr if device_edge_type is not None: cai_edge_types_ptr = device_edge_type.__cuda_array_interface__['data'][0] cdef uintptr_t cai_hop_ptr if device_hop is not None: cai_hop_ptr = device_hop.__cuda_array_interface__['data'][0] cdef uintptr_t cai_batch_id_ptr if device_batch_label is not None: cai_batch_id_ptr = device_batch_label.__cuda_array_interface__['data'][0] cdef cugraph_type_erased_device_array_view_t* c_srcs_view_ptr = ( cugraph_type_erased_device_array_view_create( <void*>cai_srcs_ptr, len(device_sources), get_c_type_from_numpy_type(device_sources.dtype)) ) cdef cugraph_type_erased_device_array_view_t* c_dsts_view_ptr = ( cugraph_type_erased_device_array_view_create( <void*>cai_dsts_ptr, len(device_destinations), get_c_type_from_numpy_type(device_destinations.dtype)) ) cdef cugraph_type_erased_device_array_view_t* c_weight_ptr = <cugraph_type_erased_device_array_view_t*>NULL if device_weights is not None: c_weight_ptr = ( cugraph_type_erased_device_array_view_create( <void*>cai_weights_ptr, len(device_weights), get_c_type_from_numpy_type(device_weights.dtype) ) ) cdef cugraph_type_erased_device_array_view_t* c_edge_id_ptr = <cugraph_type_erased_device_array_view_t*>NULL if device_weights is not None: c_edge_id_ptr = ( cugraph_type_erased_device_array_view_create( <void*>cai_edge_ids_ptr, len(device_edge_id), get_c_type_from_numpy_type(device_edge_id.dtype) ) ) cdef cugraph_type_erased_device_array_view_t* c_edge_type_ptr = <cugraph_type_erased_device_array_view_t*>NULL if device_weights is not None: c_edge_type_ptr = ( cugraph_type_erased_device_array_view_create( <void*>cai_edge_types_ptr, len(device_edge_type), get_c_type_from_numpy_type(device_edge_type.dtype) ) ) cdef cugraph_type_erased_device_array_view_t* c_hop_ptr = <cugraph_type_erased_device_array_view_t*>NULL if device_weights is not None: c_hop_ptr = ( cugraph_type_erased_device_array_view_create( <void*>cai_hop_ptr, len(device_hop), get_c_type_from_numpy_type(device_hop.dtype) ) ) cdef cugraph_type_erased_device_array_view_t* c_label_ptr = <cugraph_type_erased_device_array_view_t*>NULL if device_weights is not None: c_label_ptr = ( cugraph_type_erased_device_array_view_create( <void*>cai_batch_id_ptr, len(device_batch_label), get_c_type_from_numpy_type(device_batch_label.dtype) ) ) error_code = cugraph_test_uniform_neighborhood_sample_result_create( c_resource_handle_ptr, c_srcs_view_ptr, c_dsts_view_ptr, c_edge_id_ptr, c_edge_type_ptr, c_weight_ptr, c_hop_ptr, c_label_ptr, &result_ptr, &error_ptr) assert_success(error_code, error_ptr, "create_sampling_result") result = SamplingResult() result.set_ptr(result_ptr) # Free the non-owning view containers. This should not free result data. cugraph_type_erased_device_array_view_free(c_srcs_view_ptr) cugraph_type_erased_device_array_view_free(c_dsts_view_ptr) cugraph_type_erased_device_array_view_free(c_edge_id_ptr) cugraph_type_erased_device_array_view_free(c_edge_type_ptr) cugraph_type_erased_device_array_view_free(c_weight_ptr) cugraph_type_erased_device_array_view_free(c_hop_ptr) cugraph_type_erased_device_array_view_free(c_label_ptr) return result
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/testing/__init__.py
# Copyright (c) 2022, NVIDIA CORPORATION. # 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 pylibcugraph.testing.utils import gen_fixture_params_product
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/testing/utils.py
# Copyright (c) 2021-2023, NVIDIA CORPORATION. # 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 from pathlib import Path from itertools import product import pytest RAPIDS_DATASET_ROOT_DIR = os.getenv( "RAPIDS_DATASET_ROOT_DIR", os.path.join(os.path.dirname(__file__), "../datasets") ) RAPIDS_DATASET_ROOT_DIR_PATH = Path(RAPIDS_DATASET_ROOT_DIR) def gen_fixture_params(*param_values): """ Returns a list of pytest.param objects suitable for use as fixture parameters created by merging the values in each tuple into individual pytest.param objects. Each tuple can contain multiple values or pytest.param objects. If pytest.param objects are given, the marks and ids are also merged. If ids is specicified, it must either be a list of string ids for each combination passed in, or a callable that accepts a list of values and returns a string. gen_fixture_params( (pytest.param(True, marks=[pytest.mark.A_good], id="A:True"), pytest.param(False, marks=[pytest.mark.B_bad], id="B:False")), (pytest.param(False, marks=[pytest.mark.A_bad], id="A:False"), pytest.param(True, marks=[pytest.mark.B_good], id="B:True")), ) results in fixture param combinations: True, False - marks=[A_good, B_bad] - id="A:True-B:False" False, False - marks=[A_bad, B_bad] - id="A:False-B:True" """ fixture_params = [] param_type = pytest.param().__class__ # for vals in param_values: new_param_values = [] new_param_marks = [] new_param_ids = [] for val in vals: if isinstance(val, param_type): new_param_values += val.values new_param_marks += val.marks new_param_ids.append(val.id) else: new_param_values += val new_param_ids.append(str(val)) fixture_params.append( pytest.param( new_param_values, marks=new_param_marks, id="-".join(new_param_ids) ) ) return fixture_params def gen_fixture_params_product(*args): """ Returns the cartesian product of the param lists passed in. The lists must be flat lists of pytest.param objects, and the result will be a flat list of pytest.param objects with values and meta-data combined accordingly. A flat list of pytest.param objects is required for pytest fixtures to properly recognize the params. The combinations also include ids generated from the param values and id names associated with each list. For example: gen_fixture_params_product( ([pytest.param(True, marks=[pytest.mark.A_good]), pytest.param(False, marks=[pytest.mark.A_bad])], "A"), ([pytest.param(True, marks=[pytest.mark.B_good]), pytest.param(False, marks=[pytest.mark.B_bad])], "B") ) results in fixture param combinations: True, True - marks=[A_good, B_good] - id="A:True-B:True" True, False - marks=[A_good, B_bad] - id="A:True-B:False" False, True - marks=[A_bad, B_good] - id="A:False-B:True" False, False - marks=[A_bad, B_bad] - id="A:False-B:False" Simply using itertools.product on the lists would result in a list of sublists of individual param objects (ie. not "merged"), which would not be recognized properly as params for a fixture by pytest. NOTE: This function is only needed for parameterized fixtures. Tests/benchmarks will automatically get this behavior when specifying multiple @pytest.mark.parameterize(param_name, param_value_list) decorators. """ # Ensure each arg is a list of pytest.param objs, then separate the params # and IDs. paramLists = [] ids = [] paramType = pytest.param().__class__ for (paramList, paramId) in args: paramListCopy = paramList[:] # do not modify the incoming lists! for i in range(len(paramList)): if not isinstance(paramList[i], paramType): paramListCopy[i] = pytest.param(paramList[i]) paramLists.append(paramListCopy) ids.append(paramId) retList = [] for paramCombo in product(*paramLists): values = [p.values[0] for p in paramCombo] marks = [m for p in paramCombo for m in p.marks] id_strings = [] for (p, paramId) in zip(paramCombo, ids): # Assume paramId is either a string or a callable if isinstance(paramId, str): id_strings.append("%s:%s" % (paramId, p.values[0])) else: id_strings.append(paramId(p.values[0])) comboid = "-".join(id_strings) retList.append(pytest.param(values, marks=marks, id=comboid)) return retList
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/_cugraph_c/similarity_algorithms.pxd
# Copyright (c) 2022, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_host_array_view_t, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) from pylibcugraph._cugraph_c.graph_functions cimport ( cugraph_vertex_pairs_t ) cdef extern from "cugraph_c/similarity_algorithms.h": ########################################################################### #""" ctypedef struct cugraph_similarity_result_t: pass #""" cdef cugraph_type_erased_device_array_view_t* \ cugraph_similarity_result_get_similarity( cugraph_similarity_result_t* result ) cdef void \ cugraph_similarity_result_free( cugraph_similarity_result_t* result ) ########################################################################### # jaccard coefficients cdef cugraph_error_code_t \ cugraph_jaccard_coefficients( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, const cugraph_vertex_pairs_t* vertex_pairs, bool_t use_weight, bool_t do_expensive_check, cugraph_similarity_result_t** result, cugraph_error_t** error ) ########################################################################### # sorensen coefficients cdef cugraph_error_code_t \ cugraph_sorensen_coefficients( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, const cugraph_vertex_pairs_t* vertex_pairs, bool_t use_weight, bool_t do_expensive_check, cugraph_similarity_result_t** result, cugraph_error_t** error ) ########################################################################### # overlap coefficients cdef cugraph_error_code_t \ cugraph_overlap_coefficients( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, const cugraph_vertex_pairs_t* vertex_pairs, bool_t use_weight, bool_t do_expensive_check, cugraph_similarity_result_t** result, cugraph_error_t** error )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/_cugraph_c/graph.pxd
# Copyright (c) 2022, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_host_array_view_t, ) cdef extern from "cugraph_c/graph.h": ctypedef struct cugraph_graph_t: pass ctypedef struct cugraph_graph_properties_t: bool_t is_symmetric bool_t is_multigraph cdef cugraph_error_code_t \ cugraph_sg_graph_create( const cugraph_resource_handle_t* handle, const cugraph_graph_properties_t* properties, const cugraph_type_erased_device_array_view_t* src, const cugraph_type_erased_device_array_view_t* dst, const cugraph_type_erased_device_array_view_t* weights, const cugraph_type_erased_device_array_view_t* edge_ids, const cugraph_type_erased_device_array_view_t* edge_types, bool_t store_transposed, bool_t renumber, bool_t check, cugraph_graph_t** graph, cugraph_error_t** error) # This may get renamed to cugraph_graph_free() cdef void \ cugraph_sg_graph_free( cugraph_graph_t* graph ) cdef cugraph_error_code_t \ cugraph_mg_graph_create( const cugraph_resource_handle_t* handle, const cugraph_graph_properties_t* properties, const cugraph_type_erased_device_array_view_t* src, const cugraph_type_erased_device_array_view_t* dst, const cugraph_type_erased_device_array_view_t* weights, const cugraph_type_erased_device_array_view_t* edge_ids, const cugraph_type_erased_device_array_view_t* edge_types, bool_t store_transposed, size_t num_edges, bool_t check, cugraph_graph_t** graph, cugraph_error_t** error ) # This may get renamed to or replaced with cugraph_graph_free() cdef void \ cugraph_mg_graph_free( cugraph_graph_t* graph ) cdef cugraph_error_code_t \ cugraph_sg_graph_create_from_csr( const cugraph_resource_handle_t* handle, const cugraph_graph_properties_t* properties, const cugraph_type_erased_device_array_view_t* offsets, const cugraph_type_erased_device_array_view_t* indices, const cugraph_type_erased_device_array_view_t* weights, const cugraph_type_erased_device_array_view_t* edge_ids, const cugraph_type_erased_device_array_view_t* edge_type_ids, bool_t store_transposed, bool_t renumber, bool_t check, cugraph_graph_t** graph, cugraph_error_t** error ) cdef void \ cugraph_sg_graph_free( cugraph_graph_t* graph ) cdef cugraph_error_code_t \ cugraph_mg_graph_create( const cugraph_resource_handle_t* handle, const cugraph_graph_properties_t* properties, const cugraph_type_erased_device_array_view_t* src, const cugraph_type_erased_device_array_view_t* dst, const cugraph_type_erased_device_array_view_t* weights, const cugraph_type_erased_device_array_view_t* edge_ids, const cugraph_type_erased_device_array_view_t* edge_type_ids, bool_t store_transposed, size_t num_edges, bool_t check, cugraph_graph_t** graph, cugraph_error_t** error ) cdef void \ cugraph_mg_graph_free( cugraph_graph_t* graph )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/_cugraph_c/array.pxd
# Copyright (c) 2022, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.resource_handle cimport ( cugraph_resource_handle_t, data_type_id_t, byte_t, ) cdef extern from "cugraph_c/array.h": ctypedef struct cugraph_type_erased_device_array_t: pass ctypedef struct cugraph_type_erased_device_array_view_t: pass ctypedef struct cugraph_type_erased_host_array_t: pass ctypedef struct cugraph_type_erased_host_array_view_t: pass cdef cugraph_error_code_t \ cugraph_type_erased_device_array_create( const cugraph_resource_handle_t* handle, data_type_id_t dtype, size_t n_elems, cugraph_type_erased_device_array_t** array, cugraph_error_t** error ) cdef void \ cugraph_type_erased_device_array_free( cugraph_type_erased_device_array_t* p ) # cdef void* \ # cugraph_type_erased_device_array_release( # cugraph_type_erased_device_array_t* p # ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_type_erased_device_array_view( cugraph_type_erased_device_array_t* array ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_type_erased_device_array_view_create( void* pointer, size_t n_elems, data_type_id_t dtype ) cdef void \ cugraph_type_erased_device_array_view_free( cugraph_type_erased_device_array_view_t* p ) cdef size_t \ cugraph_type_erased_device_array_view_size( const cugraph_type_erased_device_array_view_t* p ) cdef data_type_id_t \ cugraph_type_erased_device_array_view_type( const cugraph_type_erased_device_array_view_t* p ) cdef const void* \ cugraph_type_erased_device_array_view_pointer( const cugraph_type_erased_device_array_view_t* p ) cdef cugraph_error_code_t \ cugraph_type_erased_host_array_create( const cugraph_resource_handle_t* handle, data_type_id_t dtype, size_t n_elems, cugraph_type_erased_host_array_t** array, cugraph_error_t** error ) cdef void \ cugraph_type_erased_host_array_free( cugraph_type_erased_host_array_t* p ) # cdef void* \ # cugraph_type_erased_host_array_release( # cugraph_type_erased_host_array_t* p # ) cdef cugraph_type_erased_host_array_view_t* \ cugraph_type_erased_host_array_view( cugraph_type_erased_host_array_t* array ) cdef cugraph_type_erased_host_array_view_t* \ cugraph_type_erased_host_array_view_create( void* pointer, size_t n_elems, data_type_id_t dtype ) cdef void \ cugraph_type_erased_host_array_view_free( cugraph_type_erased_host_array_view_t* p ) cdef size_t \ cugraph_type_erased_host_array_size( const cugraph_type_erased_host_array_t* p ) cdef data_type_id_t \ cugraph_type_erased_host_array_type( const cugraph_type_erased_host_array_t* p ) cdef void* \ cugraph_type_erased_host_array_pointer( const cugraph_type_erased_host_array_view_t* p ) # cdef void* \ # cugraph_type_erased_host_array_view_copy( # const cugraph_resource_handle_t* handle, # cugraph_type_erased_host_array_view_t* dst, # const cugraph_type_erased_host_array_view_t* src, # cugraph_error_t** error # ) cdef cugraph_error_code_t \ cugraph_type_erased_device_array_view_copy_from_host( const cugraph_resource_handle_t* handle, cugraph_type_erased_device_array_view_t* dst, const byte_t* h_src, cugraph_error_t** error ) cdef cugraph_error_code_t \ cugraph_type_erased_device_array_view_copy_to_host( const cugraph_resource_handle_t* handle, byte_t* h_dst, const cugraph_type_erased_device_array_view_t* src, cugraph_error_t** error ) cdef cugraph_error_code_t \ cugraph_type_erased_device_array_view_copy( const cugraph_resource_handle_t* handle, cugraph_type_erased_device_array_view_t* dst, const cugraph_type_erased_device_array_view_t* src, cugraph_error_t** error )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/_cugraph_c/algorithms.pxd
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_host_array_view_t, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) cdef extern from "cugraph_c/algorithms.h": ########################################################################### # paths and path extraction ctypedef struct cugraph_paths_result_t: pass cdef cugraph_type_erased_device_array_view_t* \ cugraph_paths_result_get_vertices( cugraph_paths_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_paths_result_get_distances( cugraph_paths_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_paths_result_get_predecessors( cugraph_paths_result_t* result ) cdef void \ cugraph_paths_result_free( cugraph_paths_result_t* result ) ctypedef struct cugraph_extract_paths_result_t: pass cdef cugraph_error_code_t \ cugraph_extract_paths( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, const cugraph_type_erased_device_array_view_t* sources, const cugraph_paths_result_t* paths_result, const cugraph_type_erased_device_array_view_t* destinations, cugraph_extract_paths_result_t** result, cugraph_error_t** error ) cdef size_t \ cugraph_extract_paths_result_get_max_path_length( cugraph_extract_paths_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_extract_paths_result_get_paths( cugraph_extract_paths_result_t* result ) cdef void \ cugraph_extract_paths_result_free( cugraph_extract_paths_result_t* result ) ########################################################################### # bfs cdef cugraph_error_code_t \ cugraph_bfs( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, # FIXME: this may become const cugraph_type_erased_device_array_view_t* sources, bool_t direction_optimizing, size_t depth_limit, bool_t compute_predecessors, bool_t do_expensive_check, cugraph_paths_result_t** result, cugraph_error_t** error ) ########################################################################### # sssp cdef cugraph_error_code_t \ cugraph_sssp( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, size_t source, double cutoff, bool_t compute_predecessors, bool_t do_expensive_check, cugraph_paths_result_t** result, cugraph_error_t** error ) ########################################################################### # random_walks ctypedef struct cugraph_random_walk_result_t: pass cdef cugraph_type_erased_device_array_view_t* \ cugraph_random_walk_result_get_paths( cugraph_random_walk_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_random_walk_result_get_weights( cugraph_random_walk_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_random_walk_result_get_path_sizes( cugraph_random_walk_result_t* result ) cdef size_t \ cugraph_random_walk_result_get_max_path_length( cugraph_random_walk_result_t* result ) cdef void \ cugraph_random_walk_result_free( cugraph_random_walk_result_t* result ) # node2vec cdef cugraph_error_code_t \ cugraph_node2vec( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, const cugraph_type_erased_device_array_view_t* sources, size_t max_depth, bool_t compress_result, double p, double q, cugraph_random_walk_result_t** result, cugraph_error_t** error ) ########################################################################### # sampling ctypedef struct cugraph_sample_result_t: pass cdef cugraph_type_erased_device_array_view_t* \ cugraph_sample_result_get_renumber_map( const cugraph_sample_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_sample_result_get_renumber_map_offsets( const cugraph_sample_result_t* result ) # Deprecated, use cugraph_sample_result_get_majors cdef cugraph_type_erased_device_array_view_t* \ cugraph_sample_result_get_sources( const cugraph_sample_result_t* result ) # Deprecated, use cugraph_sample_result_get_minors cdef cugraph_type_erased_device_array_view_t* \ cugraph_sample_result_get_destinations( const cugraph_sample_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_sample_result_get_majors( const cugraph_sample_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_sample_result_get_minors( const cugraph_sample_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_sample_result_get_major_offsets( const cugraph_sample_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_sample_result_get_index( const cugraph_sample_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_sample_result_get_edge_weight( const cugraph_sample_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_sample_result_get_edge_id( const cugraph_sample_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_sample_result_get_edge_type( const cugraph_sample_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_sample_result_get_hop( const cugraph_sample_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_sample_result_get_label_hop_offsets( const cugraph_sample_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_sample_result_get_start_labels( const cugraph_sample_result_t* result ) # Deprecated cdef cugraph_type_erased_device_array_view_t* \ cugraph_sample_result_get_offsets( const cugraph_sample_result_t* result ) cdef void \ cugraph_sample_result_free( const cugraph_sample_result_t* result ) # testing API - cugraph_sample_result_t instances are normally created only # by sampling algos cdef cugraph_error_code_t \ cugraph_test_sample_result_create( const cugraph_resource_handle_t* handle, const cugraph_type_erased_device_array_view_t* srcs, const cugraph_type_erased_device_array_view_t* dsts, const cugraph_type_erased_device_array_view_t* edge_id, const cugraph_type_erased_device_array_view_t* edge_type, const cugraph_type_erased_device_array_view_t* wgt, const cugraph_type_erased_device_array_view_t* hop, const cugraph_type_erased_device_array_view_t* label, cugraph_sample_result_t** result, cugraph_error_t** error ) ctypedef struct cugraph_sampling_options_t: pass ctypedef enum cugraph_prior_sources_behavior_t: DEFAULT=0 CARRY_OVER EXCLUDE ctypedef enum cugraph_compression_type_t: COO=0 CSR CSC DCSR DCSC cdef cugraph_error_code_t \ cugraph_sampling_options_create( cugraph_sampling_options_t** options, cugraph_error_t** error, ) cdef void \ cugraph_sampling_set_renumber_results( cugraph_sampling_options_t* options, bool_t value, ) cdef void \ cugraph_sampling_set_with_replacement( cugraph_sampling_options_t* options, bool_t value, ) cdef void \ cugraph_sampling_set_return_hops( cugraph_sampling_options_t* options, bool_t value, ) cdef void \ cugraph_sampling_set_prior_sources_behavior( cugraph_sampling_options_t* options, cugraph_prior_sources_behavior_t value, ) cdef void \ cugraph_sampling_set_dedupe_sources( cugraph_sampling_options_t* options, bool_t value, ) cdef void \ cugraph_sampling_set_compress_per_hop( cugraph_sampling_options_t* options, bool_t value, ) cdef void \ cugraph_sampling_set_compression_type( cugraph_sampling_options_t* options, cugraph_compression_type_t value, ) cdef void \ cugraph_sampling_options_free( cugraph_sampling_options_t* options, ) # uniform random walks cdef cugraph_error_code_t \ cugraph_uniform_random_walks( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, const cugraph_type_erased_device_array_view_t* start_vertices, size_t max_length, cugraph_random_walk_result_t** result, cugraph_error_t** error ) # biased random walks cdef cugraph_error_code_t \ cugraph_based_random_walks( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, const cugraph_type_erased_device_array_view_t* start_vertices, size_t max_length, cugraph_random_walk_result_t** result, cugraph_error_t** error )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/_cugraph_c/sampling_algorithms.pxd
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_host_array_view_t, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) from pylibcugraph._cugraph_c.algorithms cimport ( cugraph_sample_result_t, cugraph_sampling_options_t, ) from pylibcugraph._cugraph_c.random cimport ( cugraph_rng_state_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_t, ) cdef extern from "cugraph_c/sampling_algorithms.h": ########################################################################### cdef cugraph_error_code_t cugraph_uniform_neighbor_sample( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, const cugraph_type_erased_device_array_view_t* start_vertices, const cugraph_type_erased_device_array_view_t* start_vertex_labels, const cugraph_type_erased_device_array_view_t* label_list, const cugraph_type_erased_device_array_view_t* label_to_comm_rank, const cugraph_type_erased_host_array_view_t* fan_out, cugraph_rng_state_t* rng_state, const cugraph_sampling_options_t* options, bool_t do_expensive_check, cugraph_sample_result_t** result, cugraph_error_t** error ) cdef cugraph_error_code_t cugraph_test_uniform_neighborhood_sample_result_create( const cugraph_resource_handle_t* handle, const cugraph_type_erased_device_array_view_t* srcs, const cugraph_type_erased_device_array_view_t* dsts, const cugraph_type_erased_device_array_view_t* edge_id, const cugraph_type_erased_device_array_view_t* edge_type, const cugraph_type_erased_device_array_view_t* weight, const cugraph_type_erased_device_array_view_t* hop, const cugraph_type_erased_device_array_view_t* label, cugraph_sample_result_t** result, cugraph_error_t** error ) # random vertices selection cdef cugraph_error_code_t \ cugraph_select_random_vertices( const cugraph_resource_handle_t* handle, const cugraph_graph_t* graph, cugraph_rng_state_t* rng_state, size_t num_vertices, cugraph_type_erased_device_array_t** vertices, cugraph_error_t** error )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/_cugraph_c/random.pxd
# Copyright (c) 2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.resource_handle cimport ( cugraph_resource_handle_t, ) cdef extern from "cugraph_c/random.h": ctypedef struct cugraph_rng_state_t: pass cdef cugraph_error_code_t cugraph_rng_state_create( const cugraph_resource_handle_t* handle, size_t seed, cugraph_rng_state_t** state, cugraph_error_t** error, ) cdef void cugraph_rng_state_free(cugraph_rng_state_t* p)
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/_cugraph_c/README.md
# `pylibcugraph/_cugraph_c` This directory contains cython `.pxd` files which describe the cugraph C library to cython. The contents here are simply a mapping of the cugraph_c C APIs to cython for use in the cython code in the parent directory.
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/_cugraph_c/community_algorithms.pxd
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_host_array_view_t, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) from pylibcugraph._cugraph_c.graph_functions cimport ( cugraph_induced_subgraph_result_t, ) from pylibcugraph._cugraph_c.random cimport ( cugraph_rng_state_t, ) cdef extern from "cugraph_c/community_algorithms.h": ########################################################################### # triangle_count ctypedef struct cugraph_triangle_count_result_t: pass cdef cugraph_type_erased_device_array_view_t* \ cugraph_triangle_count_result_get_vertices( cugraph_triangle_count_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_triangle_count_result_get_counts( cugraph_triangle_count_result_t* result ) cdef void \ cugraph_triangle_count_result_free( cugraph_triangle_count_result_t* result ) cdef cugraph_error_code_t \ cugraph_triangle_count( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, const cugraph_type_erased_device_array_view_t* start, bool_t do_expensive_check, cugraph_triangle_count_result_t** result, cugraph_error_t** error ) ########################################################################### # louvain ctypedef struct cugraph_hierarchical_clustering_result_t: pass cdef cugraph_type_erased_device_array_view_t* \ cugraph_hierarchical_clustering_result_get_vertices( cugraph_hierarchical_clustering_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_hierarchical_clustering_result_get_clusters( cugraph_hierarchical_clustering_result_t* result ) cdef double cugraph_hierarchical_clustering_result_get_modularity( cugraph_hierarchical_clustering_result_t* result ) cdef void \ cugraph_hierarchical_clustering_result_free( cugraph_hierarchical_clustering_result_t* result ) cdef cugraph_error_code_t \ cugraph_louvain( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, size_t max_level, double threshold, double resolution, bool_t do_expensive_check, cugraph_hierarchical_clustering_result_t** result, cugraph_error_t** error ) # extract_ego cdef cugraph_error_code_t \ cugraph_extract_ego( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, const cugraph_type_erased_device_array_view_t* source_vertices, size_t radius, bool_t do_expensive_check, cugraph_induced_subgraph_result_t** result, cugraph_error_t** error ) # leiden ctypedef struct cugraph_hierarchical_clustering_result_t: pass cdef cugraph_type_erased_device_array_view_t* \ cugraph_hierarchical_clustering_result_get_vertices( cugraph_hierarchical_clustering_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_hierarchical_clustering_result_get_clusters( cugraph_hierarchical_clustering_result_t* result ) cdef double cugraph_hierarchical_clustering_result_get_modularity( cugraph_hierarchical_clustering_result_t* result ) cdef void \ cugraph_hierarchical_clustering_result_free( cugraph_hierarchical_clustering_result_t* result ) cdef cugraph_error_code_t \ cugraph_leiden( const cugraph_resource_handle_t* handle, cugraph_rng_state_t* rng_state, cugraph_graph_t* graph, size_t max_level, double resolution, double theta, bool_t do_expensive_check, cugraph_hierarchical_clustering_result_t** result, cugraph_error_t** error ) ########################################################################### # ECG cdef cugraph_error_code_t \ cugraph_ecg( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, double min_weight, size_t ensemble_size, bool_t do_expensive_check, cugraph_hierarchical_clustering_result_t** result, cugraph_error_t** error ) ########################################################################### # Clustering ctypedef struct cugraph_clustering_result_t: pass cdef cugraph_type_erased_device_array_view_t* \ cugraph_clustering_result_get_vertices( cugraph_clustering_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_clustering_result_get_clusters( cugraph_clustering_result_t* result ) cdef void \ cugraph_clustering_result_free( cugraph_clustering_result_t* result ) # Balanced cut clustering cdef cugraph_error_code_t \ cugraph_balanced_cut_clustering( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, size_t n_clusters, size_t n_eigenvectors, double evs_tolerance, int evs_max_iterations, double k_means_tolerance, int k_means_max_iterations, bool_t do_expensive_check, cugraph_clustering_result_t** result, cugraph_error_t** error ) # Spectral modularity maximization cdef cugraph_error_code_t \ cugraph_spectral_modularity_maximization( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, size_t n_clusters, size_t n_eigenvectors, double evs_tolerance, int evs_max_iterations, double k_means_tolerance, int k_means_max_iterations, bool_t do_expensive_check, cugraph_clustering_result_t** result, cugraph_error_t** error ) # Analyze clustering modularity cdef cugraph_error_code_t \ cugraph_analyze_clustering_modularity( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, size_t n_clusters, const cugraph_type_erased_device_array_view_t* vertices, const cugraph_type_erased_device_array_view_t* clusters, double* score, cugraph_error_t** error ) # Analyze clustering edge cut cdef cugraph_error_code_t \ cugraph_analyze_clustering_edge_cut( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, size_t n_clusters, const cugraph_type_erased_device_array_view_t* vertices, const cugraph_type_erased_device_array_view_t* clusters, double* score, cugraph_error_t** error ) # Analyze clustering ratio cut cdef cugraph_error_code_t \ cugraph_analyze_clustering_ratio_cut( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, size_t n_clusters, const cugraph_type_erased_device_array_view_t* vertices, const cugraph_type_erased_device_array_view_t* clusters, double* score, cugraph_error_t** error ) ########################################################################### # K truss cdef cugraph_error_code_t \ cugraph_k_truss_subgraph( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, size_t k, bool_t do_expensive_check, cugraph_induced_subgraph_result_t** result, cugraph_error_t** error)
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/_cugraph_c/graph_generators.pxd
# Copyright (c) 2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( cugraph_resource_handle_t, cugraph_data_type_id_t, bool_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_host_array_view_t, ) from pylibcugraph._cugraph_c.random cimport ( cugraph_rng_state_t, ) cdef extern from "cugraph_c/graph_generators.h": ctypedef enum cugraph_generator_distribution_t: POWER_LAW UNIFORM ctypedef struct cugraph_coo_t: pass ctypedef struct cugraph_coo_list_t: pass cdef cugraph_type_erased_device_array_view_t* \ cugraph_coo_get_sources( cugraph_coo_t* coo ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_coo_get_destinations( cugraph_coo_t* coo ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_coo_get_edge_weights( cugraph_coo_t* coo ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_coo_get_edge_id( cugraph_coo_t* coo ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_coo_get_edge_type( cugraph_coo_t* coo ) cdef size_t \ cugraph_coo_list_size( const cugraph_coo_list_t* coo_list ) cdef cugraph_coo_t* \ cugraph_coo_list_element( cugraph_coo_list_t* coo_list, size_t index) cdef void \ cugraph_coo_free( cugraph_coo_t* coo ) cdef void \ cugraph_coo_list_free( cugraph_coo_list_t* coo_list ) cdef cugraph_error_code_t \ cugraph_generate_rmat_edgelist( const cugraph_resource_handle_t* handle, cugraph_rng_state_t* rng_state, size_t scale, size_t num_edges, double a, double b, double c, bool_t clip_and_flip, bool_t scramble_vertex_ids, cugraph_coo_t** result, cugraph_error_t** error ) cdef cugraph_error_code_t \ cugraph_generate_rmat_edgelists( const cugraph_resource_handle_t* handle, cugraph_rng_state_t* rng_state, size_t n_edgelists, size_t min_scale, size_t max_scale, size_t edge_factor, cugraph_generator_distribution_t size_distribution, cugraph_generator_distribution_t edge_distribution, bool_t clip_and_flip, bool_t scramble_vertex_ids, cugraph_coo_list_t** result, cugraph_error_t** error ) cdef cugraph_error_code_t \ cugraph_generate_edge_weights( const cugraph_resource_handle_t* handle, cugraph_rng_state_t* rng_state, cugraph_coo_t* coo, cugraph_data_type_id_t dtype, double minimum_weight, double maximum_weight, cugraph_error_t** error ) cdef cugraph_error_code_t \ cugraph_generate_edge_ids( const cugraph_resource_handle_t* handle, cugraph_coo_t* coo, bool_t multi_gpu, cugraph_error_t** error ) cdef cugraph_error_code_t \ cugraph_generate_edge_types( const cugraph_resource_handle_t* handle, cugraph_rng_state_t* rng_state, cugraph_coo_t* coo, int min_edge_type, int max_edge_type, cugraph_error_t** error )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/_cugraph_c/core_algorithms.pxd
# Copyright (c) 2022, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_host_array_view_t, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) cdef extern from "cugraph_c/core_algorithms.h": ########################################################################### # core number ctypedef struct cugraph_core_result_t: pass cdef cugraph_type_erased_device_array_view_t* \ cugraph_core_result_get_vertices( cugraph_core_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_core_result_get_core_numbers( cugraph_core_result_t* result ) cdef void \ cugraph_core_result_free( cugraph_core_result_t* result ) ctypedef enum cugraph_k_core_degree_type_t: K_CORE_DEGREE_TYPE_IN=0, K_CORE_DEGREE_TYPE_OUT=1, K_CORE_DEGREE_TYPE_INOUT=2 cdef cugraph_error_code_t \ cugraph_core_number( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, cugraph_k_core_degree_type_t degree_type, bool_t do_expensive_check, cugraph_core_result_t** result, cugraph_error_t** error ) ########################################################################### # k-core ctypedef struct cugraph_k_core_result_t: pass cdef cugraph_type_erased_device_array_view_t* \ cugraph_k_core_result_get_src_vertices( cugraph_k_core_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_k_core_result_get_dst_vertices( cugraph_k_core_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_k_core_result_get_weights( cugraph_k_core_result_t* result ) cdef void \ cugraph_k_core_result_free( cugraph_k_core_result_t* result ) cdef cugraph_error_code_t \ cugraph_core_result_create( const cugraph_resource_handle_t* handle, cugraph_type_erased_device_array_view_t* vertices, cugraph_type_erased_device_array_view_t* core_numbers, cugraph_core_result_t** core_result, cugraph_error_t** error ) cdef cugraph_error_code_t \ cugraph_k_core( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, size_t k, cugraph_k_core_degree_type_t degree_type, const cugraph_core_result_t* core_result, bool_t do_expensive_check, cugraph_k_core_result_t** result, cugraph_error_t** error )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/_cugraph_c/graph_functions.pxd
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.resource_handle cimport ( cugraph_resource_handle_t, bool_t, ) from pylibcugraph._cugraph_c.similarity_algorithms cimport ( cugraph_similarity_result_t ) from pylibcugraph._cugraph_c.graph cimport cugraph_graph_t from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t ) cdef extern from "cugraph_c/graph_functions.h": #""" #ctypedef struct cugraph_similarity_result_t: # pass #""" ctypedef struct cugraph_vertex_pairs_t: pass from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) cdef extern from "cugraph_c/graph_functions.h": ########################################################################### # vertex_pairs ctypedef struct cugraph_vertex_pairs_t: pass cdef cugraph_type_erased_device_array_view_t* \ cugraph_vertex_pairs_get_first( cugraph_vertex_pairs_t* vertex_pairs ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_vertex_pairs_get_second( cugraph_vertex_pairs_t* vertex_pairs ) cdef void \ cugraph_vertex_pairs_free( cugraph_vertex_pairs_t* vertex_pairs ) cdef cugraph_error_code_t \ cugraph_create_vertex_pairs( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, const cugraph_type_erased_device_array_view_t* first, const cugraph_type_erased_device_array_view_t* second, cugraph_vertex_pairs_t** vertex_pairs, cugraph_error_t** error ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_vertex_pairs_get_first( cugraph_vertex_pairs_t* vertex_pairs ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_vertex_pairs_get_second( cugraph_vertex_pairs_t* vertex_pairs ) cdef void cugraph_vertex_pairs_free( cugraph_vertex_pairs_t* vertex_pairs ) cdef cugraph_error_code_t cugraph_two_hop_neighbors( const cugraph_resource_handle_t* handle, const cugraph_graph_t* graph, const cugraph_type_erased_device_array_view_t* start_vertices, bool_t do_expensive_check, cugraph_vertex_pairs_t** result, cugraph_error_t** error) cdef cugraph_error_code_t \ cugraph_two_hop_neighbors( const cugraph_resource_handle_t* handle, const cugraph_graph_t* graph, const cugraph_type_erased_device_array_view_t* start_vertices, cugraph_vertex_pairs_t** result, cugraph_error_t** error ) ########################################################################### # induced_subgraph ctypedef struct cugraph_induced_subgraph_result_t: pass cdef cugraph_type_erased_device_array_view_t* \ cugraph_induced_subgraph_get_sources( cugraph_induced_subgraph_result_t* induced_subgraph ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_induced_subgraph_get_destinations( cugraph_induced_subgraph_result_t* induced_subgraph ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_induced_subgraph_get_edge_weights( cugraph_induced_subgraph_result_t* induced_subgraph ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_induced_subgraph_get_edge_ids( cugraph_induced_subgraph_result_t* induced_subgraph ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_induced_subgraph_get_edge_type_ids( cugraph_induced_subgraph_result_t* induced_subgraph ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_induced_subgraph_get_subgraph_offsets( cugraph_induced_subgraph_result_t* induced_subgraph ) cdef void \ cugraph_induced_subgraph_result_free( cugraph_induced_subgraph_result_t* induced_subgraph ) cdef cugraph_error_code_t \ cugraph_extract_induced_subgraph( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, const cugraph_type_erased_device_array_view_t* subgraph_offsets, const cugraph_type_erased_device_array_view_t* subgraph_vertices, bool_t do_expensive_check, cugraph_induced_subgraph_result_t** result, cugraph_error_t** error ) ########################################################################### # allgather cdef cugraph_error_code_t \ cugraph_allgather( const cugraph_resource_handle_t* handle, const cugraph_type_erased_device_array_view_t* src, const cugraph_type_erased_device_array_view_t* dst, const cugraph_type_erased_device_array_view_t* weights, const cugraph_type_erased_device_array_view_t* edge_ids, const cugraph_type_erased_device_array_view_t* edge_type_ids, cugraph_induced_subgraph_result_t** result, cugraph_error_t** error )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/_cugraph_c/centrality_algorithms.pxd
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_host_array_view_t, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) cdef extern from "cugraph_c/centrality_algorithms.h": ########################################################################### # pagerank ctypedef struct cugraph_centrality_result_t: pass cdef cugraph_type_erased_device_array_view_t* \ cugraph_centrality_result_get_vertices( cugraph_centrality_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_centrality_result_get_values( cugraph_centrality_result_t* result ) cdef size_t \ cugraph_centrality_result_get_num_iterations( cugraph_centrality_result_t* result ) cdef bool_t \ cugraph_centrality_result_converged( cugraph_centrality_result_t* result ) cdef void \ cugraph_centrality_result_free( cugraph_centrality_result_t* result ) cdef cugraph_error_code_t \ cugraph_pagerank( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, const cugraph_type_erased_device_array_view_t* precomputed_vertex_out_weight_vertices, const cugraph_type_erased_device_array_view_t* precomputed_vertex_out_weight_sums, const cugraph_type_erased_device_array_view_t* initial_guess_vertices, const cugraph_type_erased_device_array_view_t* initial_guess_values, double alpha, double epsilon, size_t max_iterations, bool_t do_expensive_check, cugraph_centrality_result_t** result, cugraph_error_t** error ) cdef cugraph_error_code_t \ cugraph_pagerank_allow_nonconvergence( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, const cugraph_type_erased_device_array_view_t* precomputed_vertex_out_weight_vertices, const cugraph_type_erased_device_array_view_t* precomputed_vertex_out_weight_sums, const cugraph_type_erased_device_array_view_t* initial_guess_vertices, const cugraph_type_erased_device_array_view_t* initial_guess_values, double alpha, double epsilon, size_t max_iterations, bool_t do_expensive_check, cugraph_centrality_result_t** result, cugraph_error_t** error ) cdef cugraph_error_code_t \ cugraph_personalized_pagerank( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, const cugraph_type_erased_device_array_view_t* precomputed_vertex_out_weight_vertices, const cugraph_type_erased_device_array_view_t* precomputed_vertex_out_weight_sums, const cugraph_type_erased_device_array_view_t* initial_guess_vertices, const cugraph_type_erased_device_array_view_t* initial_guess_values, const cugraph_type_erased_device_array_view_t* personalization_vertices, const cugraph_type_erased_device_array_view_t* personalization_values, double alpha, double epsilon, size_t max_iterations, bool_t do_expensive_check, cugraph_centrality_result_t** result, cugraph_error_t** error ) cdef cugraph_error_code_t \ cugraph_personalized_pagerank_allow_nonconvergence( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, const cugraph_type_erased_device_array_view_t* precomputed_vertex_out_weight_vertices, const cugraph_type_erased_device_array_view_t* precomputed_vertex_out_weight_sums, const cugraph_type_erased_device_array_view_t* initial_guess_vertices, const cugraph_type_erased_device_array_view_t* initial_guess_values, const cugraph_type_erased_device_array_view_t* personalization_vertices, const cugraph_type_erased_device_array_view_t* personalization_values, double alpha, double epsilon, size_t max_iterations, bool_t do_expensive_check, cugraph_centrality_result_t** result, cugraph_error_t** error ) ########################################################################### # eigenvector centrality cdef cugraph_error_code_t \ cugraph_eigenvector_centrality( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, double epsilon, size_t max_iterations, bool_t do_expensive_check, cugraph_centrality_result_t** result, cugraph_error_t** error ) ########################################################################### # katz centrality cdef cugraph_error_code_t \ cugraph_katz_centrality( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, const cugraph_type_erased_device_array_view_t* betas, double alpha, double beta, double epsilon, size_t max_iterations, bool_t do_expensive_check, cugraph_centrality_result_t** result, cugraph_error_t** error ) ########################################################################### # hits ctypedef struct cugraph_hits_result_t: pass cdef cugraph_type_erased_device_array_view_t* \ cugraph_hits_result_get_vertices( cugraph_hits_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_hits_result_get_hubs( cugraph_hits_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_hits_result_get_authorities( cugraph_hits_result_t* result ) cdef void \ cugraph_hits_result_free( cugraph_hits_result_t* result ) cdef cugraph_error_code_t \ cugraph_hits( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, double tol, size_t max_iter, const cugraph_type_erased_device_array_view_t* initial_hubs_guess_vertices, const cugraph_type_erased_device_array_view_t* initial_hubs_guess_values, bool_t normalized, bool_t do_expensive_check, cugraph_hits_result_t** result, cugraph_error_t** error ) ########################################################################### # betweenness centrality cdef cugraph_error_code_t \ cugraph_betweenness_centrality( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, const cugraph_type_erased_device_array_view_t* vertex_list, bool_t normalized, bool_t include_endpoints, bool_t do_expensive_check, cugraph_centrality_result_t** result, cugraph_error_t** error ) ########################################################################### # edge betweenness centrality ctypedef struct cugraph_edge_centrality_result_t: pass cdef cugraph_type_erased_device_array_view_t* \ cugraph_edge_centrality_result_get_src_vertices( cugraph_edge_centrality_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_edge_centrality_result_get_dst_vertices( cugraph_edge_centrality_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_edge_centrality_result_get_edge_ids( cugraph_edge_centrality_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_edge_centrality_result_get_values( cugraph_edge_centrality_result_t* result ) cdef void \ cugraph_edge_centrality_result_free( cugraph_edge_centrality_result_t* result ) cdef cugraph_error_code_t \ cugraph_edge_betweenness_centrality( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, const cugraph_type_erased_device_array_view_t* vertex_list, bool_t normalized, bool_t do_expensive_check, cugraph_edge_centrality_result_t** result, cugraph_error_t** error )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/_cugraph_c/error.pxd
# Copyright (c) 2022, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 cdef extern from "cugraph_c/error.h": ctypedef enum cugraph_error_code_t: CUGRAPH_SUCCESS CUGRAPH_UNKNOWN_ERROR CUGRAPH_INVALID_HANDLE CUGRAPH_ALLOC_ERROR CUGRAPH_INVALID_INPUT CUGRAPH_NOT_IMPLEMENTED CUGRAPH_UNSUPPORTED_TYPE_COMBINATION ctypedef struct cugraph_error_t: pass const char* \ cugraph_error_message( const cugraph_error_t* error ) void \ cugraph_error_free( cugraph_error_t* error )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/_cugraph_c/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # # 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.
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/_cugraph_c/labeling_algorithms.pxd
# Copyright (c) 2022, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.resource_handle cimport ( bool_t, cugraph_resource_handle_t, ) from pylibcugraph._cugraph_c.error cimport ( cugraph_error_code_t, cugraph_error_t, ) from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, cugraph_type_erased_host_array_view_t, ) from pylibcugraph._cugraph_c.graph cimport ( cugraph_graph_t, ) cdef extern from "cugraph_c/labeling_algorithms.h": ########################################################################### # weakly connected components ctypedef struct cugraph_labeling_result_t: pass cdef cugraph_type_erased_device_array_view_t* \ cugraph_labeling_result_get_vertices( cugraph_labeling_result_t* result ) cdef cugraph_type_erased_device_array_view_t* \ cugraph_labeling_result_get_labels( cugraph_labeling_result_t* result ) cdef void \ cugraph_labeling_result_free( cugraph_labeling_result_t* result ) cdef cugraph_error_code_t \ cugraph_weakly_connected_components( const cugraph_resource_handle_t* handle, cugraph_graph_t* graph, bool_t do_expensive_check, cugraph_labeling_result_t** result, cugraph_error_t** error )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/_cugraph_c/resource_handle.pxd
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from libc.stdint cimport int8_t cdef extern from "cugraph_c/resource_handle.h": ctypedef enum bool_t: FALSE TRUE ctypedef enum data_type_id_t: INT32 INT64 FLOAT32 FLOAT64 SIZE_T ctypedef data_type_id_t cugraph_data_type_id_t ctypedef int8_t byte_t ctypedef struct cugraph_resource_handle_t: pass # FIXME: the void* raft_handle arg will change in a future release cdef cugraph_resource_handle_t* \ cugraph_create_resource_handle( void* raft_handle ) cdef int \ cugraph_resource_handle_get_rank( const cugraph_resource_handle_t* handle ) cdef void \ cugraph_free_resource_handle( cugraph_resource_handle_t* p_handle )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/experimental/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. """ The "experimental" package contains packages, functions, classes, etc. that are ready for use but do not have their API signatures or implementation finalized yet. This allows users to provide early feedback while still permitting bigger design changes to take place. ALL APIS IN EXPERIMENTAL ARE SUBJECT TO CHANGE OR REMOVAL. Calling experimental objects will raise a PendingDeprecationWarning warning. If an object is "promoted" to the public API, the experimental namespace will continue to also have that object present for at least another release. A different warning will be output in that case, indicating that the experimental API has been promoted and will no longer be importable from experimental much longer. """ from pylibcugraph.utilities.api_tools import ( experimental_warning_wrapper, promoted_experimental_warning_wrapper, ) # experimental_warning_wrapper() wraps the object in a function that provides # the appropriate warning about using experimental code. # promoted_experimental_warning_wrapper() is used instead when an object is present # in both the experimental namespace and its final, public namespace. # The convention of naming functions with the "EXPERIMENTAL__" prefix # discourages users from directly importing experimental objects that don't have # the appropriate warnings, such as what the wrapper and the "experimental" # namespace name provides. from pylibcugraph.graphs import SGGraph SGGraph = promoted_experimental_warning_wrapper(SGGraph) from pylibcugraph.graphs import MGGraph MGGraph = promoted_experimental_warning_wrapper(MGGraph) from pylibcugraph.resource_handle import ResourceHandle ResourceHandle = promoted_experimental_warning_wrapper(ResourceHandle) from pylibcugraph.graph_properties import GraphProperties GraphProperties = promoted_experimental_warning_wrapper(GraphProperties) from pylibcugraph.pagerank import pagerank pagerank = promoted_experimental_warning_wrapper(pagerank) from pylibcugraph.sssp import sssp sssp = promoted_experimental_warning_wrapper(sssp) from pylibcugraph.hits import hits hits = promoted_experimental_warning_wrapper(hits) from pylibcugraph.node2vec import node2vec # from pylibcugraph.jaccard_coefficients import EXPERIMENTAL__jaccard_coefficients # jaccard_coefficients = experimental_warning_wrapper(EXPERIMENTAL__jaccard_coefficients) # from pylibcugraph.overlap_coefficients import EXPERIMENTAL__overlap_coefficients # overlap_coefficients = experimental_warning_wrapper(EXPERIMENTAL__overlap_coefficients) # from pylibcugraph.sorensen_coefficients import EXPERIMENTAL__sorensen_coefficients # sorensen_coefficients = experimental_warning_wrapper( # EXPERIMENTAL__sorensen_coefficients # )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/internal_types/CMakeLists.txt
# ============================================================================= # Copyright (c) 2022, NVIDIA CORPORATION. # # 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. # ============================================================================= set(cython_sources sampling_result.pyx ) set(linked_libraries cugraph::cugraph;cugraph::cugraph_c) rapids_cython_create_modules( CXX SOURCE_FILES "${cython_sources}" LINKED_LIBRARIES "${linked_libraries}" ASSOCIATED_TARGETS cugraph )
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/internal_types/sampling_result.pyx
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.array cimport ( cugraph_type_erased_device_array_view_t, ) from pylibcugraph._cugraph_c.algorithms cimport ( cugraph_sample_result_t, cugraph_sample_result_get_major_offsets, cugraph_sample_result_get_majors, cugraph_sample_result_get_minors, cugraph_sample_result_get_label_hop_offsets, cugraph_sample_result_get_sources, # deprecated cugraph_sample_result_get_destinations, # deprecated cugraph_sample_result_get_edge_weight, cugraph_sample_result_get_edge_id, cugraph_sample_result_get_edge_type, cugraph_sample_result_get_hop, # deprecated cugraph_sample_result_get_start_labels, cugraph_sample_result_get_offsets, # deprecated cugraph_sample_result_get_renumber_map, cugraph_sample_result_get_renumber_map_offsets, cugraph_sample_result_free, ) from pylibcugraph.utils cimport ( create_cupy_array_view_for_device_ptr, ) cdef class SamplingResult: """ Cython interface to a cugraph_sample_result_t pointer. Instances of this call will take ownership of the pointer and free it under standard python GC rules (ie. when all references to it are no longer present). This class provides methods to return non-owning cupy ndarrays for the corresponding array members. Returning these cupy arrays increments the ref count on the SamplingResult instances from which the cupy arrays are referencing. """ def __cinit__(self): # This SamplingResult instance owns sample_result_ptr now. It will be # freed when this instance is deleted (see __dealloc__()) self.c_sample_result_ptr = NULL def __dealloc__(self): if self.c_sample_result_ptr is not NULL: cugraph_sample_result_free(self.c_sample_result_ptr) cdef set_ptr(self, cugraph_sample_result_t* sample_result_ptr): self.c_sample_result_ptr = sample_result_ptr def get_major_offsets(self): if self.c_sample_result_ptr is NULL: raise ValueError("pointer not set, must call set_ptr() with a " "non-NULL value first.") cdef cugraph_type_erased_device_array_view_t* device_array_view_ptr = ( cugraph_sample_result_get_major_offsets(self.c_sample_result_ptr) ) if device_array_view_ptr is NULL: return None return create_cupy_array_view_for_device_ptr(device_array_view_ptr, self) def get_majors(self): if self.c_sample_result_ptr is NULL: raise ValueError("pointer not set, must call set_ptr() with a " "non-NULL value first.") cdef cugraph_type_erased_device_array_view_t* device_array_view_ptr = ( cugraph_sample_result_get_majors(self.c_sample_result_ptr) ) if device_array_view_ptr is NULL: return None return create_cupy_array_view_for_device_ptr(device_array_view_ptr, self) def get_minors(self): if self.c_sample_result_ptr is NULL: raise ValueError("pointer not set, must call set_ptr() with a " "non-NULL value first.") cdef cugraph_type_erased_device_array_view_t* device_array_view_ptr = ( cugraph_sample_result_get_minors(self.c_sample_result_ptr) ) if device_array_view_ptr is NULL: return None return create_cupy_array_view_for_device_ptr(device_array_view_ptr, self) def get_sources(self): # Deprecated if self.c_sample_result_ptr is NULL: raise ValueError("pointer not set, must call set_ptr() with a " "non-NULL value first.") cdef cugraph_type_erased_device_array_view_t* device_array_view_ptr = ( cugraph_sample_result_get_sources(self.c_sample_result_ptr) ) if device_array_view_ptr is NULL: return None return create_cupy_array_view_for_device_ptr(device_array_view_ptr, self) def get_destinations(self): # Deprecated if self.c_sample_result_ptr is NULL: raise ValueError("pointer not set, must call set_ptr() with a " "non-NULL value first.") cdef cugraph_type_erased_device_array_view_t* device_array_view_ptr = ( cugraph_sample_result_get_destinations(self.c_sample_result_ptr) ) if device_array_view_ptr is NULL: return None return create_cupy_array_view_for_device_ptr(device_array_view_ptr, self) def get_edge_weights(self): if self.c_sample_result_ptr is NULL: raise ValueError("pointer not set, must call set_ptr() with a " "non-NULL value first.") cdef cugraph_type_erased_device_array_view_t* device_array_view_ptr = ( cugraph_sample_result_get_edge_weight(self.c_sample_result_ptr) ) if device_array_view_ptr is NULL: return None return create_cupy_array_view_for_device_ptr(device_array_view_ptr, self) def get_indices(self): # Deprecated return self.get_edge_weights() def get_edge_ids(self): if self.c_sample_result_ptr is NULL: raise ValueError("pointer not set, must call set_ptr() with a " "non-NULL value first.") cdef cugraph_type_erased_device_array_view_t* device_array_view_ptr = ( cugraph_sample_result_get_edge_id(self.c_sample_result_ptr) ) if device_array_view_ptr is NULL: return None return create_cupy_array_view_for_device_ptr(device_array_view_ptr, self) def get_edge_types(self): if self.c_sample_result_ptr is NULL: raise ValueError("pointer not set, must call set_ptr() with a " "non-NULL value first.") cdef cugraph_type_erased_device_array_view_t* device_array_view_ptr = ( cugraph_sample_result_get_edge_type(self.c_sample_result_ptr) ) if device_array_view_ptr is NULL: return None return create_cupy_array_view_for_device_ptr(device_array_view_ptr, self) def get_batch_ids(self): if self.c_sample_result_ptr is NULL: raise ValueError("pointer not set, must call set_ptr() with a " "non-NULL value first.") cdef cugraph_type_erased_device_array_view_t* device_array_view_ptr = ( cugraph_sample_result_get_start_labels(self.c_sample_result_ptr) ) if device_array_view_ptr is NULL: return None return create_cupy_array_view_for_device_ptr(device_array_view_ptr, self) def get_label_hop_offsets(self): if self.c_sample_result_ptr is NULL: raise ValueError("pointer not set, must call set_ptr() with a " "non-NULL value first.") cdef cugraph_type_erased_device_array_view_t* device_array_view_ptr = ( cugraph_sample_result_get_label_hop_offsets(self.c_sample_result_ptr) ) if device_array_view_ptr is NULL: return None return create_cupy_array_view_for_device_ptr(device_array_view_ptr, self) # Deprecated def get_offsets(self): if self.c_sample_result_ptr is NULL: raise ValueError("pointer not set, must call set_ptr() with a " "non-NULL value first.") cdef cugraph_type_erased_device_array_view_t* device_array_view_ptr = ( cugraph_sample_result_get_offsets(self.c_sample_result_ptr) ) if device_array_view_ptr is NULL: return None return create_cupy_array_view_for_device_ptr(device_array_view_ptr, self) # Deprecated def get_hop_ids(self): if self.c_sample_result_ptr is NULL: raise ValueError("pointer not set, must call set_ptr() with a " "non-NULL value first.") cdef cugraph_type_erased_device_array_view_t* device_array_view_ptr = ( cugraph_sample_result_get_hop(self.c_sample_result_ptr) ) if device_array_view_ptr is NULL: return None return create_cupy_array_view_for_device_ptr(device_array_view_ptr, self) def get_renumber_map(self): if self.c_sample_result_ptr is NULL: raise ValueError("pointer not set, must call set_ptr() with a " "non-NULL value first.") cdef cugraph_type_erased_device_array_view_t* device_array_view_ptr = ( cugraph_sample_result_get_renumber_map(self.c_sample_result_ptr) ) if device_array_view_ptr is NULL: return None return create_cupy_array_view_for_device_ptr(device_array_view_ptr, self) def get_renumber_map_offsets(self): if self.c_sample_result_ptr is NULL: raise ValueError("pointer not set, must call set_ptr() with a " "non-NULL value first.") cdef cugraph_type_erased_device_array_view_t* device_array_view_ptr = ( cugraph_sample_result_get_renumber_map_offsets(self.c_sample_result_ptr) ) if device_array_view_ptr is NULL: return None return create_cupy_array_view_for_device_ptr(device_array_view_ptr, self)
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/internal_types/sampling_result.pxd
# Copyright (c) 2022, NVIDIA CORPORATION. # 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. # Have cython use python 3 syntax # cython: language_level = 3 from pylibcugraph._cugraph_c.algorithms cimport ( cugraph_sample_result_t, ) cdef class SamplingResult: cdef cugraph_sample_result_t* c_sample_result_ptr cdef set_ptr(self, cugraph_sample_result_t* sample_result_ptr)
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/internal_types/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # # 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.
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/utilities/api_tools.py
# Copyright (c) 2022, NVIDIA CORPORATION. # 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 functools import warnings import inspect import types experimental_prefix = "EXPERIMENTAL" def experimental_warning_wrapper(obj): """ Wrap obj in a function or class that prints a warning about it being "experimental" (ie. it is in the public API but subject to change or removal), prior to calling obj and returning its value. The object's name used in the warning message also has any leading __ and/or EXPERIMENTAL string are removed from the name used in warning messages. This allows an object to be named with a "private" name in the public API so it can remain hidden while it is still experimental, but have a public name within the experimental namespace so it can be easily discovered and used. """ obj_type = type(obj) if not callable(obj): raise TypeError("obj must be a class or a function type, got " f"{obj_type}") obj_name = obj.__name__ obj_name = obj_name.lstrip(experimental_prefix) obj_name = obj_name.lstrip("__") # Assume the caller of this function is the module containing the # experimental obj and try to get its namespace name. Default to no # namespace name if it could not be found. call_stack = inspect.stack() calling_frame = call_stack[1].frame ns_name = calling_frame.f_locals.get("__name__") dot = "." if ns_name is not None else "" warning_msg = ( f"{ns_name}{dot}{obj_name} is experimental and will " "change or be removed in a future release." ) # If obj is a class, create a wrapper class which 1) inherits from the # incoming class, and 2) has a ctor that simply prints the warning and # calls the base class ctor. A wrapper class is needed so the new type # matches the incoming type. # Ideally a wrapper function would be created and assigned to the class as # the new __init__, but #2 is necessary since assigning attributes cannot # be done to a builtin type (such as a class defined in cython). if obj_type is type: class WarningWrapperClass(obj): def __init__(self, *args, **kwargs): warnings.warn(warning_msg, PendingDeprecationWarning) # call base class __init__ for python, but cython classes do # not have a standard callable __init__ and assigning to self # works instead. if isinstance(obj.__init__, types.FunctionType): super(WarningWrapperClass, self).__init__(*args, **kwargs) else: self = obj(*args, **kwargs) WarningWrapperClass.__module__ = ns_name WarningWrapperClass.__qualname__ = obj_name WarningWrapperClass.__name__ = obj_name WarningWrapperClass.__doc__ = obj.__doc__ return WarningWrapperClass # If this point is reached, the incoming obj is a function so simply wrap # it and return the wrapper. Since the wrapper is a function type, it will # match the incoming obj type. @functools.wraps(obj) def warning_wrapper_function(*args, **kwargs): warnings.warn(warning_msg, PendingDeprecationWarning) return obj(*args, **kwargs) warning_wrapper_function.__module__ = ns_name warning_wrapper_function.__qualname__ = obj_name warning_wrapper_function.__name__ = obj_name warning_wrapper_function.__doc__ = obj.__doc__ return warning_wrapper_function def promoted_experimental_warning_wrapper(obj): """ Wrap obj in a function of class that prints a warning about it being close to being removed, prior to calling obj and returning its value. This is different from experimental_warning_wrapper in that the object has been promoted out of EXPERIMENTAL and thus has two versions of the same object. This wrapper is applied to the one with the "private" name, urging the user to instead use the one in the public API, which does not have the experimental namespace. """ obj_type = type(obj) if not callable(obj): raise TypeError("obj must be a class or a function type, got " f"{obj_type}") obj_name = obj.__name__ obj_name = obj_name.lstrip(experimental_prefix) obj_name = obj_name.lstrip("__") call_stack = inspect.stack() calling_frame = call_stack[1].frame ns_name = calling_frame.f_locals.get("__name__") dot = "." if ns_name is not None else "" warning_msg = ( f"{ns_name}{dot}{obj_name} has been promoted out of " "experimental. Use the non-experimental version instead, " "as this one will be removed in a future release." ) if obj_type is type: class WarningWrapperClass(obj): def __init__(self, *args, **kwargs): warnings.warn(warning_msg, DeprecationWarning) # call base class __init__ for python, but cython classes do # not have a standard callable __init__ and assigning to self # works instead. if isinstance(obj.__init__, types.FunctionType): super(WarningWrapperClass, self).__init__(*args, **kwargs) else: self = obj(*args, **kwargs) WarningWrapperClass.__module__ = ns_name WarningWrapperClass.__qualname__ = obj_name WarningWrapperClass.__name__ = obj_name return WarningWrapperClass @functools.wraps(obj) def warning_wrapper_function(*args, **kwargs): warnings.warn(warning_msg, DeprecationWarning) return obj(*args, **kwargs) warning_wrapper_function.__module__ = ns_name warning_wrapper_function.__qualname__ = obj_name warning_wrapper_function.__name__ = obj_name return warning_wrapper_function def deprecated_warning_wrapper(obj): """ Wrap obj in a function or class that prints a warning about it being deprecated (ie. it is in the public API but will be removed or replaced by a refactored version), prior to calling obj and returning its value. """ obj_type = type(obj) if not callable(obj): raise TypeError("obj must be a class or a function type, got " f"{obj_type}") obj_name = obj.__name__ call_stack = inspect.stack() calling_frame = call_stack[1].frame ns_name = calling_frame.f_locals.get("__name__") dot = "." if ns_name is not None else "" warning_msg = ( f"{ns_name}{dot}{obj_name} has been deprecated and will " "be removed next release. If an experimental version " "exists, it may replace this version in a future release." ) if obj_type is type: class WarningWrapperClass(obj): def __init__(self, *args, **kwargs): warnings.warn(warning_msg, DeprecationWarning) # call base class __init__ for python, but cython classes do # not have a standard callable __init__ and assigning to self # works instead. if isinstance(obj.__init__, types.FunctionType): super(WarningWrapperClass, self).__init__(*args, **kwargs) else: self = obj(*args, **kwargs) WarningWrapperClass.__module__ = ns_name WarningWrapperClass.__qualname__ = obj_name WarningWrapperClass.__name__ = obj_name return WarningWrapperClass @functools.wraps(obj) def warning_wrapper_function(*args, **kwargs): warnings.warn(warning_msg, DeprecationWarning) return obj(*args, **kwargs) warning_wrapper_function.__module__ = ns_name warning_wrapper_function.__qualname__ = obj_name warning_wrapper_function.__name__ = obj_name return warning_wrapper_function
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/utilities/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # # 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.
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/structure/graph_primtypes.pxd
# Copyright (c) 2021-2022, NVIDIA CORPORATION. # 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. # cython: profile=False # distutils: language = c++ # cython: embedsignature = True # cython: language_level = 3 from libcpp cimport bool from pylibraft.common.handle cimport * cdef extern from "cugraph/legacy/graph.hpp" namespace "cugraph::legacy": ctypedef enum PropType: PROP_UNDEF "cugraph::legacy::PROP_UNDEF" PROP_FALSE "cugraph::legacy::PROP_FALSE" PROP_TRUE "cugraph::legacy::PROP_TRUE" ctypedef enum DegreeDirection: DIRECTION_IN_PLUS_OUT "cugraph::legacy::DegreeDirection::IN_PLUS_OUT" DIRECTION_IN "cugraph::legacy::DegreeDirection::IN" DIRECTION_OUT "cugraph::legacy::DegreeDirection::OUT" struct GraphProperties: bool directed bool weighted bool multigraph bool bipartite bool tree PropType has_negative_edges cdef cppclass GraphViewBase[VT,ET,WT]: WT *edge_data handle_t *handle; GraphProperties prop VT number_of_vertices ET number_of_edges VT* local_vertices ET* local_edges VT* local_offsets void set_handle(handle_t*) void set_local_data(VT* local_vertices_, ET* local_edges_, VT* local_offsets_) void get_vertex_identifiers(VT *) const GraphViewBase(WT*,VT,ET) cdef cppclass GraphCOOView[VT,ET,WT](GraphViewBase[VT,ET,WT]): VT *src_indices VT *dst_indices void degree(ET *,DegreeDirection) const GraphCOOView() GraphCOOView(const VT *, const ET *, const WT *, size_t, size_t) cdef cppclass GraphCompressedSparseBaseView[VT,ET,WT](GraphViewBase[VT,ET,WT]): ET *offsets VT *indices void get_source_indices(VT *) const void degree(ET *,DegreeDirection) const GraphCompressedSparseBaseView(const VT *, const ET *, const WT *, size_t, size_t) cdef cppclass GraphCSRView[VT,ET,WT](GraphCompressedSparseBaseView[VT,ET,WT]): GraphCSRView() GraphCSRView(const VT *, const ET *, const WT *, size_t, size_t) cdef cppclass GraphCSCView[VT,ET,WT](GraphCompressedSparseBaseView[VT,ET,WT]): GraphCSCView() GraphCSCView(const VT *, const ET *, const WT *, size_t, size_t)
0
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph
rapidsai_public_repos/cugraph/python/pylibcugraph/pylibcugraph/structure/__init__.py
# Copyright (c) 2021-2023, NVIDIA CORPORATION. # # 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.
0
rapidsai_public_repos/cugraph/python
rapidsai_public_repos/cugraph/python/cugraph/pyproject.toml
# Copyright (c) 2022, NVIDIA CORPORATION. [build-system] requires = [ "cmake>=3.26.4", "cython>=3.0.0", "ninja", "pylibcugraph==23.12.*", "pylibraft==23.12.*", "rmm==23.12.*", "scikit-build>=0.13.1", "setuptools>=61.0.0", "wheel", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../dependencies.yaml and run `rapids-dependency-file-generator`. build-backend = "setuptools.build_meta" [tool.pytest.ini_options] testpaths = ["cugraph/tests"] [project] name = "cugraph" dynamic = ["version"] description = "cuGraph - RAPIDS GPU Graph Analytics" readme = { file = "README.md", content-type = "text/markdown" } authors = [ { name = "NVIDIA Corporation" }, ] license = { text = "Apache 2.0" } requires-python = ">=3.9" dependencies = [ "cudf==23.12.*", "cupy-cuda11x>=12.0.0", "dask-cuda==23.12.*", "dask-cudf==23.12.*", "fsspec[http]>=0.6.0", "numba>=0.57", "numpy>=1.21", "pylibcugraph==23.12.*", "raft-dask==23.12.*", "rapids-dask-dependency==23.12.*", "rmm==23.12.*", "ucx-py==0.35.*", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../dependencies.yaml and run `rapids-dependency-file-generator`. classifiers = [ "Intended Audience :: Developers", "Programming Language :: Python", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", ] [project.optional-dependencies] test = [ "networkx>=2.5.1", "numpy>=1.21", "pandas", "pytest", "pytest-benchmark", "pytest-cov", "pytest-xdist", "python-louvain", "scikit-learn>=0.23.1", "scipy", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../dependencies.yaml and run `rapids-dependency-file-generator`. [project.urls] Homepage = "https://github.com/rapidsai/cugraph" Documentation = "https://docs.rapids.ai/api/cugraph/stable/" [tool.setuptools] license-files = ["LICENSE"] [tool.setuptools.dynamic] version = {file = "cugraph/VERSION"}
0
rapidsai_public_repos/cugraph/python
rapidsai_public_repos/cugraph/python/cugraph/CMakeLists.txt
# ============================================================================= # Copyright (c) 2022-2023, NVIDIA CORPORATION. # # 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. # ============================================================================= cmake_minimum_required(VERSION 3.26.4 FATAL_ERROR) set(cugraph_version 23.12.00) include(../../fetch_rapids.cmake) # We always need CUDA for cuML because the raft dependency brings in a # header-only cuco dependency that enables CUDA unconditionally. include(rapids-cuda) rapids_cuda_init_architectures(cugraph-python) project( cugraph-python VERSION ${cugraph_version} LANGUAGES # TODO: Building Python extension modules via the python_extension_module requires the C # language to be enabled here. The test project that is built in scikit-build to verify # various linking options for the python library is hardcoded to build with C, so until # that is fixed we need to keep C. C CXX CUDA ) ################################################################################ # - User Options -------------------------------------------------------------- option(FIND_CUGRAPH_CPP "Search for existing CUGRAPH C++ installations before defaulting to local files" OFF ) option(CUGRAPH_BUILD_WHEELS "Whether this build is generating a Python wheel." OFF) option(USE_CUGRAPH_OPS "Enable all functions that call cugraph-ops" ON) if(NOT USE_CUGRAPH_OPS) message(STATUS "Disabling libcugraph functions that reference cugraph-ops") add_compile_definitions(NO_CUGRAPH_OPS) endif() # If the user requested it, we attempt to find CUGRAPH. if(FIND_CUGRAPH_CPP) find_package(cugraph ${cugraph_version} REQUIRED) else() set(cugraph_FOUND OFF) endif() include(rapids-cython) if(NOT cugraph_FOUND) set(BUILD_TESTS OFF) set(BUILD_CUGRAPH_MG_TESTS OFF) set(BUILD_CUGRAPH_OPS_CPP_TESTS OFF) set(_exclude_from_all "") if(CUGRAPH_BUILD_WHEELS) # Statically link dependencies if building wheels set(CUDA_STATIC_RUNTIME ON) set(USE_RAFT_STATIC ON) set(CUGRAPH_COMPILE_RAFT_LIB ON) set(CUGRAPH_USE_CUGRAPH_OPS_STATIC ON) set(CUGRAPH_EXCLUDE_CUGRAPH_OPS_FROM_ALL ON) set(ALLOW_CLONE_CUGRAPH_OPS ON) # Don't install the cuML C++ targets into wheels set(_exclude_from_all EXCLUDE_FROM_ALL) endif() add_subdirectory(../../cpp cugraph-cpp ${_exclude_from_all}) set(cython_lib_dir cugraph) install(TARGETS cugraph DESTINATION ${cython_lib_dir}) endif() rapids_cython_init() add_subdirectory(cugraph/components) add_subdirectory(cugraph/dask/comms) add_subdirectory(cugraph/dask/structure) add_subdirectory(cugraph/internals) add_subdirectory(cugraph/layout) add_subdirectory(cugraph/linear_assignment) add_subdirectory(cugraph/structure) add_subdirectory(cugraph/tree) add_subdirectory(cugraph/utilities) if(DEFINED cython_lib_dir) rapids_cython_add_rpath_entries(TARGET cugraph PATHS "${cython_lib_dir}") endif()
0
rapidsai_public_repos/cugraph/python
rapidsai_public_repos/cugraph/python/cugraph/README.md
<h1 align="center"; style="font-style: italic";> <br> <img src="img/cugraph_logo_2.png" alt="cuGraph" width="500"> </h1> <div align="center"> <a href="https://github.com/rapidsai/cugraph/blob/main/LICENSE"> <img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg" alt="License"></a> <img alt="GitHub tag (latest by date)" src="https://img.shields.io/github/v/tag/rapidsai/cugraph"> <a href="https://github.com/rapidsai/cugraph/stargazers"> <img src="https://img.shields.io/github/stars/rapidsai/cugraph"></a> <img alt="Conda" src="https://img.shields.io/conda/dn/rapidsai/cugraph"> <img alt="GitHub last commit" src="https://img.shields.io/github/last-commit/rapidsai/cugraph"> <img alt="Conda" src="https://img.shields.io/conda/pn/rapidsai/cugraph" /> <a href="https://rapids.ai/"><img src="img/rapids_logo.png" alt="RAPIDS" width="125"></a> </div> <br> [RAPIDS](https://rapids.ai) cuGraph is a monorepo that represents a collection of packages focused on GPU-accelerated graph analytics, including support for property graphs, remote (graph as a service) operations, and graph neural networks (GNNs). cuGraph supports the creation and manipulation of graphs followed by the execution of scalable fast graph algorithms. <div align="center"> [Getting cuGraph](./docs/cugraph/source/installation/getting_cugraph.md) * [Graph Algorithms](./docs/cugraph/source/graph_support/algorithms.md) * [Graph Service](./readme_pages/cugraph_service.md) * [Property Graph](./readme_pages/property_graph.md) * [GNN Support](./readme_pages/gnn_support.md) </div> ----- ## News ___NEW!___ _[nx-cugraph](./python/nx-cugraph/README.md)_, a NetworkX backend that provides GPU acceleration to NetworkX with zero code change. ``` > pip install nx-cugraph-cu11 --extra-index-url https://pypi.nvidia.com > export NETWORKX_AUTOMATIC_BACKENDS=cugraph ``` That's it. NetworkX now leverages cuGraph for accelerated graph algorithms. ----- ## Table of contents - Installation - [Getting cuGraph Packages](./docs/cugraph/source/installation/getting_cugraph.md) - [Building from Source](./docs/cugraph/source/installation/source_build.md) - [Contributing to cuGraph](./readme_pages/CONTRIBUTING.md) - General - [Latest News](./readme_pages/news.md) - [Current list of algorithms](./docs/cugraph/source/graph_support/algorithms.md) - [Blogs and Presentation](./docs/cugraph/source/tutorials/cugraph_blogs.rst) - [Performance](./readme_pages/performance/performance.md) - Packages - [cuGraph Python](./readme_pages/cugraph_python.md) - [Property Graph](./readme_pages/property_graph.md) - [External Data Types](./readme_pages/data_types.md) - [pylibcugraph](./readme_pages/pylibcugraph.md) - [libcugraph (C/C++/CUDA)](./readme_pages/libcugraph.md) - [nx-cugraph](./python/nx-cugraph/README.md) - [cugraph-service](./readme_pages/cugraph_service.md) - [cugraph-dgl](./readme_pages/cugraph_dgl.md) - [cugraph-ops](./readme_pages/cugraph_ops.md) - API Docs - Python - [Python Nightly](https://docs.rapids.ai/api/cugraph/nightly/) - [Python Stable](https://docs.rapids.ai/api/cugraph/stable/) - C++ - [C++ Nightly](https://docs.rapids.ai/api/libcugraph/nightly/) - [C++ Stable](https://docs.rapids.ai/api/libcugraph/stable/) - References - [RAPIDS](https://rapids.ai/) - [ARROW](https://arrow.apache.org/) - [DASK](https://www.dask.org/) <br><br> ----- <img src="img/Stack2.png" alt="Stack" width="800"> [RAPIDS](https://rapids.ai) cuGraph is a collection of GPU-accelerated graph algorithms and services. At the Python layer, cuGraph operates on [GPU DataFrames](https://github.com/rapidsai/cudf), thereby allowing for seamless passing of data between ETL tasks in [cuDF](https://github.com/rapidsai/cudf) and machine learning tasks in [cuML](https://github.com/rapidsai/cuml). Data scientists familiar with Python will quickly pick up how cuGraph integrates with the Pandas-like API of cuDF. Likewise, users familiar with NetworkX will quickly recognize the NetworkX-like API provided in cuGraph, with the goal to allow existing code to be ported with minimal effort into RAPIDS. To simplify integration, cuGraph also supports data found in [Pandas DataFrame](https://pandas.pydata.org/), [NetworkX Graph Objects](https://networkx.org/) and several other formats. While the high-level cugraph python API provides an easy-to-use and familiar interface for data scientists that's consistent with other RAPIDS libraries in their workflow, some use cases require access to lower-level graph theory concepts. For these users, we provide an additional Python API called pylibcugraph, intended for applications that require a tighter integration with cuGraph at the Python layer with fewer dependencies. Users familiar with C/C++/CUDA and graph structures can access libcugraph and libcugraph_c for low level integration outside of python. **NOTE:** For the latest stable [README.md](https://github.com/rapidsai/cugraph/blob/main/README.md) ensure you are on the latest branch. As an example, the following Python snippet loads graph data and computes PageRank: ```python import cudf import cugraph # read data into a cuDF DataFrame using read_csv gdf = cudf.read_csv("graph_data.csv", names=["src", "dst"], dtype=["int32", "int32"]) # We now have data as edge pairs # create a Graph using the source (src) and destination (dst) vertex pairs G = cugraph.Graph() G.from_cudf_edgelist(gdf, source='src', destination='dst') # Let's now get the PageRank score of each vertex by calling cugraph.pagerank df_page = cugraph.pagerank(G) # Let's look at the top 10 PageRank Score df_page.sort_values('pagerank', ascending=False).head(10) ``` </br> [Why cuGraph does not support Method Cascading](https://docs.rapids.ai/api/cugraph/nightly/basics/cugraph_cascading.html) ------ # Projects that use cuGraph (alphabetical order) * ArangoDB - a free and open-source native multi-model database system - https://www.arangodb.com/ * CuPy - "NumPy/SciPy-compatible Array Library for GPU-accelerated Computing with Python" - https://cupy.dev/ * Memgraph - In-memory Graph database - https://memgraph.com/ * NetworkX (via [nx-cugraph](./python/nx-cugraph/README.md) backend) - an extremely popular, free and open-source package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks - https://networkx.org/ * PyGraphistry - free and open-source GPU graph ETL, AI, and visualization, including native RAPIDS & cuGraph support - http://github.com/graphistry/pygraphistry * ScanPy - a scalable toolkit for analyzing single-cell gene expression data - https://scanpy.readthedocs.io/en/stable/ (please post an issue if you have a project to add to this list) ------ <br> ## <div align="center"><img src="img/rapids_logo.png" width="265px"/></div> Open GPU Data Science <a name="rapids"></a> The RAPIDS suite of open source software libraries aims to enable execution of end-to-end data science and analytics pipelines entirely on GPUs. It relies on NVIDIA® CUDA® primitives for low-level compute optimization but exposing that GPU parallelism and high-bandwidth memory speed through user-friendly Python interfaces. <p align="center"><img src="img/rapids_arrow.png" width="50%"/></p> For more project details, see [rapids.ai](https://rapids.ai/). <br><br> ### Apache Arrow on GPU <a name="arrow"></a> The GPU version of [Apache Arrow](https://arrow.apache.org/) is a common API that enables efficient interchange of tabular data between processes running on the GPU. End-to-end computation on the GPU avoids unnecessary copying and converting of data off the GPU, reducing compute time and cost for high-performance analytics common in artificial intelligence workloads. As the name implies, cuDF uses the Apache Arrow columnar data format on the GPU. Currently, a subset of the features in Apache Arrow are supported.
0
rapidsai_public_repos/cugraph/python
rapidsai_public_repos/cugraph/python/cugraph/setup.py
# Copyright (c) 2018-2023, NVIDIA CORPORATION. # 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 from setuptools import find_packages, Command from skbuild import setup class CleanCommand(Command): """Custom clean command to tidy up the project root.""" user_options = [ ("all", None, None), ] def initialize_options(self): self.all = None def finalize_options(self): pass def run(self): setupFileDir = os.path.dirname(os.path.abspath(__file__)) os.chdir(setupFileDir) os.system("rm -rf build") os.system("rm -rf dist") os.system("rm -rf dask-worker-space") os.system('find . -name "__pycache__" -type d -exec rm -rf {} +') os.system("rm -rf *.egg-info") os.system('find . -name "*.cpp" -type f -delete') os.system('find . -name "*.cpython*.so" -type f -delete') os.system("rm -rf _skbuild") packages = find_packages(include=["cugraph*"]) setup( packages=packages, package_data={key: ["VERSION", "*.pxd", "*.yaml"] for key in packages}, cmdclass={"clean": CleanCommand}, zip_safe=False, )
0
rapidsai_public_repos/cugraph/python
rapidsai_public_repos/cugraph/python/cugraph/pytest.ini
# Copyright (c) 2021-2022, NVIDIA CORPORATION. # 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. [pytest] addopts = --benchmark-warmup=off --benchmark-max-time=0 --benchmark-min-rounds=1 --benchmark-columns="mean, rounds" ## do not run the slow tests/benchmarks by default -m "not slow" ## for use with rapids-pytest-benchmark plugin #--benchmark-gpu-disable ## for use with pytest-cov plugin #--cov=cugraph #--cov-report term-missing:skip-covered markers = managedmem_on: RMM managed memory enabled managedmem_off: RMM managed memory disabled poolallocator_on: RMM pool allocator enabled poolallocator_off: RMM pool allocator disabled preset_gpu_count: Use a hard-coded number of GPUs for specific MG tests ETL: benchmarks for ETL steps small: small datasets tiny: tiny datasets directed: directed datasets undirected: undirected datasets cugraph_types: use cuGraph input types nx_types: use NetworkX input types matrix_types: use SciPy/CuPy matrix input types slow: slow-running tests/benchmarks cugraph_ops: Tests requiring cugraph-ops mg: Test MG code paths - number of gpu > 1 sg: Test SG code paths and dask sg tests - number of gpu == 1 ci: Tests that should be run in ci python_classes = Bench* Test* python_files = bench_* test_* python_functions = bench_* test_*
0
rapidsai_public_repos/cugraph/python
rapidsai_public_repos/cugraph/python/cugraph/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2018 NVIDIA CORPORATION 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.
0
rapidsai_public_repos/cugraph/python/cugraph
rapidsai_public_repos/cugraph/python/cugraph/cugraph/exceptions.py
# Copyright (c) 2023, NVIDIA CORPORATION. # 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. """ Exception classes for cugraph. """ class FailedToConvergeError(Exception): """ Raised when an algorithm fails to converge within a predetermined set of constraints which vary based on the algorithm, and may or may not be user-configurable. """ pass
0
rapidsai_public_repos/cugraph/python/cugraph
rapidsai_public_repos/cugraph/python/cugraph/cugraph/_version.py
# Copyright (c) 2023, NVIDIA CORPORATION. # # 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 importlib.resources # Read VERSION file from the module that is symlinked to VERSION file # in the root of the repo at build time or copied to the moudle at # installation. VERSION is a separate file that allows CI build-time scripts # to update version info (including commit hashes) without modifying # source files. __version__ = ( importlib.resources.files("cugraph").joinpath("VERSION").read_text().strip() ) __git_commit__ = ""
0
rapidsai_public_repos/cugraph/python/cugraph
rapidsai_public_repos/cugraph/python/cugraph/cugraph/__init__.py
# Copyright (c) 2019-2023, NVIDIA CORPORATION. # 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 cugraph.community import ( ecg, induced_subgraph, ktruss_subgraph, k_truss, louvain, leiden, spectralBalancedCutClustering, spectralModularityMaximizationClustering, analyzeClustering_modularity, analyzeClustering_edge_cut, analyzeClustering_ratio_cut, subgraph, triangle_count, ego_graph, batched_ego_graphs, ) from cugraph.structure import ( Graph, MultiGraph, BiPartiteGraph, from_edgelist, from_cudf_edgelist, from_pandas_edgelist, to_pandas_edgelist, from_pandas_adjacency, to_pandas_adjacency, from_numpy_array, to_numpy_array, from_numpy_matrix, to_numpy_matrix, from_adjlist, hypergraph, symmetrize, symmetrize_df, symmetrize_ddf, is_weighted, is_directed, is_multigraph, is_bipartite, is_multipartite, ) from cugraph.centrality import ( betweenness_centrality, edge_betweenness_centrality, katz_centrality, degree_centrality, eigenvector_centrality, ) from cugraph.cores import core_number, k_core from cugraph.components import ( connected_components, weakly_connected_components, strongly_connected_components, ) from cugraph.link_analysis import pagerank, hits from cugraph.link_prediction import ( jaccard, jaccard_coefficient, overlap, overlap_coefficient, sorensen, sorensen_coefficient, jaccard_w, overlap_w, sorensen_w, ) from cugraph.traversal import ( bfs, bfs_edges, sssp, shortest_path, filter_unreachable, shortest_path_length, concurrent_bfs, multi_source_bfs, ) from cugraph.tree import minimum_spanning_tree, maximum_spanning_tree from cugraph.utilities import utils from cugraph.experimental import strong_connected_component from cugraph.experimental import find_bicliques from cugraph.linear_assignment import hungarian, dense_hungarian from cugraph.layout import force_atlas2 from cugraph.sampling import ( random_walks, rw_path, node2vec, uniform_neighbor_sample, ) from cugraph import experimental from cugraph import gnn from cugraph import exceptions from cugraph._version import __git_commit__, __version__
0
rapidsai_public_repos/cugraph/python/cugraph
rapidsai_public_repos/cugraph/python/cugraph/cugraph/VERSION
23.12.00
0
rapidsai_public_repos/cugraph/python/cugraph/cugraph
rapidsai_public_repos/cugraph/python/cugraph/cugraph/layout/force_atlas2.pxd
# Copyright (c) 2020-2022, NVIDIA CORPORATION. # 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. # cython: profile=False # distutils: language = c++ # cython: embedsignature = True # cython: language_level = 3 from cugraph.structure.graph_primtypes cimport * from libcpp cimport bool cdef extern from "cugraph/legacy/internals.hpp" namespace "cugraph::internals": cdef cppclass GraphBasedDimRedCallback cdef extern from "cugraph/algorithms.hpp" namespace "cugraph": cdef void force_atlas2[vertex_t, edge_t, weight_t]( const handle_t &handle, GraphCOOView[vertex_t, edge_t, weight_t] &graph, float *pos, const int max_iter, float *x_start, float *y_start, bool outbound_attraction_distribution, bool lin_log_mode, bool prevent_overlapping, const float edge_weight_influence, const float jitter_tolerance, bool barnes_hut_optimize, const float barnes_hut_theta, const float scaling_ratio, bool strong_gravity_mode, const float gravity, bool verbose, GraphBasedDimRedCallback *callback) except +
0
rapidsai_public_repos/cugraph/python/cugraph/cugraph
rapidsai_public_repos/cugraph/python/cugraph/cugraph/layout/CMakeLists.txt
# ============================================================================= # Copyright (c) 2022, NVIDIA CORPORATION. # # 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. # ============================================================================= set(cython_sources force_atlas2_wrapper.pyx) set(linked_libraries cugraph::cugraph) rapids_cython_create_modules( CXX SOURCE_FILES "${cython_sources}" LINKED_LIBRARIES "${linked_libraries}" MODULE_PREFIX layout_ ASSOCIATED_TARGETS cugraph )
0
rapidsai_public_repos/cugraph/python/cugraph/cugraph
rapidsai_public_repos/cugraph/python/cugraph/cugraph/layout/force_atlas2_wrapper.pyx
# Copyright (c) 2020-2023, NVIDIA CORPORATION. # 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. # cython: profile=False # distutils: language = c++ # cython: embedsignature = True # cython: language_level = 3 from cugraph.layout.force_atlas2 cimport force_atlas2 as c_force_atlas2 from cugraph.structure import graph_primtypes_wrapper from cugraph.structure.graph_primtypes cimport * from libcpp cimport bool from libc.stdint cimport uintptr_t import cudf from numba import cuda import numpy as np cdef extern from "cugraph/legacy/internals.hpp" namespace "cugraph::internals": cdef cppclass GraphBasedDimRedCallback def force_atlas2(input_graph, max_iter=500, pos_list=None, outbound_attraction_distribution=True, lin_log_mode=False, prevent_overlapping=False, edge_weight_influence=1.0, jitter_tolerance=1.0, barnes_hut_optimize=True, barnes_hut_theta=0.5, scaling_ratio=1.0, strong_gravity_mode=False, gravity=1.0, verbose=False, callback=None): """ Call force_atlas2 """ cdef unique_ptr[handle_t] handle_ptr handle_ptr.reset(new handle_t()) handle_ = handle_ptr.get(); if not input_graph.edgelist: input_graph.view_edge_list() # this code allows handling of renumbered graphs if input_graph.is_renumbered(): num_verts = input_graph.renumber_map.df_internal_to_external['id'].max()+1 else: num_verts = input_graph.nodes().max() + 1 num_edges = len(input_graph.edgelist.edgelist_df['src']) cdef GraphCOOView[int,int,float] graph_float cdef GraphCOOView[int,int,double] graph_double df = cudf.DataFrame() df['vertex'] = cudf.Series(np.arange(num_verts, dtype=np.int32)) src = input_graph.edgelist.edgelist_df['src'] dst = input_graph.edgelist.edgelist_df['dst'] [src, dst] = graph_primtypes_wrapper.datatype_cast([src, dst], [np.int32]) cdef uintptr_t c_src_indices = src.__cuda_array_interface__['data'][0] cdef uintptr_t c_dst_indices = dst.__cuda_array_interface__['data'][0] cdef uintptr_t c_weights = <uintptr_t> NULL if input_graph.edgelist.weights: weights = input_graph.edgelist.edgelist_df["weights"] [weights] = graph_primtypes_wrapper.datatype_cast([weights], [np.float32, np.float64]) c_weights = weights.__cuda_array_interface__['data'][0] cdef uintptr_t x_start = <uintptr_t>NULL cdef uintptr_t y_start = <uintptr_t>NULL cdef uintptr_t pos_ptr = <uintptr_t>NULL if pos_list is not None: if len(pos_list) != num_verts: raise ValueError('pos_list must have initial positions for all vertices') pos_list['x'] = pos_list['x'].astype(np.float32) pos_list['y'] = pos_list['y'].astype(np.float32) pos_list['x'][pos_list['vertex']] = pos_list['x'] pos_list['y'][pos_list['vertex']] = pos_list['y'] x_start = pos_list['x'].__cuda_array_interface__['data'][0] y_start = pos_list['y'].__cuda_array_interface__['data'][0] cdef uintptr_t callback_ptr = 0 if callback: callback_ptr = callback.get_native_callback() # We keep np.float32 as results for both cases pos = cuda.device_array( (num_verts, 2), order="F", dtype=np.float32) pos_ptr = pos.device_ctypes_pointer.value if input_graph.edgelist.weights \ and input_graph.edgelist.edgelist_df['weights'].dtype == np.float64: graph_double = GraphCOOView[int,int, double](<int*>c_src_indices, <int*>c_dst_indices, <double*>c_weights, num_verts, num_edges) c_force_atlas2[int, int, double](handle_[0], graph_double, <float*>pos_ptr, <int>max_iter, <float*>x_start, <float*>y_start, <bool>outbound_attraction_distribution, <bool>lin_log_mode, <bool>prevent_overlapping, <float>edge_weight_influence, <float>jitter_tolerance, <bool>barnes_hut_optimize, <float>barnes_hut_theta, <float>scaling_ratio, <bool> strong_gravity_mode, <float>gravity, <bool> verbose, <GraphBasedDimRedCallback*>callback_ptr) else: graph_float = GraphCOOView[int,int,float](<int*>c_src_indices, <int*>c_dst_indices, <float*>c_weights, num_verts, num_edges) c_force_atlas2[int, int, float](handle_[0], graph_float, <float*>pos_ptr, <int>max_iter, <float*>x_start, <float*>y_start, <bool>outbound_attraction_distribution, <bool>lin_log_mode, <bool>prevent_overlapping, <float>edge_weight_influence, <float>jitter_tolerance, <bool>barnes_hut_optimize, <float>barnes_hut_theta, <float>scaling_ratio, <bool> strong_gravity_mode, <float>gravity, <bool> verbose, <GraphBasedDimRedCallback*>callback_ptr) pos_df = cudf.DataFrame(pos, columns=['x', 'y']) df['x'] = pos_df['x'] df['y'] = pos_df['y'] return df
0
rapidsai_public_repos/cugraph/python/cugraph/cugraph
rapidsai_public_repos/cugraph/python/cugraph/cugraph/layout/force_atlas2.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. # 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 cugraph.layout import force_atlas2_wrapper from cugraph.utilities import ensure_cugraph_obj_for_nx def force_atlas2( input_graph, max_iter=500, pos_list=None, outbound_attraction_distribution=True, lin_log_mode=False, prevent_overlapping=False, edge_weight_influence=1.0, jitter_tolerance=1.0, barnes_hut_optimize=True, barnes_hut_theta=0.5, scaling_ratio=2.0, strong_gravity_mode=False, gravity=1.0, verbose=False, callback=None, ): """ ForceAtlas2 is a continuous graph layout algorithm for handy network visualization. NOTE: Peak memory allocation occurs at 30*V. Parameters ---------- input_graph : cugraph.Graph cuGraph graph descriptor with connectivity information. Edge weights, if present, should be single or double precision floating point values. max_iter : integer, optional (default=500) This controls the maximum number of levels/iterations of the Force Atlas algorithm. When specified the algorithm will terminate after no more than the specified number of iterations. No error occurs when the algorithm terminates in this manner. Good short-term quality can be achieved with 50-100 iterations. Above 1000 iterations is discouraged. pos_list: cudf.DataFrame, optional (default=None) Data frame with initial vertex positions containing two columns: 'x' and 'y' positions. outbound_attraction_distribution: bool, optional (default=True) Distributes attraction along outbound edges. Hubs attract less and thus are pushed to the borders. lin_log_mode: bool, optional (default=False) Switch Force Atlas model from lin-lin to lin-log. Makes clusters more tight. prevent_overlapping: bool, optional (default=False) Prevent nodes to overlap. edge_weight_influence: float, optional (default=1.0) How much influence you give to the edges weight. 0 is “no influence” and 1 is “normal”. jitter_tolerance: float, optional (default=1.0) How much swinging you allow. Above 1 discouraged. Lower gives less speed and more precision. barnes_hut_optimize: bool, optional (default=True) Whether to use the Barnes Hut approximation or the slower exact version. barnes_hut_theta: float, optional (default=0.5) Float between 0 and 1. Tradeoff for speed (1) vs accuracy (0) for Barnes Hut only. scaling_ratio: float, optional (default=2.0) How much repulsion you want. More makes a more sparse graph. Switching from regular mode to LinLog mode needs a readjustment of the scaling parameter. strong_gravity_mode: bool, optional (default=False) Sets a force that attracts the nodes that are distant from the center more. It is so strong that it can sometimes dominate other forces. gravity : float, optional (default=1.0) Attracts nodes to the center. Prevents islands from drifting away. verbose: bool, optional (default=False) Output convergence info at each interation. callback: GraphBasedDimRedCallback, optional (default=None) An instance of GraphBasedDimRedCallback class to intercept the internal state of positions while they are being trained. Example of callback usage: from cugraph.internals import GraphBasedDimRedCallback class CustomCallback(GraphBasedDimRedCallback): def on_preprocess_end(self, positions): print(positions.copy_to_host()) def on_epoch_end(self, positions): print(positions.copy_to_host()) def on_train_end(self, positions): print(positions.copy_to_host()) Returns ------- pos : cudf.DataFrame GPU data frame of size V containing three columns: the vertex identifiers and the x and y positions. Examples -------- >>> from cugraph.datasets import karate >>> G = karate.get_graph(download=True) >>> pos = cugraph.force_atlas2(G) """ input_graph, isNx = ensure_cugraph_obj_for_nx(input_graph) if pos_list is not None: if input_graph.renumbered is True: if input_graph.vertex_column_size() > 1: cols = pos_list.columns[:-2].to_list() else: cols = "vertex" pos_list = input_graph.add_internal_vertex_id(pos_list, "vertex", cols) if prevent_overlapping: raise Exception("Feature not supported") if input_graph.is_directed(): input_graph = input_graph.to_undirected() pos = force_atlas2_wrapper.force_atlas2( input_graph, max_iter=max_iter, pos_list=pos_list, outbound_attraction_distribution=outbound_attraction_distribution, lin_log_mode=lin_log_mode, prevent_overlapping=prevent_overlapping, edge_weight_influence=edge_weight_influence, jitter_tolerance=jitter_tolerance, barnes_hut_optimize=barnes_hut_optimize, barnes_hut_theta=barnes_hut_theta, scaling_ratio=scaling_ratio, strong_gravity_mode=strong_gravity_mode, gravity=gravity, verbose=verbose, callback=callback, ) if input_graph.renumbered: pos = input_graph.unrenumber(pos, "vertex") return pos
0
rapidsai_public_repos/cugraph/python/cugraph/cugraph
rapidsai_public_repos/cugraph/python/cugraph/cugraph/layout/__init__.py
# Copyright (c) 2019-2021, NVIDIA CORPORATION. # 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 cugraph.layout.force_atlas2 import force_atlas2
0
rapidsai_public_repos/cugraph/python/cugraph/cugraph
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests/conftest.py
# Copyright (c) 2021-2023, NVIDIA CORPORATION. # 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 pytest from cugraph.testing.mg_utils import ( start_dask_client, stop_dask_client, ) import os import tempfile # module-wide fixtures # Spoof the gpubenchmark fixture if it's not available so that asvdb and # rapids-pytest-benchmark do not need to be installed to run tests. if "gpubenchmark" not in globals(): def benchmark_func(func, *args, **kwargs): return func(*args, **kwargs) @pytest.fixture def gpubenchmark(): return benchmark_func @pytest.fixture(scope="module") def dask_client(): # start_dask_client will check for the SCHEDULER_FILE and # DASK_WORKER_DEVICES env vars and use them when creating a client if # set. start_dask_client will also initialize the Comms singleton. dask_client, dask_cluster = start_dask_client() yield dask_client stop_dask_client(dask_client, dask_cluster) @pytest.fixture(scope="module") def scratch_dir(): # This should always be set if doing MG testing, since temporary # directories are only accessible from the current process. tempdir_object = os.getenv( "RAPIDS_PYTEST_SCRATCH_DIR", tempfile.TemporaryDirectory() ) if isinstance(tempdir_object, tempfile.TemporaryDirectory): yield tempdir_object.name else: yield tempdir_object del tempdir_object
0
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests/layout/test_force_atlas2.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. # 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 time import pytest import cugraph from cugraph.structure import number_map from cugraph.internals import GraphBasedDimRedCallback from sklearn.manifold import trustworthiness import scipy.io from cugraph.datasets import ( karate, polbooks, dolphins, netscience, dining_prefs, ) # FIXME Removed the multi column positional due to it being non-deterministic # need to replace this coverage. Issue 3890 in cuGraph repo was created. # This method renumbers a dataframe so it can be tested using Trustworthiness. # it converts a dataframe with string vertex ids to a renumbered int one. def renumbered_edgelist(df): renumbered_df, num_map = number_map.NumberMap.renumber(df, "src", "dst") new_df = renumbered_df[["renumbered_src", "renumbered_dst", "wgt"]] column_names = {"renumbered_src": "src", "renumbered_dst": "dst"} new_df = new_df.rename(columns=column_names) return new_df # This method converts a dataframe to a sparce matrix that is required by # scipy Trustworthiness to verify the layout def get_coo_array(edgelist): coo = edgelist x = max(coo["src"].max(), coo["dst"].max()) + 1 row = coo["src"].to_numpy() col = coo["dst"].to_numpy() data = coo["wgt"].to_numpy() M = scipy.sparse.coo_array((data, (row, col)), shape=(x, x)) return M def cugraph_call( cu_M, max_iter, pos_list, outbound_attraction_distribution, lin_log_mode, prevent_overlapping, edge_weight_influence, jitter_tolerance, barnes_hut_theta, barnes_hut_optimize, scaling_ratio, strong_gravity_mode, gravity, callback=None, renumber=False, ): G = cugraph.Graph() if cu_M["src"] is not int or cu_M["dst"] is not int: renumber = True else: renumber = False G.from_cudf_edgelist( cu_M, source="src", destination="dst", edge_attr="wgt", renumber=renumber ) t1 = time.time() pos = cugraph.force_atlas2( G, max_iter=max_iter, pos_list=pos_list, outbound_attraction_distribution=outbound_attraction_distribution, lin_log_mode=lin_log_mode, prevent_overlapping=prevent_overlapping, edge_weight_influence=edge_weight_influence, jitter_tolerance=jitter_tolerance, barnes_hut_optimize=barnes_hut_optimize, barnes_hut_theta=barnes_hut_theta, scaling_ratio=scaling_ratio, strong_gravity_mode=strong_gravity_mode, gravity=gravity, callback=callback, ) t2 = time.time() - t1 print("Cugraph Time : " + str(t2)) return pos DATASETS = [ (karate, 0.70), (polbooks, 0.75), (dolphins, 0.66), (netscience, 0.66), (dining_prefs, 0.50), ] DATASETS2 = [ (polbooks, 0.75), (dolphins, 0.66), (netscience, 0.66), ] MAX_ITERATIONS = [500] BARNES_HUT_OPTIMIZE = [False, True] class TestCallback(GraphBasedDimRedCallback): def __init__(self): super(TestCallback, self).__init__() self.on_preprocess_end_called_count = 0 self.on_epoch_end_called_count = 0 self.on_train_end_called_count = 0 def on_preprocess_end(self, positions): self.on_preprocess_end_called_count += 1 def on_epoch_end(self, positions): self.on_epoch_end_called_count += 1 def on_train_end(self, positions): self.on_train_end_called_count += 1 @pytest.mark.sg @pytest.mark.parametrize("graph_file, score", DATASETS) @pytest.mark.parametrize("max_iter", MAX_ITERATIONS) @pytest.mark.parametrize("barnes_hut_optimize", BARNES_HUT_OPTIMIZE) def test_force_atlas2(graph_file, score, max_iter, barnes_hut_optimize): cu_M = graph_file.get_edgelist(download=True) test_callback = TestCallback() cu_pos = cugraph_call( cu_M, max_iter=max_iter, pos_list=None, outbound_attraction_distribution=True, lin_log_mode=False, prevent_overlapping=False, edge_weight_influence=1.0, jitter_tolerance=1.0, barnes_hut_optimize=False, barnes_hut_theta=0.5, scaling_ratio=2.0, strong_gravity_mode=False, gravity=1.0, callback=test_callback, ) """ Trustworthiness score can be used for Force Atlas 2 as the algorithm optimizes modularity. The final layout will result in different communities being drawn out. We consider here the n x n adjacency matrix of the graph as an embedding of the nodes in high dimension. The results of force atlas 2 corresponds to the layout in a 2d space. Here we check that nodes belonging to the same community or neighbors are close to each other in the final embedding. Thresholds are based on the best score that is achived after 500 iterations on a given graph. """ if "string" in graph_file.metadata["col_types"]: df = renumbered_edgelist(graph_file.get_edgelist(download=True)) M = get_coo_array(df) else: M = get_coo_array(graph_file.get_edgelist(download=True)) cu_trust = trustworthiness(M, cu_pos[["x", "y"]].to_pandas()) print(cu_trust, score) assert cu_trust > score # verify `on_preprocess_end` was only called once assert test_callback.on_preprocess_end_called_count == 1 # verify `on_epoch_end` was called on each iteration assert test_callback.on_epoch_end_called_count == max_iter # verify `on_train_end` was only called once assert test_callback.on_train_end_called_count == 1
0
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests/utils/test_utils_mg.py
# Copyright (c) 2018-2023, NVIDIA CORPORATION. # 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 gc import os import time import pytest import numpy as np import cugraph import dask_cudf import cugraph.dask as dcg from cugraph.testing import utils from cugraph.dask.common.mg_utils import is_single_gpu from cugraph.dask.common.read_utils import get_n_workers from dask.distributed import default_client, futures_of, wait from cugraph.testing.utils import RAPIDS_DATASET_ROOT_DIR_PATH from cugraph.dask.common.part_utils import concat_within_workers # ============================================================================= # Pytest Setup / Teardown - called for each test function # ============================================================================= def setup_function(): gc.collect() IS_DIRECTED = [True, False] # @pytest.mark.skipif( # is_single_gpu(), reason="skipping MG testing on Single GPU system" # ) @pytest.mark.mg @pytest.mark.parametrize("directed", IS_DIRECTED) def test_from_edgelist(dask_client, directed): input_data_path = (RAPIDS_DATASET_ROOT_DIR_PATH / "karate.csv").as_posix() print(f"dataset={input_data_path}") chunksize = dcg.get_chunksize(input_data_path) ddf = dask_cudf.read_csv( input_data_path, chunksize=chunksize, delimiter=" ", names=["src", "dst", "value"], dtype=["int32", "int32", "float32"], ) dg1 = cugraph.from_edgelist( ddf, source="src", destination="dst", edge_attr="value", create_using=cugraph.Graph(directed=directed), ) dg2 = cugraph.Graph(directed=directed) dg2.from_dask_cudf_edgelist(ddf, source="src", destination="dst", edge_attr="value") assert dg1.EdgeList == dg2.EdgeList @pytest.mark.mg @pytest.mark.skipif(is_single_gpu(), reason="skipping MG testing on Single GPU system") @pytest.mark.skip(reason="MG not supported on CI") def test_parquet_concat_within_workers(dask_client): if not os.path.exists("test_files_parquet"): print("Generate data... ") os.mkdir("test_files_parquet") for x in range(10): if not os.path.exists("test_files_parquet/df" + str(x)): df = utils.random_edgelist( e=100, ef=16, dtypes={"src": np.int32, "dst": np.int32}, seed=x ) df.to_parquet("test_files_parquet/df" + str(x), index=False) n_gpu = get_n_workers() print("Read_parquet... ") t1 = time.time() ddf = dask_cudf.read_parquet("test_files_parquet/*", dtype=["int32", "int32"]) ddf = ddf.persist() futures_of(ddf) wait(ddf) t1 = time.time() - t1 print("*** Read Time: ", t1, "s") print(ddf) assert ddf.npartitions > n_gpu print("Drop_duplicates... ") t2 = time.time() ddf.drop_duplicates(inplace=True) ddf = ddf.persist() futures_of(ddf) wait(ddf) t2 = time.time() - t2 print("*** Drop duplicate time: ", t2, "s") assert t2 < t1 print("Repartition... ") t3 = time.time() # Notice that ideally we would use : # ddf = ddf.repartition(npartitions=n_gpu) # However this is slower than reading and requires more memory # Using custom concat instead client = default_client() ddf = concat_within_workers(client, ddf) ddf = ddf.persist() futures_of(ddf) wait(ddf) t3 = time.time() - t3 print("*** repartition Time: ", t3, "s") print(ddf) assert t3 < t1
0
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests/utils/test_replication_mg.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. # 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 gc import pytest import cudf import cugraph import cugraph.testing.utils as utils import cugraph.dask.structure.replication as replication from cugraph.dask.common.mg_utils import is_single_gpu from cudf.testing import assert_series_equal, assert_frame_equal DATASETS_OPTIONS = utils.DATASETS_SMALL DIRECTED_GRAPH_OPTIONS = [False, True] @pytest.mark.mg @pytest.mark.skipif(is_single_gpu(), reason="skipping MG testing on Single GPU system") @pytest.mark.parametrize( "input_data_path", DATASETS_OPTIONS, ids=[f"dataset={d}" for d in DATASETS_OPTIONS] ) def test_replicate_cudf_dataframe_with_weights(input_data_path, dask_client): gc.collect() df = cudf.read_csv( input_data_path, delimiter=" ", names=["src", "dst", "value"], dtype=["int32", "int32", "float32"], ) worker_to_futures = replication.replicate_cudf_dataframe(df) for worker in worker_to_futures: replicated_df = worker_to_futures[worker].result() assert_frame_equal(df, replicated_df) @pytest.mark.mg @pytest.mark.skipif(is_single_gpu(), reason="skipping MG testing on Single GPU system") @pytest.mark.parametrize( "input_data_path", DATASETS_OPTIONS, ids=[f"dataset={d}" for d in DATASETS_OPTIONS] ) def test_replicate_cudf_dataframe_no_weights(input_data_path, dask_client): gc.collect() df = cudf.read_csv( input_data_path, delimiter=" ", names=["src", "dst"], dtype=["int32", "int32"], ) worker_to_futures = replication.replicate_cudf_dataframe(df) for worker in worker_to_futures: replicated_df = worker_to_futures[worker].result() assert_frame_equal(df, replicated_df) @pytest.mark.mg @pytest.mark.skipif(is_single_gpu(), reason="skipping MG testing on Single GPU system") @pytest.mark.parametrize( "input_data_path", DATASETS_OPTIONS, ids=[f"dataset={d}" for d in DATASETS_OPTIONS] ) def test_replicate_cudf_series(input_data_path, dask_client): gc.collect() df = cudf.read_csv( input_data_path, delimiter=" ", names=["src", "dst", "value"], dtype=["int32", "int32", "float32"], ) for column in df.columns.values: series = df[column] worker_to_futures = replication.replicate_cudf_series(series) for worker in worker_to_futures: replicated_series = worker_to_futures[worker].result() assert_series_equal(series, replicated_series, check_names=False) # FIXME: If we do not clear this dictionary, when comparing # results for the 2nd column, one of the workers still # has a value from the 1st column worker_to_futures = {} @pytest.mark.skip(reason="no way of currently testing this") @pytest.mark.parametrize( "graph_file", DATASETS_OPTIONS, ids=[f"dataset={d}" for d in DATASETS_OPTIONS] ) @pytest.mark.mg @pytest.mark.parametrize("directed", DIRECTED_GRAPH_OPTIONS) def test_enable_batch_no_context(graph_file, directed): gc.collect() G = utils.generate_cugraph_graph_from_file(graph_file, directed) assert G.batch_enabled is False, "Internal property should be False" with pytest.raises(Exception): G.enable_batch() @pytest.mark.skipif(is_single_gpu(), reason="skipping MG testing on Single GPU system") @pytest.mark.parametrize( "graph_file", DATASETS_OPTIONS, ids=[f"dataset={d}" for d in DATASETS_OPTIONS] ) @pytest.mark.mg @pytest.mark.parametrize("directed", DIRECTED_GRAPH_OPTIONS) def test_enable_batch_no_context_view_adj(graph_file, directed, dask_client): gc.collect() G = utils.generate_cugraph_graph_from_file(graph_file, directed) assert G.batch_enabled is False, "Internal property should be False" G.view_adj_list() @pytest.mark.mg @pytest.mark.skipif(is_single_gpu(), reason="skipping MG testing on Single GPU system") @pytest.mark.parametrize( "graph_file", DATASETS_OPTIONS, ids=[f"dataset={d}" for d in DATASETS_OPTIONS] ) @pytest.mark.parametrize("directed", DIRECTED_GRAPH_OPTIONS) def test_enable_batch_context_then_views(graph_file, directed, dask_client): gc.collect() G = utils.generate_cugraph_graph_from_file(graph_file, directed) assert G.batch_enabled is False, "Internal property should be False" G.enable_batch() assert G.batch_enabled is True, "Internal property should be True" assert G.batch_edgelists is not None, ( "The graph should have " "been created with an " "edgelist" ) assert G.batch_adjlists is None G.view_adj_list() assert G.batch_adjlists is not None assert G.batch_transposed_adjlists is None G.view_transposed_adj_list() assert G.batch_transposed_adjlists is not None @pytest.mark.mg @pytest.mark.skipif(is_single_gpu(), reason="skipping MG testing on Single GPU system") @pytest.mark.parametrize( "graph_file", DATASETS_OPTIONS, ids=[f"dataset={d}" for d in DATASETS_OPTIONS] ) @pytest.mark.parametrize("directed", DIRECTED_GRAPH_OPTIONS) def test_enable_batch_view_then_context(graph_file, directed, dask_client): gc.collect() G = utils.generate_cugraph_graph_from_file(graph_file, directed) assert G.batch_adjlists is None G.view_adj_list() assert G.batch_adjlists is None assert G.batch_transposed_adjlists is None G.view_transposed_adj_list() assert G.batch_transposed_adjlists is None assert G.batch_enabled is False, "Internal property should be False" G.enable_batch() assert G.batch_enabled is True, "Internal property should be True" assert G.batch_edgelists is not None, ( "The graph should have " "been created with an " "edgelist" ) assert G.batch_adjlists is not None assert G.batch_transposed_adjlists is not None @pytest.mark.mg @pytest.mark.skipif(is_single_gpu(), reason="skipping MG testing on Single GPU system") @pytest.mark.parametrize( "graph_file", DATASETS_OPTIONS, ids=[f"dataset={d}" for d in DATASETS_OPTIONS] ) @pytest.mark.parametrize("directed", DIRECTED_GRAPH_OPTIONS) def test_enable_batch_context_no_context_views(graph_file, directed, dask_client): gc.collect() G = utils.generate_cugraph_graph_from_file(graph_file, directed) assert G.batch_enabled is False, "Internal property should be False" G.enable_batch() assert G.batch_enabled is True, "Internal property should be True" assert G.batch_edgelists is not None, ( "The graph should have " "been created with an " "edgelist" ) G.view_edge_list() G.view_adj_list() G.view_transposed_adj_list() @pytest.mark.mg @pytest.mark.skipif(is_single_gpu(), reason="skipping MG testing on Single GPU system") @pytest.mark.parametrize( "graph_file", DATASETS_OPTIONS, ids=[f"dataset={d}" for d in DATASETS_OPTIONS] ) @pytest.mark.parametrize("directed", DIRECTED_GRAPH_OPTIONS) def test_enable_batch_edgelist_replication(graph_file, directed, dask_client): gc.collect() G = utils.generate_cugraph_graph_from_file(graph_file, directed) G.enable_batch() df = G.edgelist.edgelist_df for worker in G.batch_edgelists: replicated_df = G.batch_edgelists[worker].result() assert_frame_equal(df, replicated_df) @pytest.mark.mg @pytest.mark.skipif(is_single_gpu(), reason="skipping MG testing on Single GPU system") @pytest.mark.parametrize( "graph_file", DATASETS_OPTIONS, ids=[f"dataset={d}" for d in DATASETS_OPTIONS] ) @pytest.mark.parametrize("directed", DIRECTED_GRAPH_OPTIONS) def test_enable_batch_adjlist_replication_weights(graph_file, directed, dask_client): gc.collect() df = cudf.read_csv( graph_file, delimiter=" ", names=["src", "dst", "value"], dtype=["int32", "int32", "float32"], ) G = cugraph.Graph(directed=directed) G.from_cudf_edgelist(df, source="src", destination="dst", edge_attr="value") G.enable_batch() G.view_adj_list() adjlist = G.adjlist offsets = adjlist.offsets indices = adjlist.indices weights = adjlist.weights for worker in G.batch_adjlists: (rep_offsets, rep_indices, rep_weights) = G.batch_adjlists[worker] assert_series_equal(offsets, rep_offsets.result(), check_names=False) assert_series_equal(indices, rep_indices.result(), check_names=False) assert_series_equal(weights, rep_weights.result(), check_names=False) @pytest.mark.mg @pytest.mark.skipif(is_single_gpu(), reason="skipping MG testing on Single GPU system") @pytest.mark.parametrize( "graph_file", DATASETS_OPTIONS, ids=[f"dataset={d}" for d in DATASETS_OPTIONS] ) @pytest.mark.parametrize("directed", DIRECTED_GRAPH_OPTIONS) def test_enable_batch_adjlist_replication_no_weights(graph_file, directed, dask_client): gc.collect() df = cudf.read_csv( graph_file, delimiter=" ", names=["src", "dst"], dtype=["int32", "int32"], ) G = cugraph.Graph(directed=directed) G.from_cudf_edgelist(df, source="src", destination="dst") G.enable_batch() G.view_adj_list() adjlist = G.adjlist offsets = adjlist.offsets indices = adjlist.indices weights = adjlist.weights for worker in G.batch_adjlists: (rep_offsets, rep_indices, rep_weights) = G.batch_adjlists[worker] assert_series_equal(offsets, rep_offsets.result(), check_names=False) assert_series_equal(indices, rep_indices.result(), check_names=False) assert weights is None and rep_weights is None
0
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests/utils/test_resultset.py
# Copyright (c) 2023, NVIDIA CORPORATION. # 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 from pathlib import Path from tempfile import TemporaryDirectory import cudf from cugraph.datasets.dataset import ( set_download_dir, get_download_dir, ) from cugraph.testing.resultset import load_resultset, default_resultset_download_dir ############################################################################### def test_load_resultset(): with TemporaryDirectory() as tmpd: set_download_dir(Path(tmpd)) default_resultset_download_dir.path = Path(tmpd) / "tests" / "resultsets" default_resultset_download_dir.path.mkdir(parents=True, exist_ok=True) datasets_download_dir = get_download_dir() resultsets_download_dir = default_resultset_download_dir.path assert "tests" in os.listdir(datasets_download_dir) assert "resultsets.tar.gz" not in os.listdir(datasets_download_dir / "tests") assert "traversal_mappings.csv" not in os.listdir(resultsets_download_dir) load_resultset( "traversal", "https://data.rapids.ai/cugraph/results/resultsets.tar.gz" ) assert "resultsets.tar.gz" in os.listdir(datasets_download_dir / "tests") assert "traversal_mappings.csv" in os.listdir(resultsets_download_dir) def test_verify_resultset_load(): # This test is more detailed than test_load_resultset, where for each module, # we check that every single resultset file is included along with the # corresponding mapping file. with TemporaryDirectory() as tmpd: set_download_dir(Path(tmpd)) default_resultset_download_dir.path = Path(tmpd) / "tests" / "resultsets" default_resultset_download_dir.path.mkdir(parents=True, exist_ok=True) resultsets_download_dir = default_resultset_download_dir.path load_resultset( "traversal", "https://data.rapids.ai/cugraph/results/resultsets.tar.gz" ) resultsets = os.listdir(resultsets_download_dir) downloaded_results = cudf.read_csv( resultsets_download_dir / "traversal_mappings.csv", sep=" " ) downloaded_uuids = downloaded_results["#UUID"].values for resultset_uuid in downloaded_uuids: assert str(resultset_uuid) + ".csv" in resultsets
0
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests/utils/mg_context.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. # 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 time import pytest import cugraph.dask.comms as Comms from dask.distributed import Client from dask_cuda import LocalCUDACluster as CUDACluster from cugraph.dask.common.mg_utils import get_visible_devices # Maximal number of verifications of the number of workers DEFAULT_MAX_ATTEMPT = 100 # Time between each attempt in seconds DEFAULT_WAIT_TIME = 0.5 def skip_if_not_enough_devices(required_devices): if required_devices is not None: visible_devices = get_visible_devices() number_of_visible_devices = len(visible_devices) if required_devices > number_of_visible_devices: pytest.skip( "Not enough devices available to " "test MG({})".format(required_devices) ) class MGContext: """Utility Context Manager to start a multi GPU context using dask_cuda Parameters: ----------- number_of_devices : int Number of devices to use, verification must be done prior to call to ensure that there are enough devices available. If not specified, the cluster will be initialized to use all visible devices. rmm_managed_memory : bool True to enable managed memory (UVM) in RMM as part of the cluster. Default is False. p2p : bool Initialize UCX endpoints if True. Default is False. """ def __init__(self, number_of_devices=None, rmm_managed_memory=False, p2p=False): self._number_of_devices = number_of_devices self._rmm_managed_memory = rmm_managed_memory self._client = None self._p2p = p2p self._cluster = CUDACluster( n_workers=self._number_of_devices, rmm_managed_memory=self._rmm_managed_memory, ) @property def client(self): return self._client @property def cluster(self): return self._cluster def __enter__(self): self._prepare_mg() return self def _prepare_mg(self): self._prepare_client() self._prepare_comms() def _prepare_client(self): self._client = Client(self._cluster) self._client.wait_for_workers(self._number_of_devices) def _prepare_comms(self): Comms.initialize(p2p=self._p2p) def _close(self): Comms.destroy() if self._client is not None: self._client.close() if self._cluster is not None: self._cluster.close() def __exit__(self, type, value, traceback): self._close() # NOTE: This only looks for the number of workers # Tries to rescale the given cluster and wait until all workers are ready # or until the maximal number of attempts is reached def enforce_rescale( cluster, scale, max_attempts=DEFAULT_MAX_ATTEMPT, wait_time=DEFAULT_WAIT_TIME ): cluster.scale(scale) attempt = 0 ready = len(cluster.workers) == scale while (attempt < max_attempts) and not ready: time.sleep(wait_time) ready = len(cluster.workers) == scale attempt += 1 assert ready, "Unable to rescale cluster to {}".format(scale)
0
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests/utils/test_dataset.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # 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 gc from pathlib import Path from tempfile import TemporaryDirectory import pandas import pytest import cudf from cugraph.structure import Graph from cugraph.testing import ( RAPIDS_DATASET_ROOT_DIR_PATH, ALL_DATASETS, WEIGHTED_DATASETS, SMALL_DATASETS, BENCHMARKING_DATASETS, ) from cugraph import datasets # Add the sg marker to all tests in this module. pytestmark = pytest.mark.sg ############################################################################### # Fixtures # module fixture - called once for this module @pytest.fixture(scope="module") def tmpdir(): """ Create a tmp dir for downloads, etc., run a test, then cleanup when the test is done. """ tmpd = TemporaryDirectory() yield tmpd # teardown tmpd.cleanup() # function fixture - called once for each function in this module @pytest.fixture(scope="function", autouse=True) def setup(tmpdir): """ Fixture used for individual test setup and teardown. This ensures each Dataset object starts with the same state and cleans up when the test is done. """ # FIXME: this relies on dataset features (unload) which themselves are # being tested in this module. for dataset in ALL_DATASETS: dataset.unload() gc.collect() datasets.set_download_dir(tmpdir.name) yield # teardown for dataset in ALL_DATASETS: dataset.unload() gc.collect() ############################################################################### # Helpers # check if there is a row where src == dst def has_selfloop(dataset): if not dataset.metadata["is_directed"]: return False df = dataset.get_edgelist(download=True) df.rename(columns={df.columns[0]: "src", df.columns[1]: "dst"}, inplace=True) res = df.where(df["src"] == df["dst"]) return res.notnull().values.any() # check if dataset object is symmetric def is_symmetric(dataset): # undirected graphs are symmetric if not dataset.metadata["is_directed"]: return True else: df = dataset.get_edgelist(download=True) df_a = df.sort_values("src") # create df with swapped src/dst columns df_b = None if "wgt" in df_a.columns: df_b = df_a[["dst", "src", "wgt"]] else: df_b = df_a[["dst", "src"]] df_b.rename(columns={"dst": "src", "src": "dst"}, inplace=True) # created a df by appending the two res = cudf.concat([df_a, df_b]) # sort/unique res = res.drop_duplicates().sort_values("src") return len(df_a) == len(res) ############################################################################### # Tests # setting download_dir to None effectively re-initialized the default def test_env_var(): os.environ["RAPIDS_DATASET_ROOT_DIR"] = "custom_storage_location" datasets.set_download_dir(None) expected_path = Path("custom_storage_location").absolute() assert datasets.get_download_dir() == expected_path del os.environ["RAPIDS_DATASET_ROOT_DIR"] def test_home_dir(): datasets.set_download_dir(None) expected_path = Path.home() / ".cugraph/datasets" assert datasets.get_download_dir() == expected_path def test_set_download_dir(): tmpd = TemporaryDirectory() datasets.set_download_dir(tmpd.name) assert datasets.get_download_dir() == Path(tmpd.name).absolute() tmpd.cleanup() @pytest.mark.parametrize("dataset", ALL_DATASETS) def test_download(dataset): E = dataset.get_edgelist(download=True) assert E is not None assert dataset.get_path().is_file() @pytest.mark.parametrize("dataset", SMALL_DATASETS) def test_reader(dataset): # defaults to using cudf.read_csv E = dataset.get_edgelist(download=True) assert E is not None assert isinstance(E, cudf.core.dataframe.DataFrame) dataset.unload() # using pandas E_pd = dataset.get_edgelist(download=True, reader="pandas") assert E_pd is not None assert isinstance(E_pd, pandas.core.frame.DataFrame) dataset.unload() with pytest.raises(ValueError): dataset.get_edgelist(reader="fail") dataset.get_edgelist(reader=None) @pytest.mark.parametrize("dataset", ALL_DATASETS) def test_get_edgelist(dataset): E = dataset.get_edgelist(download=True) assert E is not None @pytest.mark.parametrize("dataset", ALL_DATASETS) def test_get_graph(dataset): G = dataset.get_graph(download=True) assert G is not None @pytest.mark.parametrize("dataset", ALL_DATASETS) def test_metadata(dataset): M = dataset.metadata assert M is not None @pytest.mark.parametrize("dataset", ALL_DATASETS) def test_get_path(dataset): tmpd = TemporaryDirectory() datasets.set_download_dir(tmpd.name) dataset.get_edgelist(download=True) assert dataset.get_path().is_file() tmpd.cleanup() @pytest.mark.parametrize("dataset", WEIGHTED_DATASETS) def test_weights(dataset): G = dataset.get_graph(download=True) assert G.is_weighted() G = dataset.get_graph(download=True, ignore_weights=True) assert not G.is_weighted() @pytest.mark.parametrize("dataset", SMALL_DATASETS) def test_create_using(dataset): G = dataset.get_graph(download=True) assert not G.is_directed() G = dataset.get_graph(download=True, create_using=Graph) assert not G.is_directed() G = dataset.get_graph(download=True, create_using=Graph(directed=True)) assert G.is_directed() def test_ctor_with_datafile(): from cugraph.datasets import karate karate_csv = RAPIDS_DATASET_ROOT_DIR_PATH / "karate.csv" # test that only a metadata file or csv can be specified, not both with pytest.raises(ValueError): datasets.Dataset(metadata_yaml_file="metadata_file", csv_file=karate_csv) # ensure at least one arg is provided with pytest.raises(ValueError): datasets.Dataset() # ensure csv file has all other required args (col names and col dtypes) with pytest.raises(ValueError): datasets.Dataset(csv_file=karate_csv) with pytest.raises(ValueError): datasets.Dataset(csv_file=karate_csv, csv_col_names=["src", "dst", "wgt"]) # test with file that DNE with pytest.raises(FileNotFoundError): datasets.Dataset( csv_file="/some/file/that/does/not/exist", csv_col_names=["src", "dst", "wgt"], csv_col_dtypes=["int32", "int32", "float32"], ) expected_karate_edgelist = karate.get_edgelist(download=True) # test with file path as string, ensure download=True does not break ds = datasets.Dataset( csv_file=karate_csv.as_posix(), csv_col_names=["src", "dst", "wgt"], csv_col_dtypes=["int32", "int32", "float32"], ) # cudf.testing.testing.assert_frame_equal() would be good to use to # compare, but for some reason it seems to be holding a reference to a # dataframe and gc.collect() does not free everything el = ds.get_edgelist() assert len(el) == len(expected_karate_edgelist) assert str(ds) == "karate" assert ds.get_path() == karate_csv # test with file path as Path object ds = datasets.Dataset( csv_file=karate_csv, csv_col_names=["src", "dst", "wgt"], csv_col_dtypes=["int32", "int32", "float32"], ) el = ds.get_edgelist() assert len(el) == len(expected_karate_edgelist) assert str(ds) == "karate" assert ds.get_path() == karate_csv def test_unload(): email_csv = RAPIDS_DATASET_ROOT_DIR_PATH / "email-Eu-core.csv" ds = datasets.Dataset( csv_file=email_csv.as_posix(), csv_col_names=["src", "dst", "wgt"], csv_col_dtypes=["int32", "int32", "float32"], ) # FIXME: another (better?) test would be to check free memory and assert # the memory use increases after get_*(), then returns to the pre-get_*() # level after unload(). However, that type of test may fail for several # reasons (the device being monitored is accidentally also being used by # another process, and the use of memory pools to name two). Instead, just # test that the internal members get cleared on unload(). assert ds._edgelist is None ds.get_edgelist() assert ds._edgelist is not None ds.unload() assert ds._edgelist is None ds.get_graph() assert ds._edgelist is not None ds.unload() assert ds._edgelist is None @pytest.mark.parametrize("dataset", ALL_DATASETS) def test_node_and_edge_count(dataset): dataset_is_directed = dataset.metadata["is_directed"] G = dataset.get_graph( download=True, create_using=Graph(directed=dataset_is_directed) ) assert G.number_of_nodes() == dataset.metadata["number_of_nodes"] assert G.number_of_edges() == dataset.metadata["number_of_edges"] @pytest.mark.parametrize("dataset", ALL_DATASETS) def test_is_directed(dataset): dataset_is_directed = dataset.metadata["is_directed"] G = dataset.get_graph( download=True, create_using=Graph(directed=dataset_is_directed) ) assert G.is_directed() == dataset.metadata["is_directed"] @pytest.mark.parametrize("dataset", ALL_DATASETS) def test_has_selfloop(dataset): assert has_selfloop(dataset) == dataset.metadata["has_loop"] @pytest.mark.parametrize("dataset", ALL_DATASETS) def test_is_symmetric(dataset): assert is_symmetric(dataset) == dataset.metadata["is_symmetric"] @pytest.mark.parametrize("dataset", ALL_DATASETS) def test_is_multigraph(dataset): G = dataset.get_graph(download=True) assert G.is_multigraph() == dataset.metadata["is_multigraph"] # The datasets used for benchmarks are in their own test, since downloading them # repeatedly would increase testing overhead significantly @pytest.mark.parametrize("dataset", BENCHMARKING_DATASETS) def test_benchmarking_datasets(dataset): dataset_is_directed = dataset.metadata["is_directed"] G = dataset.get_graph( download=True, create_using=Graph(directed=dataset_is_directed) ) assert G.is_directed() == dataset.metadata["is_directed"] assert G.number_of_nodes() == dataset.metadata["number_of_nodes"] assert G.number_of_edges() == dataset.metadata["number_of_edges"] assert has_selfloop(dataset) == dataset.metadata["has_loop"] assert is_symmetric(dataset) == dataset.metadata["is_symmetric"] assert G.is_multigraph() == dataset.metadata["is_multigraph"] dataset.unload() @pytest.mark.parametrize("dataset", ALL_DATASETS) def test_object_getters(dataset): assert dataset.is_directed() == dataset.metadata["is_directed"] assert dataset.is_multigraph() == dataset.metadata["is_multigraph"] assert dataset.is_symmetric() == dataset.metadata["is_symmetric"] assert dataset.number_of_nodes() == dataset.metadata["number_of_nodes"] assert dataset.number_of_vertices() == dataset.metadata["number_of_nodes"] assert dataset.number_of_edges() == dataset.metadata["number_of_edges"]
0
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests/utils/test_utils.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. # 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 gc import pytest import numpy as np import cudf import cugraph from cugraph.testing import utils from cugraph.datasets import karate @pytest.mark.sg def test_bfs_paths(): with pytest.raises(ValueError) as ErrorMsg: gc.collect() G = karate.get_graph() # run BFS starting at vertex 17 df = cugraph.bfs(G, 16) # Get the path to vertex 1 p_df = cugraph.utils.get_traversed_path(df, 0) assert len(p_df) == 3 # Get path to vertex 0 - which is not in graph p_df = cugraph.utils.get_traversed_path(df, 100) assert "not in the result set" in str(ErrorMsg) @pytest.mark.sg def test_bfs_paths_array(): with pytest.raises(ValueError) as ErrorMsg: gc.collect() G = karate.get_graph() # run BFS starting at vertex 17 df = cugraph.bfs(G, 16) # Get the path to vertex 1 answer = cugraph.utils.get_traversed_path_list(df, 0) assert len(answer) == 3 # Get path to vertex 0 - which is not in graph answer = cugraph.utils.get_traversed_path_list(df, 100) assert "not in the result set" in str(ErrorMsg) @pytest.mark.sg @pytest.mark.parametrize("graph_file", utils.DATASETS) @pytest.mark.skip(reason="Skipping large tests") def test_get_traversed_cost(graph_file): cu_M = utils.read_csv_file(graph_file) noise = cudf.Series(np.random.randint(10, size=(cu_M.shape[0]))) cu_M["info"] = cu_M["2"] + noise G = cugraph.Graph() G.from_cudf_edgelist(cu_M, source="0", destination="1", edge_attr="info") # run SSSP starting at vertex 17 df = cugraph.sssp(G, 16) answer = cugraph.utilities.path_retrieval.get_traversed_cost( df, 16, cu_M["0"], cu_M["1"], cu_M["info"] ) df = df.sort_values(by="vertex").reset_index() answer = answer.sort_values(by="vertex").reset_index() assert df.shape[0] == answer.shape[0] assert np.allclose(df["distance"], answer["info"])
0
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests/linear/test_hungarian.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. # 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 gc from timeit import default_timer as timer import numpy as np import pytest import cudf import cugraph from scipy.optimize import linear_sum_assignment def create_random_bipartite(v1, v2, size, dtype): # # Create a full bipartite graph # df1 = cudf.DataFrame() df1["src"] = cudf.Series(range(0, v1, 1)) df1["key"] = 1 df2 = cudf.DataFrame() df2["dst"] = cudf.Series(range(v1, v1 + v2, 1)) df2["key"] = 1 edges = df1.merge(df2, on="key")[["src", "dst"]] edges = edges.sort_values(["src", "dst"]).reset_index() # Generate edge weights a = np.random.randint(1, high=size, size=(v1, v2)).astype(dtype) edges["weight"] = a.flatten() g = cugraph.Graph() g.from_cudf_edgelist( edges, source="src", destination="dst", edge_attr="weight", renumber=False ) return df1["src"], g, a SPARSE_SIZES = [[5, 5, 100], [500, 500, 10000]] DENSE_SIZES = [[5, 100], [500, 10000]] def setup_function(): gc.collect() @pytest.mark.sg @pytest.mark.parametrize("v1_size, v2_size, weight_limit", SPARSE_SIZES) def test_hungarian(v1_size, v2_size, weight_limit): v1, g, m = create_random_bipartite(v1_size, v2_size, weight_limit, np.float64) start = timer() cugraph_cost, matching = cugraph.hungarian(g, v1) end = timer() print("cugraph time: ", (end - start)) start = timer() np_matching = linear_sum_assignment(m) end = timer() print("scipy time: ", (end - start)) scipy_cost = m[np_matching[0], np_matching[1]].sum() assert scipy_cost == cugraph_cost @pytest.mark.sg @pytest.mark.parametrize("n, weight_limit", DENSE_SIZES) def test_dense_hungarian(n, weight_limit): C = np.random.uniform(0, weight_limit, size=(n, n)).round().astype(np.float32) C_series = cudf.Series(C.flatten()) start = timer() cugraph_cost, matching = cugraph.dense_hungarian(C_series, n, n) end = timer() print("cugraph time: ", (end - start)) start = timer() np_matching = linear_sum_assignment(C) end = timer() print("scipy time: ", (end - start)) scipy_cost = C[np_matching[0], np_matching[1]].sum() assert scipy_cost == cugraph_cost
0
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests/gnn/test_dgl_uniform_sampler.py
# Copyright (c) 2023, NVIDIA CORPORATION. # 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 pytest import pandas as pd import numpy as np import cudf import cupy as cp from cugraph.gnn.dgl_extensions.dgl_uniform_sampler import DGLUniformSampler def assert_correct_eids(edge_df, sample_edge_id_df): # We test that all src, dst correspond to the correct # eids in the sample_edge_id_df # we do this by ensuring that the inner merge to edge_df # remains the same as sample_edge_id_df # if they don't correspond correctly # the inner merge would fail sample_edge_id_df = sample_edge_id_df.sort_values(by="_EDGE_ID_") sample_edge_id_df = sample_edge_id_df.reset_index(drop=True) sample_merged_df = sample_edge_id_df.merge(edge_df, how="inner") sample_merged_df = sample_merged_df.sort_values(by="_EDGE_ID_") sample_merged_df = sample_merged_df.reset_index(drop=True) assert sample_merged_df.equals(sample_edge_id_df) def convert_array_dict_to_df(d): df_d = { k: cudf.DataFrame({"_SRC_": s, "_DST_": d, "_EDGE_ID_": e}) for k, (s, d, e) in d.items() } return df_d @pytest.mark.sg def test_sampling_homogeneous_gs_out_dir(): src_ser = cudf.Series([1, 1, 1, 1, 1, 2, 2, 3]) dst_ser = cudf.Series([2, 3, 4, 5, 6, 3, 4, 7]) df = cudf.DataFrame( {"_SRC_": src_ser, "_DST_": dst_ser, "_EDGE_ID_": np.arange(len(src_ser))} ) sampler = DGLUniformSampler( {("_N", "connects", "_N"): df}, {("_N", "connects", "_N"): (0, 8)}, {(("_N", "connects", "_N")): 1}, True, ) # below are obtained from dgl runs on the same graph expected_out = { 1: ([1, 1, 1, 1, 1], [2, 3, 4, 5, 6]), 2: ([2, 2], [3, 4]), 3: ([3], [7]), 4: ([], []), } for seed in expected_out.keys(): seed_cap = cudf.Series([seed]).to_dlpack() sample_src, sample_dst, sample_eid = sampler.sample_neighbors( seed_cap, fanout=9, edge_dir="out" ) output_df = cudf.DataFrame({"src": sample_src, "dst": sample_dst}).astype( np.int64 ) output_df = output_df.sort_values(by=["src", "dst"]) output_df = output_df.reset_index(drop=True) expected_df = cudf.DataFrame( {"src": expected_out[seed][0], "dst": expected_out[seed][1]} ).astype(np.int64) cudf.testing.assert_frame_equal(output_df, expected_df) sample_edge_id_df = cudf.DataFrame( {"_SRC_": sample_src, "_DST_": sample_dst, "_EDGE_ID_": sample_eid} ) assert_correct_eids(df, sample_edge_id_df) @pytest.mark.sg def test_sampling_homogeneous_gs_in_dir(): src_ser = cudf.Series([1, 1, 1, 1, 1, 2, 2, 3]) dst_ser = cudf.Series([2, 3, 4, 5, 6, 3, 4, 7]) df = cudf.DataFrame( {"_SRC_": src_ser, "_DST_": dst_ser, "_EDGE_ID_": np.arange(len(src_ser))} ) sampler = DGLUniformSampler( {("_N", "connects", "_N"): df}, {("_N", "connects", "_N"): (0, 8)}, {("_N", "connects", "_N"): 1}, True, ) # below are obtained from dgl runs on the same graph expected_in = { 1: ([], []), 2: ([1], [2]), 3: ([1, 2], [3, 3]), 4: ([1, 2], [4, 4]), } for seed in expected_in.keys(): seed_cap = cudf.Series([seed]).to_dlpack() sample_src, sample_dst, sample_eid = sampler.sample_neighbors( seed_cap, fanout=9, edge_dir="in" ) output_df = cudf.DataFrame({"_SRC_": sample_src, "_DST_": sample_dst}).astype( np.int64 ) output_df = output_df.sort_values(by=["_SRC_", "_DST_"]) output_df = output_df.reset_index(drop=True) expected_df = cudf.DataFrame( {"_SRC_": expected_in[seed][0], "_DST_": expected_in[seed][1]} ).astype(np.int64) cudf.testing.assert_frame_equal(output_df, expected_df) sample_edge_id_df = cudf.DataFrame( {"_SRC_": sample_src, "_DST_": sample_dst, "_EDGE_ID_": sample_eid} ) assert_correct_eids(df, sample_edge_id_df) def create_gs_heterogeneous_dgl_sampler(): # Add Edge Data src_ser = [0, 1, 2, 0, 1, 2, 7, 9, 10, 11] dst_ser = [3, 4, 5, 6, 7, 8, 6, 6, 6, 6] etype_ser = [0, 0, 0, 1, 1, 1, 2, 2, 2, 2] etype_map = { 0: ("nt.a", "connects", "nt.b"), 1: ("nt.a", "connects", "nt.c"), 2: ("nt.c", "connects", "nt.c"), } df = pd.DataFrame({"_SRC_": src_ser, "_DST_": dst_ser, "etype": etype_ser}) etype_offset = 0 edge_id_range_dict = {} edge_list_dict = {} for e in df["etype"].unique(): subset_df = df[df["etype"] == e][["_SRC_", "_DST_"]] subset_df = cudf.DataFrame.from_pandas(subset_df) subset_df["_EDGE_ID_"] = cp.arange(0, len(subset_df)) + etype_offset edge_list_dict[etype_map[e]] = subset_df edge_id_range_dict[etype_map[e]] = (etype_offset, etype_offset + len(subset_df)) etype_offset = etype_offset + len(subset_df) etype_id_dict = {e: i for i, e in enumerate(edge_list_dict.keys())} return DGLUniformSampler(edge_list_dict, edge_id_range_dict, etype_id_dict, True) @pytest.mark.sg def test_sampling_gs_heterogeneous_out_dir(): sampler = create_gs_heterogeneous_dgl_sampler() # DGL expected_output from # https://gist.github.com/VibhuJawa/f85fda8e1183886078f2a34c28c4638c expeced_val_d = { 0: { ("nt.a", "connects", "nt.b"): ( cudf.Series([0], dtype=np.int32), cudf.Series([3], dtype=np.int32), ), ("nt.a", "connects", "nt.c"): ( cudf.Series([0]), cudf.Series([6]), ), ("nt.c", "connects", "nt.c"): (cudf.Series([]), cudf.Series([])), }, 1: { ("nt.a", "connects", "nt.b"): ( cudf.Series([1], dtype=np.int32), cudf.Series([4], dtype=np.int32), ), ("nt.a", "connects", "nt.c"): ( cudf.Series([1]), cudf.Series([7]), ), ("nt.c", "connects", "nt.c"): ( cudf.Series([], dtype=np.int32), cudf.Series([], dtype=np.int32), ), }, 2: { ("nt.a", "connects", "nt.b"): ( cudf.Series([2], dtype=np.int32), cudf.Series([5], dtype=np.int32), ), ("nt.a", "connects", "nt.c"): ( cudf.Series([2]), cudf.Series([8]), ), ("nt.c", "connects", "nt.c"): ( cudf.Series([], dtype=np.int32), cudf.Series([], dtype=np.int32), ), }, } for seed in expeced_val_d.keys(): fanout = 4 sampled_node_p = cudf.Series(seed).astype(np.int32).to_dlpack() sampled_g = sampler.sample_neighbors( {"nt.a": sampled_node_p}, fanout=fanout, edge_dir="out" ) sampled_g = convert_array_dict_to_df(sampled_g) for etype, df in sampled_g.items(): output_df = ( df[["_SRC_", "_DST_"]] .sort_values(by=["_SRC_", "_DST_"]) .reset_index(drop=True) .astype(np.int32) ) expected_df = cudf.DataFrame( { "_SRC_": expeced_val_d[seed][etype][0], "_DST_": expeced_val_d[seed][etype][1], } ).astype(np.int32) cudf.testing.assert_frame_equal(output_df, expected_df) @pytest.mark.sg def test_sampling_gs_heterogeneous_in_dir(): sampler = create_gs_heterogeneous_dgl_sampler() # DGL expected_output from # https://gist.github.com/VibhuJawa/f85fda8e1183886078f2a34c28c4638c expeced_val_d = { 6: { ("nt.a", "connects", "nt.b"): ( cudf.Series([], dtype=np.int32), cudf.Series([], dtype=np.int32), ), ("nt.a", "connects", "nt.c"): ( cudf.Series([0]), cudf.Series([6]), ), ("nt.c", "connects", "nt.c"): ( cudf.Series([7, 9, 10, 11]), cudf.Series([6, 6, 6, 6]), ), }, 7: { ("nt.a", "connects", "nt.b"): ( cudf.Series([], dtype=np.int32), cudf.Series([], dtype=np.int32), ), ("nt.a", "connects", "nt.c"): ( cudf.Series([1]), cudf.Series([7]), ), ("nt.c", "connects", "nt.c"): ( cudf.Series([], dtype=np.int32), cudf.Series([], dtype=np.int32), ), }, } for seed in expeced_val_d.keys(): fanout = 4 sampled_node_p = cudf.Series(seed).astype(np.int32).to_dlpack() sampled_g = sampler.sample_neighbors( {"nt.c": sampled_node_p}, fanout=fanout, edge_dir="in" ) sampled_g = convert_array_dict_to_df(sampled_g) for etype, df in sampled_g.items(): output_df = ( df[["_SRC_", "_DST_"]] .sort_values(by=["_SRC_", "_DST_"]) .reset_index(drop=True) .astype(np.int32) ) expected_df = cudf.DataFrame( { "_SRC_": expeced_val_d[seed][etype][0], "_DST_": expeced_val_d[seed][etype][1], } ).astype(np.int32) cudf.testing.assert_frame_equal(output_df, expected_df) @pytest.mark.sg def test_sampling_dgl_heterogeneous_gs_m_fanouts(): gs = create_gs_heterogeneous_dgl_sampler() # Test against DGLs output # See below notebook # https://gist.github.com/VibhuJawa/f85fda8e1183886078f2a34c28c4638c expected_output = { 1: { ("nt.a", "connects", "nt.b"): 0, ("nt.a", "connects", "nt.c"): 1, ("nt.c", "connects", "nt.c"): 1, }, 2: { ("nt.a", "connects", "nt.b"): 0, ("nt.a", "connects", "nt.c"): 1, ("nt.c", "connects", "nt.c"): 2, }, 3: { ("nt.a", "connects", "nt.b"): 0, ("nt.a", "connects", "nt.c"): 1, ("nt.c", "connects", "nt.c"): 3, }, -1: { ("nt.a", "connects", "nt.b"): 0, ("nt.a", "connects", "nt.c"): 1, ("nt.c", "connects", "nt.c"): 4, }, } for fanout in [1, 2, 3, -1]: sampled_node = [6] sampled_node_p = cudf.Series(sampled_node) sampled_g = gs.sample_neighbors({"nt.c": sampled_node_p}, fanout=fanout) sampled_g = convert_array_dict_to_df(sampled_g) for etype, output_df in sampled_g.items(): assert expected_output[fanout][etype] == len(output_df)
0
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests/gnn/test_dgl_uniform_sampler_mg.py
# Copyright (c) 2023, NVIDIA CORPORATION. # 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 pytest import pandas as pd import numpy as np import dask_cudf import cudf import cupy as cp from cugraph.gnn.dgl_extensions.dgl_uniform_sampler import DGLUniformSampler def assert_correct_eids(edge_df, sample_edge_id_df): # We test that all src, dst correspond to the correct # eids in the sample_edge_id_df # we do this by ensuring that the inner merge to edge_df # remains the same as sample_edge_id_df # if they don't correspond correctly # the inner merge would fail sample_edge_id_df = sample_edge_id_df.sort_values(by="_EDGE_ID_") sample_edge_id_df = sample_edge_id_df.reset_index(drop=True) sample_merged_df = sample_edge_id_df.merge(edge_df, how="inner") sample_merged_df = sample_merged_df.sort_values(by="_EDGE_ID_") sample_merged_df = sample_merged_df.reset_index(drop=True) assert sample_merged_df.equals(sample_edge_id_df) def convert_array_dict_to_df(d): df_d = { k: cudf.DataFrame({"_SRC_": s, "_DST_": d, "_EDGE_ID_": e}) for k, (s, d, e) in d.items() } return df_d @pytest.mark.mg def test_sampling_homogeneous_gs_out_dir(dask_client): src_ser = cudf.Series([1, 1, 1, 1, 1, 2, 2, 3]) dst_ser = cudf.Series([2, 3, 4, 5, 6, 3, 4, 7]) df = cudf.DataFrame( {"_SRC_": src_ser, "_DST_": dst_ser, "_EDGE_ID_": np.arange(len(src_ser))} ) df = dask_cudf.from_cudf(df, 4) sampler = DGLUniformSampler( {("_N", "connects", "_N"): df}, {("_N", "connects", "_N"): (0, 8)}, {("_N", "connects", "_N"): 1}, False, ) # below are obtained from dgl runs on the same graph expected_out = { 1: ([1, 1, 1, 1, 1], [2, 3, 4, 5, 6]), 2: ([2, 2], [3, 4]), 3: ([3], [7]), 4: ([], []), } for seed in expected_out.keys(): seed_cap = cudf.Series([seed]).to_dlpack() sample_src, sample_dst, sample_eid = sampler.sample_neighbors( seed_cap, fanout=9, edge_dir="out" ) output_df = cudf.DataFrame({"src": sample_src, "dst": sample_dst}).astype( np.int64 ) output_df = output_df.sort_values(by=["src", "dst"]) output_df = output_df.reset_index(drop=True) expected_df = cudf.DataFrame( {"src": expected_out[seed][0], "dst": expected_out[seed][1]} ).astype(np.int64) cudf.testing.assert_frame_equal(output_df, expected_df) sample_edge_id_df = cudf.DataFrame( {"_SRC_": sample_src, "_DST_": sample_dst, "_EDGE_ID_": sample_eid} ) assert_correct_eids(df.compute(), sample_edge_id_df) @pytest.mark.mg def test_sampling_homogeneous_gs_in_dir(dask_client): src_ser = cudf.Series([1, 1, 1, 1, 1, 2, 2, 3]) dst_ser = cudf.Series([2, 3, 4, 5, 6, 3, 4, 7]) df = cudf.DataFrame( {"_SRC_": src_ser, "_DST_": dst_ser, "_EDGE_ID_": np.arange(len(src_ser))} ) df = dask_cudf.from_cudf(df, 4) sampler = DGLUniformSampler( {("_N", "connects", "_N"): df}, {("_N", "connects", "_N"): (0, 8)}, {("_N", "connects", "_N"): 1}, False, ) # below are obtained from dgl runs on the same graph expected_in = { 1: ([], []), 2: ([1], [2]), 3: ([1, 2], [3, 3]), 4: ([1, 2], [4, 4]), } for seed in expected_in.keys(): seed_cap = cudf.Series([seed]).to_dlpack() sample_src, sample_dst, sample_eid = sampler.sample_neighbors( seed_cap, fanout=9, edge_dir="in" ) output_df = cudf.DataFrame({"_SRC_": sample_src, "_DST_": sample_dst}).astype( np.int64 ) output_df = output_df.sort_values(by=["_SRC_", "_DST_"]) output_df = output_df.reset_index(drop=True) expected_df = cudf.DataFrame( {"_SRC_": expected_in[seed][0], "_DST_": expected_in[seed][1]} ).astype(np.int64) cudf.testing.assert_frame_equal(output_df, expected_df) sample_edge_id_df = cudf.DataFrame( {"_SRC_": sample_src, "_DST_": sample_dst, "_EDGE_ID_": sample_eid} ) assert_correct_eids(df.compute(), sample_edge_id_df) def create_gs_heterogeneous_dgl_sampler(): # Add Edge Data src_ser = [0, 1, 2, 0, 1, 2, 7, 9, 10, 11] dst_ser = [3, 4, 5, 6, 7, 8, 6, 6, 6, 6] etype_ser = [0, 0, 0, 1, 1, 1, 2, 2, 2, 2] etype_map = { 0: ("nt.a", "connects", "nt.b"), 1: ("nt.a", "connects", "nt.c"), 2: ("nt.c", "connects", "nt.c"), } df = pd.DataFrame({"_SRC_": src_ser, "_DST_": dst_ser, "etype": etype_ser}) etype_offset = 0 edge_id_range_dict = {} edge_list_dict = {} for e in df["etype"].unique(): subset_df = df[df["etype"] == e][["_SRC_", "_DST_"]] subset_df = cudf.DataFrame.from_pandas(subset_df) subset_df["_EDGE_ID_"] = cp.arange(0, len(subset_df)) + etype_offset subset_df = dask_cudf.from_cudf(subset_df, 4) edge_list_dict[etype_map[e]] = subset_df edge_id_range_dict[etype_map[e]] = (etype_offset, etype_offset + len(subset_df)) etype_offset = etype_offset + len(subset_df) etype_id_dict = {value: key for key, value in etype_map.items()} return DGLUniformSampler(edge_list_dict, edge_id_range_dict, etype_id_dict, False) @pytest.mark.mg def test_sampling_gs_heterogeneous_out_dir(dask_client): sampler = create_gs_heterogeneous_dgl_sampler() # DGL expected_output from # https://gist.github.com/VibhuJawa/f85fda8e1183886078f2a34c28c4638c expeced_val_d = { 0: { ("nt.a", "connects", "nt.b"): ( cudf.Series([0], dtype=np.int32), cudf.Series([3], dtype=np.int32), ), ("nt.a", "connects", "nt.c"): ( cudf.Series([0]), cudf.Series([6]), ), ("nt.c", "connects", "nt.c"): (cudf.Series([]), cudf.Series([])), }, 1: { ("nt.a", "connects", "nt.b"): ( cudf.Series([1], dtype=np.int32), cudf.Series([4], dtype=np.int32), ), ("nt.a", "connects", "nt.c"): ( cudf.Series([1]), cudf.Series([7]), ), ("nt.c", "connects", "nt.c"): ( cudf.Series([], dtype=np.int32), cudf.Series([], dtype=np.int32), ), }, 2: { ("nt.a", "connects", "nt.b"): ( cudf.Series([2], dtype=np.int32), cudf.Series([5], dtype=np.int32), ), ("nt.a", "connects", "nt.c"): ( cudf.Series([2]), cudf.Series([8]), ), ("nt.c", "connects", "nt.c"): ( cudf.Series([], dtype=np.int32), cudf.Series([], dtype=np.int32), ), }, } for seed in expeced_val_d.keys(): fanout = 4 sampled_node_p = cudf.Series(seed).astype(np.int32).to_dlpack() sampled_g = sampler.sample_neighbors( {"nt.a": sampled_node_p}, fanout=fanout, edge_dir="out" ) sampled_g = convert_array_dict_to_df(sampled_g) for etype, df in sampled_g.items(): output_df = ( df[["_SRC_", "_DST_"]] .sort_values(by=["_SRC_", "_DST_"]) .reset_index(drop=True) .astype(np.int32) ) expected_df = cudf.DataFrame( { "_SRC_": expeced_val_d[seed][etype][0], "_DST_": expeced_val_d[seed][etype][1], } ).astype(np.int32) cudf.testing.assert_frame_equal(output_df, expected_df) @pytest.mark.mg def test_sampling_gs_heterogeneous_in_dir(dask_client): sampler = create_gs_heterogeneous_dgl_sampler() # DGL expected_output from # https://gist.github.com/VibhuJawa/f85fda8e1183886078f2a34c28c4638c expeced_val_d = { 6: { ("nt.a", "connects", "nt.b"): ( cudf.Series([], dtype=np.int32), cudf.Series([], dtype=np.int32), ), ("nt.a", "connects", "nt.c"): ( cudf.Series([0]), cudf.Series([6]), ), ("nt.c", "connects", "nt.c"): ( cudf.Series([7, 9, 10, 11]), cudf.Series([6, 6, 6, 6]), ), }, 7: { ("nt.a", "connects", "nt.b"): ( cudf.Series([], dtype=np.int32), cudf.Series([], dtype=np.int32), ), ("nt.a", "connects", "nt.c"): ( cudf.Series([1]), cudf.Series([7]), ), ("nt.c", "connects", "nt.c"): ( cudf.Series([], dtype=np.int32), cudf.Series([], dtype=np.int32), ), }, } for seed in expeced_val_d.keys(): fanout = 4 sampled_node_p = cudf.Series(seed).astype(np.int32).to_dlpack() sampled_g = sampler.sample_neighbors( {"nt.c": sampled_node_p}, fanout=fanout, edge_dir="in" ) sampled_g = convert_array_dict_to_df(sampled_g) for etype, df in sampled_g.items(): output_df = ( df[["_SRC_", "_DST_"]] .sort_values(by=["_SRC_", "_DST_"]) .reset_index(drop=True) .astype(np.int32) ) expected_df = cudf.DataFrame( { "_SRC_": expeced_val_d[seed][etype][0], "_DST_": expeced_val_d[seed][etype][1], } ).astype(np.int32) cudf.testing.assert_frame_equal(output_df, expected_df) @pytest.mark.mg def test_sampling_dgl_heterogeneous_gs_m_fanouts(dask_client): gs = create_gs_heterogeneous_dgl_sampler() # Test against DGLs output # See below notebook # https://gist.github.com/VibhuJawa/f85fda8e1183886078f2a34c28c4638c expected_output = { 1: { ("nt.a", "connects", "nt.b"): 0, ("nt.a", "connects", "nt.c"): 1, ("nt.c", "connects", "nt.c"): 1, }, 2: { ("nt.a", "connects", "nt.b"): 0, ("nt.a", "connects", "nt.c"): 1, ("nt.c", "connects", "nt.c"): 2, }, 3: { ("nt.a", "connects", "nt.b"): 0, ("nt.a", "connects", "nt.c"): 1, ("nt.c", "connects", "nt.c"): 3, }, -1: { ("nt.a", "connects", "nt.b"): 0, ("nt.a", "connects", "nt.c"): 1, ("nt.c", "connects", "nt.c"): 4, }, } for fanout in [1, 2, 3, -1]: sampled_node = [6] sampled_node_p = cudf.Series(sampled_node) sampled_g = gs.sample_neighbors({"nt.c": sampled_node_p}, fanout=fanout) sampled_g = convert_array_dict_to_df(sampled_g) for etype, output_df in sampled_g.items(): assert expected_output[fanout][etype] == len(output_df)
0
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests
rapidsai_public_repos/cugraph/python/cugraph/cugraph/tests/components/test_connectivity.py
# Copyright (c) 2019-2023, NVIDIA CORPORATION. # 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 gc import time from collections import defaultdict import pytest import cupy as cp import numpy as np import networkx as nx from cupyx.scipy.sparse import coo_matrix as cp_coo_matrix from cupyx.scipy.sparse import csr_matrix as cp_csr_matrix from cupyx.scipy.sparse import csc_matrix as cp_csc_matrix from scipy.sparse import coo_matrix as sp_coo_matrix from scipy.sparse import csr_matrix as sp_csr_matrix from scipy.sparse import csc_matrix as sp_csc_matrix from cugraph.utilities import is_nx_graph_type import cudf import cugraph from cugraph.testing import utils, DEFAULT_DATASETS from cugraph.datasets import dolphins, netscience, email_Eu_core DATASETS_BATCH = [dolphins, netscience, email_Eu_core] print("Networkx version : {} ".format(nx.__version__)) # Map of cuGraph input types to the expected output type for cuGraph # connected_components calls. cuGraph_input_output_map = { cugraph.Graph: cudf.DataFrame, nx.Graph: dict, nx.DiGraph: dict, cp_coo_matrix: tuple, cp_csr_matrix: tuple, cp_csc_matrix: tuple, sp_coo_matrix: tuple, sp_csr_matrix: tuple, sp_csc_matrix: tuple, } cupy_types = [cp_coo_matrix, cp_csr_matrix, cp_csc_matrix] # ============================================================================= # Pytest Setup / Teardown - called for each test function # ============================================================================= def setup_function(): gc.collect() # ============================================================================= # Helper functions # ============================================================================= def networkx_weak_call(graph_file): G = graph_file.get_graph() dataset_path = graph_file.get_path() M = utils.read_csv_for_nx(dataset_path) Gnx = nx.from_pandas_edgelist(M, source="0", target="1", create_using=nx.DiGraph()) # Weakly Connected components call: t1 = time.time() result = nx.weakly_connected_components(Gnx) t2 = time.time() - t1 print("Time : " + str(t2)) nx_labels = sorted(result) nx_n_components = len(nx_labels) lst_nx_components = sorted(nx_labels, key=len, reverse=True) return (G, dataset_path, nx_labels, nx_n_components, lst_nx_components, "weak") def networkx_strong_call(graph_file): G = graph_file.get_graph(create_using=cugraph.Graph(directed=True)) dataset_path = graph_file.get_path() M = utils.read_csv_for_nx(dataset_path) Gnx = nx.from_pandas_edgelist(M, source="0", target="1", create_using=nx.DiGraph()) t1 = time.time() result = nx.strongly_connected_components(Gnx) t2 = time.time() - t1 print("Time : " + str(t2)) nx_labels = sorted(result) nx_n_components = len(nx_labels) lst_nx_components = sorted(nx_labels, key=len, reverse=True) return (G, dataset_path, nx_labels, nx_n_components, lst_nx_components, "strong") def cugraph_call( gpu_benchmark_callable, cugraph_algo, input_G_or_matrix, directed=None ): """ Test helper that calls cugraph_algo (which is either weakly_connected_components() or strongly_connected_components()) on the Graph or matrix object input_G_or_matrix, via the gpu_benchmark_callable benchmark callable (which may or may not perform benchmarking based on command-line options), verify the result type, and return a dictionary for comparison. """ # if benchmarking is enabled, this call will be benchmarked (ie. run # repeatedly, run time averaged, etc.) result = gpu_benchmark_callable(cugraph_algo, input_G_or_matrix, directed) # dict of labels to list of vertices with that label label_vertex_dict = defaultdict(list) # Lookup results differently based on return type, and ensure return type # is correctly set based on input type. input_type = type(input_G_or_matrix) expected_return_type = cuGraph_input_output_map[input_type] if expected_return_type is cudf.DataFrame: assert type(result) is cudf.DataFrame for i in range(len(result)): label_vertex_dict[result["labels"][i]].append(result["vertex"][i]) # NetworkX input results in returning a dictionary mapping vertices to # their labels. elif expected_return_type is dict: assert type(result) is dict for (vert, label) in result.items(): label_vertex_dict[label].append(vert) # A CuPy/SciPy input means the return value will be a 2-tuple of: # n_components: int # The number of connected components (number of unique labels). # labels: ndarray # The length-N array of labels of the connected components. elif expected_return_type is tuple: assert type(result) is tuple assert type(result[0]) is int if input_type in cupy_types: assert type(result[1]) is cp.ndarray else: assert type(result[1]) is np.ndarray unique_labels = set([n.item() for n in result[1]]) assert len(unique_labels) == result[0] # The returned dict used in the tests for checking correctness needs # the actual vertex IDs, which are not in the returned data (the # CuPy/SciPy connected_components return types cuGraph is converting # to does not include them). So, extract the vertices from the input # COO, order them to match the returned list of labels (which is just # a sort), and include them in the returned dict. if input_type in [cp_csr_matrix, cp_csc_matrix, sp_csr_matrix, sp_csc_matrix]: coo = input_G_or_matrix.tocoo(copy=False) else: coo = input_G_or_matrix verts = sorted(set([n.item() for n in coo.col] + [n.item() for n in coo.row])) num_verts = len(verts) num_verts_assigned_labels = len(result[1]) assert num_verts_assigned_labels == num_verts for i in range(num_verts): label = result[1][i].item() label_vertex_dict[label].append(verts[i]) else: raise RuntimeError(f"unsupported return type: {expected_return_type}") return label_vertex_dict def which_cluster_idx(_cluster, _find_vertex): idx = -1 for i in range(len(_cluster)): if _find_vertex in _cluster[i]: idx = i break return idx def assert_scipy_api_compat(G, dataset_path, api_type): """ Ensure cugraph.scc() and cugraph.connected_components() can be used as drop-in replacements for scipy.connected_components(): scipy.sparse.csgraph.connected_components(csgraph, directed=True, connection='weak', return_labels=True) Parameters ---------- csgraph : array_like or sparse matrix The N x N matrix representing the compressed sparse graph. The input csgraph will be converted to csr format for the calculation. directed : bool, optional If True (default), then operate on a directed graph: only move from point i to point j along paths csgraph[i, j]. If False, then find the shortest path on an undirected graph: the algorithm can progress from point i to j along csgraph[i, j] or csgraph[j, i]. connection : str, optional [‘weak’|’strong’]. For directed graphs, the type of connection to use. Nodes i and j are strongly connected if a path exists both from i to j and from j to i. A directed graph is weakly connected if replacing all of its directed edges with undirected edges produces a connected (undirected) graph. If directed == False, this keyword is not referenced. return_labels : bool, optional If True (default), then return the labels for each of the connected components. Returns ------- n_components : int The number of connected components. labels : ndarray The length-N array of labels of the connected components. """ api_call = { "strong": cugraph.strongly_connected_components, "weak": cugraph.weakly_connected_components, }[api_type] connection = api_type wrong_connection = {"strong": "weak", "weak": "strong"}[api_type] input_cugraph_graph = G input_coo_matrix = utils.create_obj_from_csv( dataset_path, cp_coo_matrix, edgevals=True ) # Ensure scipy-only options are rejected for cugraph inputs with pytest.raises(TypeError): api_call(input_cugraph_graph, directed=False) with pytest.raises(TypeError): api_call(input_cugraph_graph, return_labels=False) # Setting connection to strong for strongly_* and weak for weakly_* is # redundant, but valid api_call(input_cugraph_graph, connection=connection) # Invalid for the API with pytest.raises(TypeError): (n_components, labels) = api_call( input_coo_matrix, directed=False, connection=wrong_connection ) (n_components, labels) = api_call(input_coo_matrix, directed=False) (n_components, labels) = api_call( input_coo_matrix, directed=False, connection=connection ) n_components = api_call(input_coo_matrix, directed=False, return_labels=False) assert type(n_components) is int # ============================================================================= # Pytest fixtures # ============================================================================= @pytest.fixture(scope="module", params=DEFAULT_DATASETS) def dataset_nxresults_weak(request): return networkx_weak_call(request.param) @pytest.fixture(scope="module", params=[DEFAULT_DATASETS[0]]) def single_dataset_nxresults_weak(request): return networkx_weak_call(request.param) @pytest.fixture(scope="module", params=DATASETS_BATCH) def dataset_nxresults_strong(request): return networkx_strong_call(request.param) @pytest.fixture(scope="module", params=[DATASETS_BATCH[0]]) def single_dataset_nxresults_strong(request): return networkx_strong_call(request.param) # ============================================================================= # Tests # ============================================================================= @pytest.mark.sg @pytest.mark.parametrize("cugraph_input_type", utils.CUGRAPH_DIR_INPUT_TYPES) def test_weak_cc(gpubenchmark, dataset_nxresults_weak, cugraph_input_type): ( G, dataset_path, netx_labels, nx_n_components, lst_nx_components, api_type, ) = dataset_nxresults_weak # cuGraph or nx 'input_type' should have this parameter set to None directed = None if not isinstance(cugraph_input_type, cugraph.Graph): input_G_or_matrix = utils.create_obj_from_csv( dataset_path, cugraph_input_type, edgevals=True ) if not is_nx_graph_type(cugraph_input_type): # directed should be set to False when creating a cuGraph from # neither a cuGraph nor nx type directed = False else: input_G_or_matrix = G cugraph_labels = cugraph_call( gpubenchmark, cugraph.weakly_connected_components, input_G_or_matrix, directed ) # while cugraph returns a component label for each vertex; cg_n_components = len(cugraph_labels) # Comapre number of components assert nx_n_components == cg_n_components lst_nx_components_lens = [len(c) for c in lst_nx_components] cugraph_vertex_lst = cugraph_labels.values() lst_cg_components = sorted(cugraph_vertex_lst, key=len, reverse=True) lst_cg_components_lens = [len(c) for c in lst_cg_components] # Compare lengths of each component assert lst_nx_components_lens == lst_cg_components_lens # Compare vertices of largest component nx_vertices = sorted(lst_nx_components[0]) first_vert = nx_vertices[0] idx = which_cluster_idx(lst_cg_components, first_vert) assert idx != -1, "Check for Nx vertex in cuGraph results failed" cg_vertices = sorted(lst_cg_components[idx]) assert nx_vertices == cg_vertices @pytest.mark.sg @pytest.mark.parametrize( "cugraph_input_type", utils.NX_DIR_INPUT_TYPES + utils.MATRIX_INPUT_TYPES ) def test_weak_cc_nonnative_inputs( gpubenchmark, single_dataset_nxresults_weak, cugraph_input_type ): test_weak_cc(gpubenchmark, single_dataset_nxresults_weak, cugraph_input_type) @pytest.mark.sg @pytest.mark.parametrize("cugraph_input_type", utils.CUGRAPH_DIR_INPUT_TYPES) def test_strong_cc(gpubenchmark, dataset_nxresults_strong, cugraph_input_type): # NetX returns a list of components, each component being a # collection (set{}) of vertex indices ( G, dataset_path, netx_labels, nx_n_components, lst_nx_components, api_type, ) = dataset_nxresults_strong if not isinstance(cugraph_input_type, cugraph.Graph): input_G_or_matrix = utils.create_obj_from_csv( dataset_path, cugraph_input_type, edgevals=True ) else: input_G_or_matrix = G cugraph_labels = cugraph_call( gpubenchmark, cugraph.strongly_connected_components, input_G_or_matrix ) if isinstance(cugraph_input_type, cugraph.Graph): assert isinstance(input_G_or_matrix, type(cugraph_input_type)) else: assert isinstance(input_G_or_matrix, cugraph_input_type) # while cugraph returns a component label for each vertex; cg_n_components = len(cugraph_labels) # Comapre number of components found assert nx_n_components == cg_n_components lst_nx_components_lens = [len(c) for c in lst_nx_components] cugraph_vertex_lst = cugraph_labels.values() lst_cg_components = sorted(cugraph_vertex_lst, key=len, reverse=True) lst_cg_components_lens = [len(c) for c in lst_cg_components] # Compare lengths of each component assert lst_nx_components_lens == lst_cg_components_lens # Compare vertices of largest component # note that there might be more than one largest component nx_vertices = sorted(lst_nx_components[0]) first_vert = nx_vertices[0] idx = which_cluster_idx(lst_cg_components, first_vert) assert idx != -1, "Check for Nx vertex in cuGraph results failed" cg_vertices = sorted(lst_cg_components[idx]) assert nx_vertices == cg_vertices @pytest.mark.sg @pytest.mark.parametrize( "cugraph_input_type", utils.NX_DIR_INPUT_TYPES + utils.MATRIX_INPUT_TYPES ) def test_strong_cc_nonnative_inputs( gpubenchmark, single_dataset_nxresults_strong, cugraph_input_type ): test_strong_cc(gpubenchmark, single_dataset_nxresults_strong, cugraph_input_type) @pytest.mark.sg def test_scipy_api_compat_weak(single_dataset_nxresults_weak): (G, dataset_path, _, _, _, api_type) = single_dataset_nxresults_weak assert_scipy_api_compat(G, dataset_path, api_type) @pytest.mark.sg def test_scipy_api_compat_strong(single_dataset_nxresults_strong): (G, dataset_path, _, _, _, api_type) = single_dataset_nxresults_strong assert_scipy_api_compat(G, dataset_path, api_type) @pytest.mark.sg @pytest.mark.parametrize("connection_type", ["strong", "weak"]) def test_scipy_api_compat(connection_type): if connection_type == "strong": graph_file = DATASETS_BATCH[0] else: graph_file = DEFAULT_DATASETS[0] input_cugraph_graph = graph_file.get_graph() dataset_path = graph_file.get_path() input_coo_matrix = utils.create_obj_from_csv( dataset_path, cp_coo_matrix, edgevals=True ) # connection is the only API that is accepted with cugraph objs retval = cugraph.connected_components( input_cugraph_graph, connection=connection_type ) assert type(retval) is cudf.DataFrame # Ensure scipy-only options (except connection) are rejected for cugraph # inputs with pytest.raises(TypeError): cugraph.connected_components(input_cugraph_graph, directed=True) with pytest.raises(TypeError): cugraph.connected_components(input_cugraph_graph, return_labels=False) with pytest.raises(TypeError): cugraph.connected_components( input_cugraph_graph, connection=connection_type, return_labels=False ) # only accept weak or strong with pytest.raises(ValueError): cugraph.connected_components(input_cugraph_graph, connection="invalid") (n_components, labels) = cugraph.connected_components( input_coo_matrix, directed=False, connection=connection_type ) # FIXME: connection should default to "weak", need to test that (n_components, labels) = cugraph.connected_components( input_coo_matrix, directed=False ) n_components = cugraph.connected_components( input_coo_matrix, directed=False, return_labels=False ) assert type(n_components) is int
0