Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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. from typing import Any, cast, List
  9. import html
  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. log = logging.getLogger(__name__)
  15. def _stabilize_graph(graph: nx.Graph) -> nx.Graph:
  16. """Ensure an undirected graph with the same relationships will always be read the same way."""
  17. fixed_graph = nx.DiGraph() if graph.is_directed() else nx.Graph()
  18. sorted_nodes = graph.nodes(data=True)
  19. sorted_nodes = sorted(sorted_nodes, key=lambda x: x[0])
  20. fixed_graph.add_nodes_from(sorted_nodes)
  21. edges = list(graph.edges(data=True))
  22. # If the graph is undirected, we create the edges in a stable way, so we get the same results
  23. # for example:
  24. # A -> B
  25. # in graph theory is the same as
  26. # B -> A
  27. # in an undirected graph
  28. # however, this can lead to downstream issues because sometimes
  29. # consumers read graph.nodes() which ends up being [A, B] and sometimes it's [B, A]
  30. # but they base some of their logic on the order of the nodes, so the order ends up being important
  31. # so we sort the nodes in the edge in a stable way, so that we always get the same order
  32. if not graph.is_directed():
  33. def _sort_source_target(edge):
  34. source, target, edge_data = edge
  35. if source > target:
  36. temp = source
  37. source = target
  38. target = temp
  39. return source, target, edge_data
  40. edges = [_sort_source_target(edge) for edge in edges]
  41. def _get_edge_key(source: Any, target: Any) -> str:
  42. return f"{source} -> {target}"
  43. edges = sorted(edges, key=lambda x: _get_edge_key(x[0], x[1]))
  44. fixed_graph.add_edges_from(edges)
  45. return fixed_graph
  46. def normalize_node_names(graph: nx.Graph | nx.DiGraph) -> nx.Graph | nx.DiGraph:
  47. """Normalize node names."""
  48. node_mapping = {node: html.unescape(node.upper().strip()) for node in graph.nodes()} # type: ignore
  49. return nx.relabel_nodes(graph, node_mapping)
  50. def stable_largest_connected_component(graph: nx.Graph) -> nx.Graph:
  51. """Return the largest connected component of the graph, with nodes and edges sorted in a stable way."""
  52. graph = graph.copy()
  53. graph = cast(nx.Graph, largest_connected_component(graph))
  54. graph = normalize_node_names(graph)
  55. return _stabilize_graph(graph)
  56. def _compute_leiden_communities(
  57. graph: nx.Graph | nx.DiGraph,
  58. max_cluster_size: int,
  59. use_lcc: bool,
  60. seed=0xDEADBEEF,
  61. ) -> dict[int, dict[str, int]]:
  62. """Return Leiden root communities."""
  63. results: dict[int, dict[str, int]] = {}
  64. if is_empty(graph): 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. log.info(
  80. "Running leiden with max_cluster_size=%s, lcc=%s", max_cluster_size, use_lcc
  81. )
  82. if not graph.nodes(): return {}
  83. node_id_to_community_map = _compute_leiden_communities(
  84. graph=graph,
  85. max_cluster_size=max_cluster_size,
  86. use_lcc=use_lcc,
  87. seed=args.get("seed", 0xDEADBEEF),
  88. )
  89. levels = args.get("levels")
  90. # If they don't pass in levels, use them all
  91. if levels is None:
  92. levels = sorted(node_id_to_community_map.keys())
  93. results_by_level: dict[int, dict[str, list[str]]] = {}
  94. for level in levels:
  95. result = {}
  96. results_by_level[level] = result
  97. for node_id, raw_community_id in node_id_to_community_map[level].items():
  98. community_id = str(raw_community_id)
  99. if community_id not in result:
  100. result[community_id] = {"weight": 0, "nodes": []}
  101. result[community_id]["nodes"].append(node_id)
  102. result[community_id]["weight"] += graph.nodes[node_id].get("rank", 0) * graph.nodes[node_id].get("weight", 1)
  103. weights = [comm["weight"] for _, comm in result.items()]
  104. if not weights:continue
  105. max_weight = max(weights)
  106. for _, comm in result.items(): comm["weight"] /= max_weight
  107. return results_by_level
  108. def add_community_info2graph(graph: nx.Graph, commu_info: dict[str, dict[str, dict]]):
  109. for lev, cluster_info in commu_info.items():
  110. for cid, nodes in cluster_info.items():
  111. for n in nodes["nodes"]:
  112. if "community" not in graph.nodes[n]: graph.nodes[n]["community"] = {}
  113. graph.nodes[n]["community"].update({lev: cid})
  114. def add_community_info2graph(graph: nx.Graph, nodes: List[str], community_title):
  115. for n in nodes:
  116. if "communities" not in graph.nodes[n]:
  117. graph.nodes[n]["communities"] = []
  118. graph.nodes[n]["communities"].append(community_title)