您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

leiden.py 5.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. # Copyright (c) 2024 Microsoft Corporation.
  2. # Licensed under the MIT License
  3. """
  4. Reference:
  5. - [graphrag](https://github.com/microsoft/graphrag)
  6. """
  7. import logging
  8. import html
  9. from typing import Any, cast
  10. from graspologic.partition import hierarchical_leiden
  11. from graspologic.utils import largest_connected_component
  12. import networkx as nx
  13. from networkx import is_empty
  14. def _stabilize_graph(graph: nx.Graph) -> nx.Graph:
  15. """Ensure an undirected graph with the same relationships will always be read the same way."""
  16. fixed_graph = nx.DiGraph() if graph.is_directed() else nx.Graph()
  17. sorted_nodes = graph.nodes(data=True)
  18. sorted_nodes = sorted(sorted_nodes, key=lambda x: x[0])
  19. fixed_graph.add_nodes_from(sorted_nodes)
  20. edges = list(graph.edges(data=True))
  21. # If the graph is undirected, we create the edges in a stable way, so we get the same results
  22. # for example:
  23. # A -> B
  24. # in graph theory is the same as
  25. # B -> A
  26. # in an undirected graph
  27. # however, this can lead to downstream issues because sometimes
  28. # consumers read graph.nodes() which ends up being [A, B] and sometimes it's [B, A]
  29. # but they base some of their logic on the order of the nodes, so the order ends up being important
  30. # so we sort the nodes in the edge in a stable way, so that we always get the same order
  31. if not graph.is_directed():
  32. def _sort_source_target(edge):
  33. source, target, edge_data = edge
  34. if source > target:
  35. temp = source
  36. source = target
  37. target = temp
  38. return source, target, edge_data
  39. edges = [_sort_source_target(edge) for edge in edges]
  40. def _get_edge_key(source: Any, target: Any) -> str:
  41. return f"{source} -> {target}"
  42. edges = sorted(edges, key=lambda x: _get_edge_key(x[0], x[1]))
  43. fixed_graph.add_edges_from(edges)
  44. return fixed_graph
  45. def normalize_node_names(graph: nx.Graph | nx.DiGraph) -> nx.Graph | nx.DiGraph:
  46. """Normalize node names."""
  47. node_mapping = {node: html.unescape(node.upper().strip()) for node in graph.nodes()} # type: ignore
  48. return nx.relabel_nodes(graph, node_mapping)
  49. def stable_largest_connected_component(graph: nx.Graph) -> nx.Graph:
  50. """Return the largest connected component of the graph, with nodes and edges sorted in a stable way."""
  51. graph = graph.copy()
  52. graph = cast(nx.Graph, largest_connected_component(graph))
  53. graph = normalize_node_names(graph)
  54. return _stabilize_graph(graph)
  55. def _compute_leiden_communities(
  56. graph: nx.Graph | nx.DiGraph,
  57. max_cluster_size: int,
  58. use_lcc: bool,
  59. seed=0xDEADBEEF,
  60. ) -> dict[int, dict[str, int]]:
  61. """Return Leiden root communities."""
  62. results: dict[int, dict[str, int]] = {}
  63. if is_empty(graph):
  64. return results
  65. if use_lcc:
  66. graph = stable_largest_connected_component(graph)
  67. community_mapping = hierarchical_leiden(
  68. graph, max_cluster_size=max_cluster_size, random_seed=seed
  69. )
  70. for partition in community_mapping:
  71. results[partition.level] = results.get(partition.level, {})
  72. results[partition.level][partition.node] = partition.cluster
  73. return results
  74. def run(graph: nx.Graph, args: dict[str, Any]) -> dict[int, dict[str, dict]]:
  75. """Run method definition."""
  76. max_cluster_size = args.get("max_cluster_size", 12)
  77. use_lcc = args.get("use_lcc", True)
  78. if args.get("verbose", False):
  79. logging.debug(
  80. "Running leiden with max_cluster_size=%s, lcc=%s", max_cluster_size, use_lcc
  81. )
  82. if not graph.nodes():
  83. return {}
  84. node_id_to_community_map = _compute_leiden_communities(
  85. graph=graph,
  86. max_cluster_size=max_cluster_size,
  87. use_lcc=use_lcc,
  88. seed=args.get("seed", 0xDEADBEEF),
  89. )
  90. levels = args.get("levels")
  91. # If they don't pass in levels, use them all
  92. if levels is None:
  93. levels = sorted(node_id_to_community_map.keys())
  94. results_by_level: dict[int, dict[str, list[str]]] = {}
  95. for level in levels:
  96. result = {}
  97. results_by_level[level] = result
  98. for node_id, raw_community_id in node_id_to_community_map[level].items():
  99. community_id = str(raw_community_id)
  100. if community_id not in result:
  101. result[community_id] = {"weight": 0, "nodes": []}
  102. result[community_id]["nodes"].append(node_id)
  103. result[community_id]["weight"] += graph.nodes[node_id].get("rank", 0) * graph.nodes[node_id].get("weight", 1)
  104. weights = [comm["weight"] for _, comm in result.items()]
  105. if not weights:
  106. continue
  107. max_weight = max(weights)
  108. for _, comm in result.items():
  109. comm["weight"] /= max_weight
  110. return results_by_level
  111. def add_community_info2graph(graph: nx.Graph, nodes: list[str], community_title):
  112. for n in nodes:
  113. if "communities" not in graph.nodes[n]:
  114. graph.nodes[n]["communities"] = []
  115. graph.nodes[n]["communities"].append(community_title)
  116. graph.nodes[n]["communities"] = list(set(graph.nodes[n]["communities"]))