選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

leiden.py 5.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. """
  17. Reference:
  18. - [graphrag](https://github.com/microsoft/graphrag)
  19. """
  20. import logging
  21. from typing import Any, cast, List
  22. import html
  23. from graspologic.partition import hierarchical_leiden
  24. from graspologic.utils import largest_connected_component
  25. import networkx as nx
  26. log = logging.getLogger(__name__)
  27. def _stabilize_graph(graph: nx.Graph) -> nx.Graph:
  28. """Ensure an undirected graph with the same relationships will always be read the same way."""
  29. fixed_graph = nx.DiGraph() if graph.is_directed() else nx.Graph()
  30. sorted_nodes = graph.nodes(data=True)
  31. sorted_nodes = sorted(sorted_nodes, key=lambda x: x[0])
  32. fixed_graph.add_nodes_from(sorted_nodes)
  33. edges = list(graph.edges(data=True))
  34. # If the graph is undirected, we create the edges in a stable way, so we get the same results
  35. # for example:
  36. # A -> B
  37. # in graph theory is the same as
  38. # B -> A
  39. # in an undirected graph
  40. # however, this can lead to downstream issues because sometimes
  41. # consumers read graph.nodes() which ends up being [A, B] and sometimes it's [B, A]
  42. # but they base some of their logic on the order of the nodes, so the order ends up being important
  43. # so we sort the nodes in the edge in a stable way, so that we always get the same order
  44. if not graph.is_directed():
  45. def _sort_source_target(edge):
  46. source, target, edge_data = edge
  47. if source > target:
  48. temp = source
  49. source = target
  50. target = temp
  51. return source, target, edge_data
  52. edges = [_sort_source_target(edge) for edge in edges]
  53. def _get_edge_key(source: Any, target: Any) -> str:
  54. return f"{source} -> {target}"
  55. edges = sorted(edges, key=lambda x: _get_edge_key(x[0], x[1]))
  56. fixed_graph.add_edges_from(edges)
  57. return fixed_graph
  58. def normalize_node_names(graph: nx.Graph | nx.DiGraph) -> nx.Graph | nx.DiGraph:
  59. """Normalize node names."""
  60. node_mapping = {node: html.unescape(node.upper().strip()) for node in graph.nodes()} # type: ignore
  61. return nx.relabel_nodes(graph, node_mapping)
  62. def stable_largest_connected_component(graph: nx.Graph) -> nx.Graph:
  63. """Return the largest connected component of the graph, with nodes and edges sorted in a stable way."""
  64. graph = graph.copy()
  65. graph = cast(nx.Graph, largest_connected_component(graph))
  66. graph = normalize_node_names(graph)
  67. return _stabilize_graph(graph)
  68. def _compute_leiden_communities(
  69. graph: nx.Graph | nx.DiGraph,
  70. max_cluster_size: int,
  71. use_lcc: bool,
  72. seed=0xDEADBEEF,
  73. ) -> dict[int, dict[str, int]]:
  74. """Return Leiden root communities."""
  75. if use_lcc:
  76. graph = stable_largest_connected_component(graph)
  77. community_mapping = hierarchical_leiden(
  78. graph, max_cluster_size=max_cluster_size, random_seed=seed
  79. )
  80. results: dict[int, dict[str, int]] = {}
  81. for partition in community_mapping:
  82. results[partition.level] = results.get(partition.level, {})
  83. results[partition.level][partition.node] = partition.cluster
  84. return results
  85. def run(graph: nx.Graph, args: dict[str, Any]) -> dict[int, dict[str, dict]]:
  86. """Run method definition."""
  87. max_cluster_size = args.get("max_cluster_size", 12)
  88. use_lcc = args.get("use_lcc", True)
  89. if args.get("verbose", False):
  90. log.info(
  91. "Running leiden with max_cluster_size=%s, lcc=%s", max_cluster_size, use_lcc
  92. )
  93. if not graph.nodes(): return {}
  94. node_id_to_community_map = _compute_leiden_communities(
  95. graph=graph,
  96. max_cluster_size=max_cluster_size,
  97. use_lcc=use_lcc,
  98. seed=args.get("seed", 0xDEADBEEF),
  99. )
  100. levels = args.get("levels")
  101. # If they don't pass in levels, use them all
  102. if levels is None:
  103. levels = sorted(node_id_to_community_map.keys())
  104. results_by_level: dict[int, dict[str, list[str]]] = {}
  105. for level in levels:
  106. result = {}
  107. results_by_level[level] = result
  108. for node_id, raw_community_id in node_id_to_community_map[level].items():
  109. community_id = str(raw_community_id)
  110. if community_id not in result:
  111. result[community_id] = {"weight": 0, "nodes": []}
  112. result[community_id]["nodes"].append(node_id)
  113. result[community_id]["weight"] += graph.nodes[node_id].get("rank", 0) * graph.nodes[node_id].get("weight", 1)
  114. weights = [comm["weight"] for _, comm in result.items()]
  115. if not weights:continue
  116. max_weight = max(weights)
  117. for _, comm in result.items(): comm["weight"] /= max_weight
  118. return results_by_level
  119. def add_community_info2graph(graph: nx.Graph, commu_info: dict[str, dict[str, dict]]):
  120. for lev, cluster_info in commu_info.items():
  121. for cid, nodes in cluster_info.items():
  122. for n in nodes["nodes"]:
  123. if "community" not in graph.nodes[n]: graph.nodes[n]["community"] = {}
  124. graph.nodes[n]["community"].update({lev: cid})
  125. def add_community_info2graph(graph: nx.Graph, nodes: List[str], community_title):
  126. for n in nodes:
  127. if "communities" not in graph.nodes[n]:
  128. graph.nodes[n]["communities"] = []
  129. graph.nodes[n]["communities"].append(community_title)