Multi-Objective Graph Optimization: NSGA-II and Pareto Fronts in TGraphX
Many graph-design problems pull in opposite directions. You want a network that is well connected and sparse, or rich in triangles and cheap to build. There is then no single best graph. What you can ask for is the Pareto front: the solutions that cannot be improved in one objective without losing in another. TGraphX implements the classic evolutionary algorithm for this, NSGA-II (Deb et al., 2002), in tgraphx.evolutionary.
The introductory article on evolutionary optimization of graph structures covers the one-call API, custom fitness, the single-objective optimisers and a first NSGA-II run. This note goes into what NSGA-II computes, how to read its result, and how to check it against a front that is known exactly.
Treat the subsystem as experimental: tgx.api_status("NSGAIIOptimizer"), the module docstring and the repository's evolutionary guide say so, although the README capability map says Beta. Examples tested with TGraphX 1.5.1 on CPU.
Pareto dominance, precisely
With objectives f₁, …, f_m, all to be maximised, solution a dominates b when it is at least as good on every objective and strictly better on at least one:
a ≻ b ⟺ fᵢ(a) ≥ fᵢ(b) for all i, and fⱼ(a) > fⱼ(b) for some j
A solution is Pareto-optimal if no feasible solution dominates it. A search algorithm only sees the candidates it has generated, so what it returns is the non-dominated set of those candidates, an approximation of the true front.
NSGA-II in two ideas
Non-dominated sorting ranks a population into fronts. Front 0 is the set nothing dominates; front 1 is what becomes non-dominated once front 0 is removed, and so on.
Crowding distance measures how isolated a solution is within its front. For each objective, sort the front, give the two extreme solutions an infinite distance, and add to every other solution the normalised gap between its two neighbours:
dᵢ += ( fₘ(next) − fₘ(previous) ) / ( fₘ_max − fₘ_min )
Each generation creates children, pools them with their parents, and fills the next population front by front. When a front does not fit entirely, the least crowded solutions are kept. The first rule pushes towards the front, the second spreads the population along it, and keeping parents in the pool means a good solution is not lost merely because its children are worse.
TGraphX exposes the two building blocks as non_dominated_sort and crowding_distance:
import torch
from tgraphx.evolutionary import non_dominated_sort, crowding_distance, pareto_dominates
# Six candidates scored on two objectives, both to be maximised
names = "ABCDEF"
scores = [[1.0, 9.0], [3.0, 7.0], [4.0, 4.0], [8.0, 2.0], [2.0, 6.0], [7.0, 1.0]]
print(pareto_dominates(scores[1], scores[4]), pareto_dominates(scores[0], scores[3]))
# True False B beats E on both; A and D trade off
population = [None] * len(scores) # only the score vectors are used here
fronts = non_dominated_sort(population, scores)
print([[names[i] for i in front] for front in fronts])
# [['A', 'B', 'C', 'D'], ['E', 'F']]
distances = crowding_distance(scores, fronts[0])
print({names[i]: round(d, 3) for i, d in zip(fronts[0], distances)})
# {'A': inf, 'B': 1.143, 'C': 1.429, 'D': inf}
Encoding graphs and scoring them
The thing being evolved is a GraphGenome: a directed edge_index, a node count and optional features and types. Objectives are functions from a genome to a number.
Do not put node_features on genomes you pass to NSGAIIOptimizer in 1.5.1. Its crossover gives each child the larger of the parents' node counts but a copy of the first parent's features, so rows and nodes can stop matching and the run can fail with IndexError. Keep features outside the genome; the warning in the introductory article has the details.
tgraphx.evolutionary ships these objectives:
| Fitness | Value |
|---|---|
connectivity_fitness |
fraction of node pairs joined by a path, ignoring direction |
density_fitness |
closeness to a target density (0.5 by default) |
sparsity_fitness |
1 - edges / (N(N-1)) |
clustering_fitness |
mean local clustering coefficient |
motif_count_fitness |
raw triangle count (or wedge count) |
composite_fitness |
weighted sum of other fitness functions |
A problem with a known front
To judge a multi-objective optimiser, give it a front you can compute independently. Take graphs on 6 nodes and two goals: as many triangles as possible, with as few edges as possible. There are only 2^15 = 32,768 undirected graphs on 6 nodes, so brute force finds the exact front. This block reuses the imports above:
from itertools import combinations
N = 6
pairs = list(combinations(range(N), 2))
def count_triangles(edges):
s = set(edges)
return sum({(a, b), (a, c), (b, c)} <= s for a, b, c in combinations(range(N), 3))
best_for_size = {}
for mask in range(2 ** len(pairs)):
edges = [p for bit, p in enumerate(pairs) if mask >> bit & 1]
m = len(edges)
best_for_size[m] = max(best_for_size.get(m, 0), count_triangles(edges))
true_front, record = [], -1 # (triangles, edges)
for m in sorted(best_for_size):
if best_for_size[m] > record:
record = best_for_size[m]
true_front.append((record, m))
print(len(true_front), true_front)
# 11 [(0, 0), (1, 3), (2, 5), (4, 6), (5, 8), (7, 9), (10, 10), (11, 12), (13, 13), (16, 14), (20, 15)]
Running NSGA-II and reading the result
NSGAIIOptimizer takes an EvolutionConfig and a list of objectives, and optimize takes a list of starting genomes. Two details matter. The built-in mutations add and remove nodes, so the objectives must reject genomes of the wrong size. And the starting genomes should differ from one another, so we draw random ones.
from tgraphx.evolutionary import (
EvolutionConfig, GraphGenome, NSGAIIOptimizer, motif_count_fitness, sparsity_fitness,
)
def random_genome(generator):
m = int(torch.randint(len(pairs) + 1, (1,), generator=generator))
chosen = torch.randperm(len(pairs), generator=generator)[:m].tolist()
edge_index = torch.tensor([pairs[k] for k in chosen], dtype=torch.long).reshape(-1, 2).t()
return GraphGenome(edge_index=edge_index.contiguous(), num_nodes=N)
def fixed_size(objective):
return lambda genome: objective(genome) if genome.num_nodes == N else -1.0
objectives = [fixed_size(motif_count_fitness), fixed_size(sparsity_fitness)]
def initial_population(seed, size=40):
generator = torch.Generator().manual_seed(seed)
return [random_genome(generator) for _ in range(size)]
def run_nsga(seed, population=None):
config = EvolutionConfig(population_size=40, n_generations=100, mutation_rate=0.8,
seed=seed, max_nodes=N, max_edges=30)
return NSGAIIOptimizer(config, objectives).optimize(population or initial_population(seed))
def front_points(genomes):
return sorted({(int(motif_count_fitness(g)), g.num_edges) for g in genomes})
result = run_nsga(seed=0)
front = result.pareto_front
print(len(front), "genomes,", len(front_points(front.genomes)), "distinct points")
# 40 genomes, 9 distinct points
print(front_points(front.genomes))
# [(0, 0), (1, 3), (2, 5), (4, 6), (5, 8), (7, 9), (11, 12), (13, 13), (20, 15)]
print(len(set(front_points(front.genomes)) & set(true_front)), "of them are on the true front")
# 9 of them are on the true front
genome, vector = front.best_by_objective(0) # most triangles
print(genome.num_edges, [round(v, 3) for v in vector])
# 15 [20.0, 0.5]
optimize returns an EvolutionResult. Its pareto_front holds parallel lists:
genomesandfitness_vectors: the non-dominated members of the final population. Duplicates are common, so group by score, asfront_pointsdoes, before reporting how many solutions you found.crowding_distances: how isolated each member is. Large finite values next to a gap suggest a thinly sampled part of the front.best_by_objective(i): the extreme solution for objectivei.
result.best_genome is simply the best member for the first objective, and result.fitness_history tracks that objective only. Plot the points in objective space before choosing one: a flat stretch means one objective can be improved cheaply, and a sharp knee is often the interesting operating point.
What can go wrong
Identical starting genomes
Start the same search from 40 empty graphs and it never moves:
empty = lambda: GraphGenome(edge_index=torch.empty((2, 0), dtype=torch.long), num_nodes=N)
stuck = run_nsga(seed=0, population=[empty() for _ in range(40)])
print(len(stuck.pareto_front), front_points(stuck.pareto_front.genomes))
# 40 [(0, 0)]
A graph with one or two edges has no triangle, so the empty graph dominates it and it is discarded before a third edge can arrive. Copies of the empty graph then fill the population, because selection does not remove duplicates. If an objective only rewards a structure once it is complete, diverse starting graphs matter.
The crossover operator
TGraphX's variation step differs from the original algorithm. It pairs parents in list order, with no tournament selection, applies edge_set_crossover to every pair, and ignores crossover_rate. That operator splits the union of the two parents' edges between two children, so two similar dense parents produce two sparse children (the introductory article shows the effect on another problem). You can compare against a mutation-only loop built from the same selection primitive, nsga2_select:
from tgraphx.evolutionary import mutate_add_edge, mutate_remove_edge, nsga2_select
def mutation_only(seed, generations=100):
rng = torch.Generator().manual_seed(seed)
def mutate(genome):
if genome.num_edges and torch.rand(1, generator=rng).item() < 0.5:
return mutate_remove_edge(genome, generator=rng)
if genome.num_edges < N * (N - 1):
return mutate_add_edge(genome, generator=rng)
return genome.clone()
population = initial_population(seed)
for _ in range(generations):
children = [mutate(g) for g in population]
population = nsga2_select(population, children, objectives, n_select=40)
vectors = [[f(g) for f in objectives] for g in population]
return [population[i] for i in non_dominated_sort(population, vectors)[0]]
for seed in range(5):
with_crossover = set(front_points(run_nsga(seed).pareto_front.genomes)) & set(true_front)
without = set(front_points(mutation_only(seed))) & set(true_front)
print(seed, len(with_crossover), len(without))
# 0 9 11
# 1 7 11
# 2 8 11
# 3 8 11
# 4 8 11
On this problem the mutation-only loop recovers all 11 points for every seed and the built-in optimiser finds 7 to 9. This is one small problem, not a general ranking of the two, but it shows why a check against a known case is worth the few minutes. Points that are non-dominated within the population are not necessarily Pareto-optimal.
Cost of the objectives
The 1.5.1 optimiser does not cache scores; it re-evaluates them several times in each generation:
calls = {"n": 0}
def counted(genome):
calls["n"] += 1
return sparsity_fitness(genome)
config = EvolutionConfig(population_size=10, n_generations=5, seed=0, max_nodes=N, max_edges=30)
NSGAIIOptimizer(config, [counted, counted]).optimize(initial_population(0, size=10))
print(calls["n"]) # 370; scoring 10 starting genomes and 50 children once needs 120
If an objective is expensive (training a model, say), wrap it in a cache keyed on the node count and edge set.
Comparing runs with hypervolume
The hypervolume is the area (for two objectives) that a front dominates above a fixed reference point; larger is better. TGraphX exports compute_hypervolume_2d, but in 1.5.1 it returns 0.0 for maximisation fronts like these, so compute it yourself:
from tgraphx.evolutionary import compute_hypervolume_2d
def hypervolume_2d(points, reference):
"""Area dominated by 2-D points (both maximised) above the reference point."""
area, covered = 0.0, reference[1]
for f1, f2 in sorted(points, reverse=True):
if f1 > reference[0] and f2 > covered:
area += (f1 - reference[0]) * (f2 - covered)
covered = f2
return area
print(hypervolume_2d([(3.0, 1.0), (2.0, 2.0), (1.0, 3.0)], (0.0, 0.0))) # 6.0
reference = (-1.0, 0.0) # worse than any valid genome in both objectives
optimum = hypervolume_2d([(t, 1 - m / (N * (N - 1))) for t, m in true_front], reference)
for label, genomes in [("NSGAIIOptimizer", front.genomes), ("mutation only", mutation_only(0))]:
points = [(motif_count_fitness(g), sparsity_fitness(g)) for g in genomes]
print(label, round(hypervolume_2d(points, reference) / optimum, 3))
# NSGAIIOptimizer 0.978
# mutation only 1.0
print(compute_hypervolume_2d(front, reference)) # 0.0
Use the same reference point for every run you compare. Note that 9 of 11 points still covers about 98% of the area here, so report both measures.
When to prefer single-objective
If your objectives can be combined into one, through a weighting you can defend or a hard constraint plus a single objective, a single-objective optimiser (GeneticAlgorithmOptimizer, SimulatedAnnealingOptimizer, or a gradient method when the objective is differentiable) is simpler and usually cheaper. Reserve multi-objective search for when the trade-off itself is the deliverable and you cannot pick weights in advance.
Limits and reporting
Evolutionary search is stochastic and uses many objective evaluations. Results depend on population size, mutation rate, starting population and seed, so report all of them; a Pareto front from one run is one sample, and another seed can give a different set. Whether it beats a problem-specific method has to be measured on your problem. The example here was chosen because brute force can check it; when you can solve a problem exactly, do that.
Related guides
- Evolutionary Optimization of Graph Structures
- Measuring Generated Graphs
- Graph Generation with Tensor-Valued Node Features
References
- Deb, Pratap, Agarwal and Meyarivan (2002). A fast and elitist multiobjective genetic algorithm: NSGA-II. IEEE Transactions on Evolutionary Computation.