This function calculates the optimal community structure of a graph, by maximizing the modularity measure over all possible partitions.

## Arguments

- graph
The input graph. Edge directions are ignored for directed graphs.

- weights
The weights of the edges. It must be a positive numeric vector,

`NULL`

or`NA`

. If it is`NULL`

and the input graph has a ‘weight’ edge attribute, then that attribute will be used. If`NULL`

and no such attribute is present, then the edges will have equal weights. Set this to`NA`

if the graph was a ‘weight’ edge attribute, but you don't want to use it for community detection. A larger edge weight means a stronger connection for this function.

## Value

`cluster_optimal()`

returns a `communities()`

object,
please see the `communities()`

manual page for details.

## Details

This function calculates the optimal community structure for a graph, in terms of maximal modularity score.

The calculation is done by transforming the modularity maximization into an integer programming problem, and then calling the GLPK library to solve that. Please the reference below for details.

Note that modularity optimization is an NP-complete problem, and all known algorithms for it have exponential time complexity. This means that you probably don't want to run this function on larger graphs. Graphs with up to fifty vertices should be fine, graphs with a couple of hundred vertices might be possible.

## Examples

```
## Zachary's karate club
g <- make_graph("Zachary")
## We put everything into a big 'try' block, in case
## igraph was compiled without GLPK support
## The calculation only takes a couple of seconds
oc <- cluster_optimal(g)
## Double check the result
print(modularity(oc))
print(modularity(g, membership(oc)))
## Compare to the greedy optimizer
fc <- cluster_fast_greedy(g)
print(modularity(fc))
```

## References

Ulrik Brandes, Daniel Delling, Marco Gaertler, Robert Gorke,
Martin Hoefer, Zoran Nikoloski, Dorothea Wagner: On Modularity Clustering,
*IEEE Transactions on Knowledge and Data Engineering* 20(2):172-188,
2008.

## See also

`communities()`

for the documentation of the result,
`modularity()`

. See also `cluster_fast_greedy()`

for a
fast greedy optimizer.

Community detection
`as_membership()`

,
`cluster_edge_betweenness()`

,
`cluster_fast_greedy()`

,
`cluster_fluid_communities()`

,
`cluster_infomap()`

,
`cluster_label_prop()`

,
`cluster_leading_eigen()`

,
`cluster_leiden()`

,
`cluster_louvain()`

,
`cluster_spinglass()`

,
`cluster_walktrap()`

,
`compare()`

,
`groups()`

,
`make_clusters()`

,
`membership()`

,
`modularity.igraph()`

,
`plot_dendrogram()`

,
`split_join_distance()`

,
`voronoi_cells()`

## Author

Gabor Csardi csardi.gabor@gmail.com