### Construct and Optimise Partition Manually Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md This example shows how to manually construct a partition using CPMVertexPartition and then optimize it using the Optimiser class. ```python >>> G = ig.Graph.Tree(100, 3) >>> partition = la.CPMVertexPartition(G, resolution_parameter = 0.1) >>> optimiser = la.Optimiser() >>> diff = optimiser.optimise_partition(partition) ``` -------------------------------- ### Install build tools on Ubuntu Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/install.md On Ubuntu systems, you need to install essential build tools before compiling from source. This command ensures that both C and C++ compilers are available. ```bash sudo apt-get install build-essential ``` -------------------------------- ### Run tests with setup.py Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/install.md After installation, you can verify the package integrity by running its test suite. This command executes the tests defined in the setup.py script. ```bash python setup.py test ``` -------------------------------- ### Initialize Optimiser Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/multiplex.md An optimiser object is required for multiplex community detection. This is the initial setup step. ```python optimiser = la.Optimiser() ``` -------------------------------- ### Find Partition using Modularity (Zachary's Karate Club) Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md This example demonstrates finding a community partition on Zachary's Karate Club graph using the ModularityVertexPartition method. ```python >>> G = ig.Graph.Famous('Zachary') >>> partition = la.find_partition(G, la.ModularityVertexPartition) ``` -------------------------------- ### Install Leidenalg with pip Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/install.md The simplest way to install Leidenalg is using pip. This command installs the latest stable version from the Python Package Index. ```bash pip install leidenalg ``` -------------------------------- ### Bipartite Community Detection with CPM Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/multiplex.md This example demonstrates how to set up and detect communities in a bipartite network using the CPM method. It involves creating three layers representing the bipartite structure and optimizing them with specific layer weights. ```pycon >>> p_01, p_0, p_1 = la.CPMVertexPartition.Bipartite(G, ... resolution_parameter_01=0.1); >>> diff = optimiser.optimise_partition_multiplex([p_01, p_0, p_1], ... layer_weights=[1, -1, -1]); ``` -------------------------------- ### Temporal Community Detection Example Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Demonstrates finding a community partition across multiple time slices using modularity optimization. Requires igraph and leidenalg libraries. ```python >>> n = 100 >>> G_1 = ig.Graph.Lattice([n], 1) >>> G_1.vs['id'] = range(n) >>> G_2 = ig.Graph.Lattice([n], 1) >>> G_2.vs['id'] = range(n) >>> membership, improvement = la.find_partition_temporal([G_1, G_2], ... la.ModularityVertexPartition, ... interslice_weight=1) ``` -------------------------------- ### Loading a Famous Network Graph Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/intro.md Load the Zachary karate club graph, a common example in network science, using igraph's built-in Famous() function. This graph is often used for demonstrating community detection algorithms. ```python >>> G = ig.Graph.Famous('Zachary') ``` -------------------------------- ### Instantiate Optimiser Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/advanced.md Create an instance of the Optimiser class. This is the first step to using its advanced partitioning functionalities. ```python >>> optimiser = la.Optimiser() ``` -------------------------------- ### Initialize Partitions for Layers and Interslice Layer Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/multiplex.md This snippet initializes community partitions for each layer and the interslice layer. It highlights the specific settings required for the interslice layer, such as `resolution_parameter=0` and `node_sizes='node_size'`, which are crucial for methods like `CPMVertexPartition`. ```python >>> partitions = [la.CPMVertexPartition(H, node_sizes='node_size', ... weights='weight', resolution_parameter=gamma) ... for H in layers]; >>> interslice_partition = la.CPMVertexPartition(interslice_layer, resolution_parameter=0, ... node_sizes='node_size', weights='weight'); ``` -------------------------------- ### Find Partition using New Method in Python Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/implement.md Demonstrates how to use the newly implemented 'CoolVertexPartition' with the Leiden algorithm's 'find_partition' function. ```python >>> la.find_partition(G, la.CoolVertexPartition); ``` -------------------------------- ### Constructing a Resolution Profile Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/advanced.md Use the Optimiser to generate a profile of partitions across a range of resolution parameters. This helps in scanning for optimal partitions at different resolutions. ```python >>> G = ig.Graph.Famous('Zachary') >>> optimiser = la.Optimiser() >>> profile = optimiser.resolution_profile(G, la.CPMVertexPartition, ... resolution_range=(0,1)) ``` -------------------------------- ### Aggregate Graph and Partition Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Shows how to aggregate a graph based on a partition and verify that the quality of the aggregated partition matches the original. ```python >>> G = ig.Graph.Famous('Zachary') >>> partition = la.find_partition(G, la.ModularityVertexPartition) >>> aggregate_partition = partition.aggregate_partition(partition) >>> aggregate_graph = aggregate_partition.graph >>> aggregate_partition.quality() == partition.quality() True ``` -------------------------------- ### Find Partition using Modularity Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md This snippet demonstrates the simplest way to find a community partition using the ModularityVertexPartition method. ```python >>> G = ig.Graph.Tree(100, 3) >>> partition = la.find_partition(G, la.ModularityVertexPartition) ``` -------------------------------- ### Emulate Louvain Algorithm Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/advanced.md A concise implementation of the Louvain algorithm using move_nodes and aggregate_partition. This process iteratively refines and aggregates the partition. ```python >>> partition = la.ModularityVertexPartition(G) >>> while optimiser.move_nodes(partition) > 0: ... partition = partition.aggregate_partition() ``` -------------------------------- ### Optimize Multiplex Partitions Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/multiplex.md This snippet demonstrates how to optimize the initialized partitions for all layers, including the interslice partition, using the `optimise_partition_multiplex` function. ```python >>> diff = optimiser.optimise_partition_multiplex(partitions + [interslice_partition]); ``` -------------------------------- ### Move Node to a New Community Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Demonstrates the basic usage of moving a specific node to a different community within a partition. ```python >>> G = ig.Graph.Famous('Zachary') >>> partition = la.ModularityVertexPartition(G) >>> partition.move_node(0, 1) ``` -------------------------------- ### Optimize Multiplex Partition with Different Resolutions Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/multiplex.md Optimizes a multiplex partition using CPMVertexPartition for each layer with potentially different resolution parameters. The membership will be identical across layers. ```python part_telephone = la.CPMVertexPartition( G_telephone, resolution_parameter=0.01) part_email = la.CPMVertexPartition( G_email, resolution_parameter=0.3) diff = optimiser.optimise_partition_multiplex( [part_telephone, part_email]) ``` -------------------------------- ### Import Packages for Leiden Algorithm Source: https://github.com/vtraag/leidenalg/blob/main/README.rst Import the leidenalg and igraph packages to utilize the Leiden algorithm and graph functionalities. ```python import leidenalg import igraph as ig ``` -------------------------------- ### Update Partition from Coarser Partition Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Illustrates how to update a partition to reflect changes made in an aggregated (coarser) partition. ```python >>> diff = optimiser.move_nodes(partition) >>> aggregate_partition = partition.aggregate_partition() >>> diff = optimiser.move_nodes(aggregate_partition) >>> partition.from_coarse_partition(aggregate_partition) ``` -------------------------------- ### Optimize Multiplex Partition with Layer Weights Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md This snippet demonstrates how to optimize a partition across multiple graphs (layers) with associated weights. It's useful for scenarios like multiplex graphs or time-sliced data, especially when dealing with negative links. ```python >>> G_pos = ig.Graph.SBM(100, pref_matrix=[[0.5, 0.1], [0.1, 0.5]], block_sizes=[50, 50]) >>> G_neg = ig.Graph.SBM(100, pref_matrix=[[0.1, 0.5], [0.5, 0.1]], block_sizes=[50, 50]) >>> optimiser = la.Optimiser() >>> partition_pos = la.ModularityVertexPartition(G_pos) >>> partition_neg = la.ModularityVertexPartition(G_neg) >>> diff = optimiser.optimise_partition_multiplex( ... partitions=[partition_pos, partition_neg], ... layer_weights=[1,-1]) ``` -------------------------------- ### Louvain Algorithm with Node Membership Update Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/advanced.md Implement the Louvain algorithm while keeping track of individual node memberships. This involves updating the partition from a coarse aggregate partition. ```python >>> partition = la.ModularityVertexPartition(G) >>> partition_agg = partition.aggregate_partition() >>> while optimiser.move_nodes(partition_agg): ... partition.from_coarse_partition(partition_agg) ... partition_agg = partition_agg.aggregate_partition() ``` -------------------------------- ### Calculate Partition Significance Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Demonstrates how to find a partition and then calculate its significance using the SignificanceVertexPartition class. ```python >>> p = la.find_partition(ig.Graph.Famous('Zachary'), ... la.ModularityVertexPartition) >>> sig = la.SignificanceVertexPartition.FromPartition(p).quality() ``` -------------------------------- ### C++ VertexPartition Creation Method Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/implement.md Implement these methods in your new C++ VertexPartition class to allow for its creation based on a graph, with or without an existing membership. ```c++ CoolVertexPartition* CoolVertexPartition::create(Graph* graph) { return new CoolVertexPartition(graph); } ``` ```c++ CoolVertexPartition* CoolVertexPartition::create(Graph* graph, vector const& membership) { return new CoolVertexPartition(graph, membership); } ``` -------------------------------- ### Define Python VertexPartition Class Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/implement.md Create the Python class for your new partition, inheriting from 'MutableVertexPartition' and adapting its constructor and docstring. ```python class CoolVertexPartition(MutableVertexPartition): def __init__(self, ... ): ... ``` -------------------------------- ### Optimise Partition with Max Iterations Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/advanced.md Use optimise_partition with a specified number of iterations. This limits the optimization process to a fixed number of steps. ```python >>> diff = optimiser.optimise_partition(partition, n_iterations=10) ``` -------------------------------- ### Node Movement in Partition Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/advanced.md Iterates through all vertices, finds the best community for each vertex based on diff_move, and then moves the node to that community using move_node. This provides a general idea of the optimiser's node movement logic. ```python for v in G.vs: best_comm = max(range(len(partition)), key=lambda c: partition.diff_move(v.index, c)) partition.move_node(v.index, best_comm) ``` -------------------------------- ### Calculate Difference in Quality by Moving a Node Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Compares the direct calculation of quality difference when moving a node to the actual change in quality after the move. ```python >>> partition = la.find_partition(ig.Graph.Famous('Zachary'), ... la.ModularityVertexPartition) >>> diff = partition.diff_move(v=0, new_comm=0) >>> q1 = partition.quality() >>> partition.move_node(v=0, new_comm=0) >>> q2 = partition.quality() >>> round(diff, 10) == round(q2 - q1, 10) True ``` -------------------------------- ### High-Level Leiden Algorithm Implementation Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/advanced.md A high-level implementation of the Leiden algorithm using constrained node movements and merging. This approach refines the partition before aggregation. ```python >>> # Set initial partition >>> partition = la.ModularityVertexPartition(G) >>> refined_partition = la.ModularityVertexPartition(G) >>> partition_agg = refined_partition.aggregate_partition() >>> >>> while optimiser.move_nodes(partition_agg): ... ... # Get individual membership for partition ... partition.from_coarse_partition(partition_agg, refined_partition.membership) ... ... # Refine partition ... refined_partition = la.ModularityVertexPartition(G) ... optimiser.merge_nodes_constrained(refined_partition, partition) ... ... # Define aggregate partition on refined partition ... partition_agg = refined_partition.aggregate_partition() ... ``` -------------------------------- ### resolution_profile Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Constructs a resolution profile by performing bisectioning on the resolution parameter. It scans a given range of resolution values to find partitions. ```APIDOC ## resolution_profile ### Description Use bisectioning on the resolution parameter in order to construct a resolution profile. ### Parameters * **graph** – The graph for which to construct a resolution profile. * **partition_type** – The type of [`MutableVertexPartition`](#leidenalg.VertexPartition.MutableVertexPartition) used to find a partition (must support resolution parameters obviously). * **resolution_range** – The range of resolution values that we would like to scan. * **weights** – If provided, indicates the edge attribute to use as a weight. * **bisect_func** – The function used for bisectioning. For the methods currently implemented, this should usually not be altered. * **min_diff_bisect_value** – The difference in the value returned by the bisect_func below which the bisectioning stops (i.e. by default, a difference of a single edge does not trigger further bisectioning). * **min_diff_resolution** – The difference in resolution below which the bisectioning stops. For positive differences, the logarithmic difference is used by default, i.e. `diff = log(res_1) - log(res_2) = log(res_1/res_2)`, for which `diff > min_diff_resolution` to continue bisectioning. Set the linear_bisection to true in order to use only linear bisectioning (in the case of negative resolution parameters for example, which can happen with negative weights). * **linear_bisection** – Whether the bisectioning will be done on a linear or on a logarithmic basis (if possible). * **number_iterations** – Indicates the number of iterations of the algorithm to run. If negative (or zero) the algorithm is run until a stable iteration. ### Returns A list of partitions for different resolutions. ### Return type list of [`MutableVertexPartition`](#leidenalg.VertexPartition.MutableVertexPartition) ### Examples ```pycon >>> G = ig.Graph.Famous('Zachary') >>> optimiser = la.Optimiser() >>> profile = optimiser.resolution_profile(G, la.CPMVertexPartition, ... resolution_range=(0,1)) ``` ``` -------------------------------- ### Import Python Class in __init__.py Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/implement.md Make your newly created Python class available at the package level by importing it in the package's '__init__.py' file. ```python from .VertexPartition import CoolVertexPartition ``` -------------------------------- ### Importing Libraries for Network Analysis Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/intro.md Import the igraph and leidenalg libraries to perform network analysis and community detection. These are the essential imports for most operations in this documentation. ```python >>> import igraph as ig >>> import leidenalg as la ``` -------------------------------- ### Create a Random Graph Source: https://github.com/vtraag/leidenalg/blob/main/README.rst Generate a random graph using the Erdos-Renyi model for testing purposes. This graph will have 100 nodes and a 0.1 probability of an edge between any two nodes. ```python G = ig.Graph.Erdos_Renyi(100, 0.1); ``` -------------------------------- ### Find Partition using Modularity Source: https://github.com/vtraag/leidenalg/blob/main/README.rst Use the leidenalg.find_partition function to determine the community structure of a graph based on the ModularityVertexPartition objective. ```python part = leidenalg.find_partition(G, leidenalg.ModularityVertexPartition); ``` -------------------------------- ### Construct Resolution Profile Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Generates a resolution profile for a given graph using the CPMVertexPartition method. Requires the igraph library for graph creation. ```python import igraph as ig import leidenalg as la G = ig.Graph.Famous('Zachary') optimiser = la.Optimiser() profile = optimiser.resolution_profile(G, la.CPMVertexPartition, resolution_range=(0,1)) ``` -------------------------------- ### leidenalg.RBConfigurationVertexPartition Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Implements Reichardt and Bornholdt’s Potts model with a configuration null model, suitable for graphs with positive edge weights. This quality function uses a linear resolution parameter. ```APIDOC ## class leidenalg.RBConfigurationVertexPartition(graph, initial_membership=None, weights=None, resolution_parameter=1.0) ### Description Implements Reichardt and Bornholdt’s Potts model with a configuration null model. This quality function is well-defined only for positive edge weights. This quality function uses a linear resolution parameter. ### Parameters: #### Path Parameters - **graph** (`ig.Graph`) - Description: Graph to define the partition on. - **initial_membership** (*list* *of* *int*) - Description: Initial membership for the partition. If `None` then defaults to a singleton partition. - **weights** (*list* *of* *double* *, or* *edge attribute*) - Description: Weights of edges. Can be either an iterable or an edge attribute. - **resolution_parameter** (*double*) - Description: The resolution parameter for the quality function. ``` -------------------------------- ### Optimize Multiplex Partition with Layer Weights Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/multiplex.md Optimizes a multiplex partition with specified weights for each layer. This allows for differential importance of layers in the community detection process. ```python diff = optimiser.optimise_partition_multiplex( [part_telephone, part_email], layer_weights=[1,0.5]) ``` -------------------------------- ### Python Interface for New VertexPartition Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/implement.md Add a new C++ function to the Python interface in 'python_partition_interface.cpp' to handle the creation of your new VertexPartition type. ```c++ PyObject* _new_CoolVertexPartition(PyObject *self, PyObject *args, PyObject *keywds) { return new CoolVertexPartition(graph); } ``` -------------------------------- ### Basic Community Detection with Modularity Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/intro.md Detect communities in a graph G using the ModularityVertexPartition method. This is the simplest way to find communities when modularity is the primary optimization goal. ```python >>> partition = la.find_partition(G, la.ModularityVertexPartition) ``` -------------------------------- ### Finding Partition with Maximum Community Size Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/advanced.md Constrain the size of communities during partition finding by setting the `max_comm_size` parameter. This ensures that no community exceeds the specified maximum size. ```python >>> partition = la.find_partition(G, la.ModularityVertexPartition, max_comm_size=10) ``` -------------------------------- ### Community Detection with CPMVertexPartition and Resolution Parameter Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/intro.md Detect communities using the CPMVertexPartition method, allowing customization with parameters like resolution_parameter. This method can uncover different community structures compared to modularity-based methods. ```python >>> partition = la.find_partition(G, la.CPMVertexPartition, ... resolution_parameter = 0.05) ``` -------------------------------- ### leidenalg.find_partition Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Detect communities using the default settings of the Leiden algorithm. This function takes a graph and a partition type, and optionally initial membership, edge weights, and other parameters to find an optimized partition. ```APIDOC ## leidenalg.find_partition(graph, partition_type, initial_membership=None, weights=None, n_iterations=2, max_comm_size=0, seed=None, **kwargs) ### Description Detect communities using the default settings. This function detects communities given the specified method in the `partition_type`. This should be type derived from [`VertexPartition.MutableVertexPartition`](#leidenalg.VertexPartition.MutableVertexPartition), e.g. [`ModularityVertexPartition`](#leidenalg.ModularityVertexPartition) or [`CPMVertexPartition`](#leidenalg.CPMVertexPartition). Optionally an initial membership and edge weights can be provided. Remaining `**kwargs` are passed on to the constructor of the `partition_type`, including for example a `resolution_parameter`. ### Parameters #### Path Parameters * **graph** (`ig.Graph`) – The graph for which to detect communities. * **partition_type** (type of :class:` ``` ``` ) – The type of partition to use for optimisation. * **initial_membership** (*list* *of* *int*) – Initial membership for the partition. If `None` then defaults to a singleton partition. * **weights** (*list* *of* *double* *, or* *edge attribute*) – Weights of edges. Can be either an iterable or an edge attribute. * **n_iterations** (*int*) – Number of iterations to run the Leiden algorithm. By default, 2 iterations are run. If the number of iterations is negative, the Leiden algorithm is run until an iteration in which there was no improvement. * **max_comm_size** (*non-negative int*) – Maximal total size of nodes in a community. If zero (the default), then communities can be of any size. * **seed** (*int*) – Seed for the random number generator. By default uses a random seed if nothing is specified. * **kwargs** – Remaining keyword arguments, passed on to constructor of `partition_type`. ### Returns The optimised partition. ### Return type partition #### SEE ALSO [`Optimiser.optimise_partition()`](#leidenalg.Optimiser.optimise_partition) ### Examples ```pycon >>> G = ig.Graph.Famous('Zachary') >>> partition = la.find_partition(G, la.ModularityVertexPartition) ``` ``` -------------------------------- ### Repeatedly Optimise Partition Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/advanced.md Continuously call optimise_partition until no further improvement is made. This is useful for finding a stable partition. ```python >>> G = ig.Graph.Erdos_Renyi(100, p=5./100) >>> partition = la.ModularityVertexPartition(G) >>> diff = 1 >>> while diff > 0: ... diff = optimiser.optimise_partition(partition) ``` -------------------------------- ### Create Coupling Graph and Define Slice Membership Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/multiplex.md This snippet demonstrates how to create a coupling graph where nodes represent slices and edges represent their couplings. It also shows how to assign the actual graph objects to the 'slice' attribute of the coupling graph's vertices. ```python >>> G_coupling = ig.Graph.Formula('1 -- 2 -- 3'); >>> G_coupling.es['weight'] = 0.1; # Interslice coupling strength >>> G_coupling.vs['slice'] = [G_1, G_2, G_3] ``` -------------------------------- ### Optimise Partition in LeidenAlg Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Optimizes a given graph partition using the Leiden algorithm for a specified number of iterations. Can fix the membership of certain nodes to prevent them from changing communities. ```python >>> G = ig.Graph.Famous('Zachary') >>> optimiser = la.Optimiser() >>> partition = la.ModularityVertexPartition(G) >>> diff = optimiser.optimise_partition(partition) ``` ```python >>> is_membership_fixed = [False for v in G.vs] >>> is_membership_fixed[4] = True >>> is_membership_fixed[6] = True >>> diff = optimiser.optimise_partition(partition, is_membership_fixed=is_membership_fixed) ``` -------------------------------- ### Move Nodes for Partition Optimization Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Use `move_nodes` to optimize a partition by moving nodes to alternative communities. The function continues until no more nodes can be moved to improve the partition. ```python >>> G = ig.Graph.Famous('Zachary') >>> optimiser = la.Optimiser() >>> partition = la.ModularityVertexPartition(G) >>> diff = optimiser.move_nodes(partition) ``` -------------------------------- ### Expose C++ Method in pynterface.h Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/implement.md Register the C++ function created in the previous step within the 'leiden_funcs' array in 'pynterface.h' to make it accessible from Python. ```c++ leiden_funcs[] = { ... "cool_vertex_partition", _new_CoolVertexPartition, ... }; ``` -------------------------------- ### Separating Graph Edges into Positive and Negative Layers Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/multiplex.md This snippet demonstrates how to create two separate graph layers from an original graph: one containing only positive edge weights and another with negative edge weights. The weights in the negative layer are then inverted to be used with algorithms that expect positive weights. ```python >>> G_pos = G.subgraph_edges(G.es.select(weight_gt = 0), delete_vertices=False); >>> G_neg = G.subgraph_edges(G.es.select(weight_lt = 0), delete_vertices=False); >>> G_neg.es['weight'] = [-w for w in G_neg.es['weight']]; ``` -------------------------------- ### Optimiser.move_nodes Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Moves nodes to alternative communities to optimize the partition quality. The function iteratively considers moving nodes until no further improvements can be made. ```APIDOC ## move_nodes(partition, is_membership_fixed=None, consider_comms=None) ### Description Move nodes to alternative communities for *optimising* the partition. ### Parameters * **partition** – The partition for which to move nodes. * **is_membership_fixed** (*list* *of* *bools* *or* *None*) – Boolean list of nodes that are not allowed to change community. The length of this list must be equal to the number of nodes. By default (None) all nodes can change community during the optimization. * **consider_comms** – If `None` uses [`consider_comms`](#leidenalg.Optimiser.consider_comms), but can be set to something else. ### Returns Improvement in quality function. ### Return type float ### Notes When moving nodes, the function loops over nodes and considers moving the node to an alternative community. Which community depends on `consider_comms`. The function terminates when no more nodes can be moved to an alternative community. ### SEE ALSO [`Optimiser.move_nodes_constrained()`](#leidenalg.Optimiser.move_nodes_constrained), [`Optimiser.merge_nodes()`](#leidenalg.Optimiser.merge_nodes) ### Examples ```pycon >>> G = ig.Graph.Famous('Zachary') >>> optimiser = la.Optimiser() >>> partition = la.ModularityVertexPartition(G) >>> diff = optimiser.move_nodes(partition) ``` ``` -------------------------------- ### Optimise Partition Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/advanced.md Call the optimise_partition method to improve a given partition. This method attempts to find a better partitioning of the graph. ```python >>> diff = optimiser.optimise_partition(partition) ``` -------------------------------- ### optimise_partition_multiplex Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Optimizes multiple partitions simultaneously, considering layer weights and optionally fixing node memberships. Returns the improvement in the quality of the combined partitions. ```APIDOC ## optimise_partition_multiplex(partitions, layer_weights=None, n_iterations=2, is_membership_fixed=None) ### Description Optimise the given partitions simultaneously. ### Parameters #### Path Parameters * **partitions** (list of MutableVertexPartition) - Required - List of [`MutableVertexPartition`](#leidenalg.VertexPartition.MutableVertexPartition) layers to optimise. * **layer_weights** (list) - Optional - List of weights of layers. * **is_membership_fixed** (list of bools or None) - Optional - Boolean list of nodes that are not allowed to change community. The length of this list must be equal to the number of nodes. By default (None) all nodes can change community during the optimization. * **n_iterations** (int) - Optional - Number of iterations to run the Leiden algorithm. By default, 2 iterations are run. If the number of iterations is negative, the Leiden algorithm is run until an iteration in which there was no improvement. ### Returns Improvement in quality of combined partitions, see [Notes](#notes-multiplex). ### Return type float ``` -------------------------------- ### optimise_partition Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Optimizes the given partition by running the Leiden algorithm for a specified number of iterations or until no improvement is made. It can also optionally fix the membership of certain nodes. ```APIDOC ## optimise_partition(partition, n_iterations=2, is_membership_fixed=None) ### Description Optimise the given partition. ### Parameters #### Path Parameters * **partition** (MutableVertexPartition) - Required - The [`MutableVertexPartition`](#leidenalg.VertexPartition.MutableVertexPartition) to optimise. * **n_iterations** (int) - Optional - Number of iterations to run the Leiden algorithm. By default, 2 iterations are run. If the number of iterations is negative, the Leiden algorithm is run until an iteration in which there was no improvement. * **is_membership_fixed** (list of bools or None) - Optional - Boolean list of nodes that are not allowed to change community. The length of this list must be equal to the number of nodes. By default (None) all nodes can change community during the optimization. ### Returns Improvement in quality function. ### Return type float ### Examples ```pycon >>> G = ig.Graph.Famous('Zachary') >>> optimiser = la.Optimiser() >>> partition = la.ModularityVertexPartition(G) >>> diff = optimiser.optimise_partition(partition) ``` or, fixing the membership of some nodes: ```pycon >>> is_membership_fixed = [False for v in G.vs] >>> is_membership_fixed[4] = True >>> is_membership_fixed[6] = True >>> diff = optimiser.optimise_partition(partition, is_membership_fixed=is_membership_fixed) ``` ``` -------------------------------- ### Move Nodes Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/advanced.md Call the move_nodes method to attempt to improve the partition by moving individual nodes between communities. ```python >>> diff = optimiser.move_nodes(partition) ``` -------------------------------- ### Time Slices to Layers Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/multiplex.md Obtain actual partitions from time slices using this function. It converts a list of graph slices into layers and creates an interslice layer for community detection. ```python >>> layers, interslice_layer, G_full = \ ... la.time_slices_to_layers([G_1, G_2, G_3], ... interslice_weight=0.1); >>> partitions = [la.CPMVertexPartition(H, node_sizes='node_size', ... weights='weight', ... resolution_parameter=gamma) ... for H in layers]; >>> interslice_partition = \ ... la.CPMVertexPartition(interslice_layer, resolution_parameter=0, ... node_sizes='node_size', weights='weight'); >>> diff = optimiser.optimise_partition_multiplex(partitions + [interslice_partition]); ``` -------------------------------- ### CPMVertexPartition Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Implements the Constant Potts Model (CPM). This quality function is well-defined for both positive and negative edge weights and uses a linear resolution parameter. ```APIDOC ## CPMVertexPartition ### class leidenalg.CPMVertexPartition(graph, initial_membership=None, weights=None, node_sizes=None, resolution_parameter=1.0, correct_self_loops=None) Bases: `LinearResolutionParameterVertexPartition` Implements the Constant Potts Model (CPM). This quality function is well-defined for both positive and negative edge weights. This quality function uses a linear resolution parameter. ``` -------------------------------- ### from_coarse_partition Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Updates the current partition according to a coarser partition. This is useful for reflecting changes made in an aggregated graph back to the original partition. ```APIDOC ## from_coarse_partition(partition, coarse_node=None) ### Description Update current partition according to coarser partition. This function is to be used to determine the correct partition for an aggregated graph, reflecting changes made in the aggregate partition back to the original. ### Method Not specified (assumed to be a method of a partition object) ### Endpoint Not applicable (Python method) ### Parameters * **partition** (MutableVertexPartition) - The coarser partition used to update the current partition. * **coarse_node** (list of int, optional) - The coarser node which represents the current node in the partition. ### Notes If `coarse_node` is `None`, it is assumed the coarse node was defined based on the membership of the current partition. ### Examples ```pycon # Assuming 'partition' and 'aggregate_partition' are already defined partition.from_coarse_partition(aggregate_partition) ``` ``` -------------------------------- ### total_possible_edges_in_all_comms Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Calculates the total possible number of edges within all communities in the partition. This is based on the number of nodes in each community. ```APIDOC ## total_possible_edges_in_all_comms() ### Description The total possible number of edges in all communities. ### Method Not specified (assumed to be a method of a partition object) ### Endpoint Not applicable (Python method) ### Returns Total possible edges. ### Notes If we denote by $n_c$ the number of nodes in community $c$, this is simply $\sum_c \binom{n_c}{2}$. ### Examples ```pycon total_edges = partition.total_possible_edges_in_all_comms() ``` ``` -------------------------------- ### Community Detection on Multiplex Layers with Negative Weights Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/multiplex.md This code snippet shows how to perform community detection on separate positive and negative graph layers using the ModularityVertexPartition algorithm. It then uses the optimise_partition_multiplex function to find communities across these layers, applying a specific weight to the negative layer. ```python >>> part_pos = la.ModularityVertexPartition(G_pos, weights='weight'); >>> part_neg = la.ModularityVertexPartition(G_neg, weights='weight'); >>> diff = optimiser.optimise_partition_multiplex( ... [part_pos, part_neg], ... layer_weights=[1,-1]); ``` -------------------------------- ### Updating Partition with Fixed Nodes Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/advanced.md When extending a graph, preserve existing community assignments for old nodes while updating assignments for new nodes. This uses the `is_membership_fixed` argument to selectively update the partition. ```python >>> new_membership = list(range(G2.vcount())) ... new_membership[:G.vcount()] = partition.membership >>> new_partition = la.CPMVertexPartition(G2, new_membership, ... resolution_parameter=partition.resolution_parameter) >>> is_membership_fixed = [i < G.vcount() for i in range(G2.vcount())] >>> diff = optimiser.optimise_partition(new_partition, is_membership_fixed=is_membership_fixed) ``` -------------------------------- ### RBERVertexPartition Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Implements Reichardt and Bornholdt’s Potts model with an Erdős-Rényi null model. This quality function is well-defined only for positive edge weights and uses a linear resolution parameter. ```APIDOC ## RBERVertexPartition ### class leidenalg.RBERVertexPartition(graph, initial_membership=None, weights=None, node_sizes=None, resolution_parameter=1.0) Bases: `LinearResolutionParameterVertexPartition` Implements Reichardt and Bornholdt’s Potts model with an Erdős-Rényi null model. This quality function is well-defined only for positive edge weights. This quality function uses a linear resolution parameter. ### Parameters * **graph** (`ig.Graph`) – Graph to define the partition on. * **initial_membership** (*list* *of* *int*) – Initial membership for the partition. If `None` then defaults to a singleton partition. * **weights** (*list* *of* *double* *, or* *edge attribute*) – Weights of edges. Can be either an iterable or an edge attribute. * **node_sizes** (*list* *of* *int* *, or* *vertex attribute*) – The quality function takes into account the size of a community, which is defined as the sum over the sizes of each individual node. By default, the node sizes are set to 1, meaning that the size of a community equals the number of nodes of a community. If a node already represents an aggregation, this could be reflect in its node size. * **resolution_parameter** (*double*) – Resolution parameter. ``` -------------------------------- ### total_weight_to_comm(comm) Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Calculates the total weight (number of edges) directed to a specified community. This includes edges internal to the community and is sometimes referred to as the community's in-degree. ```APIDOC ## total_weight_to_comm(comm) ### Description The total weight (i.e. number of edges) to a community. ### Notes This includes all edges, also the ones that are internal to a community. Sometimes this is also referred to as the community (in)degree. ### Parameters: #### Path Parameters - **comm** (Community) - Description: Community ### SEE ALSO `total_weight_from_comm()`, `total_weight_in_comm()`, `total_weight_in_all_comms()` ``` -------------------------------- ### quality Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Returns the current quality score of the partition. This method is used to assess the quality of the community structure. ```APIDOC ## quality() ### Description The current quality of the partition. ### Method Not specified (assumed to be a method of a partition object) ### Endpoint Not applicable (Python method) ### Returns The quality score of the partition. ### Examples ```pycon partition = la.find_partition(ig.Graph.Famous('Zachary'), la.ModularityVertexPartition) quality_score = partition.quality() ``` ``` -------------------------------- ### Find Partition for Multiplex Graphs Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Detects communities in a list of multiplex graphs. Ensure all graphs share the same set of vertices. This function is useful for analyzing networks with multiple layers of interaction. ```python import leidenalg as la import igraph as ig n = 100 G_1 = ig.Graph.Lattice([n], 1) G_2 = ig.Graph.Lattice([n], 1) membership, improvement = la.find_partition_multiplex([G_1, G_2], la.ModularityVertexPartition) ``` -------------------------------- ### total_weight_from_comm Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Calculates the total weight (number of edges) originating from a specific community. This helps in understanding the connectivity of a community. ```APIDOC ## total_weight_from_comm(comm) ### Description The total weight (i.e. number of edges) from a community. ### Method Not specified (assumed to be a method of a partition object) ### Endpoint Not applicable (Python method) ### Parameters * **comm** (int) - The community identifier. ### Returns Total weight (number of edges) from the specified community. ### Examples ```pycon total_weight = partition.total_weight_from_comm(0) ``` ``` -------------------------------- ### total_weight_in_all_comms() Source: https://github.com/vtraag/leidenalg/blob/main/doc/source/reference.md Calculates the total weight (number of edges) within all communities. This value should be the sum of `total_weight_in_comm` for all individual communities. ```APIDOC ## total_weight_in_all_comms() ### Description The total weight (i.e. number of edges) within all communities. ### Notes This should be equal to simply the sum of `total_weight_in_comm` for all communities. ### SEE ALSO `total_weight_to_comm()`, `total_weight_from_comm()`, `total_weight_in_comm()` ```