Search documentation of Ragex

# Ragex.Graph.Algorithms (Ragex v0.4.0)

View Source

Graph algorithms for analyzing code structure and relationships.

Provides algorithms for:

- PageRank: Importance scoring based on call relationships
- Path Finding: Discovering call chains between functions
- Centrality Metrics: Degree, betweenness, clustering
- Graph Statistics: Overall graph analysis

## Summary

### Functions

betweenness_centrality(opts \\ [])

Computes betweenness centrality for nodes in the graph.

closeness_centrality(opts \\ [])

Computes closeness centrality for nodes in the graph.

degree_centrality()

Computes degree centrality for all nodes.

detect_communities(opts \\ [])

Detects communities in the graph using the Louvain method.

detect_communities_lp(opts \\ [])

Detects communities using label propagation algorithm.

export_d3_json(opts \\ [])

Exports the graph in D3.js force-directed JSON format.

export_graphviz(opts \\ [])

Exports the graph in Graphviz DOT format.

find_paths(from, to, opts \\ [])

Finds all paths between two nodes up to a maximum depth.

graph_stats()

Computes comprehensive graph statistics.

pagerank(opts \\ [])

Computes PageRank scores for all nodes in the graph.

## Functions

# betweenness_centrality(opts \\ [])

Computes betweenness centrality for nodes in the graph.

Betweenness measures how often a node appears on shortest paths between other nodes. Higher scores indicate "bridge" or "bottleneck" functions.

Uses Brandes' algorithm (O(nm) complexity).

## Parameters

- `:max_nodes` - Limit computation to N highest-degree nodes (default: from config, 1000)
- `:normalize` - Return normalized scores 0-1 (default: true)
- `:directed` - Treat graph as directed (default: true)

## Returns

Map of node_id => betweenness_score

## Examples

    # Compute for all nodes (up to configured max)
    betweenness_centrality()

    # Compute for top 100 nodes by degree
    betweenness_centrality(max_nodes: 100)

    # Get raw (unnormalized) scores
    betweenness_centrality(normalize: false)

# closeness_centrality(opts \\ [])

Computes closeness centrality for nodes in the graph.

Closeness is the inverse of the average shortest path distance from a node to all other reachable nodes. Higher scores indicate more "central" functions.

## Parameters

- `:normalize` - Return normalized scores 0-1 (default: true)

## Returns

Map of node_id => closeness_score

## Examples

    # Compute closeness for all nodes
    closeness_centrality()

    # Get raw (unnormalized) scores
    closeness_centrality(normalize: false)

# degree_centrality()

Computes degree centrality for all nodes.

Returns:

- `in_degree`: Number of incoming edges (callers)
- `out_degree`: Number of outgoing edges (callees)
- `total_degree`: Sum of in and out degree

# detect_communities(opts \\ [])

Detects communities in the graph using the Louvain method.

The Louvain algorithm iteratively optimizes modularity to discover communities. It naturally produces a hierarchy through aggregation phases.

## Parameters

- `:max_iterations` - Maximum optimization iterations (default: 10)
- `:min_improvement` - Minimum modularity improvement to continue (default: 0.0001)
- `:resolution` - Resolution parameter for multi-scale detection (default: 1.0)
- `:hierarchical` - Return hierarchical community structure (default: false)

## Returns

- When `:hierarchical` is false: Map of community_id => [node_ids]
- When `:hierarchical` is true: Map with :communities, :hierarchy, :modularity_per_level

## Examples

    # Detect communities
    detect_communities()

    # Get hierarchical structure
    detect_communities(hierarchical: true)

    # Adjust resolution for finer/coarser communities
    detect_communities(resolution: 0.5)

# detect_communities_lp(opts \\ [])

Detects communities using label propagation algorithm.

Fast alternative to Louvain. Each node adopts the most common label among neighbors. Converges quickly but results can be non-deterministic.

## Parameters

- `:max_iterations` - Maximum iterations (default: 20)
- `:seed` - Random seed for deterministic results (optional)

## Returns

Map of community_id => [node_ids]

## Examples

    # Detect communities with label propagation
    detect_communities_lp()

    # With deterministic seed
    detect_communities_lp(seed: 42)

# export_d3_json(opts \\ [])

Exports the graph in D3.js force-directed JSON format.

## Parameters

- `:include_communities` - Include community metadata (default: true)
- `:max_nodes` - Maximum nodes to include (default: from config, 500)

## Returns

`{:ok, json_map}` or `{:error, reason}`

## Examples

    # Export for D3.js visualization
    {:ok, json} = export_d3_json()
    File.write!("graph.json", Jason.encode!(json))

# export_graphviz(opts \\ [])

Exports the graph in Graphviz DOT format.

## Parameters

- `:include_communities` - Include community clustering (default: true)
- `:color_by` - Centrality metric for node coloring: :pagerank, :betweenness, :degree (default: :pagerank)
- `:max_nodes` - Maximum nodes to include (default: from config, 500)

## Returns

`{:ok, dot_string}` or `{:error, reason}`

## Examples

    # Export with default settings
    {:ok, dot} = export_graphviz()

    # Color by betweenness centrality
    {:ok, dot} = export_graphviz(color_by: :betweenness)

# find_paths(from, to, opts \\ [])

Finds all paths between two nodes up to a maximum depth.

## Parameters

- `from`: Source node ID
- `to`: Target node ID
- `opts`: Keyword list of options
  - `:max_depth` - Maximum path length in edges (default: 10)
  - `:max_paths` - Maximum number of paths to return (default: 100)
  - `:warn_dense` - Emit warnings for dense graphs (default: true)

## Returns

List of paths, where each path is a list of node IDs. Returns up to `max_paths` paths to prevent hangs on dense graphs.

## Examples

    # Find up to 100 paths with max depth of 10
    find_paths(from, to)

    # Find up to 50 paths with max depth of 5
    find_paths(from, to, max_depth: 5, max_paths: 50)

    # Disable warnings for dense graphs
    find_paths(from, to, warn_dense: false)

# graph_stats()

Computes comprehensive graph statistics.

Returns a map with:

- Node counts by type
- Edge counts
- Average degree
- Density
- Connected components count
- Top nodes by PageRank

# pagerank(opts \\ [])

Computes PageRank scores for all nodes in the graph.

PageRank measures the importance of nodes based on incoming edges. Higher scores indicate more "important" functions/modules (those called by many others).

## Parameters

- `damping_factor`: Probability of following an edge (default: 0.85)
- `max_iterations`: Maximum iterations (default: 100)
- `tolerance`: Convergence threshold (default: 0.0001)

## Returns

Map of node_id => pagerank_score