You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

graphdata.py 15 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """
  16. graphdata.py supports loading graph dataset for GNN network training,
  17. and provides operations related to graph data.
  18. """
  19. import atexit
  20. import time
  21. import numpy as np
  22. from mindspore._c_dataengine import GraphDataClient
  23. from mindspore._c_dataengine import GraphDataServer
  24. from mindspore._c_dataengine import Tensor
  25. from .validators import check_gnn_graphdata, check_gnn_get_all_nodes, check_gnn_get_all_edges, \
  26. check_gnn_get_nodes_from_edges, check_gnn_get_all_neighbors, check_gnn_get_sampled_neighbors, \
  27. check_gnn_get_neg_sampled_neighbors, check_gnn_get_node_feature, check_gnn_get_edge_feature, \
  28. check_gnn_random_walk
  29. class GraphData:
  30. """
  31. Reads the graph dataset used for GNN training from the shared file and database.
  32. Args:
  33. dataset_file (str): One of file names in the dataset.
  34. num_parallel_workers (int, optional): Number of workers to process the dataset in parallel
  35. (default=None).
  36. working_mode (str, optional): Set working mode, now supports 'local'/'client'/'server' (default='local').
  37. - 'local', used in non-distributed training scenarios.
  38. - 'client', used in distributed training scenarios. The client does not load data,
  39. but obtains data from the server.
  40. - 'server', used in distributed training scenarios. The server loads the data
  41. and is available to the client.
  42. hostname (str, optional): Hostname of the graph data server. This parameter is only valid when
  43. working_mode is set to 'client' or 'server' (default='127.0.0.1').
  44. port (int, optional): Port of the graph data server. The range is 1024-65535. This parameter is
  45. only valid when working_mode is set to 'client' or 'server' (default=50051).
  46. num_client (int, optional): Maximum number of clients expected to connect to the server. The server will
  47. allocate resources according to this parameter. This parameter is only valid when working_mode
  48. is set to 'server' (default=1).
  49. auto_shutdown (bool, optional): Valid when working_mode is set to 'server',
  50. when the number of connected clients reaches num_client and no client is being connected,
  51. the server automatically exits (default=True).
  52. Examples:
  53. >>> import mindspore.dataset as ds
  54. >>>
  55. >>> data_graph = ds.GraphData('dataset_file', 2)
  56. >>> nodes = data_graph.get_all_nodes(0)
  57. >>> features = data_graph.get_node_feature(nodes, [1])
  58. """
  59. @check_gnn_graphdata
  60. def __init__(self, dataset_file, num_parallel_workers=None, working_mode='local', hostname='127.0.0.1', port=50051,
  61. num_client=1, auto_shutdown=True):
  62. self._dataset_file = dataset_file
  63. self._working_mode = working_mode
  64. if num_parallel_workers is None:
  65. num_parallel_workers = 1
  66. def stop():
  67. self._graph_data.stop()
  68. if working_mode in ['local', 'client']:
  69. self._graph_data = GraphDataClient(dataset_file, num_parallel_workers, working_mode, hostname, port)
  70. atexit.register(stop)
  71. if working_mode == 'server':
  72. self._graph_data = GraphDataServer(
  73. dataset_file, num_parallel_workers, hostname, port, num_client, auto_shutdown)
  74. atexit.register(stop)
  75. try:
  76. while self._graph_data.is_stoped() is not True:
  77. time.sleep(1)
  78. except KeyboardInterrupt:
  79. raise Exception("Graph data server receives KeyboardInterrupt")
  80. @check_gnn_get_all_nodes
  81. def get_all_nodes(self, node_type):
  82. """
  83. Get all nodes in the graph.
  84. Args:
  85. node_type (int): Specify the type of node.
  86. Returns:
  87. numpy.ndarray: Array of nodes.
  88. Examples:
  89. >>> import mindspore.dataset as ds
  90. >>>
  91. >>> data_graph = ds.GraphData('dataset_file', 2)
  92. >>> nodes = data_graph.get_all_nodes(0)
  93. Raises:
  94. TypeError: If `node_type` is not integer.
  95. """
  96. if self._working_mode == 'server':
  97. raise Exception("This method is not supported when working mode is server")
  98. return self._graph_data.get_all_nodes(node_type).as_array()
  99. @check_gnn_get_all_edges
  100. def get_all_edges(self, edge_type):
  101. """
  102. Get all edges in the graph.
  103. Args:
  104. edge_type (int): Specify the type of edge.
  105. Returns:
  106. numpy.ndarray: array of edges.
  107. Examples:
  108. >>> import mindspore.dataset as ds
  109. >>>
  110. >>> data_graph = ds.GraphData('dataset_file', 2)
  111. >>> nodes = data_graph.get_all_edges(0)
  112. Raises:
  113. TypeError: If `edge_type` is not integer.
  114. """
  115. if self._working_mode == 'server':
  116. raise Exception("This method is not supported when working mode is server")
  117. return self._graph_data.get_all_edges(edge_type).as_array()
  118. @check_gnn_get_nodes_from_edges
  119. def get_nodes_from_edges(self, edge_list):
  120. """
  121. Get nodes from the edges.
  122. Args:
  123. edge_list (Union[list, numpy.ndarray]): The given list of edges.
  124. Returns:
  125. numpy.ndarray: Array of nodes.
  126. Raises:
  127. TypeError: If `edge_list` is not list or ndarray.
  128. """
  129. if self._working_mode == 'server':
  130. raise Exception("This method is not supported when working mode is server")
  131. return self._graph_data.get_nodes_from_edges(edge_list).as_array()
  132. @check_gnn_get_all_neighbors
  133. def get_all_neighbors(self, node_list, neighbor_type):
  134. """
  135. Get `neighbor_type` neighbors of the nodes in `node_list`.
  136. Args:
  137. node_list (Union[list, numpy.ndarray]): The given list of nodes.
  138. neighbor_type (int): Specify the type of neighbor.
  139. Returns:
  140. numpy.ndarray: Array of nodes.
  141. Examples:
  142. >>> import mindspore.dataset as ds
  143. >>>
  144. >>> data_graph = ds.GraphData('dataset_file', 2)
  145. >>> nodes = data_graph.get_all_nodes(0)
  146. >>> neighbors = data_graph.get_all_neighbors(nodes, 0)
  147. Raises:
  148. TypeError: If `node_list` is not list or ndarray.
  149. TypeError: If `neighbor_type` is not integer.
  150. """
  151. if self._working_mode == 'server':
  152. raise Exception("This method is not supported when working mode is server")
  153. return self._graph_data.get_all_neighbors(node_list, neighbor_type).as_array()
  154. @check_gnn_get_sampled_neighbors
  155. def get_sampled_neighbors(self, node_list, neighbor_nums, neighbor_types):
  156. """
  157. Get sampled neighbor information.
  158. The api supports multi-hop neighbor sampling. That is, the previous sampling result is used as the input of
  159. next-hop sampling. A maximum of 6-hop are allowed.
  160. The sampling result is tiled into a list in the format of [input node, 1-hop sampling result,
  161. 2-hop samling result ...]
  162. Args:
  163. node_list (Union[list, numpy.ndarray]): The given list of nodes.
  164. neighbor_nums (Union[list, numpy.ndarray]): Number of neighbors sampled per hop.
  165. neighbor_types (Union[list, numpy.ndarray]): Neighbor type sampled per hop.
  166. Returns:
  167. numpy.ndarray: Array of nodes.
  168. Examples:
  169. >>> import mindspore.dataset as ds
  170. >>>
  171. >>> data_graph = ds.GraphData('dataset_file', 2)
  172. >>> nodes = data_graph.get_all_nodes(0)
  173. >>> neighbors = data_graph.get_sampled_neighbors(nodes, [2, 2], [0, 0])
  174. Raises:
  175. TypeError: If `node_list` is not list or ndarray.
  176. TypeError: If `neighbor_nums` is not list or ndarray.
  177. TypeError: If `neighbor_types` is not list or ndarray.
  178. """
  179. if self._working_mode == 'server':
  180. raise Exception("This method is not supported when working mode is server")
  181. return self._graph_data.get_sampled_neighbors(
  182. node_list, neighbor_nums, neighbor_types).as_array()
  183. @check_gnn_get_neg_sampled_neighbors
  184. def get_neg_sampled_neighbors(self, node_list, neg_neighbor_num, neg_neighbor_type):
  185. """
  186. Get `neg_neighbor_type` negative sampled neighbors of the nodes in `node_list`.
  187. Args:
  188. node_list (Union[list, numpy.ndarray]): The given list of nodes.
  189. neg_neighbor_num (int): Number of neighbors sampled.
  190. neg_neighbor_type (int): Specify the type of negative neighbor.
  191. Returns:
  192. numpy.ndarray: Array of nodes.
  193. Examples:
  194. >>> import mindspore.dataset as ds
  195. >>>
  196. >>> data_graph = ds.GraphData('dataset_file', 2)
  197. >>> nodes = data_graph.get_all_nodes(0)
  198. >>> neg_neighbors = data_graph.get_neg_sampled_neighbors(nodes, 5, 0)
  199. Raises:
  200. TypeError: If `node_list` is not list or ndarray.
  201. TypeError: If `neg_neighbor_num` is not integer.
  202. TypeError: If `neg_neighbor_type` is not integer.
  203. """
  204. if self._working_mode == 'server':
  205. raise Exception("This method is not supported when working mode is server")
  206. return self._graph_data.get_neg_sampled_neighbors(
  207. node_list, neg_neighbor_num, neg_neighbor_type).as_array()
  208. @check_gnn_get_node_feature
  209. def get_node_feature(self, node_list, feature_types):
  210. """
  211. Get `feature_types` feature of the nodes in `node_list`.
  212. Args:
  213. node_list (Union[list, numpy.ndarray]): The given list of nodes.
  214. feature_types (Union[list, numpy.ndarray]): The given list of feature types.
  215. Returns:
  216. numpy.ndarray: array of features.
  217. Examples:
  218. >>> import mindspore.dataset as ds
  219. >>>
  220. >>> data_graph = ds.GraphData('dataset_file', 2)
  221. >>> nodes = data_graph.get_all_nodes(0)
  222. >>> features = data_graph.get_node_feature(nodes, [1])
  223. Raises:
  224. TypeError: If `node_list` is not list or ndarray.
  225. TypeError: If `feature_types` is not list or ndarray.
  226. """
  227. if self._working_mode == 'server':
  228. raise Exception("This method is not supported when working mode is server")
  229. if isinstance(node_list, list):
  230. node_list = np.array(node_list, dtype=np.int32)
  231. return [
  232. t.as_array() for t in self._graph_data.get_node_feature(
  233. Tensor(node_list),
  234. feature_types)]
  235. @check_gnn_get_edge_feature
  236. def get_edge_feature(self, edge_list, feature_types):
  237. """
  238. Get `feature_types` feature of the edges in `edge_list`.
  239. Args:
  240. edge_list (Union[list, numpy.ndarray]): The given list of edges.
  241. feature_types (Union[list, numpy.ndarray]): The given list of feature types.
  242. Returns:
  243. numpy.ndarray: array of features.
  244. Examples:
  245. >>> import mindspore.dataset as ds
  246. >>>
  247. >>> data_graph = ds.GraphData('dataset_file', 2)
  248. >>> edges = data_graph.get_all_edges(0)
  249. >>> features = data_graph.get_edge_feature(edges, [1])
  250. Raises:
  251. TypeError: If `edge_list` is not list or ndarray.
  252. TypeError: If `feature_types` is not list or ndarray.
  253. """
  254. if self._working_mode == 'server':
  255. raise Exception("This method is not supported when working mode is server")
  256. if isinstance(edge_list, list):
  257. edge_list = np.array(edge_list, dtype=np.int32)
  258. return [
  259. t.as_array() for t in self._graph_data.get_edge_feature(
  260. Tensor(edge_list),
  261. feature_types)]
  262. def graph_info(self):
  263. """
  264. Get the meta information of the graph, including the number of nodes, the type of nodes,
  265. the feature information of nodes, the number of edges, the type of edges, and the feature information of edges.
  266. Returns:
  267. dict: Meta information of the graph. The key is node_type, edge_type, node_num, edge_num,
  268. node_feature_type and edge_feature_type.
  269. """
  270. if self._working_mode == 'server':
  271. raise Exception("This method is not supported when working mode is server")
  272. return self._graph_data.graph_info()
  273. @check_gnn_random_walk
  274. def random_walk(
  275. self,
  276. target_nodes,
  277. meta_path,
  278. step_home_param=1.0,
  279. step_away_param=1.0,
  280. default_node=-1):
  281. """
  282. Random walk in nodes.
  283. Args:
  284. target_nodes (list[int]): Start node list in random walk
  285. meta_path (list[int]): node type for each walk step
  286. step_home_param (float, optional): return hyper parameter in node2vec algorithm (Default = 1.0).
  287. step_away_param (float, optional): inout hyper parameter in node2vec algorithm (Default = 1.0).
  288. default_node (int, optional): default node if no more neighbors found (Default = -1).
  289. A default value of -1 indicates that no node is given.
  290. Returns:
  291. numpy.ndarray: Array of nodes.
  292. Examples:
  293. >>> import mindspore.dataset as ds
  294. >>>
  295. >>> data_graph = ds.GraphData('dataset_file', 2)
  296. >>> nodes = data_graph.random_walk([1,2], [1,2,1,2,1])
  297. Raises:
  298. TypeError: If `target_nodes` is not list or ndarray.
  299. TypeError: If `meta_path` is not list or ndarray.
  300. """
  301. if self._working_mode == 'server':
  302. raise Exception("This method is not supported when working mode is server")
  303. return self._graph_data.random_walk(target_nodes, meta_path, step_home_param, step_away_param,
  304. default_node).as_array()