yog/community/leiden

Leiden method for community detection.

An improvement over the Louvain algorithm that guarantees well-connected communities. Adds a refinement step to ensure communities are properly connected internally.

Algorithm

The Leiden method works in three phases that repeat until convergence:

  1. Local Optimization (like Louvain): Nodes move to improve modularity
  2. Refinement: Partition communities into well-connected sub-communities
  3. Aggregation: Communities become super-nodes
  4. Repeat until convergence

Key Differences from Louvain

FeatureLouvainLeiden
SpeedFasterSlightly slower
Well-connected communitiesNot guaranteed✓ Guaranteed
Hierarchical qualityGoodBetter
Disconnected communitiesPossiblePrevented

When to Use

Complexity

Example

import yog
import yog/community/leiden
import yog/community/metrics

let graph =
  yog.undirected()
  |> yog.add_node(1, "A")
  |> yog.add_node(2, "B")
  |> yog.add_node(3, "C")
  |> yog.add_edges([#(1, 2, 1), #(2, 3, 1), #(3, 1, 1)])

// Basic usage
let communities = leiden.detect(graph)
io.debug(communities.num_communities)

// With custom options
let options = leiden.LeidenOptions(
  min_modularity_gain: 0.0001,
  max_iterations: 100,
  refinement_iterations: 5,
  seed: 42,
)
let communities = leiden.detect_with_options(graph, options)

References

Types

Options for the Leiden algorithm.

pub type LeidenOptions {
  LeidenOptions(
    min_modularity_gain: Float,
    max_iterations: Int,
    refinement_iterations: Int,
    seed: Int,
  )
}

Constructors

  • LeidenOptions(
      min_modularity_gain: Float,
      max_iterations: Int,
      refinement_iterations: Int,
      seed: Int,
    )

    Arguments

    min_modularity_gain

    Phase 1: stop when gain < threshold

    max_iterations

    Max iterations per phase

    refinement_iterations

    Refinement step iterations

    seed

    Random seed for tie-breaking

Values

pub fn default_options() -> LeidenOptions

Default options for Leiden algorithm.

pub fn detect(
  graph: model.Graph(n, Int),
) -> community.Communities

Detects communities using the Leiden algorithm with default options.

pub fn detect_hierarchical(
  graph: model.Graph(n, Int),
) -> community.Dendrogram

Full hierarchical Leiden detection.

pub fn detect_hierarchical_with_options(
  graph: model.Graph(n, Int),
  options: LeidenOptions,
) -> community.Dendrogram

Full hierarchical Leiden detection with custom options.

pub fn detect_with_options(
  graph: model.Graph(n, Int),
  options: LeidenOptions,
) -> community.Communities

Detects communities using the Leiden algorithm with custom options.

Search Document