TGraphX › Insights › Evolutionary Optimization over Graph Structures with TGraphX
← Back to Insights

Evolutionary Optimization over Graph Structures with TGraphX

Topic: Graph mining, generation, optimization and RL

Some problems search over graph structure itself: which edges to keep, how to connect a set of nodes cheaply, how to trade one structural property against another. The choice of edges is discrete, so gradient descent does not apply directly. Evolutionary algorithms are one option, because all they need is a function that scores a candidate graph.

TGraphX ships a genetic algorithm (GA), NSGA-II, simulated annealing, hill climbing and random search in tgraphx.evolutionary. Treat the subsystem as experimental: tgx.api_status("optimize_graph") returns experimental, and list_evolutionary_optimizers() labels GA, SA and NSGA-II Experimental and the two simpler searches Beta. Examples tested with TGraphX 1.5.1 on CPU.

What the subsystem includes

All optimizers maximise fitness:

Class Starts from How it searches
GeneticAlgorithmOptimizer list of genomes elitism, tournament selection, edge crossover, mutation
NSGAIIOptimizer list of genomes several objectives at once, returns a Pareto front
SimulatedAnnealingOptimizer one genome random mutations with a cooling acceptance rule
HillClimbingOptimizer one genome keeps mutations that do not lower the score
RandomSearchOptimizer one genome baseline: 1 to 3 random mutations of the start genome

A candidate is a GraphGenome: an edge_index, a node count and optional node and edge features and types. Edges are directed. The built-in fitness functions take a genome and return a number:

  • connectivity_fitness: fraction of node pairs joined by a path, ignoring edge direction (1.0 for a connected graph).
  • density_fitness: 1 - |density - target_density|, with target_density=0.5 by default. It rewards being close to a target, not being dense.
  • sparsity_fitness: 1 - density, where density is the number of directed edges divided by N(N-1).
  • clustering_fitness: mean local clustering coefficient.
  • motif_count_fitness: raw triangle count, or wedge count with motif_type="wedge". It is not normalised, although its docstring says it is.
  • composite_fitness(genome, [(fn, weight), ...]): a weighted sum.

Warning: do not put node_features on genomes you pass to GeneticAlgorithmOptimizer or NSGAIIOptimizer in 1.5.1. Their crossover gives each child the larger of the two parents' node counts but a copy of the first parent's features. The rows and num_nodes can then disagree, and a later node removal raises IndexError. With a population of 40 ten-node genomes carrying features, every GA run on connectivity_fitness and every NSGA-II run on connectivity and sparsity failed this way (seeds 0 to 4, 50 generations). A node-count check in the fitness function does not prevent it, and even when nothing crashes, features do not follow their nodes through crossover. Keep features outside the genome and attach them to the winning structure, as the spanning-tree example below does.

The package also has mutation operators for nodes, edges, features and types, several crossover and selection functions, and constraint_penalty. The built-in optimizers use only five structural mutations (add node, remove node, add edge, remove edge, rewire edge) and, in GA and NSGA-II, edge_set_crossover. They never mutate features or types.

The one-call API

python
import tgraphx as tgx

result = tgx.optimize_graph(
    "clustering",
    algorithm="ga",
    num_nodes=20,
    generations=50,
    population_size=30,
    max_edges=100,
    seed=42,
    fast_mode=False,  # the default, True, caps the run at 3 generations and population 6
)
history = result.fitness_history
print(len(history), round(history[0], 3), round(result.best_fitness, 3))
print(result.best_genome.num_nodes, result.best_genome.num_edges)
# Output with TGraphX 1.5.1 on CPU:
# 50 0.335 0.568
# 17 34

The return value is an OptimizationResult with best_genome, best_fitness, fitness_history, metrics, pareto_front and config. Several behaviours are easy to miss:

  • fast_mode=True is the default and silently caps generations at 3 and population size at 6.
  • Unrecognised keywords are ignored without a warning. num_generations=100 or mutation_rate=0.9 change nothing.
  • The string objectives are connectivity, density, clustering and motif_count. "sparsity" raises ValueError even though the docstring lists it, and you cannot pass your own Python function.
  • num_nodes is the starting size and an upper limit, not a fixed size. Mutations can delete nodes, which is why the best graph above has 17.
  • The search starts from a path graph (GA and NSGA-II may add a few random edges to copies of it). A path is already connected, so "connectivity" scores 1.0 from the first generation.
  • max_edges defaults to 20, and a path on 11 or more nodes already has at least 20 directed edges, so mutations cannot add edges until some are removed. Set it yourself.

A problem with a known answer

To judge an optimizer, give it a problem whose optimum you know. Connect 10 nodes with as few edges as possible. The answer is a spanning tree with 9 edges, so with a cost of 0.01 per edge the best possible score is 1.0 - 0.09 = 0.91. Custom fitness functions go to the optimizer classes:

python
import torch
from tgraphx import Graph
from tgraphx.evolutionary import (
    GeneticAlgorithmConfig,
    GeneticAlgorithmOptimizer,
    GraphGenome,
    connectivity_fitness,
)

N = 10

def empty_genome():
    return GraphGenome(edge_index=torch.empty((2, 0), dtype=torch.long), num_nodes=N)

def fitness(genome):
    if genome.num_nodes != N:  # the built-in mutations also add and remove nodes
        return -1.0
    return connectivity_fitness(genome) - 0.01 * genome.num_edges

config = GeneticAlgorithmConfig(
    population_size=40, n_generations=150, mutation_rate=0.2,
    seed=0, max_nodes=N, max_edges=30,
)
ga = GeneticAlgorithmOptimizer(config, fitness).optimize([empty_genome() for _ in range(40)])
best = ga.best_genome
print(round(ga.best_fitness, 2), best.num_nodes, best.num_edges, connectivity_fitness(best))
# 0.91 10 9 1.0

# Turn the winning structure into a Graph with image-like node features
g = Graph(node_features=torch.randn(best.num_nodes, 3, 8, 8), edge_index=best.edge_index.clone())
g.make_undirected()  # genome edges are directed; add the reverse direction for message passing

Do not skip the node-count check. A one-node graph counts as connected and has no edges, so without the check it scores 1.0, higher than any 10-node solution. With the check removed, runs with seeds 0 to 4 all ended with fewer than 5 nodes, two of them with a single node. With the check, all five seeds reached 0.91.

The GA calls the fitness function once per initial genome and then once per genome in every generation, elites included: 40 + 40 × 150 = 6,040 calls here. Cache results if one call is expensive.

The single-genome optimizers

Simulated annealing, hill climbing and random search take an EvolutionConfig and one starting genome. This block reuses fitness from above:

python
from tgraphx.evolutionary import (
    EvolutionConfig,
    HillClimbingOptimizer,
    RandomSearchOptimizer,
    SimulatedAnnealingOptimizer,
)

sa_config = EvolutionConfig(seed=0, max_nodes=N, max_edges=30,
                            T_init=0.05, T_min=0.001, cooling_rate=0.995)
hc_config = EvolutionConfig(seed=0, max_nodes=N, max_edges=30,
                            n_generations=500, num_restarts=1)

sa = SimulatedAnnealingOptimizer(sa_config, fitness).optimize(empty_genome())
hc = HillClimbingOptimizer(hc_config, fitness).optimize(empty_genome())
rs = RandomSearchOptimizer(hc_config, fitness, num_graphs=500).optimize(empty_genome())

for name, res in [("annealing", sa), ("hill climbing", hc), ("random search", rs)]:
    print(f"{name:14s} {res.best_fitness:.3f} edges={res.best_genome.num_edges}")
# annealing      0.910 edges=9
# hill climbing  0.910 edges=9
# random search  0.103 edges=3

This is a check of the settings on a very easy problem, not a ranking of the algorithms. What matters in practice:

  • Annealing ignores n_generations and runs until the temperature falls below T_min. Choose temperatures on the scale of your score differences (a redundant edge costs 0.01 here). With the default temperature schedule (T_init=1.0, T_min=0.01, cooling_rate=0.95: 90 steps) and the same size limits, seeds 0 to 4 returned best_fitness values from 0.0 to 0.91. Its fitness_history records the current score, not the best so far.
  • Hill climbing runs n_generations // num_restarts steps per restart (10 with the defaults). If n_generations is smaller than num_restarts, no climbing happens. That includes optimize_graph(algorithm="hill_climb") with fewer than 10 generations, and so every fast-mode run.
  • Random search applies only 1 to 3 mutations to the start genome, so from an empty graph it cannot reach 9 edges.

Multi-objective optimization with NSGA-II

For competing objectives, use NSGA-II to find the Pareto front (details in NSGA-II and Pareto fronts): the set of solutions that cannot be improved in one objective without losing in another.

Connectivity against sparsity on 10 nodes is a good test because the true front is known. With m edges, for m from 0 to 9, the best connectivity is m(m+1)/90 (all edges in one tree) at sparsity 1 - m/90. That gives 10 points.

python
from tgraphx.evolutionary import NSGAIIOptimizer, sparsity_fitness

def same_size(fn):
    return lambda genome: fn(genome) if genome.num_nodes == N else -1.0

true_front = {(round(m * (m + 1) / 90, 4), round(1 - m / 90, 4)) for m in range(N)}

def points_found(vectors):
    return len({(round(a, 4), round(b, 4)) for a, b in vectors} & true_front)

nsga_config = EvolutionConfig(population_size=40, n_generations=100, mutation_rate=0.8,
                              seed=0, max_nodes=N, max_edges=30)
nsga = NSGAIIOptimizer(nsga_config, [same_size(connectivity_fitness), same_size(sparsity_fitness)])
out = nsga.optimize([empty_genome() for _ in range(40)])
print(len(out.pareto_front), points_found(out.pareto_front.fitness_vectors))
# 40 4

The returned front holds 40 genomes but only 4 of the 10 points; seeds 0 to 4 all gave the same count. The cause is the variation step. NSGAIIOptimizer applies edge_set_crossover to every pair of parents (it ignores crossover_rate), and that operator splits the union of the two edge sets between two children. Two identical parents with 8 edges produce two children with 4. With the crossover replaced by plain copying as a test, the same optimizer found all 10 points on all five seeds.

You can build a mutation-only loop from the same primitives. nsga2_select does the non-dominated sorting and crowding-distance selection over parents plus children:

python
from tgraphx.evolutionary import (
    mutate_add_edge,
    mutate_remove_edge,
    non_dominated_sort,
    nsga2_select,
)

objectives = [connectivity_fitness, sparsity_fitness]  # edge mutations keep the node count
rng = torch.Generator().manual_seed(0)

def mutate(genome):
    if genome.num_edges and torch.rand(1, generator=rng).item() < 0.5:
        return mutate_remove_edge(genome, generator=rng)
    return mutate_add_edge(genome, generator=rng)

population = [empty_genome() for _ in range(40)]
for _ in range(100):
    children = [mutate(genome) for genome in population]
    population = nsga2_select(population, children, objectives, n_select=40)

vectors = [[f(genome) for f in objectives] for genome in population]
front = non_dominated_sort(population, vectors)[0]
print(points_found([vectors[i] for i in front]))
# 10

The one-call API also runs NSGA-II when you pass a list of objectives and algorithm="nsga2". Set max_edges here too. Without it, a call that keeps the default size, run length and seed returns the start path unchanged (every genome on the front has 20 nodes and 38 directed edges), with or without fast_mode, and raises no error.

python
one_call = tgx.optimize_graph(
    ["connectivity", "clustering"],
    algorithm="nsga2",
    num_nodes=20,
    max_edges=100,      # the default, 20, is below the 38 edges of the start path
    generations=50,
    population_size=30,
    seed=42,
    fast_mode=False,
)
pareto = one_call.pareto_front
for genome, vector in zip(pareto.genomes, pareto.fitness_vectors):
    print(genome.num_nodes, genome.num_edges, [round(v, 3) for v in vector])
# 20 37 [1.0, 0.437]
# 19 32 [0.795, 0.478]

Each vector is (connectivity, clustering). The call runs the same NSGAIIOptimizer, with the edge_set_crossover limitation described above, so do not read these two points as the true front. It accepts only the string objectives and has no node-count guard, which is why one genome has 19 nodes. A list of objectives with the default algorithm="ga" raises TypeError.

Can this drive architecture search?

Not directly. The built-in optimizers change topology only, and edge_set_crossover drops node types and edge features and mishandles node features (see the warning above), so you cannot encode layer choices in them and expect them to evolve. You would write your own variation operators and loop, as in the mutation-only NSGA-II loop above.

If each fitness call trains a model, score candidates on a validation split, keep the test split for a single final evaluation, and budget for roughly population × generations training runs. Weight-sharing methods such as DARTS (Liu et al., ICLR 2019) and ProxylessNAS (Cai et al., ICLR 2019) were designed to avoid training every candidate from scratch.

Reproducibility

The optimizer classes read their seed from the config object (seed=None by default, which uses the global RNG). optimize_graph defaults to seed=42 and also calls torch.manual_seed, which resets your global random state. Your fitness function has to be deterministic too.

python
again = GeneticAlgorithmOptimizer(config, fitness).optimize([empty_genome() for _ in range(40)])
assert again.fitness_history == ga.fitness_history
assert torch.equal(again.best_genome.edge_index, ga.best_genome.edge_index)

This checks repeatability in one environment. A different PyTorch version or platform can produce a different random stream.

Honest limitations

  • Fitness is evaluated one genome at a time in Python, and the operators are Python loops: mutate_add_edge lists every free node pair, and connectivity_fitness searches from every node. Cost grows quickly with graph size, so time a few generations at your size first.
  • max_nodes and max_edges limit mutations. They are not checked against the genomes you pass in.
  • A better score from one seed proves little. Run several seeds and compare with a simple baseline.

When this subsystem is the right fit

  • Combinatorial graph design with a scoring function and no useful gradient.
  • Exploring trade-offs between objectives, after checking the search on a small case with a known answer.
  • Teaching how selection, mutation and Pareto fronts behave.

When it is not

  • Problems with an exact algorithm. The spanning-tree example above is a test case; for a real one, use Kruskal's or Prim's algorithm (for instance networkx.minimum_spanning_tree).
  • Problems you can write as an integer or constraint program, where a solver such as Gurobi or OR-Tools can report optimality bounds.
  • Large architecture searches.

FAQ

Q: Can I run several optimizations in parallel?
A: Independent runs with different seeds can go in separate processes, for example with Python's multiprocessing. Inside one run, fitness calls are sequential.

Q: Can I track population diversity?
A: The GA and NSGA-II optimizer classes return diversity_history, the fraction of distinct 1-Weisfeiler-Lehman hashes in each generation. The one-call OptimizationResult does not include it.

Q: What about hybrid GA plus local search?
A: Chain them: HillClimbingOptimizer(hc_config, fitness).optimize(ga.best_genome).

Q: Is there a repository example?
A: examples/evolutionary_graph_optimization_demo.py in the TGraphX GitHub repository (tag v1.5.1) runs the GA, simulated annealing and NSGA-II. It is not part of the PyPI package. Do not copy how it builds genomes: it attaches node_features to them, which the warning above advises against, so with other seeds or settings it can hit the same IndexError.