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 14 kB

6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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 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 support '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): Valid when working_mode is set to 'client' or 'server',
  43. set the hostname of the graph data server (default='127.0.0.1').
  44. port (int, optional): Valid when working_mode is set to 'client' or 'server',
  45. set the port of the graph data server, the range is 1024-65535 (default=50051).
  46. num_client (int, optional): Valid when working_mode is set to 'server',
  47. set the number of clients expected to connect, and the server will allocate corresponding
  48. resources according to this parameter (default=1).
  49. auto_shutdown (bool, optional): Valid when working_mode is set to 'server',
  50. Control when all clients have connected and no client connected to the server,
  51. automatically exit the server (default=True).
  52. """
  53. @check_gnn_graphdata
  54. def __init__(self, dataset_file, num_parallel_workers=None, working_mode='local', hostname='127.0.0.1', port=50051,
  55. num_client=1, auto_shutdown=True):
  56. self._dataset_file = dataset_file
  57. self._working_mode = working_mode
  58. if num_parallel_workers is None:
  59. num_parallel_workers = 1
  60. def stop():
  61. self._graph_data.stop()
  62. atexit.register(stop)
  63. if working_mode in ['local', 'client']:
  64. self._graph_data = GraphDataClient(dataset_file, num_parallel_workers, working_mode, hostname, port)
  65. if working_mode == 'server':
  66. self._graph_data = GraphDataServer(
  67. dataset_file, num_parallel_workers, hostname, port, num_client, auto_shutdown)
  68. try:
  69. while self._graph_data.is_stoped() is not True:
  70. time.sleep(1)
  71. except KeyboardInterrupt:
  72. # self._graph_data.stop()
  73. raise Exception("Graph data server receives KeyboardInterrupt")
  74. @check_gnn_get_all_nodes
  75. def get_all_nodes(self, node_type):
  76. """
  77. Get all nodes in the graph.
  78. Args:
  79. node_type (int): Specify the type of node.
  80. Returns:
  81. numpy.ndarray: array of nodes.
  82. Examples:
  83. >>> import mindspore.dataset as ds
  84. >>> data_graph = ds.GraphData('dataset_file', 2)
  85. >>> nodes = data_graph.get_all_nodes(0)
  86. Raises:
  87. TypeError: If `node_type` is not integer.
  88. """
  89. if self._working_mode == 'server':
  90. raise Exception("This method is not supported when working mode is server")
  91. return self._graph_data.get_all_nodes(node_type).as_array()
  92. @check_gnn_get_all_edges
  93. def get_all_edges(self, edge_type):
  94. """
  95. Get all edges in the graph.
  96. Args:
  97. edge_type (int): Specify the type of edge.
  98. Returns:
  99. numpy.ndarray: array of edges.
  100. Examples:
  101. >>> import mindspore.dataset as ds
  102. >>> data_graph = ds.GraphData('dataset_file', 2)
  103. >>> nodes = data_graph.get_all_edges(0)
  104. Raises:
  105. TypeError: If `edge_type` is not integer.
  106. """
  107. if self._working_mode == 'server':
  108. raise Exception("This method is not supported when working mode is server")
  109. return self._graph_data.get_all_edges(edge_type).as_array()
  110. @check_gnn_get_nodes_from_edges
  111. def get_nodes_from_edges(self, edge_list):
  112. """
  113. Get nodes from the edges.
  114. Args:
  115. edge_list (Union[list, numpy.ndarray]): The given list of edges.
  116. Returns:
  117. numpy.ndarray: array of nodes.
  118. Raises:
  119. TypeError: If `edge_list` is not list or ndarray.
  120. """
  121. if self._working_mode == 'server':
  122. raise Exception("This method is not supported when working mode is server")
  123. return self._graph_data.get_nodes_from_edges(edge_list).as_array()
  124. @check_gnn_get_all_neighbors
  125. def get_all_neighbors(self, node_list, neighbor_type):
  126. """
  127. Get `neighbor_type` neighbors of the nodes in `node_list`.
  128. Args:
  129. node_list (Union[list, numpy.ndarray]): The given list of nodes.
  130. neighbor_type (int): Specify the type of neighbor.
  131. Returns:
  132. numpy.ndarray: array of nodes.
  133. Examples:
  134. >>> import mindspore.dataset as ds
  135. >>> data_graph = ds.GraphData('dataset_file', 2)
  136. >>> nodes = data_graph.get_all_nodes(0)
  137. >>> neighbors = data_graph.get_all_neighbors(nodes, 0)
  138. Raises:
  139. TypeError: If `node_list` is not list or ndarray.
  140. TypeError: If `neighbor_type` is not integer.
  141. """
  142. if self._working_mode == 'server':
  143. raise Exception("This method is not supported when working mode is server")
  144. return self._graph_data.get_all_neighbors(node_list, neighbor_type).as_array()
  145. @check_gnn_get_sampled_neighbors
  146. def get_sampled_neighbors(self, node_list, neighbor_nums, neighbor_types):
  147. """
  148. Get sampled neighbor information.
  149. The api supports multi-hop neighbor sampling. That is, the previous sampling result is used as the input of
  150. next-hop sampling. A maximum of 6-hop are allowed.
  151. The sampling result is tiled into a list in the format of [input node, 1-hop sampling result,
  152. 2-hop samling result ...]
  153. Args:
  154. node_list (Union[list, numpy.ndarray]): The given list of nodes.
  155. neighbor_nums (Union[list, numpy.ndarray]): Number of neighbors sampled per hop.
  156. neighbor_types (Union[list, numpy.ndarray]): Neighbor type sampled per hop.
  157. Returns:
  158. numpy.ndarray: array of nodes.
  159. Examples:
  160. >>> import mindspore.dataset as ds
  161. >>> data_graph = ds.GraphData('dataset_file', 2)
  162. >>> nodes = data_graph.get_all_nodes(0)
  163. >>> neighbors = data_graph.get_all_neighbors(nodes, [2, 2], [0, 0])
  164. Raises:
  165. TypeError: If `node_list` is not list or ndarray.
  166. TypeError: If `neighbor_nums` is not list or ndarray.
  167. TypeError: If `neighbor_types` is not list or ndarray.
  168. """
  169. if self._working_mode == 'server':
  170. raise Exception("This method is not supported when working mode is server")
  171. return self._graph_data.get_sampled_neighbors(
  172. node_list, neighbor_nums, neighbor_types).as_array()
  173. @check_gnn_get_neg_sampled_neighbors
  174. def get_neg_sampled_neighbors(self, node_list, neg_neighbor_num, neg_neighbor_type):
  175. """
  176. Get `neg_neighbor_type` negative sampled neighbors of the nodes in `node_list`.
  177. Args:
  178. node_list (Union[list, numpy.ndarray]): The given list of nodes.
  179. neg_neighbor_num (int): Number of neighbors sampled.
  180. neg_neighbor_type (int): Specify the type of negative neighbor.
  181. Returns:
  182. numpy.ndarray: array of nodes.
  183. Examples:
  184. >>> import mindspore.dataset as ds
  185. >>> data_graph = ds.GraphData('dataset_file', 2)
  186. >>> nodes = data_graph.get_all_nodes(0)
  187. >>> neg_neighbors = data_graph.get_neg_sampled_neighbors(nodes, 5, 0)
  188. Raises:
  189. TypeError: If `node_list` is not list or ndarray.
  190. TypeError: If `neg_neighbor_num` is not integer.
  191. TypeError: If `neg_neighbor_type` is not integer.
  192. """
  193. if self._working_mode == 'server':
  194. raise Exception("This method is not supported when working mode is server")
  195. return self._graph_data.get_neg_sampled_neighbors(
  196. node_list, neg_neighbor_num, neg_neighbor_type).as_array()
  197. @check_gnn_get_node_feature
  198. def get_node_feature(self, node_list, feature_types):
  199. """
  200. Get `feature_types` feature of the nodes in `node_list`.
  201. Args:
  202. node_list (Union[list, numpy.ndarray]): The given list of nodes.
  203. feature_types (Union[list, numpy.ndarray]): The given list of feature types.
  204. Returns:
  205. numpy.ndarray: array of features.
  206. Examples:
  207. >>> import mindspore.dataset as ds
  208. >>> data_graph = ds.GraphData('dataset_file', 2)
  209. >>> nodes = data_graph.get_all_nodes(0)
  210. >>> features = data_graph.get_node_feature(nodes, [1])
  211. Raises:
  212. TypeError: If `node_list` is not list or ndarray.
  213. TypeError: If `feature_types` is not list or ndarray.
  214. """
  215. if self._working_mode == 'server':
  216. raise Exception("This method is not supported when working mode is server")
  217. if isinstance(node_list, list):
  218. node_list = np.array(node_list, dtype=np.int32)
  219. return [
  220. t.as_array() for t in self._graph_data.get_node_feature(
  221. Tensor(node_list),
  222. feature_types)]
  223. @check_gnn_get_edge_feature
  224. def get_edge_feature(self, edge_list, feature_types):
  225. """
  226. Get `feature_types` feature of the edges in `edge_list`.
  227. Args:
  228. edge_list (Union[list, numpy.ndarray]): The given list of edges.
  229. feature_types (Union[list, numpy.ndarray]): The given list of feature types.
  230. Returns:
  231. numpy.ndarray: array of features.
  232. Examples:
  233. >>> import mindspore.dataset as ds
  234. >>> data_graph = ds.GraphData('dataset_file', 2)
  235. >>> edges = data_graph.get_all_edges(0)
  236. >>> features = data_graph.get_edge_feature(edges, [1])
  237. Raises:
  238. TypeError: If `edge_list` is not list or ndarray.
  239. TypeError: If `feature_types` is not list or ndarray.
  240. """
  241. if self._working_mode == 'server':
  242. raise Exception("This method is not supported when working mode is server")
  243. if isinstance(edge_list, list):
  244. edge_list = np.array(edge_list, dtype=np.int32)
  245. return [
  246. t.as_array() for t in self._graph_data.get_edge_feature(
  247. Tensor(edge_list),
  248. feature_types)]
  249. def graph_info(self):
  250. """
  251. Get the meta information of the graph, including the number of nodes, the type of nodes,
  252. the feature information of nodes, the number of edges, the type of edges, and the feature information of edges.
  253. Returns:
  254. dict: Meta information of the graph. The key is node_type, edge_type, node_num, edge_num,
  255. node_feature_type and edge_feature_type.
  256. """
  257. if self._working_mode == 'server':
  258. raise Exception("This method is not supported when working mode is server")
  259. return self._graph_data.graph_info()
  260. @check_gnn_random_walk
  261. def random_walk(
  262. self,
  263. target_nodes,
  264. meta_path,
  265. step_home_param=1.0,
  266. step_away_param=1.0,
  267. default_node=-1):
  268. """
  269. Random walk in nodes.
  270. Args:
  271. target_nodes (list[int]): Start node list in random walk
  272. meta_path (list[int]): node type for each walk step
  273. step_home_param (float, optional): return hyper parameter in node2vec algorithm (Default = 1.0).
  274. step_away_param (float, optional): inout hyper parameter in node2vec algorithm (Default = 1.0).
  275. default_node (int, optional): default node if no more neighbors found (Default = -1).
  276. A default value of -1 indicates that no node is given.
  277. Returns:
  278. numpy.ndarray: array of nodes.
  279. Examples:
  280. >>> import mindspore.dataset as ds
  281. >>> data_graph = ds.GraphData('dataset_file', 2)
  282. >>> nodes = data_graph.random_walk([1,2], [1,2,1,2,1])
  283. Raises:
  284. TypeError: If `target_nodes` is not list or ndarray.
  285. TypeError: If `meta_path` is not list or ndarray.
  286. """
  287. if self._working_mode == 'server':
  288. raise Exception("This method is not supported when working mode is server")
  289. return self._graph_data.random_walk(target_nodes, meta_path, step_home_param, step_away_param,
  290. default_node).as_array()