diff --git a/docs/dev/documentation-architecture.md b/docs/dev/documentation-architecture.md
index a7c7f802f..e8c98ea69 100644
--- a/docs/dev/documentation-architecture.md
+++ b/docs/dev/documentation-architecture.md
@@ -39,6 +39,7 @@ The public information architecture is task-first:
3. **How-to Guides** — locate a specific operation, cookbook recipe, or optional workflow.
4. **Reference** — inspect exact API, algorithm, problem, constraint, and stopping contracts, and the support and version commitments.
5. **Developer** — roadmap, extension contracts, tests, architecture, and maintenance material.
+6. **Foundations** — learn the concepts of multi-objective optimization at three levels (Basic, Intermediate, Advanced), with interactive figures, runnable VAMOS examples and the original references.
Roadmap is the first entry under Developer. The stability policy, known limitations, documentation versions, and release notes are listed under Reference → Support & Versions, without a separate Project tab; every release adds its notes there. Hosting and repository governance keep their contextual links without a navigation entry. Project pages keep their existing URLs.
diff --git a/docs/dev/documentation-navigation.md b/docs/dev/documentation-navigation.md
index 5907f6283..e8e6e3105 100644
--- a/docs/dev/documentation-navigation.md
+++ b/docs/dev/documentation-navigation.md
@@ -10,6 +10,9 @@ from several routes while retaining one source and one primary navigation entry.
- **Tutorial:** follow a worked example or learning path. Beginner setup remains
under Get Started; algorithm lessons and the examples gallery are in Tutorials.
+ Concept lessons that teach multi-objective optimization itself, rather than a
+ VAMOS workflow, form the Foundations tab, placed after Developer and ordered
+ Basic, Intermediate and Advanced.
- **How-to:** complete a specific operation. The How-to Guides index also links
directly to relevant sections of tutorials and reference pages.
- **Reference:** look up exact interfaces, capabilities, support, or version
@@ -36,6 +39,7 @@ three homepage journeys lead directly to T01, T02, and T06.
| Cookbook | Keep the recipe index now; split selected tasks into dedicated guides as they are developed. | Retain the recipe anchors as routing points when content is extracted. |
| Study and analysis material | Keep the lifecycle and analysis pages; connect T06–T08 and their retained study report. | Keep the synthetic API matrix distinct from actual study observations. |
| Merging pages | No page merge is needed for this navigation change. | Prefer cross-links between complementary tutorial, how-to, and reference roles. |
+| Foundations | Concept lessons B1–B4, I1–I11 and A1–A10 under their own tab, including an in-depth lesson for every built-in algorithm. Interactive figures live in `docs/javascripts/foundations.js` and `docs/stylesheets/foundations.css`. | Link to the algorithm lessons and study tutorials instead of repeating their workflows. `tests/docs/test_foundations.py` runs every example against its documented output and keeps each source excerpt verbatim in VAMOS; keep the figures' algorithms equal to the NumPy kernel they port. |
## Complete page inventory
@@ -95,6 +99,32 @@ and reachable through the named parent pages even when absent from the menu.
| [dev/testing.md](testing.md) | Development | Developer → Maintainers → Testing and Validation | Regroup |
| [dev/typing.md](typing.md) | Development | Developer → Maintainers → Typing Policy | Regroup |
| [examples.md](../examples.md) | Tutorial | Tutorials → Examples Gallery | Regroup |
+| [foundations/index.md](../foundations/index.md) | Tutorial | Foundations → Overview | Add |
+| [foundations/basic/multi-objective-problems.md](../foundations/basic/multi-objective-problems.md) | Tutorial | Foundations → Basic → B1. Multi-objective Problems | Add |
+| [foundations/basic/pareto-dominance.md](../foundations/basic/pareto-dominance.md) | Tutorial | Foundations → Basic → B2. Pareto Dominance | Add |
+| [foundations/basic/quality-aspects.md](../foundations/basic/quality-aspects.md) | Tutorial | Foundations → Basic → B3. Quality Aspects | Add |
+| [foundations/basic/quality-indicators.md](../foundations/basic/quality-indicators.md) | Tutorial | Foundations → Basic → B4. Quality Indicators | Add |
+| [foundations/intermediate/nsga-ii.md](../foundations/intermediate/nsga-ii.md) | Tutorial | Foundations → Intermediate → I1. NSGA-II at a Glance | Add |
+| [foundations/intermediate/non-dominated-sorting.md](../foundations/intermediate/non-dominated-sorting.md) | Tutorial | Foundations → Intermediate → I2. Non-dominated Sorting | Add |
+| [foundations/intermediate/crowding-distance.md](../foundations/intermediate/crowding-distance.md) | Tutorial | Foundations → Intermediate → I3. Crowding and Tournaments | Add |
+| [foundations/intermediate/variation-operators.md](../foundations/intermediate/variation-operators.md) | Tutorial | Foundations → Intermediate → I4. SBX and Polynomial Mutation | Add |
+| [foundations/intermediate/elitist-survival.md](../foundations/intermediate/elitist-survival.md) | Tutorial | Foundations → Intermediate → I5. Elitist Survival | Add |
+| [foundations/intermediate/beyond-nsga-ii.md](../foundations/intermediate/beyond-nsga-ii.md) | Tutorial | Foundations → Intermediate → I6. Beyond NSGA-II | Add |
+| [foundations/advanced/many-objective.md](../foundations/advanced/many-objective.md) | Tutorial | Foundations → Advanced → A1. Many Objectives | Add |
+| [foundations/advanced/constrained.md](../foundations/advanced/constrained.md) | Tutorial | Foundations → Advanced → A5. Constraints | Add |
+| [foundations/advanced/performance-assessment.md](../foundations/advanced/performance-assessment.md) | Tutorial | Foundations → Advanced → A10. Rigorous Comparison | Add |
+| [foundations/intermediate/spea2.md](../foundations/intermediate/spea2.md) | Tutorial | Foundations → Intermediate → I7. SPEA2 | Add |
+| [foundations/intermediate/moead.md](../foundations/intermediate/moead.md) | Tutorial | Foundations → Intermediate → I8. MOEA/D | Add |
+| [foundations/intermediate/smsemoa.md](../foundations/intermediate/smsemoa.md) | Tutorial | Foundations → Intermediate → I9. SMS-EMOA | Add |
+| [foundations/intermediate/ibea.md](../foundations/intermediate/ibea.md) | Tutorial | Foundations → Intermediate → I10. IBEA | Add |
+| [foundations/intermediate/smpso.md](../foundations/intermediate/smpso.md) | Tutorial | Foundations → Intermediate → I11. SMPSO | Add |
+| [foundations/advanced/nsga-iii.md](../foundations/advanced/nsga-iii.md) | Tutorial | Foundations → Advanced → A2. NSGA-III | Add |
+| [foundations/advanced/rvea.md](../foundations/advanced/rvea.md) | Tutorial | Foundations → Advanced → A3. RVEA | Add |
+| [foundations/advanced/agemoea.md](../foundations/advanced/agemoea.md) | Tutorial | Foundations → Advanced → A4. AGE-MOEA | Add |
+| [foundations/advanced/ccmo.md](../foundations/advanced/ccmo.md) | Tutorial | Foundations → Advanced → A6. CCMO | Add |
+| [foundations/advanced/ctaea.md](../foundations/advanced/ctaea.md) | Tutorial | Foundations → Advanced → A7. C-TAEA | Add |
+| [foundations/advanced/top.md](../foundations/advanced/top.md) | Tutorial | Foundations → Advanced → A8. ToP | Add |
+| [foundations/advanced/cmoeams.md](../foundations/advanced/cmoeams.md) | Tutorial | Foundations → Advanced → A9. CMOEA-MS | Add |
| [experiment/stopping_and_archive.md](../experiment/stopping_and_archive.md) | Reference | Reference → Stopping & Archive | Keep |
| [guide/cli.md](../guide/cli.md) | How-to | How-to Guides → CLI & Config | Regroup |
| [guide/cookbook.md](../guide/cookbook.md) | How-to | How-to Guides → Cookbook | Regroup |
diff --git a/docs/foundations/advanced/agemoea.md b/docs/foundations/advanced/agemoea.md
new file mode 100644
index 000000000..a16a7ab38
--- /dev/null
+++ b/docs/foundations/advanced/agemoea.md
@@ -0,0 +1,373 @@
+---
+description: 'A4. AGE-MOEA: normalizing the first front, estimating its curvature p from a central point, proximity and diversity in the Lp norm, the greedy survival score and the truncation of the last front, as VAMOS implements them, with an interactive figure and VAMOS code.'
+search:
+ boost: 0.5
+---
+
+# A4. AGE-MOEA: adapting to the geometry of the front
+
+NSGA-III and RVEA (lessons [A2](nsga-iii.md) and [A3](rvea.md)) spread their
+solutions along directions fixed before the run. That works when the front
+covers the simplex the directions were made for, and less well when it does
+not [6]. AGE-MOEA, the adaptive geometry estimation MOEA of Panichella [1],
+takes the opposite route: it has no reference directions. At every generation
+it estimates the shape of the current front and measures distances in the
+geometry that shape implies.
+
+The rest is NSGA-II [2]: merge parents and offspring, sort them into fronts,
+keep whole fronts while they fit (lesson
+[I5](../intermediate/elitist-survival.md)). Only the measure that cuts the
+last front changes. The crowding distance is replaced by a **survival score**
+that combines the proximity of a solution to the ideal point with its
+distance to the solutions already kept, both measured in the estimated
+geometry.
+
+In this lesson you will learn:
+
+- how AGE-MOEA normalizes the first front with its corner points;
+- how a single point estimates the curvature p of a front
+ f₁ᵖ + … + f_mᵖ = 1;
+- how proximity and diversity are measured in the Lp norm and combined into
+ the survival score;
+- how the last front is cut and parents are chosen, and where VAMOS follows
+ pymoo or the author's code.
+
+## Why the geometry matters
+
+Many fronts are well described, after normalization, by one family of
+surfaces:
+
+
f̃₁ᵖ + f̃₂ᵖ + … + f̃_mᵖ = 1 (the front model)
+‖y‖_p = ( |y₁|ᵖ + |y₂|ᵖ + … + |y_m|ᵖ )^(1/p) (Lp norm; Minkowski distance ‖y − y′‖_p)
+
+p = 1 gives a flat front (DTLZ1 [4]), p = 2 a sphere (DTLZ2), p below 1 a
+convex front bulging towards the ideal point (ZDT1 [3] is close to p = 0.72)
+and p above 2 a front that bulges even further away from it than the sphere.
+
+The model has a useful property: every point of the front lies at distance 1
+from the ideal point **in the Lp norm with the right p**. Measured with the
+Euclidean norm instead, the points of a convex front near its knee look closer
+to the ideal point, that is better converged, than the points near its
+corners, although all of them are Pareto-optimal. Distances between
+neighbours along the front are distorted in the same way. Crowding distance
+and Euclidean distances implicitly assume one geometry; AGE-MOEA estimates p
+and uses it [1].
+
+## Normalizing the first front
+
+The geometry is estimated on the first front F₁ of the merged population,
+after three steps:
+
+1. **Translate** by the ideal point of F₁, the smallest value of each objective
+ in F₁, so that it becomes the origin (VAMOS rounds the translated values to
+ 12 decimals to settle near-ties).
+2. **Corner points.** For each axis i, take the point of F₁ closest to the line
+ through the origin and the unit vector eᵢ (VAMOS adds 10⁻⁶ to every
+ component of eᵢ), excluding points already chosen.
+3. **Intercepts.** Solve for the hyperplane through the m corner points; its
+ intercepts a₁, …, a_m divide each objective: f̃ᵢ = f′ᵢ / aᵢ. When the corners
+ are not distinct, the system is singular, or an intercept is not finite or
+ not positive, VAMOS divides by the largest value of each objective in F₁
+ instead.
+
+This is the hyperplane of NSGA-III [5], with two differences: the corners are
+the points nearest to the axes rather than the minimizers of an achievement
+scalarizing function, and nothing is remembered between generations. If F₁
+has fewer points than objectives, no hyperplane exists: VAMOS sets p = 1 and
+gives every point of F₁ the score 0.
+
+## Estimating the curvature
+
+AGE-MOEA reads p from one point. If a point of the front had all its
+coordinates equal to c̄, the model would give m · c̄ᵖ = 1, so
+
+central point c = the non-corner point of F₁ closest to the diagonal through (1, 1, …, 1)
+c̄ = mean of the coordinates of c
+p̂ = ln m / ln( 1 / c̄ )
+
+On DTLZ2, c̄ = 1/√2 with two objectives and p̂ = ln 2 / ln √2 = 2. On a flat
+front c̄ = 1/m and p̂ = 1. VAMOS guards the estimate: if c̄ ≤ 0, or p̂ is
+undefined or at most 0.1, it uses p̂ = 1, and it caps p̂ at 20. One point makes
+the estimate cheap and noisy, but it is repeated every generation, and the
+first front changes slowly.
+
+## Proximity, diversity and the survival score
+
+With p̂ fixed, every point s of F₁ gets a proximity, and every pair of points a
+distance, both in the Lp norm:
+
+P(s) = ‖ f̃(s) ‖_p̂ (proximity: distance to the ideal point)
+d̂(s, q) = ‖ f̃(s) − f̃(q) ‖_p̂ / P(s) (distance from s to q, relative to P(s))
+score(s) = ∞ for the m corner points, which form the selected set S
+repeat until every point of F₁ is in S:
+ for each s outside S: D(s) = d̂(s, q₁) + d̂(s, q₂), q₁, q₂ the two points of S nearest to s
+ move the s with the largest D(s) into S; score(s) ← D(s)
+
+The score is diversity divided by proximity: a point scores high when it is far
+from the points already kept and close to the ideal point. The selection is
+greedy, so each score depends on the points kept before it, and the scores
+never increase along the order of selection. With only one point in S, D(s) is the
+distance to that point. VAMOS, like pymoo and the author's code, uses the two
+nearest selected points.
+
+## Survival and mating
+
+AGE-MOEA keeps whole fronts while they fit and cuts the last one by
+decreasing score:
+
+- If the last front is F₁, its points are kept in the order of the greedy
+ selection: the corners first, then the most diverse and best converged
+ points.
+- If it is a later front, VAMOS follows the author's code in PlatEMO: each of
+ its points scores 1/P(s), the inverse of its Lp distance to the ideal point,
+ measured with F₁'s p̂ in F₁'s translated and normalized coordinates, so the
+ points closest to the ideal point survive. pymoo cuts a later front by index
+ instead. VAMOS translates the later fronts by F₁'s ideal point before
+ dividing, which PlatEMO and pymoo do not, so the survivors do not depend on
+ where the objectives' origin lies.
+
+Parents are chosen by binary tournament on rank, then survival score, as in
+the author's code: the lower rank wins, and on equal rank the higher score.
+With constraints VAMOS puts feasible solutions first: when more are feasible
+than survive, the survival runs on the feasible ones; otherwise every feasible
+solution survives and the least violated infeasible ones fill the population.
+The tournament compares infeasible solutions by violation, and
+`constraint_handling` can replace the rule (lesson [A5](constrained.md)).
+
+## Explore the geometry
+
+The figure samples ten points at fixed angles on the front f₁ᵖ + f₂ᵖ = 1. All
+ten are non-dominated, so they form F₁, and with fewer than ten survivors F₁ is
+also the last front. Move the true p from 0.5 to 3 and watch the estimate p̂
+and the fitted curve follow the true front; they differ slightly because no
+point lies exactly on the diagonal. With six survivors, compare p = 0.5 and
+p = 2: the same angles, different picks. Then, at p = 0.5, tick the Euclidean
+comparison: the knee points look best converged and their scores jump.
+
+
+
+## In VAMOS
+
+AGE-MOEA does not report p̂, but the estimate is easy to repeat on a returned
+front. The example runs AGE-MOEA on three two-objective problems, ZDT1
+(convex), ZDT2 (concave) and DTLZ2 (a quarter circle), and applies the
+estimate to each result. The value in parentheses is the curvature of the
+true front, read from its point on the diagonal:
+
+```python
+import numpy as np
+
+from vamos import optimize
+from vamos.problems import DTLZ2, ZDT1, ZDT2
+
+
+def estimate_p(F):
+ """AGE-MOEA's curvature estimate for a two-objective front."""
+ Z = (F - F.min(axis=0)) / (F.max(axis=0) - F.min(axis=0)) # ideal → (0, 0), corners → (1, 0) and (0, 1)
+ central = Z[np.argmin(np.abs(Z[:, 0] - Z[:, 1]))] # the point closest to the diagonal
+ return np.log(2) / np.log(1 / central.mean())
+
+
+problems = [("ZDT1, convex", ZDT1(n_var=30), 0.72), ("ZDT2, concave", ZDT2(n_var=30), 1.44), ("DTLZ2, circle", DTLZ2(n_var=11, n_obj=2), 2.0)]
+for name, problem, true_p in problems:
+ result = optimize(problem, algorithm="agemoea", pop_size=100, max_evaluations=10_000, engine="numpy", seed=1)
+ print(f"{name}: {result.F.shape[0]} solutions, estimated p = {estimate_p(result.F):.2f} (front: {true_p:.2f})")
+```
+
+Output:
+
+```text
+ZDT1, convex: 100 solutions, estimated p = 0.72 (front: 0.72)
+ZDT2, concave: 100 solutions, estimated p = 1.41 (front: 1.44)
+DTLZ2, circle: 100 solutions, estimated p = 2.00 (front: 2.00)
+```
+
+With two objectives the corner points are the extremes of each objective, so
+dividing by the range is the hyperplane normalization, and the point closest
+to the diagonal is the one with the smallest |f̃₁ − f̃₂|. ZDT2's front,
+f₂ = 1 − f₁², is not exactly an Lp curve, and its estimate depends on which
+point happens to be nearest the diagonal.
+
+Inside VAMOS, the estimate and the distances follow the formulas. In
+`_compute_geometry`, `d` is the squared distance of each point to the
+diagonal, the corners are excluded with `np.inf`, and `p` is the formula of
+p̂ with its guards. In `_survival_score`, `nn` holds the proximities and
+`distances` the Lp distances, each row divided by the proximity of its point:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/agemoea/geometry.py
+def _compute_geometry(front: np.ndarray[Any, Any], extreme: np.ndarray[Any, Any], n_obj: int) -> float:
+ d = _point_to_line_distance(front, np.zeros(n_obj), np.ones(n_obj))
+ d[extreme] = np.inf
+ index = int(np.argmin(d))
+ mean_val = np.mean(front[index, :])
+ if mean_val <= 0.0:
+ return 1.0
+ p = np.log(n_obj) / np.log(1.0 / mean_val)
+ if np.isnan(p) or p <= 0.1:
+ p = 1.0
+ elif p > 20.0:
+ p = 20.0
+ return float(p)
+ front = np.round(front - ideal_point, 12)
+ extreme = _find_corner_solutions(front)
+ front, normalization = _normalize_front(front, extreme)
+
+ crowd_dist[extreme] = np.inf
+ selected = np.full(m, False)
+ selected[extreme] = True
+
+ ii = variant == "agemoea_ii"
+ p = _compute_geometry_ii(front, extreme) if ii else _compute_geometry(front, extreme, n)
+ nn = np.linalg.norm(front, ord=p, axis=1)
+ nn[nn < 1e-8] = 1.0
+
+ distances = _geodesic_distances(front, p) if ii else _pairwise_distances(front, p)
+ distances[distances < 1e-8] = 1e-8
+ distances = distances / nn[:, None]
+```
+
+**VAMOS 1.5.0:** the `ii` lines choose between AGE-MOEA, the
+default, and AGE-MOEA-II [7], selected with `variant("agemoea_ii")`. AGE-MOEA-II
+estimates p from the non-corner point nearest to the ideal point by
+Newton-Raphson, so that its Lp norm is 1, and replaces the Lp distances of F₁
+by approximate geodesic distances on the estimated front: each pair of points
+is projected onto the Lp surface and measured through their projected
+midpoint. The rest of the survival is AGE-MOEA's.
+
+The greedy loop keeps, for every unselected point, its two smallest distances
+to the selected set (`best1`, `best2`) and their sum (`scores`). Each pass
+selects the largest sum, records it as the survival score in `crowd_dist`, and
+updates the two nearest distances with the newly selected point. The
+`selected_count == 2` branch only matters when S started from a single
+corner: it sorts the first two distances once both exist:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/agemoea/geometry.py
+ while remaining.size > 0:
+ index = int(np.argmax(scores))
+ best = int(remaining[index])
+ d = float(scores[index])
+ selected[best] = True
+ crowd_dist[best] = d
+
+ remaining = np.delete(remaining, index)
+ best1 = np.delete(best1, index)
+ best2 = np.delete(best2, index)
+ scores = np.delete(scores, index)
+ selected_count += 1
+ if remaining.size == 0:
+ break
+
+ new_dist = distances[remaining, best]
+ if selected_count == 2:
+ lo = np.minimum(best1, new_dist)
+ hi = np.maximum(best1, new_dist)
+ best1 = lo
+ best2 = hi
+ scores = best1 + best2
+ continue
+
+ better_first = new_dist < best1
+ best2 = np.where(better_first, best1, best2)
+ best1 = np.where(better_first, new_dist, best1)
+ better_second = (~better_first) & (new_dist < best2)
+ best2 = np.where(better_second, new_dist, best2)
+ scores = best1 + best2
+```
+
+`age_survival` then assembles the generation: whole fronts below `last_rank`
+survive, F₁ is scored by the greedy procedure, the later fronts up to the last
+one by the inverse Lp distance to the ideal point, and the last front is cut by
+decreasing score:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/agemoea/geometry.py
+ selected = ranks < last_rank
+ crowd_dist = np.zeros(F.shape[0], dtype=float)
+
+ front0 = F[ranks == 0, :]
+ ideal_point = np.min(front0, axis=0)
+ crowd_dist[ranks == 0], p, normalization = _survival_score(front0, ideal_point, kernel.selection_kernels(), variant)
+
+ for r in range(1, last_rank + 1):
+ front_idx = fronts[r]
+ if front_idx.size == 0:
+ continue
+ # Same ideal-centred, normalized coordinates as the first-front score.
+ front = (F[front_idx] - ideal_point) / normalization
+ dist = _minkowski_distances(front, np.zeros((1, F.shape[1])), p).squeeze()
+ dist = np.where(dist < 1e-12, 1e-12, dist)
+ crowd_dist[front_idx] = 1.0 / dist
+
+ last = fronts[last_rank]
+ if last.size > 0:
+ order = np.argsort(crowd_dist[last])[::-1]
+ remaining = n_survive - int(np.sum(selected))
+ selected[last[order[:remaining]]] = True
+
+ survivors = np.flatnonzero(selected)
+ return survivors, crowd_dist[survivors]
+```
+
+`AGEMOEAConfig.default` uses a population of 100, SBX crossover (probability
+0.9, distribution index 15) and polynomial mutation (probability 1/n, index
+20). Unlike NSGA-III and RVEA, the population size has no lattice to match.
+The [AGE-MOEA lesson](../../algorithms/agemoea.md) records a run on
+three-objective DTLZ2, and the
+[configuration reference](../../reference/api/algorithms/agemoea.md) lists the
+builder methods.
+
+## AGE-MOEA and the reference-direction algorithms
+
+| | NSGA-II | NSGA-III, RVEA | AGE-MOEA |
+| --- | --- | --- | --- |
+| Diversity measure | Crowding distance | Fixed reference directions | Lp distances with the estimated p |
+| Convergence measure | Rank | Rank (NSGA-III), distance to the ideal point (RVEA) | Rank, then proximity in the Lp norm |
+| Population size | Free | Tied to the lattice | Free |
+| Cost of the last cut | Sorting per objective | Association with H directions | Pairwise distances in F₁ |
+
+**Strengths.** AGE-MOEA needs no directions, so the population can have any
+size and nothing is wasted on parts of the simplex that the front does not
+cover. Its distances adapt to convex, flat and concave fronts, and its
+proximity does not favour the knee of a convex front.
+
+**Limits.** The model has one exponent for all objectives and assumes a
+connected front that touches every axis: disconnected, degenerate or
+irregular fronts break it, and the estimate rests on a single point. The
+pairwise distances cost O(m·|F₁|²) per generation, which grows with large
+populations. And like every algorithm that normalizes by the corners of the
+current front, it can be misled early in the run, when those corners are still
+poor.
+
+## Key points
+
+- AGE-MOEA keeps NSGA-II's structure and replaces the crowding distance by a
+ survival score computed in the geometry of the first front.
+- The first front is translated by its ideal point and divided by the
+ intercepts of the hyperplane through its corner points.
+- The curvature is read from the point closest to the diagonal:
+ p̂ = ln m / ln(1/c̄); VAMOS replaces an estimate of at most 0.1 by 1 and
+ caps it at 20.
+- Proximity is the Lp distance to the ideal point; the greedy score adds the Lp
+ distances to the two nearest kept points and divides by the proximity.
+- VAMOS scores later fronts by inverse proximity, as the author's code does,
+ and measures them in the first front's translated, normalized coordinates.
+
+**Next:** [A5. Constrained multi-objective optimization](constrained.md).
+
+## References
+
+[1] Panichella, A. (2019). [An adaptive evolutionary algorithm based on non-Euclidean geometry for many-objective optimization](https://doi.org/10.1145/3321707.3321839). *Proceedings of the Genetic and Evolutionary Computation Conference (GECCO '19)*, 595–603.
+
+[2] Deb, K., Pratap, A., Agarwal, S., and Meyarivan, T. (2002). [A fast and elitist multiobjective genetic algorithm: NSGA-II](https://doi.org/10.1109/4235.996017). *IEEE Transactions on Evolutionary Computation*, 6(2), 182–197.
+
+[3] Zitzler, E., Deb, K., and Thiele, L. (2000). [Comparison of multiobjective evolutionary algorithms: Empirical results](https://doi.org/10.1162/106365600568202). *Evolutionary Computation*, 8(2), 173–195.
+
+[4] Deb, K., Thiele, L., Laumanns, M., and Zitzler, E. (2005). [Scalable test problems for evolutionary multiobjective optimization](https://doi.org/10.1007/1-84628-137-7_6). In A. Abraham, L. Jain and R. Goldberg (Eds.), *Evolutionary Multiobjective Optimization*, 105–145. Springer.
+
+[5] Deb, K., and Jain, H. (2014). [An evolutionary many-objective optimization algorithm using reference-point-based nondominated sorting approach, Part I: Solving problems with box constraints](https://doi.org/10.1109/TEVC.2013.2281535). *IEEE Transactions on Evolutionary Computation*, 18(4), 577–601.
+
+[6] Ishibuchi, H., Setoguchi, Y., Masuda, H., and Nojima, Y. (2017). [Performance of decomposition-based many-objective algorithms strongly depends on Pareto front shapes](https://doi.org/10.1109/TEVC.2016.2587749). *IEEE Transactions on Evolutionary Computation*, 21(2), 169–190.
+
+[7] Panichella, A. (2022). [An improved Pareto front modeling algorithm for large-scale many-objective optimization](https://doi.org/10.1145/3512290.3528732). *Proceedings of the Genetic and Evolutionary Computation Conference (GECCO '22)*, 565–573.
diff --git a/docs/foundations/advanced/ccmo.md b/docs/foundations/advanced/ccmo.md
new file mode 100644
index 000000000..a97149c28
--- /dev/null
+++ b/docs/foundations/advanced/ccmo.md
@@ -0,0 +1,384 @@
+---
+description: 'A6. CCMO in depth: a constrained population and a helper population that ignores the constraints, cooperation through shared offspring, SPEA2 fitness with the violation first, environmental selection, budget, and where VAMOS follows the authors'' code, with an interactive figure and VAMOS code.'
+search:
+ boost: 0.5
+---
+
+# A6. CCMO: two cooperating populations
+
+Lesson [A5](constrained.md#beyond-feasibility-first) ended with a warning:
+selection that puts feasibility first can be trapped. Once a few feasible
+solutions are found they take over the population, and the parts of the
+constrained front that lie behind an infeasible barrier are never reached.
+CCMO, the **coevolutionary framework for constrained multi-objective
+optimization** of Tian, Zhang, Xiao, Zhang and Jin [1], avoids the trap by
+keeping a second population that is not bound by the constraints at all.
+
+The two populations have the same size. Population 1 solves the problem as
+stated; population 2 solves a *helper problem*, the same objectives without the
+constraints. They never mix their members: in every generation each population
+breeds its own offspring, and then each one selects its survivors from itself
+together with the offspring of **both**. Population 2 moves freely across
+infeasible regions towards the unconstrained front, and its offspring give
+population 1 candidates in places it could not reach on its own.
+
+NSGA-II with constrained domination (lesson [A5](constrained.md#constrained-domination))
+has one population and one rule. CCMO has two populations, two rules and one
+pool of offspring. In VAMOS, as in the authors' code, each population is
+evolved with the fitness and the environmental selection of SPEA2 [6] (lesson
+[I7](../intermediate/spea2.md)), with the constraint violation put first in
+population 1.
+
+In this lesson you will learn:
+
+- why a population that ignores the constraints helps the one that respects
+ them;
+- the helper problem and the weak cooperation through shared offspring;
+- the fitness, environmental selection and mating selection of each population
+ in VAMOS;
+- how a generation spends the budget, and where VAMOS follows the authors' code
+ instead of the paper.
+
+## Why a second population
+
+Deb's feasibility rules [2], used by NSGA-II [3], compare two solutions by
+feasibility first and by their objectives second. The rules have no parameter
+and work well when the feasible region is large and connected. On problems
+such as CTP2 [4], whose feasible region near the front is a row of narrow
+"tunnels" (lesson [A5](constrained.md#constrained-domination)), they fail in a
+characteristic way: a population that has entered one tunnel cannot cross the
+infeasible band beside it, because every step across is an infeasible
+solution, and feasibility first discards it.
+
+Two remedies were common before CCMO: relax the constraints (penalties,
+ε-constrained methods, stochastic ranking; lesson
+[A5](constrained.md#beyond-feasibility-first)) or keep infeasible solutions in
+an archive. Tian et al. [1] proposed a framework instead. A *helper problem*,
+easier than the original one, is solved by a second population, and the two
+populations cooperate weakly: they share their offspring and nothing else. In
+CCMO the helper problem is the original problem without its constraints. Its
+population converges to the unconstrained front, crossing infeasible regions
+on the way, and wherever the constrained and the unconstrained fronts are close,
+its offspring land near the constrained front.
+
+## The helper problem and the shared offspring
+
+One generation of CCMO, with N solutions in each population:
+
+population 1: minimize f(x) subject to g_j(x) ≤ 0 (the original problem)
+population 2: minimize f(x) (the helper problem)
+Q₁ ← offspring of population 1, Q₂ ← offspring of population 2 (mating within each population)
+P₁ ← the best N of P₁ ∪ Q₁ ∪ Q₂, ranked with the constraint violation
+P₂ ← the best N of P₂ ∪ Q₁ ∪ Q₂, ranked without it
+
+Each population chooses its parents among its own members, so neither one is
+pulled towards the other's region. Every offspring is evaluated once and
+offered to both. The cooperation is *weak* in that sense: no migration, no
+shared archive, no change to either selection rule.
+
+With the default GA variation each population creates N/2 offspring, so both
+selections choose N survivors from 2N candidates, as NSGA-II does. The result
+of the run is population 1; population 2 is a means, not an answer.
+
+## Fitness with the violation first
+
+Each population ranks its 2N candidates with SPEA2's fitness (lesson
+[I7](../intermediate/spea2.md#strength-and-raw-fitness)), computed with a
+dominance relation in which the constraint violation CV of lesson
+[A5](constrained.md#feasibility-and-violation) comes first:
+
+a ≺_c b ⇔ CV(a) < CV(b), or CV(a) = CV(b) and a ≺ b (Pareto dominance)
+S(i) = |{ j : i ≺_c j }| (strength: how many candidates i dominates)
+R(j) = Σ_{i ≺_c j} S(i) (raw fitness: the strengths of j's dominators)
+D(i) = 1 / ( σ_i^k + 2 ), k = ⌊√n⌋ (σ_i^k: distance to the k-th nearest other candidate)
+fitness(i) = R(i) + D(i) (to be minimized)
+
+- Every feasible candidate dominates every infeasible one, and of two
+ infeasible candidates the less violated one dominates. Two candidates with
+ the same violation, both feasible or both infeasible, are compared by Pareto
+ dominance.
+- Population 2 passes a violation of zero for every candidate, so ≺_c becomes
+ plain Pareto dominance: population 2 sees the helper problem.
+- σ_i^k is the Euclidean distance in the objective space, without
+ normalization, and n is the number of candidates (k = 14 for 2N = 200).
+- R is 0 exactly for the candidates that no other one dominates, and
+ D ≤ 1/2, so those candidates are the ones with a fitness below 1.
+
+## Environmental selection and mating
+
+Each population keeps N of its candidates by SPEA2's environmental selection:
+
+keep every candidate with fitness < 1 (the non-dominated ones)
+if fewer than N: keep the N lowest fitness values instead
+if more than N: repeatedly remove the candidate whose sorted distances
+ to the remaining ones are lexicographically smallest
+
+The removal is SPEA2's truncation operator (lesson
+[I7](../intermediate/spea2.md#the-truncation-operator)): the candidate with the
+closest neighbour goes first, a tie is broken by the second closest, and so on.
+The survivors are stored in increasing order of fitness, and that fitness,
+computed on the 2N candidates, is reused for mating.
+
+Parents are chosen by binary tournaments on the fitness: two members are drawn
+at random (possibly the same one twice), the lower fitness wins, and a tie goes
+to the one that comes first. The crossover chooses the variation:
+
+- **GA** (SBX by default, or any two-parent crossover): N tournaments; the i-th
+ winner of the first half mates with the i-th of the second half, and only the
+ first child of each pair is kept and mutated. Each population creates N/2
+ offspring.
+- **DE** (crossover `de`, real variables): the i-th child is
+ x_i + F (r1_i − r2_i), with r1 and r2 from 2N tournaments, binomial crossover
+ of rate CR, then mutation, after Storn and Price [5]. Each population creates
+ N offspring.
+
+The two initial populations cost 2N evaluations, so the budget must be at least
+2N. A GA generation then costs 2·⌊N/2⌋ evaluations and a DE generation 2N.
+
+## Try it: one set of candidates, two rules
+
+The figure shows the CTP2 objective space of lesson
+[A5](constrained.md#constrained-domination) with 16 candidates: eight members
+of a population (P1 to P8) and eight offspring (O1 to O8). Circles are
+feasible, squares infeasible. Both selection rules of CCMO are applied to the
+same 16 candidates and keep N = 8. Start with population 1, then switch to
+population 2 and compare the regions each one keeps. Hover a point to see its
+violation, its dominators and its fitness.
+
+
+
+Nine candidates are feasible. Population 1 keeps eight of them: the six that no
+feasible candidate dominates, then P2 and O2, each dominated only by O1. It
+drops P6, dominated by three feasible candidates, and every infeasible one.
+Population 2 keeps the seven candidates that are non-dominated when the
+constraints are ignored, six of them infeasible and close to the dashed
+unconstrained front, plus P8, dominated only by O7. The two populations cover
+different parts of the plane, which is the point: the next offspring of
+population 2 will be bred near the unconstrained front, and population 1 will
+keep those that turn out to be feasible.
+
+## In VAMOS
+
+CCMO on CTP2 [4], with two populations of 100 and 20,000 evaluations. On CTP2
+the sum f₁ + f₂ equals the distance function g(x), whose minimum 1 is reached
+on the unconstrained front; on the constrained front f₁ + f₂ grows from 1 at
+f₁ = 0 to about 1.27 at f₁ = 1.
+
+```python
+import numpy as np
+
+from vamos import optimize
+from vamos.problems import CTP
+
+result = optimize(CTP(2), algorithm="ccmo", pop_size=100, max_evaluations=20_000, engine="numpy", seed=1)
+print("evaluations:", result.data["evaluations"])
+for name in ("population", "helper_population"):
+ F, G = result.data[name]["F"], result.data[name]["G"]
+ feasible = int(np.all(G <= 0.0, axis=1).sum())
+ print(f"{name}: {feasible} of {len(F)} feasible, mean f1 + f2 = {F.sum(axis=1).mean():.3f}")
+```
+
+Output:
+
+```text
+evaluations: 20000
+population: 100 of 100 feasible, mean f1 + f2 = 1.088
+helper_population: 1 of 100 feasible, mean f1 + f2 = 1.001
+```
+
+Population 1 is entirely feasible. Population 2 sits on the unconstrained front
+(f₁ + f₂ ≈ 1), and all but one of its members are infeasible, as expected from
+a population that never looks at the constraints. `result.data["population"]`
+is population 1, the result of the authors' code; `result.X` and `result.F`
+hold its rows, or its feasible non-dominated rows when the configuration asks
+for `result_mode="non_dominated"` (the default of `CCMOConfig.default()`).
+
+The dominance relation and the fitness follow the formulas above line by line.
+`strength_raw_fitness` is SPEA2's: the strength of each row, then the sum of the
+strengths of its dominators.
+
+```python
+# Excerpt from src/vamos/engine/algorithm/ccmo/selection.py
+def constraint_first_dominance(F: NDArray[Any], violation: NDArray[Any]) -> NDArray[np.bool_]:
+ objectives = np.asarray(F, dtype=float)
+ cv = np.asarray(violation, dtype=float)
+ smaller = cv[:, None] < cv[None, :]
+ equal = cv[:, None] == cv[None, :]
+ no_worse = np.all(objectives[:, None, :] <= objectives[None, :, :], axis=2)
+ better = np.any(objectives[:, None, :] < objectives[None, :, :], axis=2)
+ return np.asarray(smaller | (equal & no_worse & better), dtype=bool)
+
+
+def ccmo_fitness(F: NDArray[Any], violation: NDArray[Any]) -> tuple[FloatArray, FloatArray]:
+ objectives = np.asarray(F, dtype=float)
+ n = objectives.shape[0]
+ distances = objective_distances(objectives)
+ if n == 0:
+ return np.empty(0, dtype=float), distances
+ raw = strength_raw_fitness(constraint_first_dominance(objectives, violation))
+ others = distances.copy()
+ np.fill_diagonal(others, np.inf)
+ k = math.isqrt(n)
+ # Every row has n - 1 finite distances, and k <= n - 1 for n >= 2; with n = 1 the distance is infinite.
+ kth = np.partition(others, kth=k - 1, axis=1)[:, k - 1]
+ return np.asarray(raw + 1.0 / (kth + 2.0), dtype=float), distances
+```
+
+`smaller` and `equal` compare every pair of violations at once; a row
+dominates another if its violation is smaller or, with an equal violation, if
+it is no worse in every objective and better in one. In the fitness, the
+diagonal of the distance matrix is set to infinity so that a candidate is not
+its own neighbour, and `np.partition` finds the k-th smallest distance of each
+row without sorting it.
+
+The environmental selection keeps the rows with a fitness below 1 and falls
+back on the lowest fitness or on the truncation:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/ccmo/selection.py
+ fitness, distances = ccmo_fitness(F, violation)
+ n = fitness.shape[0]
+ size = min(int(n_select), n)
+ nondominated = np.flatnonzero(fitness < 1.0)
+ if nondominated.size < size:
+ selected = np.argsort(fitness, kind="stable")[:size]
+ elif nondominated.size > size:
+ keep = truncate_lexicographic(distances[np.ix_(nondominated, nondominated)], size, selection_kernels)
+ selected = nondominated[keep]
+ else:
+ selected = nondominated
+ selected = np.sort(selected)
+ order = np.asarray(selected[np.argsort(fitness[selected], kind="stable")], dtype=int)
+ return order, np.asarray(fitness[order], dtype=float)
+```
+
+The stable sorts give every tie to the row that comes first, as the authors'
+code does. The truncation receives only the distances among the non-dominated
+rows. The last two lines return the survivors in increasing order of fitness.
+
+The algorithm class puts the pieces together. `ask` breeds the offspring of
+both populations, population 1's first, and cuts them to the remaining budget;
+`tell` runs the two selections on the same offspring, once with the violation
+and once with zeros:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/ccmo/ccmo.py
+ request = capped_offspring_size(st.n_eval, st.max_evals, st.offspring_size, "CCMO")
+ main = self._offspring(st.X, st.fitness)
+ helper = self._offspring(st.helper_X, st.helper_fitness)
+ X_off = np.concatenate([main, helper])[:request]
+
+ # Population 1 selects from [itself, offspring] with the constraint violation.
+ X_union = np.vstack([st.X, X_off])
+ F_union = np.vstack([st.F, F_off])
+ G_union = combine_constraints(st.G, G_off, st.constraint_mode, algorithm="CCMO")
+ selected, st.fitness = ccmo_environmental_selection(F_union, _violation(G_union, F_union.shape[0]), st.pop_size, kernels)
+ st.X, st.F = X_union[selected], F_union[selected]
+ st.G = G_union[selected] if G_union is not None else None
+
+ # Population 2 selects from [itself, offspring] without it.
+ helper_X_union = np.vstack([st.helper_X, X_off])
+ helper_F_union = np.vstack([st.helper_F, F_off])
+ helper_G_union = combine_constraints(st.helper_G, G_off, st.constraint_mode, algorithm="CCMO")
+ selected, st.helper_fitness = ccmo_environmental_selection(helper_F_union, np.zeros(helper_F_union.shape[0]), st.pop_size, kernels)
+```
+
+`[:request]` is the exact budget: when fewer evaluations are left than a full
+generation creates, the offspring of population 2, which come last, are the
+first to be cut, and both populations then select from the offspring that were
+evaluated. Population 2 still stores the constraint values of its members
+(`helper_G_union`), so that a result can report their feasibility, but its
+selection never reads them.
+
+## Where VAMOS differs from the paper
+
+VAMOS follows the authors' reference code through jMetal's port, whose fitness
+and selection the [CCMO lesson](../../algorithms/ccmo.md#where-vamos-departs-from-the-reference-code)
+checks against jMetal's own classes. The code differs from the paper, and VAMOS
+follows the code:
+
+- the paper embeds NSGA-II with SPEA2's truncation; the code evolves each
+ population with SPEA2's fitness and environmental selection;
+- the paper treats two infeasible solutions with the same violation as
+ non-dominated; the code compares them by Pareto dominance;
+- the GA variation selects N parents for N/2 offspring per population; the
+ paper selects N/2. The DE variation is not described in the paper.
+
+VAMOS departs from the code itself only where the framework requires it:
+
+- **Budget:** exact; the reference code checks the budget before a generation
+ and can exceed it in the last one.
+- **Initialization:** both populations come from the configured initializer
+ (uniform by default), population 1 first, from the run's generator.
+- **Result:** the reference code returns population 1, which is
+ `result.data["population"]`; `result.X` and `result.F` follow the configured
+ `result_mode`.
+
+The [CCMO lesson](../../algorithms/ccmo.md#agreement-with-the-published-results)
+records the agreement with jMetal and with the paper on MW1, MW3 and C1-DTLZ1.
+
+## CCMO among the constrained algorithms
+
+| | NSGA-II with constrained domination | CCMO |
+| --- | --- | --- |
+| Populations | One | Two of the same size |
+| Constraints | Feasible first, then violation, then dominance | Population 1 like NSGA-II; population 2 ignores them |
+| Diversity | Crowding distance | SPEA2 density and truncation |
+| Extra parameters | None | None (the helper problem is fixed) |
+| Evaluations per generation | N | N with the GA variation, shared by both populations |
+
+Strengths:
+
+- **No new parameter.** There is no penalty factor, no ε schedule and no
+ switching threshold; the configuration is that of a GA.
+- **Exploration across barriers.** Population 2 is never stopped by an
+ infeasible region, so population 1 receives offspring from places it could
+ not reach.
+- **Population 1 is unaffected when the help is useless.** It selects with the
+ violation first, so infeasible offspring of population 2 cannot displace its
+ feasible members.
+
+Limits:
+
+- **Half of the offspring come from the helper.** When the unconstrained front
+ is far from the constrained one, population 2 converges where its offspring
+ are of little use, and population 1 effectively evolves with half its
+ offspring.
+- **Population 1 can still be trapped.** It keeps feasibility first; the
+ [CCMO lesson](../../algorithms/ccmo.md#agreement-with-the-published-results)
+ reports two of 31 runs on MW1 that ended trapped; jMetal's own CCMO was
+ trapped in one of 100.
+
+The next three lessons answer the same question differently: C-TAEA keeps two
+archives with one population of offspring, ToP splits the run into two phases,
+and CMOEA-MS switches between two ranking rules.
+
+## Key points
+
+- CCMO evolves population 1 on the constrained problem and population 2 on a
+ helper problem, the same objectives without constraints.
+- The populations cooperate only through their offspring: each one selects N
+ survivors from itself and the offspring of both.
+- In VAMOS, as in the authors' code, each population uses SPEA2's fitness,
+ R + 1/(σ^k + 2), with a dominance relation that puts the violation first in
+ population 1 and ignores it in population 2.
+- Survivors are the candidates with fitness below 1, completed by the lowest
+ fitness or reduced by SPEA2's truncation.
+- The result is population 1; the budget is exact, and the offspring of
+ population 2 are cut first.
+
+**Next:** [A7. C-TAEA: a convergence archive and a diversity archive](ctaea.md).
+
+## References
+
+[1] Tian, Y., Zhang, T., Xiao, J., Zhang, X., and Jin, Y. (2021). [A coevolutionary framework for constrained multiobjective optimization problems](https://doi.org/10.1109/TEVC.2020.3004012). *IEEE Transactions on Evolutionary Computation*, 25(1), 102–116.
+
+[2] Deb, K. (2000). [An efficient constraint handling method for genetic algorithms](https://doi.org/10.1016/S0045-7825(99)00389-8). *Computer Methods in Applied Mechanics and Engineering*, 186(2–4), 311–338.
+
+[3] Deb, K., Pratap, A., Agarwal, S., and Meyarivan, T. (2002). [A fast and elitist multiobjective genetic algorithm: NSGA-II](https://doi.org/10.1109/4235.996017). *IEEE Transactions on Evolutionary Computation*, 6(2), 182–197.
+
+[4] Deb, K., Pratap, A., and Meyarivan, T. (2001). [Constrained test problems for multi-objective evolutionary optimization](https://doi.org/10.1007/3-540-44719-9_20). *Evolutionary Multi-Criterion Optimization – EMO 2001*, Lecture Notes in Computer Science 1993, 284–298.
+
+[5] Storn, R., and Price, K. (1997). [Differential Evolution – A Simple and Efficient Heuristic for Global Optimization over Continuous Spaces](https://doi.org/10.1023/A:1008202821328). *Journal of Global Optimization*, 11(4), 341–359.
+
+[6] Zitzler, E., Laumanns, M., and Thiele, L. (2001). [SPEA2: Improving the strength Pareto evolutionary algorithm](https://tik-db.ee.ethz.ch/db/public/tik/?db=publications&form=report_single_publication&publication_id=1287). TIK Report 103, Computer Engineering and Networks Laboratory, ETH Zurich.
diff --git a/docs/foundations/advanced/cmoeams.md b/docs/foundations/advanced/cmoeams.md
new file mode 100644
index 000000000..755a97b51
--- /dev/null
+++ b/docs/foundations/advanced/cmoeams.md
@@ -0,0 +1,418 @@
+---
+description: 'A9. CMOEA-MS in depth: a normalized constraint violation, stage A that ranks density and violation as two objectives, stage B that puts the violation first, the switch on the feasible share and lambda, SPEA2 fitness with cosine distances, and where VAMOS follows PlatEMO and jMetal, with an interactive figure and VAMOS code.'
+search:
+ boost: 0.5
+---
+
+# A9. CMOEA-MS: two stages
+
+ToP (lesson [A8](top.md)) explores first and converges afterwards, and once its
+second phase starts it never goes back. The **constrained multi-objective
+evolutionary algorithm with multiple stages**, CMOEA-MS, of Tian, Zhang, Su,
+Zhang, Tan and Jin [1] also has two ways of ranking solutions, but it chooses
+between them at every generation, from the share of feasible solutions, and it
+can return to the first one whenever feasibility becomes scarce again.
+
+In **stage A** the objectives and the constraints have the same priority: each
+solution is described by two numbers, its density in the objective space and
+its constraint violation, and these two numbers are ranked by Pareto
+dominance. A sparse infeasible solution can then beat a crowded feasible one.
+In **stage B** the constraints come first: a smaller violation is better, and
+equal violations are compared by the objectives. The algorithm is in stage B
+while more than half of the candidates are feasible, once 10% of the budget is
+spent.
+
+CMOEA-MS keeps a single population, like NSGA-II, and both stages use the
+fitness and the environmental selection of SPEA2 [3] (lesson
+[I7](../intermediate/spea2.md)). What changes between the stages is the
+dominance relation behind the fitness.
+
+In this lesson you will learn:
+
+- the normalized constraint violation of CMOEA-MS;
+- the shift-based density estimation, and how stage A ranks density and
+ violation as two objectives;
+- stage B, the fitness and the environmental selection with cosine distances;
+- the rule that chooses the stage, its parameter λ, and where VAMOS follows
+ PlatEMO's implementation through jMetal's port.
+
+## Balancing objectives and constraints
+
+A feasibility-first rule (lesson [A5](constrained.md#constrained-domination))
+gives constraint satisfaction absolute priority, and can be trapped behind
+infeasible barriers. Ignoring the constraints gives the objectives absolute
+priority, and converges where the solutions cannot be used. CMOEA-MS [1]
+makes the balance depend on the state of the search: while few solutions are
+feasible, objective optimization and constraint satisfaction weigh the same,
+and the population can keep well-spread solutions on both sides of the
+feasibility boundary; once most solutions are feasible, constraint
+satisfaction comes first, and the population converges inside the feasible
+region.
+
+The two stages implement these two priorities, and the share of feasible
+solutions decides between them. Unlike ToP's phases, the stages alternate as
+often as the share crosses its threshold.
+
+## The normalized violation
+
+The violation of each constraint is divided by its largest value among the
+candidates, and the violation of a solution is the mean over the constraints:
+
+CV(x) = (1/q) Σ_j max( 0, g_j(x) ) / max_{y ∈ Q} max( 0, g_j(y) ) (a term is 0 if nobody violates g_j)
+
+Q is the union of the population and the offspring, and q the number of
+constraints. Every constraint contributes on the same scale, and CV is in
+[0, 1]. A solution is feasible when CV(x) = 0.
+
+## Stage A: density and violation as two objectives
+
+Stage A replaces the m objectives by one measure of how good and how isolated
+a solution is in the objective space, the **shift-based density estimation**
+(SDE) of Li, Yang and Liu [2]. To estimate the density around x, every other
+solution y is first *shifted*: in each objective where y is better than x, it
+takes x's value. Then distances are measured as usual:
+
+f̂ = objectives normalized to [0, 1] over Q
+y′_i = max( f̂_i(y), f̂_i(x) ) (y shifted towards x)
+d(x) = the (⌊√|Q|⌋ + 1)-th smallest of ‖ f̂(x) − y′ ‖ over all y ∈ Q (x itself included, at distance 0)
+SDE(x) = 1 / ( d(x) + 2 ) (lower = less crowded)
+stage A ranks the points [ SDE(x), CV(x) ] by Pareto dominance
+
+Shifting moves the solutions that are better than x in some objective onto x
+in that objective. A solution that is worse than many others therefore sees
+them close by and gets a high density; a solution that is good in the
+objectives and far from its neighbours gets a low one. SDE was designed for
+many-objective Pareto-based algorithms, where it penalizes poor convergence and
+crowding in one number [2]. In stage A that number becomes one objective and
+the violation the other: a solution survives if no other one is both less
+crowded and less violated.
+
+## Stage B: the violation first
+
+Stage B ranks the objectives themselves, with the violation first:
+
+a ≺_B b ⇔ CV(a) < CV(b), or CV(a) = CV(b) and a ≺ b (Pareto dominance on the objectives)
+
+This is the relation of CCMO's population 1 (lesson
+[A6](ccmo.md#fitness-with-the-violation-first)): every feasible solution
+dominates every infeasible one, and infeasible solutions are ordered by their
+violation.
+
+## Fitness and environmental selection
+
+Both stages compute SPEA2's fitness of the 2N solutions of Q with their own
+dominance relation, on their own points ([SDE, CV] in stage A, the objectives in
+stage B):
+
+S(i) = number of solutions that i dominates R(j) = Σ_{i dominates j} S(i)
+fitness(i) = R(i) + 1 / ( d_cos(i) + 2 ), d_cos = cosine distance to the ⌊√|Q|⌋-th nearest other point
+keep every solution with fitness < 1
+if fewer than N: keep the N lowest fitness values
+if more than N: remove one at a time the solution whose sorted cosine distances
+ between objective vectors are lexicographically smallest
+
+The cosine distance, 1 − cos of the angle between two vectors, compares
+directions from the origin rather than positions. The truncation always uses
+the objective vectors, in stage A too. The survivors keep their order in Q, and
+their fitness is reused by the binary tournaments of the next generation.
+
+## The stage rule
+
+Q is in stage B ⇔ |{ x ∈ Q : CV(x) = 0 }| / |Q| > λ and evaluations ≥ 10% of the budget
+otherwise, and for the initial population, Q is in stage A (λ = 0.5 by default)
+
+The rule is checked at every generation, after the offspring are evaluated, so
+the algorithm moves back to stage A whenever half or more of Q is infeasible.
+λ is `feasible_ratio_threshold` in `CMOEAMSConfig`. Stage A tends to keep
+infeasible solutions, which lowers the feasible share, so a high λ can hold the
+algorithm in stage A for good, as the example below shows.
+
+## Try it: the two stages on the same candidates
+
+The figure shows the 16 CTP2 candidates of lesson
+[A6](ccmo.md#try-it-one-set-of-candidates-two-rules): P1 to P8 are the
+population and O1 to O8 the offspring, so the 16 together are Q. Start with
+stage A, whose ranking happens in the plane [SDE, CV] (hover a point to see both
+values), then switch to stage B. The line under the plot applies the stage rule
+to Q.
+
+
+
+Nine of the 16 candidates are feasible: 9/16 = 0.5625 > λ = 0.5, so after the
+first 10% of the budget VAMOS would use stage B. In stage A, O1 has both the
+lowest density and no violation, so it dominates every other point [SDE, CV]
+and is the only one with a fitness below 1; the other seven survivors are those
+with the lowest fitness: P1, P3, O7, O5, O3, P8 and P2. Five of the eight are
+infeasible, and the feasible P5, P7, O6 and O8 on the constrained front are
+dropped because their region of the front is crowded. Stage B keeps eight of
+the nine feasible candidates, as a feasibility-first rule would, and drops P6,
+which three of them dominate.
+
+## In VAMOS
+
+CMOEA-MS on CTP2 with λ = 0.5 and on MW3 with λ = 0.5 and 0.9, with a
+population of 100 and 20,000 evaluations:
+
+```python
+import numpy as np
+
+from vamos import optimize
+from vamos.algorithms import CMOEAMSConfig
+
+for name, threshold in (("ctp2", 0.5), ("mw3", 0.5), ("mw3", 0.9)):
+ config = (
+ CMOEAMSConfig.builder()
+ .pop_size(100)
+ .crossover("sbx", prob=1.0, eta=20.0)
+ .mutation("pm", prob="1/n", eta=20.0)
+ .feasible_ratio_threshold(threshold)
+ .result_mode("population")
+ .build()
+ )
+ result = optimize(name, algorithm="cmoeams", algorithm_config=config, max_evaluations=20_000, engine="numpy", seed=1)
+ G = result.data["population"]["G"]
+ feasible = int(np.all(G <= 0.0, axis=1).sum())
+ stage_b = result.data["stage_b_generations"]
+ print(f"{name}, lambda {threshold}: stage B in {stage_b} of {result.data['generation']} generations, final stage {result.data['stage']}, {feasible} of {len(G)} feasible")
+```
+
+Output:
+
+```text
+ctp2, lambda 0.5: stage B in 181 of 199 generations, final stage B, 100 of 100 feasible
+mw3, lambda 0.5: stage B in 177 of 199 generations, final stage B, 100 of 100 feasible
+mw3, lambda 0.9: stage B in 0 of 199 generations, final stage A, 64 of 100 feasible
+```
+
+Each generation evaluates 100 offspring, so the first 18 generations end before
+2,000 evaluations, 10% of the budget, and are in stage A whatever the share of
+feasible solutions. With λ = 0.5, every later generation on CTP2 is in stage B
+(181 = 199 − 18): its random solutions lie far above the front, where the whole
+objective space is feasible. On MW3 four later generations fall back to stage
+A. With λ = 0.9 the picture changes: the feasible share of Q never exceeds 0.9
+and the run stays in stage A, which keeps infeasible solutions: 64 of the final
+100 are feasible.
+
+A λ close to the feasible share that a run settles at makes the stages fragile.
+On CTP2 with λ = 0.9 the share stays near 0.9, so the last-digit differences
+between platforms decide whether a generation is in stage A or B, and the same
+seed gives different runs: on the Windows machine that recorded these outputs
+the share is 0.9 or less in 22 of the generations after the first 10% and the
+run ends in stage A with 26 feasible solutions, while on Linux it stays above
+0.9 and the run ends in stage B with all 100 feasible. The example leaves that
+case out because its output depends on the platform.
+
+The shift-based density, for all the solutions of Q at once:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/cmoeams/fitness.py
+def shift_based_density(F: NDArray[Any]) -> FloatArray:
+ normalized = _normalized_objectives(F)
+ n, n_obj = normalized.shape
+ if n < 2:
+ raise ValueError("CMOEA-MS's shift-based density needs at least two solutions.")
+ squares = np.zeros((n, n), dtype=float)
+ for j in range(n_obj):
+ own = normalized[:, j][:, None]
+ other = normalized[:, j][None, :]
+ # Row i, column k: solution k shifted to solution i.
+ shifted = np.where(other < own, own, other)
+ difference = own - shifted
+ squares = squares + difference * difference
+ distances = np.sort(np.sqrt(squares), axis=1)
+ neighbour = int(math.floor(math.sqrt(n)))
+ return np.asarray(1.0 / (distances[:, neighbour] + 2.0), dtype=float)
+```
+
+`np.where(other < own, own, other)` is the shift: where solution k is better
+than solution i in objective j, it takes i's value, and the difference is zero.
+Each row of `distances` starts with the zero distance of i to itself, so index
+⌊√n⌋ is the (⌊√n⌋ + 1)-th smallest distance, as in PlatEMO.
+
+The fitness of both stages and the stage rule:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/cmoeams/fitness.py
+def spea2_fitness(points: NDArray[Any], violation: NDArray[Any]) -> FloatArray:
+ values = np.asarray(points, dtype=float)
+ n = values.shape[0]
+ if n == 0:
+ raise ValueError("CMOEA-MS's fitness needs at least one solution.")
+ dominates = dominance_matrix(values, violation)
+ strength = dominates.sum(axis=1, dtype=np.int64)
+ raw = (dominates.T.astype(np.int64) @ strength).astype(float)
+ distances = cosine_distances(values)
+ np.fill_diagonal(distances, np.inf)
+ neighbour = int(math.floor(math.sqrt(n))) - 1
+ kth = np.sort(distances, axis=1)[:, neighbour]
+ return np.asarray(raw + 1.0 / (kth + 2.0), dtype=float)
+
+
+def stage_a_fitness(F: NDArray[Any], violation: NDArray[Any]) -> FloatArray:
+ cv = np.asarray(violation, dtype=float)
+ points = np.column_stack([shift_based_density(F), cv])
+ return spea2_fitness(points, np.zeros(cv.shape[0], dtype=float))
+
+
+def stage_b_fitness(F: NDArray[Any], violation: NDArray[Any]) -> FloatArray:
+ return spea2_fitness(F, violation)
+
+
+def is_stage_b(violation: NDArray[Any], threshold: float, evaluations: int, max_evaluations: int) -> bool:
+ cv = np.asarray(violation, dtype=float)
+ ratio = int(np.count_nonzero(cv <= 0.0)) / cv.shape[0]
+ return bool(ratio > threshold and evaluations >= STAGE_B_EVALUATION_FRACTION * max_evaluations)
+```
+
+One function serves both stages. Stage A passes the points [SDE, CV] and zero
+violations, so `dominance_matrix` reduces to Pareto dominance on those two
+numbers; stage B passes the objectives and the normalized violations. In stage
+A every feasible point is [SDE, 0], so the feasible points all have the same
+direction and a cosine distance of 0 between them; when Q holds enough
+feasible solutions, their density term is exactly 1/2.
+
+The environmental selection:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/cmoeams/selection.py
+def environmental_selection(
+ fitness: NDArray[Any], F: NDArray[Any], n_select: int, selection_kernels: SelectionKernels | None = None
+) -> IndexArray:
+ values = np.asarray(fitness, dtype=float)
+ objectives = np.asarray(F, dtype=float)
+ n = values.shape[0]
+ selected = values < 1.0
+ count = int(np.count_nonzero(selected))
+ if count < n_select:
+ selected[sorted_indices(values)[: int(n_select)]] = True
+ elif count > n_select:
+ candidates = np.flatnonzero(selected)
+ selected[candidates[truncation(objectives[candidates], count - int(n_select), selection_kernels)]] = False
+ return np.asarray(np.flatnonzero(selected), dtype=int)
+```
+
+`sorted_indices` is a stable sort that puts NaN last, as MATLAB's `sort`, so
+ties go to the earlier solution. `truncation` is SPEA2's operator on the cosine
+distances between the objective vectors of the candidates.
+
+Finally, `tell` builds Q, chooses the stage and selects:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/cmoeams/cmoeams.py
+ # The union of the population and the offspring, in that order.
+ X_union = np.vstack([st.X, X_off])
+ F_union = np.vstack([st.F, F_off])
+ G_union = combine_constraints(st.G, G_off, st.constraint_mode, algorithm="CMOEA-MS")
+ violation = normalized_violation(G_union, F_union.shape[0])
+ st.stage_b = is_stage_b(violation, st.feasible_ratio_threshold, st.n_eval, st.max_evals)
+ fitness = stage_b_fitness(F_union, violation) if st.stage_b else stage_a_fitness(F_union, violation)
+ selected = environmental_selection(fitness, F_union, st.pop_size, self.kernel.selection_kernels())
+ st.X, st.F = X_union[selected], F_union[selected]
+ st.G = G_union[selected] if G_union is not None else None
+ st.fitness = fitness[selected]
+ st.stage_b_generations += int(st.stage_b)
+```
+
+`st.n_eval` already includes the offspring of this generation when the stage is
+decided, as in jMetal. The violation is normalized over Q, so the same
+solution can have different values of CV in two generations.
+
+## Where VAMOS differs from the paper
+
+VAMOS follows jMetal's port, which follows the authors' implementation in
+PlatEMO where it differs from the paper; the
+[CMOEA-MS lesson](../../algorithms/cmoeams.md#where-vamos-departs-from-jmetals-port)
+lists the checks against jMetal's classes. Relative to the paper:
+
+- stage B needs a feasible share greater than λ **and** 10% of the
+ evaluations, where the paper's Algorithm 1 has no condition on the
+ evaluations;
+- the violation is normalized per constraint and averaged, instead of the sum
+ of the violations;
+- SDE is computed on normalized objectives with the (⌊√|Q|⌋ + 1)-th shifted
+ neighbour, instead of the nearest one;
+- the density term of the fitness and the truncation use the cosine distance
+ instead of the Euclidean distance, and the truncation uses the objectives in
+ stage A too;
+- the tournaments use the fitness computed on the union of the previous
+ generation.
+
+Relative to jMetal's port:
+
+- **Budget:** exact; a cut last generation evaluates the first offspring only,
+ while jMetal can exceed the budget.
+- **Random draws:** in blocks (tournaments, then crossovers, then mutations),
+ so runs with the same seed differ from jMetal's, with the same
+ distributions.
+- **Parent order:** the GA variation passes the second parent of each pair
+ first, so that each child of VAMOS's SBX has the distribution of jMetal's
+ child at its position.
+- **Result:** jMetal returns the whole final population, which is
+ `result.data["population"]`; `result.X` and `result.F` follow the configured
+ `result_mode`.
+
+The [CMOEA-MS lesson](../../algorithms/cmoeams.md#agreement-with-jmetals-port-and-the-published-results)
+records the agreement with jMetal's classes, bit for bit, and with the
+published results.
+
+## The four constrained algorithms
+
+| | CCMO (A6) | C-TAEA (A7) | ToP (A8) | CMOEA-MS (A9) |
+| --- | --- | --- | --- | --- |
+| Exploring part | Population without constraints | Diversity archive | Phase 1, single objective | Stage A, density and violation |
+| Converging part | Population with violation first | Convergence archive | Phase 2, NSGA-II | Stage B, violation first |
+| When each acts | Always, in parallel | Always, mating by non-dominated shares | Phase 1, then phase 2 | Each generation, by the feasible share |
+| Switch parameters | None | None | δ, Pf, 90% limit | λ, 10% limit |
+| Selection | SPEA2 | Subregions of weight vectors | Feasibility rule, then NSGA-II | SPEA2 with cosine distances |
+
+Strengths of CMOEA-MS:
+
+- **One population, one parameter.** No helper population, no archives; λ is
+ the only switching parameter.
+- **Reversible.** The algorithm returns to stage A whenever feasibility becomes
+ scarce, for example after the population reaches a new infeasible barrier.
+- **A balanced stage A.** Sparse infeasible solutions survive next to feasible
+ ones, without a penalty factor to tune.
+
+Limits:
+
+- **λ matters.** In the example, λ = 0.9 keeps the run on MW3 in stage A from
+ start to end, and 64 of the final 100 solutions are feasible instead of all
+ of them. A λ near the feasible share that a run settles at makes the stage
+ sequence, and the result, depend on rounding.
+- **Stage A ranks two scalars.** SDE condenses the objectives into one number,
+ so a feasible solution with the lowest density can dominate every other
+ point, as O1 does in the figure, and the rest is ranked by raw fitness.
+- **Gaps on some problems.** The
+ [CMOEA-MS lesson](../../algorithms/cmoeams.md#agreement-with-jmetals-port-and-the-published-results)
+ records LIR-CMOP10 runs, in VAMOS and in jMetal, that miss a part of the
+ front.
+
+Lesson [A10](performance-assessment.md) explains how to compare such
+algorithms fairly: on several problems, with several runs, and with the
+feasibility rate reported separately (lesson
+[A5](constrained.md#measuring-constrained-results)).
+
+## Key points
+
+- CMOEA-MS ranks one population with SPEA2's fitness under two dominance
+ relations, one per stage.
+- Stage A ranks the points [SDE, CV] by Pareto dominance: density in the
+ objective space and normalized violation weigh the same.
+- Stage B puts the violation first and compares equal violations by the
+ objectives.
+- The union Q is in stage B when more than λ = 0.5 of it is feasible and 10% of
+ the budget is spent; otherwise in stage A, and the stages can alternate.
+- VAMOS follows PlatEMO's implementation through jMetal's port: normalized and
+ averaged violations, SDE on normalized objectives, cosine distances, and an
+ exact budget.
+
+**Next:** [A10. Comparing algorithms rigorously](performance-assessment.md).
+
+## References
+
+[1] Tian, Y., Zhang, Y., Su, Y., Zhang, X., Tan, K. C., and Jin, Y. (2022). [Balancing objective optimization and constraint satisfaction in constrained evolutionary multiobjective optimization](https://doi.org/10.1109/TCYB.2020.3021138). *IEEE Transactions on Cybernetics*, 52(9), 9559–9572.
+
+[2] Li, M., Yang, S., and Liu, X. (2014). [Shift-based density estimation for Pareto-based algorithms in many-objective optimization](https://doi.org/10.1109/TEVC.2013.2262178). *IEEE Transactions on Evolutionary Computation*, 18(3), 348–365.
+
+[3] Zitzler, E., Laumanns, M., and Thiele, L. (2001). [SPEA2: Improving the strength Pareto evolutionary algorithm](https://tik-db.ee.ethz.ch/db/public/tik/?db=publications&form=report_single_publication&publication_id=1287). TIK Report 103, Computer Engineering and Networks Laboratory, ETH Zurich.
diff --git a/docs/foundations/advanced/constrained.md b/docs/foundations/advanced/constrained.md
new file mode 100644
index 000000000..52160f7f7
--- /dev/null
+++ b/docs/foundations/advanced/constrained.md
@@ -0,0 +1,207 @@
+---
+description: 'A5. Constrained multi-objective optimization: feasibility and constraint violation, constrained domination, epsilon-constrained and stochastic ranking, why feasibility-first selection can fail, and the constrained algorithms in VAMOS.'
+search:
+ boost: 0.5
+---
+
+# A5. Constrained multi-objective optimization
+
+Real problems come with limits: a stress below the yield strength, a budget,
+a delivery time. Constraints split the decision space into feasible and
+infeasible regions, and the best feasible trade-offs can look very different
+from the unconstrained ones. This lesson explains how evolutionary algorithms
+compare solutions when some of them break the rules.
+
+In this lesson you will learn:
+
+- how constraints and constraint violation are defined;
+- constrained domination, the default rule of NSGA-II in VAMOS;
+- the alternatives that relax feasibility first;
+- why difficult feasible regions call for dedicated algorithms, and which ones
+ VAMOS provides.
+
+## Feasibility and violation
+
+With inequality constraints written as g_j(x) ≤ 0, the convention of VAMOS
+(lesson [B1](../basic/multi-objective-problems.md#the-formal-problem)), a
+solution is **feasible** when every g_j(x) ≤ 0. Its **constraint violation**
+aggregates how much it breaks them:
+
+CV(x) = Σ_j max( 0, g_j(x) ) CV(x) = 0 ⇔ x is feasible
+
+An equality h(x) = 0 is usually relaxed to |h(x)| − δ ≤ 0 for a small tolerance
+δ. Constraints of different magnitudes should be normalized before they are
+added, or the largest one dominates CV. The [constraint
+reference](../../reference/constraints.md#define-inequality-constraints) shows
+how to declare them in VAMOS.
+
+The **constrained Pareto front** is the Pareto front of the feasible solutions.
+It can coincide with the unconstrained front, lie partly on it, or lie on the
+boundary of the feasible region, possibly in disconnected pieces.
+
+## Constrained domination
+
+Deb's feasibility rules [1], used by NSGA-II [2], define a solution a to
+*constrained-dominate* b when
+
+a is feasible and b is not, or
+both are infeasible and CV(a) < CV(b), or
+both are feasible and a ≺ b (Pareto dominance)
+
+Fast non-dominated sorting runs unchanged with this relation in place of
+dominance (lesson [I2](../intermediate/non-dominated-sorting.md)). The rule has
+no parameter: feasibility comes first, then the objectives.
+
+The figure uses CTP2 of Deb, Pratap and Meyarivan [3], a problem whose
+constraint carves the objective space into feasible "tunnels". The dashed line
+is the unconstrained front; it is infeasible everywhere except at its end. The
+constrained front, in blue, is a set of short disconnected segments on the
+boundary of the feasible region. Switch between the two ranking rules and
+compare the first front:
+
+
+
+Ignoring the constraints, the infeasible solutions closest to the unconstrained
+front take the best ranks, and selection would push the population into a
+region it can never use. Constrained domination ranks every feasible solution
+first and orders the infeasible ones by how close they are to feasibility.
+
+## Beyond feasibility first
+
+Feasibility first is simple and effective when the feasible region is large
+and connected. It fails when it is not: once a few feasible solutions are found,
+they dominate the population, and feasible regions separated from them by
+infeasible barriers are never reached. Several techniques relax the rule:
+
+- **Penalty functions** add a multiple of CV(x) to each objective. They are
+ simple, but the result depends on the penalty factor.
+- **ε-constrained methods** treat a solution as feasible when its violation is
+ at most ε, and shrink ε to zero during the run, so that slightly infeasible
+ solutions can cross barriers early on [4].
+- **Stochastic ranking** compares two solutions by their objectives with a fixed
+ probability, even when they are infeasible, and by their violation otherwise
+ [5].
+
+Modern constrained algorithms go further and keep **two sources of
+information**: one that ignores or relaxes the constraints and explores, and one
+that enforces them and converges to the constrained front.
+
+| Algorithm | Idea | Lessons |
+| --- | --- | --- |
+| CCMO [6] | Two populations evolve in parallel, one solving the constrained problem and one a helper problem without constraints, sharing their offspring. | [A6](ccmo.md) · [CCMO](../../algorithms/ccmo.md) |
+| C-TAEA [7] | Two archives, one that pushes towards feasibility and convergence and one that keeps diversity, including infeasible solutions. | [A7](ctaea.md) · [C-TAEA](../../algorithms/ctaea.md) |
+| ToP [8] | Two phases: first find promising regions by treating the problem as a single-objective constrained problem, then optimize all objectives there. | [A8](top.md) · [ToP](../../algorithms/top.md) |
+| CMOEA-MS [9] | Two stages: one gives the objectives the same priority as the constraint violation, the other puts the constraints first; the share of feasible solutions decides which stage runs. | [A9](cmoeams.md) · [CMOEA-MS](../../algorithms/cmoeams.md) |
+
+The [constraint reference](../../reference/constraints.md#choose-a-constraint-handling-technique)
+lists the constraint-handling techniques that VAMOS' algorithms accept, such as
+`epsilon_constrained`, `stochastic_ranking` and `push_pull`, and the
+[problem reference](../../reference/problems.md) lists the constrained benchmark
+families.
+
+## In VAMOS
+
+A CTP2-style problem, written with `make_problem`. Both functions are
+vectorized: they receive a whole population, one row per solution. The
+constraint function returns G = −c, because the paper writes the constraint as
+c(x) ≥ 0 and VAMOS treats G ≤ 0 as feasible. Here g = 1 + Σ x_i² is a simpler
+distance function than the paper's; since VAMOS 1.5.0, the original CTP1 to
+CTP7 are also built-in problems.
+
+```python
+import numpy as np
+
+from vamos import make_problem, optimize
+
+THETA, A, B, C, D, E = -0.2 * np.pi, 0.2, 10.0, 1.0, 6.0, 1.0 # CTP2 parameters
+
+
+def objectives(X):
+ g = 1.0 + np.sum(X[:, 1:] ** 2, axis=1)
+ f1 = X[:, 0]
+ return np.column_stack([f1, g - f1]) # f2 = g (1 - f1 / g)
+
+
+def constraints(X):
+ F = objectives(X)
+ f1, f2 = F[:, 0], F[:, 1]
+ across = np.cos(THETA) * (f2 - E) - np.sin(THETA) * f1
+ along = np.sin(THETA) * (f2 - E) + np.cos(THETA) * f1
+ c = across - A * np.abs(np.sin(B * np.pi * along**C)) ** D # c(x) >= 0 in the paper
+ return -c[:, None] # VAMOS: G <= 0 is feasible
+
+
+problem = make_problem(
+ objectives,
+ n_var=5,
+ n_obj=2,
+ bounds=[(0.0, 1.0)] + [(-1.0, 1.0)] * 4,
+ vectorized=True,
+ encoding="real",
+ constraints=constraints,
+ n_constraints=1,
+ name="ctp2_style",
+)
+result = optimize(problem, algorithm="nsgaii", pop_size=100, max_evaluations=20_000, engine="numpy", seed=3)
+
+G = result.data["G"]
+feasible = np.all(G <= 0.0, axis=1)
+front = result.front()
+print("feasible returned solutions:", int(feasible.sum()), "of", len(G))
+print("constrained front:", len(front), "points, f1 from", round(float(front[:, 0].min()), 3), "to", round(float(front[:, 0].max()), 3))
+```
+
+Output:
+
+```text
+feasible returned solutions: 100 of 100
+constrained front: 100 points, f1 from 0.0 to 0.985
+```
+
+`result.front()` keeps feasible rows only (`feasible_only=True` by default) and
+falls back to the least violated rows when none is feasible. To change the
+rule, pass a technique to the builder, for example
+`.constraint_handling("epsilon_constrained")`; to change the algorithm, pass
+`algorithm="ccmo"` or one of the others in the table.
+
+## Measuring constrained results
+
+- Compute quality indicators on the **feasible** non-dominated points only, with
+ a reference set from the **constrained** front.
+- Report, per algorithm, how many runs found at least one feasible solution,
+ and how quickly. An indicator averaged over the successful runs alone hides
+ the failures.
+
+## Key points
+
+- A solution is feasible when every g_j(x) ≤ 0; the violation CV(x) sums the
+ positive parts.
+- Constrained domination (feasible first, then less violation, then Pareto
+ dominance) is the default rule of NSGA-II in VAMOS.
+- Feasibility-first selection can be trapped by disconnected or narrow feasible
+ regions; ε-constrained methods, stochastic ranking and two-population or
+ two-stage algorithms address that.
+- Evaluate constrained results on feasible solutions and report the feasibility
+ rate separately.
+
+**Next:** [A6. CCMO](ccmo.md).
+
+## References
+
+[1] Deb, K. (2000). [An efficient constraint handling method for genetic algorithms](https://doi.org/10.1016/S0045-7825(99)00389-8). *Computer Methods in Applied Mechanics and Engineering*, 186(2–4), 311–338.
+
+[2] Deb, K., Pratap, A., Agarwal, S., and Meyarivan, T. (2002). [A fast and elitist multiobjective genetic algorithm: NSGA-II](https://doi.org/10.1109/4235.996017). *IEEE Transactions on Evolutionary Computation*, 6(2), 182–197.
+
+[3] Deb, K., Pratap, A., and Meyarivan, T. (2001). [Constrained test problems for multi-objective evolutionary optimization](https://doi.org/10.1007/3-540-44719-9_20). *Evolutionary Multi-Criterion Optimization – EMO 2001*, Lecture Notes in Computer Science 1993, 284–298.
+
+[4] Takahama, T., and Sakai, S. (2006). Constrained optimization by the ε constrained differential evolution with gradient-based mutation and feasible elites. *Proceedings of the 2006 IEEE Congress on Evolutionary Computation*, 1–8.
+
+[5] Runarsson, T. P., and Yao, X. (2000). [Stochastic ranking for constrained evolutionary optimization](https://doi.org/10.1109/4235.873238). *IEEE Transactions on Evolutionary Computation*, 4(3), 284–294.
+
+[6] Tian, Y., Zhang, T., Xiao, J., Zhang, X., and Jin, Y. (2021). [A coevolutionary framework for constrained multiobjective optimization problems](https://doi.org/10.1109/TEVC.2020.3004012). *IEEE Transactions on Evolutionary Computation*, 25(1), 102–116.
+
+[7] Li, K., Chen, R., Fu, G., and Yao, X. (2019). [Two-archive evolutionary algorithm for constrained multiobjective optimization](https://doi.org/10.1109/TEVC.2018.2855411). *IEEE Transactions on Evolutionary Computation*, 23(2), 303–315.
+
+[8] Liu, Z.-Z., and Wang, Y. (2019). [Handling constrained multiobjective optimization problems with constraints in both the decision and objective spaces](https://doi.org/10.1109/TEVC.2019.2894743). *IEEE Transactions on Evolutionary Computation*, 23(5), 870–884.
+
+[9] Tian, Y., Zhang, Y., Su, Y., Zhang, X., Tan, K. C., and Jin, Y. (2022). [Balancing objective optimization and constraint satisfaction in constrained evolutionary multiobjective optimization](https://doi.org/10.1109/TCYB.2020.3021138). *IEEE Transactions on Cybernetics*, 52(9), 9559–9572.
diff --git a/docs/foundations/advanced/ctaea.md b/docs/foundations/advanced/ctaea.md
new file mode 100644
index 000000000..7762d4ce7
--- /dev/null
+++ b/docs/foundations/advanced/ctaea.md
@@ -0,0 +1,405 @@
+---
+description: 'A7. C-TAEA in depth: weight vectors and subregions, the convergence archive and its three update cases, the diversity archive that ignores the constraints, restricted mating selection, and where VAMOS follows PlatEMO and jMetal instead of the paper, with an interactive figure and VAMOS code.'
+search:
+ boost: 0.5
+---
+
+# A7. C-TAEA: a convergence archive and a diversity archive
+
+CCMO (lesson [A6](ccmo.md)) helps a constrained population with a second
+population that ignores the constraints. The **two-archive evolutionary
+algorithm for constrained multi-objective optimization**, C-TAEA, of Li, Chen,
+Fu and Yao [1] keeps the same two roles in a different structure: two archives
+of N solutions, both fed by one stream of offspring, and a mating rule that
+decides, generation by generation, which archive the parents come from.
+
+The **convergence archive (CA)** is driven by feasibility and convergence, and
+it is the result of the run. The **diversity archive (DA)** ignores the
+constraints and keeps solutions where the CA has few, so that the search can
+cross infeasible regions towards the parts of the front that the CA has not
+reached. Both archives are organized by **weight vectors**, as in
+decomposition-based algorithms (lesson [I8](../intermediate/moead.md)): each
+vector defines a subregion of the objective space, and "where the CA has few"
+means "in the subregions with few CA members".
+
+Unlike NSGA-II, C-TAEA has no population that is sorted and truncated as a
+whole. Feasibility decides the CA, density in subregions decides both
+archives, and the Tchebycheff function chooses within a subregion.
+
+In this lesson you will learn:
+
+- how weight vectors divide the objective space into subregions;
+- the three cases of the CA update, and how it removes solutions from the most
+ crowded subregion;
+- how the DA fills the subregions that the CA neglects, without looking at the
+ constraints;
+- how the restricted mating selection chooses each parent's archive, and where
+ VAMOS follows PlatEMO and jMetal instead of the paper.
+
+## Why two archives
+
+Feasibility-first selection (lesson [A5](constrained.md#beyond-feasibility-first))
+throws away infeasible solutions as soon as enough feasible ones exist, and with
+them the paths across infeasible barriers. Li et al. [1] separate the two jobs.
+The CA does what a feasibility-first algorithm does: it keeps feasible
+solutions and pushes them towards the constrained front. The DA does what
+feasibility first forbids: it keeps good solutions *whatever their
+feasibility*, but only in the subregions where the CA is thin, so that it adds
+diversity instead of duplicating the CA.
+
+The two archives do not evolve separately. Each generation creates N offspring
+from parents taken from either archive, and both archives are updated with the
+same offspring. Which archive supplies the parents depends on which one is
+currently more useful, measured by its share of non-dominated solutions.
+
+## Weight vectors and subregions
+
+C-TAEA spreads N weight vectors over the unit simplex with Das and Dennis'
+lattice [2] (lesson [A1](many-objective.md)), as MOEA/D [3]
+does. A solution belongs to the subregion of the vector closest to it in angle,
+and inside a subregion solutions are compared by a Tchebycheff function with
+the subregion's own vector:
+
+subregion(x) = argmax_k cos( f(x), wᵏ ) (the largest cosine similarity)
+g(x | w, z) = max_i | f_i(x) − z_i | / w_i (z: the ideal point of the set compared)
+
+VAMOS takes the requested population size as the requested number of vectors:
+the lattice with the most divisions that gives at most that many, with an inner
+layer when it has fewer divisions than objectives, and every component raised
+to at least 10⁻⁶ so that g never divides by zero. Their number is the size of
+both archives and of each generation: 100 requested vectors give 100 for two
+objectives and 91 for three.
+
+## The convergence archive
+
+The candidates of the CA update are the CA and the new offspring, 2N
+solutions. The update has three cases, decided by the number of feasible
+candidates:
+
+exactly N feasible: they are the new CA
+more than N: add the fronts of the feasible candidates (non-dominated sorting) until ≥ N,
+ then, while more than N:
+ normalize with the ideal and nadir points of the selection,
+ take the most crowded subregion,
+ among its members at the smallest distance from another one,
+ remove the one with the largest Tchebycheff value
+fewer than N: keep every feasible candidate, then rank the infeasible ones by
+ non-dominated sorting on ( CV, Tchebycheff value ),
+ add fronts until ≥ N and drop the largest violations of the last front
+
+The second case is where C-TAEA differs most from NSGA-II. Removal is driven by
+crowding in subregions, not by rank: a dominated solution alone in its
+subregion can survive, and a non-dominated solution in a crowded subregion can
+go. The CA may therefore hold dominated solutions. In the third case the
+infeasible candidates compete on two criteria at once, their violation and
+their convergence in their subregion, so a slightly more violated solution that
+is much closer to the front can enter the CA.
+
+## The diversity archive
+
+The candidates of the DA update are the DA and the offspring, and the
+constraints play no part. The update counts the members of the **new** CA in
+each subregion and fills the subregions where the CA is thin first:
+
+c_k = number of CA members in subregion k
+for itr = 1, 2, 3, ...:
+ for each subregion k in order:
+ add up to itr − c_k candidates of k, one at a time, each time the one that is
+ non-dominated among the remaining candidates of k and has the smallest Tchebycheff value
+stop when the DA has N members or no candidate is left
+
+In the first iteration, every subregion without a CA member receives one
+candidate; in the second, every subregion with fewer than two CA members
+receives up to 2 − c_k more, and so on. The picks of earlier iterations do not
+reduce the quota, so a subregion that the CA leaves empty receives one
+candidate in the first iteration and up to two more in the second, if it has
+them. Because feasibility is ignored, the DA collects the best
+solutions of the neglected subregions even when they are infeasible, much as
+population 2 of CCMO does along the whole front.
+
+## Restricted mating selection
+
+Each offspring has two parents, and each parent is chosen from one archive:
+
+ρ_c, ρ_d = numbers of non-dominated solutions of CA ∪ DA that lie in the CA, in the DA, divided by |CA ∪ DA|
+first parent: from the CA if ρ_c > ρ_d, otherwise from the DA (the same for the whole generation)
+second parent: from the CA with probability P_C = share of non-dominated solutions in the CA alone,
+ otherwise from the DA
+
+While the CA is behind (few of its solutions are non-dominated when compared
+with the DA), mating draws on the DA; as the CA catches up, it supplies more
+parents. Within an archive each parent wins a binary tournament: a feasible
+solution beats an infeasible one; of two feasible ones, the first wins unless
+the second dominates it; of two infeasible ones, a third solution drawn at
+random wins. The offspring is the first child of SBX [4], mutated: one
+offspring per weight vector and generation.
+
+## Try it: the two updates on the same candidates
+
+The figure shows the 16 CTP2 candidates of lesson [A6](ccmo.md#try-it-one-set-of-candidates-two-rules),
+with N = 8 weight vectors drawn as rays from the origin. In a run, the CA update
+receives the CA and the offspring, and the DA update the DA and the offspring;
+here both receive the same 16 candidates, so that only the rules differ. Start
+with the CA update, then switch to the DA update and compare the subregions
+each archive covers.
+
+
+
+Nine candidates are feasible, one more than the CA holds, so the second case
+applies. The first two fronts of the feasible candidates hold all nine; after
+normalization, subregions 2 and 4 hold two each, and the first, subregion 2,
+loses O2, whose Tchebycheff value (0.379) is worse than that of P3 (0.070). P2
+and P6, both dominated, stay because their subregions are not crowded. The DA
+then starts where the CA has nothing: subregion 6 receives O7 in the first
+iteration; subregions 2, 4 and 6 receive O3, O5 and P8 in the second; and the
+third iteration adds O1, P3, P4 and O4. Six of its eight members are infeasible.
+
+## In VAMOS
+
+C-TAEA on CTP2 [5] with 50 requested weight vectors and 10,000 evaluations.
+The script counts, for each archive, the feasible members and the subregions
+they occupy, using the weight vectors that the result stores:
+
+```python
+import numpy as np
+
+from vamos import optimize
+from vamos.algorithms import CTAEAConfig
+from vamos.problems import CTP
+
+problem = CTP(2)
+config = CTAEAConfig.default(pop_size=50, n_var=problem.n_var)
+result = optimize(problem, algorithm="ctaea", algorithm_config=config, max_evaluations=10_000, engine="numpy", seed=1)
+W = result.data["weights"]
+print("weight vectors:", W.shape)
+print("non-dominated feasible solutions of the CA:", result.F.shape[0])
+for name in ("population", "diversity_archive"):
+ F, G = result.data[name]["F"], result.data[name]["G"]
+ feasible = int(np.all(G <= 0.0, axis=1).sum())
+ cosine = (F @ W.T) / np.outer(np.linalg.norm(F, axis=1), np.linalg.norm(W, axis=1))
+ occupied = len(np.unique(np.argmax(cosine, axis=1)))
+ print(f"{name}: {feasible} of {len(F)} feasible, {occupied} subregions, mean f1 + f2 = {F.sum(axis=1).mean():.3f}")
+```
+
+Output:
+
+```text
+weight vectors: (50, 2)
+non-dominated feasible solutions of the CA: 25
+population: 50 of 50 feasible, 11 subregions, mean f1 + f2 = 1.801
+diversity_archive: 3 of 50 feasible, 34 subregions, mean f1 + f2 = 1.054
+```
+
+`result.data["population"]` is the whole CA, the result of PlatEMO's
+implementation and of jMetal; `result.F` keeps its feasible non-dominated
+members, here 25 of 50: the CA holds dominated solutions, as described above.
+On CTP2 the sum f₁ + f₂ is the distance function g(x), equal to 1 on the
+unconstrained front. After this short run the CA is feasible but concentrated
+in 11 subregions, while the DA, almost entirely infeasible, lies close to the
+unconstrained front and covers 34.
+
+The truncation of the second case and the dispatch between the three cases:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/ctaea/archives.py
+def worst_of_the_most_crowded_subregion(F: NDArray[Any], weights: NDArray[Any]) -> int:
+ objectives = np.asarray(F, dtype=float)
+ W = np.asarray(weights, dtype=float)
+ regions = associate(_normalized(objectives), W)
+ most_crowded = int(np.argmax(np.bincount(regions, minlength=W.shape[0])))
+ crowded = np.flatnonzero(regions == most_crowded)
+ closest = crowded[_closest_rows(objectives[crowded])]
+ return int(closest[int(np.argmax(tchebycheff_in_own_subregion(objectives[closest], W)))])
+
+
+def _select_among_feasible(F: FloatArray, feasible: IndexArray, weights: FloatArray) -> list[int]:
+ size = weights.shape[0]
+ selected: list[int] = []
+ _add_fronts_until_full(feasible, front_ranks(F[feasible]), selected, size)
+ while len(selected) > size:
+ del selected[worst_of_the_most_crowded_subregion(F[selected], weights)]
+ return selected
+
+
+def convergence_archive_update(F: NDArray[Any], violation: NDArray[Any], weights: NDArray[Any]) -> IndexArray:
+ objectives = np.asarray(F, dtype=float)
+ cv = np.asarray(violation, dtype=float)
+ W = np.asarray(weights, dtype=float)
+ feasible_mask = cv == 0.0
+ feasible = np.flatnonzero(feasible_mask)
+ infeasible = np.flatnonzero(~feasible_mask)
+ size = W.shape[0]
+ if feasible.size == size:
+ return np.asarray(feasible, dtype=int)
+ if feasible.size > size:
+ return np.asarray(_select_among_feasible(objectives, feasible, W), dtype=int)
+ return np.asarray(_complete_with_infeasible(objectives, cv, feasible, infeasible, W), dtype=int)
+```
+
+`np.argmax` of the subregion counts returns the first subregion on a tie, as in
+the figure. `_closest_rows` lists the members at the smallest non-zero distance
+from another member (distances on the raw objectives), and
+`tchebycheff_in_own_subregion` evaluates each of them with the vector of its own
+subregion and the ideal point of those members. One solution is removed per
+pass, so the counts are recomputed after every removal.
+
+The DA update follows the loop of the previous section:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/ctaea/archives.py
+def diversity_archive_update(convergence_F: NDArray[Any], F: NDArray[Any], weights: NDArray[Any]) -> IndexArray:
+ objectives = np.asarray(F, dtype=float)
+ W = np.asarray(weights, dtype=float)
+ size = W.shape[0]
+ regions = associate(objectives, W)
+ in_convergence_archive = np.bincount(associate(np.asarray(convergence_F, dtype=float), W), minlength=size)
+ left = np.bincount(regions, minlength=size)
+ available = np.ones(objectives.shape[0], dtype=bool)
+ remaining = int(objectives.shape[0])
+ selected: list[int] = []
+ iteration = 1
+ while len(selected) < size and remaining:
+ for region in range(size):
+ if len(selected) >= size:
+ break
+ for _ in range(iteration - int(in_convergence_archive[region])):
+ if not left[region]:
+ break
+ best = _best_of_the_subregion(objectives, np.flatnonzero(available & (regions == region)), W)
+ available[best] = False
+ left[region] -= 1
+ remaining -= 1
+ if len(selected) < size:
+ selected.append(best)
+ iteration += 1
+ return np.asarray(selected, dtype=int)
+```
+
+`range(iteration - in_convergence_archive[region])` is the number of
+candidates a subregion may still receive in this iteration: none when the CA
+already has `iteration` members there. The function receives no violation at
+all; `_best_of_the_subregion` takes the non-dominated candidates of the
+subregion and returns the one with the smallest Tchebycheff value.
+
+Mating, in the algorithm class:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/ctaea/ctaea.py
+ def _offspring(self) -> np.ndarray[Any, Any]:
+ st = self._st
+ n = st.offspring_size
+ proportions = mating_proportions(st.F, st.diversity_F)
+ feasible = _violation(st.G, st.F.shape[0]) == 0.0
+ diversity_feasible = _violation(st.diversity_G, st.diversity_F.shape[0]) == 0.0
+ if proportions.first_parent_from_convergence_archive:
+ first = st.X[ctaea_tournament(st.F, feasible, n, st.rng)]
+ else:
+ first = st.diversity_X[ctaea_tournament(st.diversity_F, diversity_feasible, n, st.rng)]
+ from_convergence = st.rng.random(n) < proportions.non_dominated_share_of_convergence_archive
+ in_convergence = st.X[ctaea_tournament(st.F, feasible, n, st.rng)]
+ in_diversity = st.diversity_X[ctaea_tournament(st.diversity_F, diversity_feasible, n, st.rng)]
+ second = np.where(from_convergence[:, None], in_convergence, in_diversity)
+ parents = np.stack([second, first], axis=1).reshape(2 * n, st.X.shape[1])
+ children = st.variation.recombine(parents, st.rng)
+ first_children = np.ascontiguousarray(children[:: st.variation.children_per_group])
+ return st.variation.mutate(first_children, st.rng)
+```
+
+The archive of the first parent is chosen once for the whole generation; the
+archive of each second parent by its own random draw. Tournament winners are
+drawn from both archives for every offspring, and `np.where` keeps the one the
+draw asks for. The pairs are stacked as (second, first), which the next section
+explains.
+
+## Where VAMOS differs from the paper
+
+VAMOS follows jMetal's port, which follows PlatEMO's implementation where it
+differs from the paper; the [C-TAEA lesson](../../algorithms/ctaea.md#where-vamos-departs-from-jmetals-port)
+lists the checks against jMetal's classes. Relative to the paper:
+
+- the second parent comes from the CA with the share of non-dominated
+ solutions of the CA alone, P_C, not with the share that chooses the first
+ parent's archive;
+- solutions are associated with subregions on their raw objectives, except in
+ the truncation of the CA's feasible solutions, while the paper normalizes
+ before every association;
+- the ideal point of each Tchebycheff function is that of the set it is
+ applied to;
+- ties go to the solution that comes first instead of a random one, and a
+ tournament between two infeasible solutions picks a third one at random,
+ which gives the winner the same distribution.
+
+Relative to jMetal's port:
+
+- **Budget:** exact; the last generation evaluates only the first offspring,
+ in the order of the weight vectors, while jMetal can exceed the budget by up
+ to N − 1 evaluations.
+- **Parent order:** jMetal's SBX gives a variable that it does not cross to the
+ other child, and VAMOS's leaves it with its own parent, so VAMOS passes the
+ second parent first; the kept child then has jMetal's distribution.
+- **Result:** jMetal returns the whole CA, which is `result.data["population"]`;
+ `result.X` and `result.F` follow the configured `result_mode`.
+
+The [C-TAEA lesson](../../algorithms/ctaea.md#agreement-with-jmetals-port-and-the-published-results)
+records the agreement with jMetal and with the published results.
+
+## C-TAEA and CCMO
+
+| | CCMO (lesson A6) | C-TAEA |
+| --- | --- | --- |
+| Structure | Two populations, each breeding its own offspring | Two archives, one stream of offspring |
+| Constraint-free part | Population 2, over the whole front | DA, only where the CA is thin |
+| Diversity | SPEA2 density and truncation | Subregions of N weight vectors |
+| Who breeds | Each population from itself | Parents from the CA or the DA, by non-dominated shares |
+| Result | Population 1 | The CA |
+
+Strengths:
+
+- **Targeted exploration.** The DA spends its places in the subregions that
+ the CA neglects, not along the whole unconstrained front.
+- **Adaptive mating.** The share of non-dominated solutions decides which
+ archive breeds, without a schedule or a threshold.
+- **Two criteria for infeasible solutions.** While the CA has too few feasible
+ solutions, violation and convergence decide together which infeasible ones
+ enter it.
+
+Limits:
+
+- **Weight vectors fix the archive size and assume a front that they cover
+ well.** The number of solutions follows the lattice (91 for 100 requested
+ with three objectives), and, as for MOEA/D, a front whose shape does not match
+ the vectors leaves subregions empty.
+- **The CA can hold dominated solutions,** as the example shows; the result
+ needs the non-dominated filter that `result.F` applies.
+- **Cost.** The updates work subregion by subregion and solution by solution;
+ in VAMOS a C-TAEA generation is slower than one of NSGA-II or CCMO with the
+ same number of evaluations.
+
+## Key points
+
+- C-TAEA keeps a convergence archive and a diversity archive of N solutions,
+ one per weight vector, and updates both with the same offspring.
+- The CA keeps feasible solutions; with too many, it removes the worst
+ Tchebycheff solution of the most crowded subregion, whatever its rank; with
+ too few, it ranks the infeasible ones on violation and Tchebycheff value.
+- The DA ignores the constraints and fills the subregions with the fewest CA
+ members first.
+- The first parent's archive is the one with the larger share of non-dominated
+ solutions of CA ∪ DA; the second parent comes from the CA with probability
+ equal to the CA's own non-dominated share.
+- VAMOS follows PlatEMO's implementation through jMetal's port, with an exact
+ budget.
+
+**Next:** [A8. ToP: two phases](top.md).
+
+## References
+
+[1] Li, K., Chen, R., Fu, G., and Yao, X. (2019). [Two-archive evolutionary algorithm for constrained multiobjective optimization](https://doi.org/10.1109/TEVC.2018.2855411). *IEEE Transactions on Evolutionary Computation*, 23(2), 303–315.
+
+[2] Das, I., and Dennis, J. E. (1998). [Normal-boundary intersection: A new method for generating the Pareto surface in nonlinear multicriteria optimization problems](https://doi.org/10.1137/S1052623496307510). *SIAM Journal on Optimization*, 8(3), 631–657.
+
+[3] Zhang, Q., and Li, H. (2007). [MOEA/D: A multiobjective evolutionary algorithm based on decomposition](https://doi.org/10.1109/TEVC.2007.892759). *IEEE Transactions on Evolutionary Computation*, 11(6), 712–731.
+
+[4] Deb, K., and Agrawal, R. B. (1995). Simulated binary crossover for continuous search space. *Complex Systems*, 9(2), 115–148.
+
+[5] Deb, K., Pratap, A., and Meyarivan, T. (2001). [Constrained test problems for multi-objective evolutionary optimization](https://doi.org/10.1007/3-540-44719-9_20). *Evolutionary Multi-Criterion Optimization – EMO 2001*, Lecture Notes in Computer Science 1993, 284–298.
diff --git a/docs/foundations/advanced/many-objective.md b/docs/foundations/advanced/many-objective.md
new file mode 100644
index 000000000..0ef8eef50
--- /dev/null
+++ b/docs/foundations/advanced/many-objective.md
@@ -0,0 +1,199 @@
+---
+description: 'A1. Many-objective optimization: why Pareto dominance and crowding lose power with four or more objectives, the remedies, and NSGA-III reference directions in detail, with interactive figures and VAMOS code.'
+search:
+ boost: 0.5
+---
+
+# A1. Many-objective optimization
+
+The algorithms of the Intermediate level were designed, and are mostly tested,
+with two or three objectives. Real problems often have more: a car design is
+judged on cost, mass, emissions, safety and comfort at once. With four or more
+objectives, the problem is called *many-objective*, and several mechanisms that
+NSGA-II relies on stop working [1, 2, 3].
+
+In this lesson you will learn:
+
+- why Pareto dominance loses its selective power as objectives are added;
+- the other difficulties: diversity, visualization, indicators, population size;
+- the families of remedies;
+- how NSGA-III replaces crowding with reference directions, and how VAMOS
+ configures it.
+
+## Dominance resistance
+
+Two random vectors are comparable only if one is better in **every**
+objective. With m objectives that chance shrinks quickly, so most pairs become
+incomparable, and most solutions end up in the first front. The figure samples
+random points uniformly in the unit hypercube and measures the share that is
+non-dominated:
+
+
+
+When the whole population is in front 1, rank no longer pushes it towards the
+Pareto front; selection is decided by the secondary criterion, crowding
+distance, which rewards spread, not convergence. Purshouse and Fleming [2]
+analysed this loss of selection pressure, and Ishibuchi, Tsukamoto and Nojima
+[1] showed its effect on NSGA-II and SPEA2.
+
+## Other difficulties
+
+- **Diversity estimates degrade.** The crowding distance sums per-objective
+ gaps, and in high dimension nearly every solution is extreme in some
+ objective. Distances also concentrate: all points look equally far apart.
+- **The front grows.** The front of an m-objective problem is an
+ (m − 1)-dimensional surface. Covering it with the same density needs a
+ population that grows exponentially with m.
+- **Recombination becomes less effective.** Parents that are both
+ non-dominated can be far apart in decision space, and their children land
+ far from either.
+- **Indicators get expensive or unreliable.** Exact hypervolume grows
+ exponentially with m (lesson [B4](../basic/quality-indicators.md#hypervolume)),
+ and reference sets for IGD+ need many points to represent the front.
+- **People cannot see the front.** Beyond three objectives, scatter plots give
+ way to parallel coordinates, heat maps or projections, each of which hides
+ something.
+
+## Families of remedies
+
+Li et al. [3] survey the many-objective algorithms. The main ideas are:
+
+- **Relaxed dominance**, which lets more pairs be compared, for example
+ ε-dominance [4].
+- **Decomposition and reference directions**: spread a set of directions over
+ the objective space and maintain one solution per direction, as MOEA/D
+ [5], NSGA-III [6] and RVEA [7] do. Diversity then comes from the directions,
+ not from distances between solutions.
+- **Indicator-based selection** with fast or approximate hypervolume, such as
+ HypE [8].
+- **Adaptive geometry**: AGE-MOEA [9] estimates the shape of the front from the
+ population and measures diversity accordingly.
+
+## NSGA-III in detail
+
+NSGA-III [6] keeps NSGA-II's structure (merge, non-dominated sort, fill whole
+fronts) and changes only the way the last front is truncated. Crowding distance
+is replaced by **niching around reference directions**, in four steps.
+Lesson [A2](nsga-iii.md) follows each of them into the VAMOS code.
+
+**1. Reference points.** Before the run, place H points on the unit simplex
+(w₁ + … + w_m = 1, w_i ≥ 0) with Das and Dennis' systematic method [10]:
+every point whose coordinates are multiples of 1/p, for p *divisions*. Their
+number is
+
+H = C(p + m − 1, m − 1)
+
+Each point defines a reference direction from the origin. Change m and p
+below:
+
+
+
+H grows fast: with m = 10 and p = 3, H = 220 directions, but they all lie on
+the boundary of the simplex. For eight or more objectives Deb and Jain combine
+two layers with few divisions, an outer one and an inner one scaled towards
+the centre [6].
+
+**2. Adaptive normalization.** The population's objectives are translated so
+that the ideal point is the origin, and scaled by the intercepts of the
+hyperplane through the extreme points of the population. Fronts with very
+different scales per objective then map onto the simplex.
+
+**3. Association.** Each normalized solution is associated with the reference
+direction to which it has the smallest perpendicular distance.
+
+**4. Niche preservation.** Count, for each direction, the solutions already
+selected from the earlier fronts. Repeatedly pick the direction with the fewest
+associated solutions and add a member of the last front associated with it
+(the closest one if the niche is empty, a random one otherwise), until the
+population is full.
+
+The population size must be at least H, so that every direction can keep a
+solution. VAMOS checks this before the run: a population smaller than the
+number of directions stops with an error that asks for a larger population or
+fewer divisions, instead of silently dropping directions.
+
+## In VAMOS
+
+NSGA-III on DTLZ2 [11] with three objectives and p = 12, so H = 91 and a
+population of 91. DTLZ2's front is the part of the unit sphere in the positive
+orthant, so the distance of each point to the origin should approach 1:
+
+```python
+from math import comb
+
+import numpy as np
+
+from vamos import optimize
+from vamos.algorithms import NSGAIIIConfig
+from vamos.problems import DTLZ2
+
+problem = DTLZ2(n_var=12, n_obj=3)
+divisions = 12
+pop_size = comb(divisions + problem.n_obj - 1, problem.n_obj - 1)
+config = (
+ NSGAIIIConfig.builder()
+ .pop_size(pop_size)
+ .crossover("sbx", prob=1.0, eta=30.0)
+ .mutation("pm", prob="1/n", eta=20.0)
+ .selection("random")
+ .reference_directions(divisions=divisions)
+ .result_mode("population")
+ .build()
+)
+result = optimize(problem, algorithm="nsgaiii", algorithm_config=config, max_evaluations=10_000, engine="numpy", seed=42)
+
+radius = np.linalg.norm(result.F, axis=1)
+print("reference directions:", pop_size)
+print("returned:", result.F.shape)
+print("distance to the origin: median", round(float(np.median(radius)), 3), "max", round(float(radius.max()), 3))
+```
+
+Output:
+
+```text
+reference directions: 91
+returned: (91, 3)
+distance to the origin: median 1.003 max 1.029
+```
+
+The [NSGA-III lesson](../../algorithms/nsgaiii.md) draws this result and
+discusses the configuration. The [problem reference](../../reference/problems.md)
+lists the scalable families (DTLZ and others) for experiments with more
+objectives.
+
+## Key points
+
+- With many objectives most solutions are mutually non-dominated, so rank stops
+ driving convergence and distance-based diversity degrades.
+- Covering a higher-dimensional front needs larger populations, and indicators
+ become harder to compute and interpret.
+- Reference-direction methods restore diversity by keeping one solution per
+ direction; NSGA-III does this inside NSGA-II's structure.
+- For H = C(p + m − 1, m − 1) directions the population must hold at least H
+ solutions.
+
+**Next:** [A2. NSGA-III](nsga-iii.md).
+
+## References
+
+[1] Ishibuchi, H., Tsukamoto, N., and Nojima, Y. (2008). [Evolutionary many-objective optimization: A short review](https://doi.org/10.1109/CEC.2008.4631121). *Proceedings of the 2008 IEEE Congress on Evolutionary Computation*, 2419–2426.
+
+[2] Purshouse, R. C., and Fleming, P. J. (2007). [On the evolutionary optimization of many conflicting objectives](https://doi.org/10.1109/TEVC.2007.910138). *IEEE Transactions on Evolutionary Computation*, 11(6), 770–784.
+
+[3] Li, B., Li, J., Tang, K., and Yao, X. (2015). [Many-objective evolutionary algorithms: A survey](https://doi.org/10.1145/2792984). *ACM Computing Surveys*, 48(1), Article 13.
+
+[4] Laumanns, M., Thiele, L., Deb, K., and Zitzler, E. (2002). [Combining convergence and diversity in evolutionary multiobjective optimization](https://doi.org/10.1162/106365602760234108). *Evolutionary Computation*, 10(3), 263–282.
+
+[5] Zhang, Q., and Li, H. (2007). [MOEA/D: A multiobjective evolutionary algorithm based on decomposition](https://doi.org/10.1109/TEVC.2007.892759). *IEEE Transactions on Evolutionary Computation*, 11(6), 712–731.
+
+[6] Deb, K., and Jain, H. (2014). [An evolutionary many-objective optimization algorithm using reference-point-based nondominated sorting approach, Part I: Solving problems with box constraints](https://doi.org/10.1109/TEVC.2013.2281535). *IEEE Transactions on Evolutionary Computation*, 18(4), 577–601.
+
+[7] Cheng, R., Jin, Y., Olhofer, M., and Sendhoff, B. (2016). [A reference vector guided evolutionary algorithm for many-objective optimization](https://doi.org/10.1109/TEVC.2016.2519378). *IEEE Transactions on Evolutionary Computation*, 20(5), 773–791.
+
+[8] Bader, J., and Zitzler, E. (2011). [HypE: An algorithm for fast hypervolume-based many-objective optimization](https://doi.org/10.1162/EVCO_a_00009). *Evolutionary Computation*, 19(1), 45–76.
+
+[9] Panichella, A. (2019). [An adaptive evolutionary algorithm based on non-Euclidean geometry for many-objective optimization](https://doi.org/10.1145/3321707.3321839). *Proceedings of the Genetic and Evolutionary Computation Conference (GECCO '19)*, 595–603.
+
+[10] Das, I., and Dennis, J. E. (1998). [Normal-boundary intersection: A new method for generating the Pareto surface in nonlinear multicriteria optimization problems](https://doi.org/10.1137/S1052623496307510). *SIAM Journal on Optimization*, 8(3), 631–657.
+
+[11] Deb, K., Thiele, L., Laumanns, M., and Zitzler, E. (2005). [Scalable test problems for evolutionary multiobjective optimization](https://doi.org/10.1007/1-84628-137-7_6). In A. Abraham, L. Jain and R. Goldberg (Eds.), *Evolutionary Multiobjective Optimization*, 105–145. Springer.
diff --git a/docs/foundations/advanced/nsga-iii.md b/docs/foundations/advanced/nsga-iii.md
new file mode 100644
index 000000000..5826110fa
--- /dev/null
+++ b/docs/foundations/advanced/nsga-iii.md
@@ -0,0 +1,473 @@
+---
+description: 'A2. NSGA-III step by step as VAMOS implements it: Das and Dennis reference directions and the population rule, adaptive normalization with extreme points and intercepts, association by perpendicular distance, niche counts and the niche-preservation loop, mating selection and constraints, with an interactive figure and VAMOS code.'
+search:
+ boost: 0.5
+---
+
+# A2. NSGA-III: reference-point niching
+
+Lesson [A1](many-objective.md#nsga-iii-in-detail) introduced NSGA-III [1] as
+NSGA-II with a different rule for the last front: reference directions instead
+of crowding distance. This lesson follows that rule into the VAMOS code, one
+mechanism at a time, and shows where VAMOS makes a choice that the paper
+leaves open.
+
+NSGA-III was proposed by Deb and Jain in 2014 for problems with four or more
+objectives; a companion paper extended it to constraints and to reference
+points that move during the run [2]. Merging parents and offspring,
+non-dominated sorting and filling whole fronts are inherited unchanged from
+NSGA-II (lessons [I2](../intermediate/non-dominated-sorting.md) to
+[I5](../intermediate/elitist-survival.md)). What changes is how the last
+front is cut, and how parents are chosen.
+
+In this lesson you will learn:
+
+- how VAMOS builds the reference directions, and why it refuses a population
+ smaller than their number;
+- how adaptive normalization finds the ideal point, the extreme points and the
+ intercepts, and what happens when the hyperplane is degenerate;
+- how solutions are associated with directions, and how niche counts and the
+ niche-preservation loop fill the last places;
+- how VAMOS chooses parents and treats constraints.
+
+## Why reference points
+
+NSGA-II measures density *between solutions*: the crowding distance sums the
+gaps to the neighbours in each objective (lesson
+[I3](../intermediate/crowding-distance.md)). With many objectives nearly every
+solution is extreme in some objective, and the gaps stop describing how
+crowded a region is. Deb and Jain measure density *against a fixed set of
+directions* supplied before the run [1]. The directions come from
+decomposition: MOEA/D [4] solves one scalar subproblem per weight vector, and
+the systematic design of Das and Dennis [3] spreads the weights evenly.
+NSGA-III keeps the directions but not the scalarization: a direction never
+ranks solutions, it only counts how many survivors it already has.
+
+## Reference directions
+
+A Das and Dennis lattice with p *divisions* contains every point of the unit
+simplex whose m coordinates are multiples of 1/p. Each point w defines a ray
+from the origin, a reference direction:
+
+w = (k₁, …, k_m) / p, k_i ∈ {0, 1, …, p}, k₁ + … + k_m = p
+H = C(p + m − 1, m − 1) (number of directions)
+
+| m | p | H |
+| --- | --- | --- |
+| 2 | 99 | 100 |
+| 3 | 12 | 91 |
+| 5 | 6 | 210 |
+| 8 | 3 | 120 |
+
+VAMOS generates the complete lattice and never truncates it. The builder
+method `reference_directions(divisions=p)` fixes p; without it, VAMOS takes the
+largest complete lattice that fits in the population. `NSGAIIIConfig.default`
+uses p = 99 for two objectives, 12 for three and 6 for four or more, with
+N = H.
+
+With eight or more objectives a single lattice either has too many directions
+or puts them all on the boundary of the simplex. Deb and Jain then combine two
+layers: an outer lattice with p₁ divisions and an inner one with p₂ divisions
+shrunk towards the centre, for example 120 + 36 = 156 directions for m = 8
+with p₁ = 3 and p₂ = 2 [1]. **VAMOS 1.5.0:**
+`reference_directions(divisions=p₁, inner_divisions=p₂)` generates that
+two-layer set, the inner lattice shrunk by half towards the centre,
+w/2 + 1/(2m), as pymoo does; VAMOS 1.4.0 generated one layer only. Any other
+set can be read from a file with `reference_directions(path=...)`: rows that
+are non-negative, sum to one and have one column per objective, separated by
+commas or, since the same development, by whitespace, as in jMetal's weight
+files.
+
+### The population rule
+
+Every direction must be able to keep a survivor, so the population must hold
+at least one solution per direction:
+
+N ≥ H
+
+Deb and Jain used the smallest multiple of four that is at least H, for
+example N = 92 for H = 91 [1]. VAMOS accepts any N ≥ H and checks the rule
+before the first evaluation. A smaller population stops with a `ValueError`
+that names H and asks for a larger population or fewer directions; VAMOS
+neither enlarges the population nor drops directions.
+
+## Adaptive normalization
+
+The directions live on the unit simplex, but objectives can have any scale.
+Before associating solutions with directions, NSGA-III maps the merged
+population onto a space where the front's corners lie on the unit axes:
+
+z*_i = min f_i over the solutions evaluated so far (ideal point)
+f′_i(x) = f_i(x) − z*_i (translation)
+ASF(x, wʲ) = max_i f′_i(x) / wʲ_i, wʲ_i = 1 if i = j, 10⁻⁶ otherwise
+zʲ = the solution that minimizes ASF(·, wʲ) (extreme point of axis j)
+a₁, …, a_m = intercepts of the hyperplane through z¹, …, z^m
+fⁿ_i(x) = f′_i(x) / a_i (normalized objectives)
+
+The achievement scalarizing function (ASF) of Wierzbicki [6] with a weight of
+10⁻⁶ on every other objective is minimized by the solution that is smallest in
+all the other objectives, the corner of the front on axis j. The m extreme
+points span a hyperplane, and its intercepts with the axes estimate how far
+the front extends in each objective: the nadir point is estimated as z* + a.
+Dividing by the intercepts maps the extreme points onto the unit axes.
+
+VAMOS makes these choices:
+
+- The ideal point is the smallest value of each objective seen during the
+ whole run, not only in the current population.
+- Translated values below 10⁻³ are set to 0 before the ASF, and the extreme
+ points are searched among the first front **and** the previous generation's
+ extreme points, so a good corner is not lost when it leaves the population.
+- The hyperplane is rejected when its linear system is singular or not
+ satisfied, when an intercept is not above 10⁻⁶, or when the estimated nadir
+ exceeds, in some objective, the worst value seen so far. VAMOS then uses the
+ worst point of the first front for every objective. An objective whose range
+ is still not above 10⁻⁶ takes the worst value of the merged population.
+
+The paper does not fix the fallback, and libraries differ: pymoo 0.6 replaces
+only the objectives whose intercept is out of range. The
+[NSGA-III lesson](../../algorithms/nsgaiii.md#variants-and-their-effect)
+records the difference.
+
+## Association by perpendicular distance
+
+Each normalized solution is attached to the direction whose ray passes
+closest to it:
+
+d⊥(x, w) = ‖ fⁿ(x) − ( wᵀfⁿ(x) / ‖w‖² ) · w ‖ = ‖fⁿ(x)‖ · sin θ(x, w)
+π(x) = argmin_w d⊥(x, w) (the direction of x)
+
+For one solution ‖fⁿ(x)‖ is fixed, so the closest ray is also the one at the
+smallest angle θ. VAMOS uses that: it takes the direction with the largest
+cosine and computes the distance as ‖fⁿ‖·√(1 − cos²θ). The distance d⊥ is a
+second, local measure of quality: a solution close to its ray represents its
+direction well.
+
+## Niche counts and niche preservation
+
+Let F_l be the last front, the first one that does not fit. The niche count
+ρⱼ of direction j counts the solutions of the earlier fronts, all of which
+survive, associated with it. The free places are then filled from F_l:
+
+ρⱼ ← number of solutions of F₁ ∪ … ∪ F_(l−1) associated with wⱼ
+while fewer than N solutions are selected:
+ J ← the directions with at least one unselected member of F_l
+ J_min ← the directions of J with the smallest ρⱼ, in random order
+ for each j in J_min, while places are left:
+ if ρⱼ = 0: add the member of F_l on wⱼ with the smallest d⊥
+ else: add a random member of F_l on wⱼ
+ ρⱼ ← ρⱼ + 1
+
+The least crowded direction is served first. An empty direction receives its
+best representative, the closest candidate; a direction that already has
+survivors receives a random one, because closeness to the ray no longer
+matters once the direction is represented. A direction without candidates in
+F_l is ignored for the rest of the generation, so it can stay empty.
+
+Deb and Jain serve one direction at a time and break ties between directions at
+random [1]. VAMOS, like pymoo, serves all the tied directions of J_min in one
+shuffled round. The outcome has the same distribution: once a direction has
+been served its count exceeds that of the others in the tie, so the
+one-at-a-time rule would choose among the remaining ones anyway.
+
+## Step through the niche loop
+
+The figure shows one generation with two objectives, already normalized (the
+ideal point is the origin and both intercepts are 1), six directions
+(p = 5) and N = 9. Front 1 fits whole and fills five places; front 2 is the
+last front and has four; front 3 is never examined. Press **Step**: round 1
+serves the two empty directions w2 and w5 with their closest candidates, G
+and K. Round 2 serves w2 and w3, now at count 1, with random candidates: press
+**Reshuffle** to see the other choice on w3. Notice F, almost on ray w1 but
+never chosen, because w1 already holds two solutions; set N = 10 to let it
+compete. With N = 6 a single place is disputed by two empty directions.
+
+
+
+## Mating selection and constraints
+
+**Parents.** Deb and Jain choose parents at random, since niching already
+keeps the population diverse [1]; their constrained version runs a binary
+tournament on constraint violation [2]. VAMOS offers two selections, and
+neither uses the crowding distance, which is not part of NSGA-III:
+
+- `selection("random")`, the default, draws the parents at random, as Deb and
+ Jain do. With constraints, each parent is the winner of a binary tournament
+ on violation: a feasible solution beats an infeasible one, the smaller
+ violation wins, and a tie, such as two feasible solutions, is drawn at
+ random [2]. pymoo's NSGA-III does the same.
+- `selection("tournament", size=k)` is jMetal's NSGA-III tournament: k
+ distinct solutions (2 by default) are drawn at random and the one with the
+ lowest non-dominated rank wins, with ties drawn at random.
+
+**VAMOS 1.5.0:** VAMOS 1.4.0 and earlier chose NSGA-III's parents
+by NSGA-II's tournament on rank and crowding distance
+(lesson [I3](../intermediate/crowding-distance.md)), whatever the configured
+selection, so the same seed gives other results than with VAMOS 1.4.0.
+
+**Constraints.** With constraint values, VAMOS puts feasible solutions first,
+following Jain and Deb [2]. When at most N merged solutions are feasible, all
+of them survive and the least violated infeasible ones fill the remaining
+places, with no niching. Otherwise the infeasible ones are discarded and
+sorting, normalization and niching run on the feasible solutions only. The
+rank-based tournament ranks every infeasible solution after the feasible ones
+and compares two infeasible solutions by violation. Since VAMOS 1.2.0,
+`constraint_handling` replaces this rule by another technique, whose fronts
+take the place of the non-dominated ones in the survival and in the
+rank-based tournament, while the random selection then ignores constraints (lesson
+[A5](constrained.md) and the
+[constraint reference](../../reference/constraints.md#choose-a-constraint-handling-technique)).
+
+## In VAMOS
+
+WFG4 [7] has a concave front with very different scales,
+(f₁/2)² + (f₂/4)² + (f₃/6)² = 1. The example first asks for a population
+smaller than H, then runs NSGA-III with N = H = 91 and counts how many of the
+91 directions are the nearest direction of at least one returned solution,
+once on objectives normalized by their range and once on the raw objectives:
+
+```python
+import numpy as np
+
+from vamos import optimize
+from vamos.algorithms import NSGAIIIConfig
+from vamos.problems import WFG4
+
+problem = WFG4(n_var=12, n_obj=3) # front: (f₁/2)² + (f₂/4)² + (f₃/6)² = 1
+
+
+def config(pop_size):
+ return (
+ NSGAIIIConfig.builder()
+ .pop_size(pop_size)
+ .crossover("sbx", prob=1.0, eta=30.0)
+ .mutation("pm", prob="1/n", eta=20.0)
+ .selection("random")
+ .reference_directions(divisions=12) # H = C(14, 2) = 91 directions
+ .result_mode("population")
+ .build()
+ )
+
+
+try:
+ optimize(problem, algorithm="nsgaiii", algorithm_config=config(80), max_evaluations=20_000, engine="numpy", seed=1)
+except ValueError as error:
+ print(error)
+
+result = optimize(problem, algorithm="nsgaiii", algorithm_config=config(91), max_evaluations=20_000, engine="numpy", seed=1)
+F = result.F
+
+W = np.array([(i, j, 12 - i - j) for i in range(13) for j in range(13 - i)], dtype=float)
+W /= np.linalg.norm(W, axis=1, keepdims=True) # the 91 directions as unit vectors
+
+
+def occupied(Z):
+ """Number of directions that are the nearest direction of at least one point."""
+ cosine = (Z / np.linalg.norm(Z, axis=1, keepdims=True)) @ W.T
+ return np.unique(np.argmax(cosine, axis=1)).size
+
+
+ideal, nadir = F.min(axis=0), F.max(axis=0)
+print("objective maxima:", nadir.round(1))
+print("directions with a solution, normalized objectives:", occupied((F - ideal) / (nadir - ideal)), "of 91")
+print("directions with a solution, raw objectives:", occupied(F - ideal), "of 91")
+```
+
+Output:
+
+```text
+NSGA-III reference directions for divisions=12 (91) need pop_size >= 91 (pop_size=80). Increase pop_size or choose fewer reference directions.
+objective maxima: [2. 4. 6.]
+directions with a solution, normalized objectives: 91 of 91
+directions with a solution, raw objectives: 65 of 91
+```
+
+In normalized space every direction holds a solution. On the raw objectives
+more than a quarter of the directions look empty, because the front is
+stretched along f₃:
+normalization is what lets one set of directions serve objectives of different
+scales.
+
+The population rule is checked from the binomial count, before any lattice is
+built:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/nsgaiii/initialization.py
+ elif ref_divisions is not None:
+ lattice = f"divisions={ref_divisions}" if ref_inner is None else f"divisions={ref_divisions} and inner_divisions={ref_inner}"
+ source = f"NSGA-III reference directions for {lattice}"
+ if n_obj >= 2:
+ # Reject from the binomial count: an oversized lattice can need gigabytes.
+ n_directions = (
+ lattice_size(n_obj, int(ref_divisions)) if ref_inner is None else two_layer_size(n_obj, int(ref_divisions), int(ref_inner))
+ )
+ if n_directions > pop_size:
+ raise ValueError(
+ f"{source} ({n_directions}) need pop_size >= {n_directions} (pop_size={pop_size}). "
+ "Increase pop_size or choose fewer reference directions."
+ )
+ ref_dirs = load_or_generate_weight_vectors(
+ pop_size, n_obj, divisions=int(ref_divisions), inner_divisions=None if ref_inner is None else int(ref_inner)
+ )
+ ref_dirs_norm = ref_dirs / np.linalg.norm(ref_dirs, axis=1, keepdims=True)
+```
+
+The last line turns each lattice point into a unit vector, which the
+association below needs.
+
+The extreme points and the nadir estimate come from two helpers. In
+`get_extreme_points`, `base` stacks the previous extreme points on top of the
+first front; `asf` is the identity matrix with 10⁶ off the diagonal, so
+row j of `vals` is the ASF of every candidate for axis j, and `argmin` picks
+the extreme point of each axis. In `get_nadir_point`, `np.linalg.solve` finds
+the hyperplane through the translated extreme points; any of the four
+rejection tests raises `LinAlgError`, and the `except` branch falls back to
+the worst point of the first front; the `mask` lines repair objectives that
+still have no range:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/nsgaiii/helpers.py
+ base = F
+ if extreme_points is not None and extreme_points.size:
+ base = np.vstack([extreme_points, F])
+
+ shifted = base - ideal_point
+ shifted[shifted < 1e-3] = 0.0
+
+ asf = np.eye(n_obj)
+ asf[asf == 0] = 1e6
+ vals = np.max(shifted * asf[:, None, :], axis=2)
+ idx = np.argmin(vals, axis=1)
+ return np.asarray(base[idx], dtype=float)
+
+
+def get_nadir_point(
+ try:
+ M = extreme_points - ideal_point
+ b = np.ones(extreme_points.shape[1])
+ plane = np.linalg.solve(M, b)
+ intercepts = 1.0 / plane
+ nadir = ideal_point + intercepts
+ if not np.allclose(M @ plane, b) or np.any(intercepts <= 1e-6) or np.any(nadir > worst_point):
+ raise np.linalg.LinAlgError
+ except Exception:
+ nadir = worst_of_front
+
+ mask = nadir - ideal_point <= 1e-6
+ nadir = nadir.copy()
+ nadir[mask] = worst_of_population[mask]
+ return np.asarray(nadir)
+```
+
+Association and niching follow the formulas line by line. `associate` takes
+the largest cosine and converts it to a perpendicular distance. In
+`niche_selection`, `unique_refs` is J, `candidate_refs` is J_min after the
+shuffle, cut to the places left; inside the loop, `candidates` is shuffled
+before the choice, so `argmin` breaks ties in distance at random and
+`candidates[0]` is a random member:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/nsgaiii/helpers.py
+ norms = np.linalg.norm(normalized_F, axis=1, keepdims=True)
+ norms = np.where(norms > 0, norms, 1e-12)
+ normalized_vectors = normalized_F / norms
+ cosine = normalized_vectors @ ref_dirs_norm.T
+ cosine = np.clip(cosine, -1.0, 1.0)
+ associations = np.argmax(cosine, axis=1)
+ cos_selected = cosine[np.arange(cosine.shape[0]), associations]
+ distances = norms.flatten() * np.sqrt(1.0 - np.square(cos_selected))
+ return associations, distances
+
+
+def niche_selection(
+ mask = np.ones(front.size, dtype=bool)
+ while len(selected) < n_remaining:
+ remaining = n_remaining - len(selected)
+ active_pos = np.where(mask)[0]
+ if active_pos.size == 0:
+ break
+
+ assoc_front = associations[front[active_pos]]
+ unique_refs = np.unique(assoc_front)
+ ref_counts = niche_counts[unique_refs]
+ min_count = np.min(ref_counts)
+ candidate_refs = unique_refs[ref_counts == min_count]
+ rng.shuffle(candidate_refs)
+ candidate_refs = candidate_refs[:remaining]
+
+ for ref_choice in candidate_refs:
+ # Never empty: every candidate reference is associated with an active row.
+ candidates = active_pos[assoc_front == ref_choice]
+ rng.shuffle(candidates)
+ if niche_counts[ref_choice] == 0:
+ cand_dist = distances[front[candidates]]
+ pick = candidates[int(np.argmin(cand_dist))]
+ else:
+ pick = candidates[0]
+ mask[pick] = False
+ selected.append(int(front[pick]))
+ niche_counts[ref_choice] += 1
+```
+
+The [NSGA-III lesson](../../algorithms/nsgaiii.md) runs the DTLZ2 example of
+lesson A1, draws its result and records the configuration choices; the
+[configuration reference](../../reference/api/algorithms/nsgaiii.md) lists
+every builder method.
+
+## NSGA-III among its relatives
+
+- **NSGA-II.** The two share everything except the cut of the last front and
+ the parent selection. With two or three objectives they often perform
+ similarly; NSGA-III then mainly adds the requirement N ≥ H.
+- **MOEA/D** (lesson [I6](../intermediate/beyond-nsga-ii.md#decomposition-based-algorithms)).
+ Both spread weight vectors with the Das and Dennis design. MOEA/D compares
+ solutions by a scalarizing function within neighbourhoods of vectors;
+ NSGA-III compares them by dominance and uses the directions only to count.
+ It needs no scalarizing function and no neighbourhood size.
+- **RVEA** (lesson [A3](rvea.md)) drops dominance and chooses each direction's
+ survivor by an angle-penalized distance; **AGE-MOEA** (lesson
+ [A4](agemoea.md)) drops the directions and adapts its distances to the shape
+ of the front.
+
+NSGA-III works best when the front covers the simplex, as on DTLZ2 or WFG4.
+Fronts that are degenerate, disconnected or inverted leave many directions
+without solutions and pile the survivors onto the others: Ishibuchi et al. [5]
+showed that the performance of reference-direction algorithms depends strongly
+on the shape of the front. Normalization can also be misled by poor extreme
+points early in the run. And H grows combinatorially with m, which fixes a
+minimum population whether or not the problem needs it.
+
+## Key points
+
+- NSGA-III keeps NSGA-II's structure and replaces the crowding distance by
+ niching around H = C(p + m − 1, m − 1) Das and Dennis directions; VAMOS
+ requires N ≥ H and raises a `ValueError` otherwise.
+- Adaptive normalization translates by the ideal point and divides by the
+ intercepts of the hyperplane through the ASF extreme points; when the
+ hyperplane is degenerate VAMOS uses the worst point of the first front.
+- Each solution is associated with the direction at the smallest
+ perpendicular distance.
+- The last front fills the least crowded directions first: the closest
+ candidate for an empty direction, a random one otherwise, with random
+ tie-breaks.
+- VAMOS selects parents at random by default, as Deb and Jain, or by a
+ tournament on rank, never by crowding distance, and treats constraints
+ feasibility first, unless `constraint_handling` names another technique.
+
+**Next:** [A3. RVEA: angle-penalized distance](rvea.md).
+
+## References
+
+[1] Deb, K., and Jain, H. (2014). [An evolutionary many-objective optimization algorithm using reference-point-based nondominated sorting approach, Part I: Solving problems with box constraints](https://doi.org/10.1109/TEVC.2013.2281535). *IEEE Transactions on Evolutionary Computation*, 18(4), 577–601.
+
+[2] Jain, H., and Deb, K. (2014). [An evolutionary many-objective optimization algorithm using reference-point based nondominated sorting approach, Part II: Handling constraints and extending to an adaptive approach](https://doi.org/10.1109/TEVC.2013.2281534). *IEEE Transactions on Evolutionary Computation*, 18(4), 602–622.
+
+[3] Das, I., and Dennis, J. E. (1998). [Normal-boundary intersection: A new method for generating the Pareto surface in nonlinear multicriteria optimization problems](https://doi.org/10.1137/S1052623496307510). *SIAM Journal on Optimization*, 8(3), 631–657.
+
+[4] Zhang, Q., and Li, H. (2007). [MOEA/D: A multiobjective evolutionary algorithm based on decomposition](https://doi.org/10.1109/TEVC.2007.892759). *IEEE Transactions on Evolutionary Computation*, 11(6), 712–731.
+
+[5] Ishibuchi, H., Setoguchi, Y., Masuda, H., and Nojima, Y. (2017). [Performance of decomposition-based many-objective algorithms strongly depends on Pareto front shapes](https://doi.org/10.1109/TEVC.2016.2587749). *IEEE Transactions on Evolutionary Computation*, 21(2), 169–190.
+
+[6] Wierzbicki, A. P. (1980). The use of reference objectives in multiobjective optimization. In G. Fandel and T. Gal (Eds.), *Multiple Criteria Decision Making Theory and Application*, Lecture Notes in Economics and Mathematical Systems 177, 468–486. Springer.
+
+[7] Huband, S., Hingston, P., Barone, L., and While, L. (2006). [A review of multiobjective test problems and a scalable test problem toolkit](https://doi.org/10.1109/TEVC.2005.861417). *IEEE Transactions on Evolutionary Computation*, 10(5), 477–506.
diff --git a/docs/foundations/advanced/performance-assessment.md b/docs/foundations/advanced/performance-assessment.md
new file mode 100644
index 000000000..b56352426
--- /dev/null
+++ b/docs/foundations/advanced/performance-assessment.md
@@ -0,0 +1,234 @@
+---
+description: 'A10. Comparing stochastic multi-objective algorithms rigorously: experimental design, empirical attainment functions, statistical tests and effect sizes, anytime performance and common pitfalls, with VAMOS and MooCore code.'
+search:
+ boost: 0.5
+---
+
+# A10. Comparing algorithms rigorously
+
+"Algorithm A is better than algorithm B" is the most common claim in the
+field, and the easiest to get wrong. Evolutionary algorithms are randomized,
+their output is a set, and their performance depends on the problem, the
+budget and the settings. This lesson turns the tools of the previous lessons
+into a method for comparisons that survive scrutiny.
+
+In this lesson you will learn:
+
+- why one run is one random sample, and what that implies;
+- what to fix before running an experiment;
+- how attainment functions show the distribution of whole approximation sets;
+- how to test differences in an indicator and report their size;
+- how to run such a comparison with VAMOS.
+
+## A run is a sample
+
+Run an algorithm twice with different seeds and you get two different
+approximation sets. The outcome of a run is a **random set**, and the
+algorithm's performance is the distribution of that set [1]. Consequently:
+
+- one run per algorithm proves nothing, however good the plot looks;
+- runs must be **independent**: different seeds, recorded in advance;
+- every summary (a median hypervolume, a plot of one run) must say which runs
+ it summarizes and how much they vary.
+
+## Design the experiment first
+
+Decide the following **before** the first run [2, 3]:
+
+1. **The question.** "Is A better than B on bi-objective problems with
+ disconnected fronts within 10,000 evaluations?" is testable; "Is A better?"
+ is not.
+2. **The problems.** Choose problems that represent the question, with
+ different front shapes and difficulties; avoid tuning the problem set until
+ your algorithm wins.
+3. **The budget**, in function evaluations, not in time. Several budgets
+ reveal whether a ranking changes as runs get longer.
+4. **The settings.** Give every algorithm the same care: published defaults for
+ all, or the same tuning effort for all. Tuning only your own algorithm
+ biases the comparison.
+5. **The number of runs** and their seeds. A few dozen independent runs per
+ algorithm and problem is common; decide the number in advance.
+6. **The reference data**: reference points, reference sets and normalization
+ bounds (lesson [B4](../basic/quality-indicators.md#choosing-and-using-indicators)).
+7. **The indicators and the statistical procedure**, including the correction
+ for multiple comparisons.
+
+VAMOS supports this discipline: a durable study fixes the matrix of
+algorithms, problems and seeds before it runs and saves every run with its
+resolved configuration. [T06. Run a fair comparative
+study](../../tutorials/t06-fair-study.md) applies the checklist step by step.
+
+## Attainment functions: the distribution of whole sets
+
+An indicator reduces each run to one number. Attainment functions keep the
+sets [1, 4]. A point z of objective space is **attained** by a run if the
+run's approximation set weakly dominates it. The **empirical attainment
+function** (EAF) gives, for every z, the fraction of runs that attain it. Its
+level sets are the **k%-attainment surfaces**:
+
+- the *best* surface bounds what at least one run attained;
+- the *median* (50%) surface bounds what half of the runs attained, a typical
+ run;
+- the *worst* surface bounds what every run attained.
+
+Comparing the median surfaces of two algorithms, or plotting the difference of
+their EAFs, shows **where** in objective space each one is better [5]. The
+figure uses synthetic runs of two algorithms: A covers the whole front but
+converges less; B converges closer, but only on part of the front.
+
+
+
+The median surfaces usually cross: B is better in the region its runs
+converged to, and A where B's runs rarely reach. The hypervolume weights those
+regions in its own way and declares one winner; the attainment surfaces show
+what that verdict is made of. Press **New runs** a few times to see how much
+the picture varies with only eleven runs each.
+
+## Test the differences
+
+With one indicator value per run, two algorithms on one problem give two
+samples. Indicator values are rarely normally distributed, so use
+non-parametric tests [6, 7]:
+
+- **Per problem**, compare the independent runs of two algorithms with the
+ Mann–Whitney U test, also called the Wilcoxon rank-sum test [8, 9].
+- **Across problems**, summarize each algorithm on each problem by one
+ pre-defined statistic (for example the median hypervolume), and compare the
+ algorithms with the Friedman test followed by post-hoc tests [10, 6].
+- **Correct for multiple comparisons**, for example with Holm's procedure [11]:
+ with twenty comparisons at 5%, one "significant" result is expected by chance.
+- **Report the effect size**, not only the p-value. The Vargha–Delaney A₁₂
+ statistic [12] estimates the probability that a run of A beats a run of B:
+ 0.5 means no difference, 1 means A always wins. A tiny difference can be
+ "significant" with enough runs, and a large one can be "not significant"
+ with too few.
+
+A p-value says how surprising the data would be if the algorithms performed
+the same; it says nothing about how much better one is, or whether the
+difference matters to anyone. VAMOS' experimental analysis helpers include the
+Friedman test and pairwise Wilcoxon tests for the across-problem case; see
+[analysis and visualization](../../topics/analysis.md#statistical-comparison).
+
+## Anytime performance
+
+A single budget gives a snapshot. Plotting the indicator against the number of
+evaluations, as the live figure of lesson
+[I1](../intermediate/nsga-ii.md#watch-it-converge) does, shows which algorithm
+is better early and which is better late. When the budget of a real application
+is uncertain, that is often the relevant comparison. [T07. Measure quality and
+progress with budget](../../tutorials/t07-quality-and-budget.md) measures saved
+runs at several budgets.
+
+## Common pitfalls
+
+- Reporting one run, or the best of several runs.
+- Different budgets, population sizes or numbers of runs for different
+ algorithms, or a budget counted in generations when the population sizes
+ differ.
+- Choosing the reference point, the reference set or the normalization after
+ seeing the results.
+- Using an indicator that is not Pareto compliant as the only evidence
+ (lesson [B4](../basic/quality-indicators.md#pareto-compliance)).
+- Generalizing beyond the problems tested. No algorithm is best on all
+ problems [13]; a comparison supports a claim only about problems like those
+ in it.
+- Discarding failed or infeasible runs from the summary without reporting them.
+
+## In VAMOS
+
+Eleven independent runs each of NSGA-II and SPEA2 on ZDT1, with the hypervolume
+of every run, a Mann–Whitney test, the Vargha–Delaney effect size, and the
+median attainment surface of NSGA-II computed by MooCore. Passing a list of
+seeds to `optimize` runs one independent run per seed.
+
+```python
+import moocore
+import numpy as np
+from scipy.stats import mannwhitneyu
+
+from vamos import optimize
+
+seeds = list(range(1, 12)) # 11 independent runs per algorithm, fixed in advance
+reference_point = [1.1, 1.1]
+hv = {}
+fronts = {}
+for algorithm in ("nsgaii", "spea2"):
+ runs = optimize("zdt1", algorithm=algorithm, pop_size=100, max_evaluations=5_000, engine="numpy", seed=seeds)
+ fronts[algorithm] = [run.front() for run in runs]
+ hv[algorithm] = np.array([moocore.hypervolume(front, ref=reference_point) for front in fronts[algorithm]])
+ q1, median, q3 = np.percentile(hv[algorithm], [25, 50, 75])
+ print(f"{algorithm:<7} runs {len(runs)} median HV {median:.4f} IQR {q3 - q1:.4f}")
+
+a, b = hv["nsgaii"], hv["spea2"]
+test = mannwhitneyu(a, b, alternative="two-sided")
+a12 = (np.sum(a[:, None] > b[None, :]) + 0.5 * np.sum(a[:, None] == b[None, :])) / (len(a) * len(b))
+print(f"Mann-Whitney U {test.statistic:.1f}, p {test.pvalue:.4f}, A12 {a12:.2f}")
+
+labelled = np.vstack([np.column_stack([front, np.full(len(front), k)]) for k, front in enumerate(fronts["nsgaii"], start=1)])
+median_surface = moocore.eaf(labelled[:, :2], sets=labelled[:, 2], percentiles=[50])
+print("median attainment surface of NSGA-II:", median_surface.shape[0], "points")
+```
+
+Output:
+
+```text
+nsgaii runs 11 median HV 0.6636 IQR 0.0822
+spea2 runs 11 median HV 0.6411 IQR 0.0642
+Mann-Whitney U 74.0, p 0.3933, A12 0.61
+median attainment surface of NSGA-II: 109 points
+```
+
+The medians differ by less than the spread between runs, and with eleven
+runs each the test cannot distinguish the two algorithms (p ≈ 0.39). The
+effect size says that a random NSGA-II run beats a random SPEA2 run in about
+61% of the pairs: a modest difference that more runs might confirm or not.
+Read the result for what it is: one problem, one budget, default settings. It
+concerns NSGA-II and SPEA2 with these settings on ZDT1 at 5,000 evaluations,
+and nothing more general. A durable
+[study](../../guide/studies.md) runs the same design for many problems,
+algorithms and seeds, records every run and its configuration, and
+[T08](../../tutorials/t08-study-report.md) turns it into a report.
+
+## Key points
+
+- An algorithm's output is a random set: compare distributions over many
+ independent runs, never single runs.
+- Fix the question, problems, budget, settings, runs, reference data,
+ indicators and tests before running.
+- Attainment surfaces show where in objective space each algorithm is
+ better; indicators summarize it in one number.
+- Use non-parametric tests with corrections for multiple comparisons, and
+ report effect sizes together with p-values.
+- Conclusions hold for the problems, budgets and settings tested.
+
+**You have completed the Foundations path.** Continue with the
+[study tutorials](../../tutorials/t06-fair-study.md) to apply it with saved,
+verifiable evidence.
+
+## References
+
+[1] Fonseca, C. M., and Fleming, P. J. (1996). [On the performance assessment and comparison of stochastic multiobjective optimizers](https://doi.org/10.1007/3-540-61723-X_1022). *Parallel Problem Solving from Nature – PPSN IV*, Lecture Notes in Computer Science 1141, 584–593.
+
+[2] Knowles, J., Thiele, L., and Zitzler, E. (2006). *A tutorial on the performance assessment of stochastic multiobjective optimizers*. TIK Report 214, Computer Engineering and Networks Laboratory, ETH Zurich.
+
+[3] Bartz-Beielstein, T., et al. (2020). [Benchmarking in optimization: Best practice and open issues](https://arxiv.org/abs/2007.03488). arXiv:2007.03488.
+
+[4] Grunert da Fonseca, V., Fonseca, C. M., and Hall, A. O. (2001). [Inferential performance assessment of stochastic optimisers and the attainment function](https://doi.org/10.1007/3-540-44719-9_15). *Evolutionary Multi-Criterion Optimization – EMO 2001*, Lecture Notes in Computer Science 1993, 213–225.
+
+[5] López-Ibáñez, M., Paquete, L., and Stützle, T. (2010). [Exploratory analysis of stochastic local search algorithms in biobjective optimization](https://doi.org/10.1007/978-3-642-02538-9_9). In T. Bartz-Beielstein et al. (Eds.), *Experimental Methods for the Analysis of Optimization Algorithms*, 209–222. Springer.
+
+[6] Derrac, J., García, S., Molina, D., and Herrera, F. (2011). [A practical tutorial on the use of nonparametric statistical tests as a methodology for comparing evolutionary and swarm intelligence algorithms](https://doi.org/10.1016/j.swevo.2011.02.002). *Swarm and Evolutionary Computation*, 1(1), 3–18.
+
+[7] Demšar, J. (2006). Statistical comparisons of classifiers over multiple data sets. *Journal of Machine Learning Research*, 7, 1–30.
+
+[8] Wilcoxon, F. (1945). [Individual comparisons by ranking methods](https://doi.org/10.2307/3001968). *Biometrics Bulletin*, 1(6), 80–83.
+
+[9] Mann, H. B., and Whitney, D. R. (1947). [On a test of whether one of two random variables is stochastically larger than the other](https://doi.org/10.1214/aoms/1177730491). *The Annals of Mathematical Statistics*, 18(1), 50–60.
+
+[10] Friedman, M. (1937). [The use of ranks to avoid the assumption of normality implicit in the analysis of variance](https://doi.org/10.1080/01621459.1937.10503522). *Journal of the American Statistical Association*, 32(200), 675–701.
+
+[11] Holm, S. (1979). A simple sequentially rejective multiple test procedure. *Scandinavian Journal of Statistics*, 6(2), 65–70.
+
+[12] Vargha, A., and Delaney, H. D. (2000). [A critique and improvement of the CL common language effect size statistics of McGraw and Wong](https://doi.org/10.3102/10769986025002101). *Journal of Educational and Behavioral Statistics*, 25(2), 101–132.
+
+[13] Wolpert, D. H., and Macready, W. G. (1997). [No free lunch theorems for optimization](https://doi.org/10.1109/4235.585893). *IEEE Transactions on Evolutionary Computation*, 1(1), 67–82.
diff --git a/docs/foundations/advanced/rvea.md b/docs/foundations/advanced/rvea.md
new file mode 100644
index 000000000..956c8128f
--- /dev/null
+++ b/docs/foundations/advanced/rvea.md
@@ -0,0 +1,388 @@
+---
+description: 'A3. RVEA, the reference vector guided evolutionary algorithm: unit reference vectors, translation by the ideal point, association by angle, the angle-penalized distance and its schedule, and the adaptation of the vectors to the scales of the objectives, as VAMOS implements them, with an interactive figure and VAMOS code.'
+search:
+ boost: 0.5
+---
+
+# A3. RVEA: angle-penalized distance
+
+NSGA-III (lesson [A2](nsga-iii.md)) still sorts the population into fronts and
+uses its directions only to cut the last one. RVEA, the reference vector
+guided evolutionary algorithm of Cheng, Jin, Olhofer and Sendhoff [1], drops
+dominance altogether. Each reference vector keeps one solution, chosen by a
+single number, the **angle-penalized distance** (APD): the distance to the
+ideal point measures convergence, the angle to the vector measures diversity.
+The weight of the angle grows during the run, so RVEA first pushes the
+population towards the front and then spreads it along the vectors.
+
+A second idea replaces NSGA-III's hyperplane: from time to time the reference
+vectors themselves are stretched to the ranges of the objectives, so that
+objectives of different scales still receive evenly spread solutions.
+
+In this lesson you will learn:
+
+- how RVEA builds its unit reference vectors, and why VAMOS requires exactly
+ one individual per vector;
+- how solutions are translated by the ideal point and associated with vectors
+ by angle;
+- how the angle-penalized distance works, and what its parameters α and γ do;
+- how and when the vectors adapt to the scales of the objectives;
+- where VAMOS follows the article and where it follows pymoo.
+
+## From niches to subproblems
+
+Decomposition-based algorithms divide the objective space among a set of
+vectors and look for one good solution per vector. MOEA/D [3] gives each
+vector a scalarizing function and lets neighbouring vectors exchange
+solutions (lesson
+[I6](../intermediate/beyond-nsga-ii.md#decomposition-based-algorithms));
+NSGA-III [2] keeps dominance and uses the vectors to count. Cheng et al.
+observed that an angle between a solution and a vector is a natural measure of
+diversity that does not depend on how far the solution is from the front, and
+combined it with the distance to the ideal point into one criterion that
+changes its emphasis over time [1].
+
+The article also shows that vectors restricted to a region of interest express
+a decision maker's preferences, proposes a variant that regenerates the
+vectors left without solutions on irregular fronts (RVEA\*), and extends the
+algorithm to constraints [1]. VAMOS implements the basic RVEA with vector
+adaptation.
+
+## Reference vectors
+
+RVEA starts from the same Das and Dennis lattice as NSGA-III [4] and
+normalizes each point to a unit vector. Each vector also gets its own angular
+spacing γ, the angle to its nearest neighbour:
+
+vᵢ = wᵢ / ‖wᵢ‖ (w a Das and Dennis point, ‖vᵢ‖ = 1)
+γᵢ = min_(j ≠ i) arccos( vᵢᵀ vⱼ ) (smallest angle to another vector)
+
+With p divisions the lattice has H = C(p + m − 1, m − 1) vectors, and RVEA
+keeps at most one solution per vector, so in VAMOS the population must have
+**exactly** H individuals. `n_partitions` sets p (12 by default). A run whose
+`pop_size` differs from H stops before the first evaluation with a
+`ValueError`. `RVEAConfig.default(pop_size=N, n_obj=m)` looks for the lattice
+with exactly N vectors and, when there is none, raises an error naming the two
+nearest valid sizes. Without a population size it uses p = 99 for two
+objectives, 12 for three and 6 for four or more.
+
+## Translation and association by angle
+
+At each generation the merged parents and offspring are translated so that the
+ideal point becomes the origin. Each solution then joins the vector at the
+smallest angle, forming one subpopulation per vector:
+
+z_min,i = min f_i over the solutions seen so far (ideal point)
+f′(x) = f(x) − z_min
+cos θ(x, vⱼ) = f′(x)ᵀ vⱼ / ‖f′(x)‖
+P̄ⱼ = { x : vⱼ has the largest cos θ(x, ·) } (subpopulation of vⱼ)
+
+Unlike NSGA-III, RVEA does not rescale the objectives here: the angle is
+measured on translated, unscaled objectives, and scales are handled by
+adapting the vectors (below). VAMOS keeps the smallest value of each objective
+seen during the run, as pymoo does; the article computes the ideal point from
+the current population [1].
+
+## The angle-penalized distance
+
+Within each subpopulation, RVEA keeps the solution with the smallest APD:
+
+APD(x, vⱼ) = ( 1 + P(θ) ) · ‖f′(x)‖
+P(θ) = M · ( t / t_max )^α · θ(x, vⱼ) / γⱼ
+survivor of vⱼ = argmin over x ∈ P̄ⱼ of APD(x, vⱼ) (for every non-empty P̄ⱼ)
+
+- **‖f′(x)‖**, the distance to the ideal point, measures convergence.
+- **θ / γⱼ** is the angle to the vector relative to the local spacing of the
+ vectors: the same angle weighs more where the vectors are dense.
+- **M**, the number of objectives, scales the penalty because solutions spread
+ over more angles in higher dimension.
+- **(t / t_max)^α** is the schedule. At the start (t ≈ 0) the penalty vanishes
+ and each vector keeps the solution closest to the ideal point, whatever its
+ angle. At the end it keeps a solution well aligned with the vector. The
+ exponent α (2 by default, as in the article) decides how long RVEA favours
+ convergence: the larger α, the later the angle starts to count.
+
+A worked example: two solutions in the cone of a vector with γ = 18.4°, a at
+distance 0.80 and 9.6° off the vector, b at distance 0.95 and 0.4° off. With
+M = 1 and α = 2, a has the smaller APD until 0.80·(1 + s·9.6/18.4) exceeds
+0.95·(1 + s·0.4/18.4), that is until s = (t/t_max)² ≈ 0.38, or
+t/t_max ≈ 0.62. From then on b survives.
+
+A vector whose subpopulation is empty keeps nothing, so the population can
+become smaller than N, as in the article, PlatEMO and pymoo. The next
+generation still creates N offspring. Parents are drawn at random: VAMOS takes
+them from random permutations of the population, without replacement, as
+pymoo does.
+
+VAMOS details and deviations:
+
+- **M = 1 with two objectives.** VAMOS, like pymoo, uses M = 1 instead of 2 when
+ m = 2, which halves the penalty; with three or more objectives M = m.
+- **The schedule.** The first survival uses t = 1, and t_max is the number of
+ generations the budget allows, ⌈(max_evaluations − N) / N⌉: 219 for 20,000
+ evaluations with N = 91.
+- **Ties.** On equal APD, the solution listed first wins.
+- **VAMOS 1.5.0: two variants.** `variant("pymoo")`, the default,
+ makes the choices above. `variant("platemo")` follows the authors' code in
+ PlatEMO, which jMetal also follows: M = m with two objectives too, the
+ objectives are translated by the minimum of each generation's candidates
+ instead of the accumulated ideal point, and the vectors adapt to the range of
+ the population (below).
+
+## Explore the penalty
+
+The figure has five reference vectors (p = 4) drawn from the ideal point of
+twelve solutions. Vector v3 has no solution in its cone. Move t/t_max from 0
+to 1 with α = 2: at first every vector keeps its solution closest to the ideal
+point, then v1, v2 and v4 switch, one after the other, to a better-aligned
+solution; v3 keeps nothing, so four solutions survive. Change α to 1 and to 5
+to move the switches earlier and later. Finally tick the article's M = 2: the
+penalty doubles, and even v5 abandons its near solution 11 for the distant but
+perfectly aligned 12.
+
+
+
+## Adapting the reference vectors
+
+If one objective ranges over [0, 1] and another over [0, 100], evenly spread
+unit vectors crowd the solutions into a small part of the front. Every
+f_r · t_max generations RVEA stretches the initial vectors to the current
+ranges and normalizes them again:
+
+vᵢ ← ( v⁰ᵢ ∘ (z_max − z_min) ) / ‖ v⁰ᵢ ∘ (z_max − z_min) ‖ every ⌈f_r · t_max⌉ generations
+
+Here ∘ multiplies element by element, v⁰ᵢ are the initial unit vectors, z_max
+is the largest value of each objective in the current population and z_min is
+the ideal point. The spacings γᵢ are recomputed from the new vectors. The
+article recommends f_r = 0.1, so the vectors adapt ten times per run [1]:
+adapting at every generation would make them chase a population that is still
+far from the front.
+
+In VAMOS, `adapt_freq(f_r)` sets the frequency (0.1 by default) and
+`adapt_freq(None)` disables adaptation. Adaptation happens after the survival
+of every generation t that is a multiple of ⌈f_r · t_max⌉, with z_max taken
+from the survivors. With constraints only feasible solutions define z_min and
+z_max, and the vectors do not adapt until a feasible solution exists. The
+`variant("platemo")` scales instead by the range of the current population,
+its largest minus its smallest value of each objective.
+
+## In VAMOS
+
+The example first asks `RVEAConfig.default` for a population that matches no
+lattice. It then runs RVEA on WFG4 [6], whose front
+(f₁/2)² + (f₂/4)² + (f₃/6)² = 1 has very different scales, with and without
+adaptation, and counts how many of the 91 Das and Dennis directions are the
+nearest direction of at least one solution once the front is mapped onto the
+unit sphere:
+
+```python
+import numpy as np
+
+from vamos import optimize
+from vamos.algorithms import RVEAConfig
+from vamos.problems import WFG4
+
+try:
+ RVEAConfig.default(pop_size=100, n_obj=3)
+except ValueError as error:
+ print(error)
+
+problem = WFG4(n_var=12, n_obj=3) # front: (f₁/2)² + (f₂/4)² + (f₃/6)² = 1
+W = np.array([(i, j, 12 - i - j) for i in range(13) for j in range(13 - i)], dtype=float)
+W /= np.linalg.norm(W, axis=1, keepdims=True) # the 91 Das and Dennis directions, p = 12
+
+
+def occupied(Z):
+ """Number of directions that are the nearest direction of at least one point."""
+ cosine = (Z / np.linalg.norm(Z, axis=1, keepdims=True)) @ W.T
+ return np.unique(np.argmax(cosine, axis=1)).size
+
+
+for adapt_freq in (0.1, None):
+ config = (
+ RVEAConfig.builder()
+ .pop_size(91)
+ .n_partitions(12)
+ .alpha(2.0)
+ .adapt_freq(adapt_freq)
+ .crossover("sbx", prob=1.0, eta=30.0)
+ .mutation("pm", prob="1/n", eta=20.0)
+ .result_mode("population")
+ .build()
+ )
+ result = optimize(problem, algorithm="rvea", algorithm_config=config, max_evaluations=20_000, engine="numpy", seed=1)
+ scaled = result.F / np.array([2.0, 4.0, 6.0]) # maps the true front onto the unit sphere
+ print(f"adapt_freq={adapt_freq}: {len(result.F)} solutions, {occupied(scaled)} of 91 directions occupied")
+```
+
+Output:
+
+```text
+RVEA needs one individual per reference vector, and no Das-Dennis lattice for n_obj=3 has 100 vectors. Use pop_size=91 (12 partitions) or pop_size=105 (13 partitions).
+adapt_freq=0.1: 91 solutions, 90 of 91 directions occupied
+adapt_freq=None: 91 solutions, 65 of 91 directions occupied
+```
+
+With adaptation the solutions cover almost every direction of the scaled
+front. Without it the vectors stay evenly spread in the raw objective space,
+and the solutions follow them, leaving a large part of the stretched front
+empty.
+
+The vectors and their spacings come from two small functions. `_calc_gamma`
+sorts each row of the cosine matrix in decreasing order; the first entry is
+the vector itself (cosine 1), so the second is its nearest neighbour:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/rvea/rvea.py
+def _calc_V(ref_dirs: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
+ norms = np.linalg.norm(ref_dirs, axis=1, keepdims=True)
+ norms[norms == 0.0] = 1.0
+ return np.asarray(ref_dirs / norms, dtype=float)
+
+
+def _calc_gamma(V: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
+ cosine = V @ V.T
+ gamma = np.arccos((-np.sort(-1.0 * cosine, axis=1))[:, 1])
+ gamma = np.maximum(gamma, 1e-64)
+ return np.asarray(gamma, dtype=float)
+```
+
+The survival follows the formulas. `angle_penalized_distances` translates the
+objectives by an origin, associates each solution with the vector at the
+smallest angle (`niches`), and computes the penalty, with M = 1 for two
+objectives in the default variant, and the APD. `apd_survival` passes the
+accumulated ideal point as the origin. `np.lexsort` orders the solutions by
+vector, then by APD, then by position, so the first solution of each vector in
+that order is its survivor; vectors without solutions simply do not appear:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/rvea/survival.py
+ n_obj = F.shape[1]
+ F_shift = F - origin
+ dist_to_origin = np.linalg.norm(F_shift, axis=1)
+ dist_to_origin[dist_to_origin < 1e-64] = 1e-64
+ F_prime = F_shift / dist_to_origin[:, None]
+
+ cos_theta = np.clip(F_prime @ V.T, -1.0, 1.0)
+ acute_angle = np.arccos(cos_theta)
+ niches = acute_angle.argmin(axis=1)
+
+ M = float(n_obj) if n_obj > 2 or variant == "platemo" else 1.0
+ progress = (n_gen / n_max_gen) ** alpha
+ theta = acute_angle[np.arange(F.shape[0]), niches]
+ penalty = M * progress * (theta / gamma[niches])
+ return niches, penalty, dist_to_origin * (1.0 + penalty)
+
+
+def apd_survival(
+ ideal = np.minimum(F.min(axis=0), ideal)
+ origin = F.min(axis=0) if variant == "platemo" else ideal
+ niches, _penalty, apd = angle_penalized_distances(F, origin, V, gamma, n_gen, n_max_gen, alpha, variant)
+
+ order = np.lexsort((np.arange(F.shape[0]), apd, niches))
+ sorted_niches = niches[order]
+ first_in_niche = np.empty(sorted_niches.shape[0], dtype=bool)
+ first_in_niche[0] = True
+ first_in_niche[1:] = sorted_niches[1:] != sorted_niches[:-1]
+ survivors = order[first_in_niche][: min(int(n_survive), F.shape[0])]
+
+ nadir = F[survivors].max(axis=0) if survivors.size else None
+ return survivors, ideal, nadir
+```
+
+The last lines return the largest objective values of the survivors, the
+z_max of the adaptation. The run computes t_max from the budget, builds one
+reference vector per individual (`_reference_vectors` raises when the lattice
+does not match `pop_size`), sets the adaptation interval, and stretches the
+vectors at each multiple of it:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/rvea/rvea.py
+ # The APD penalty grows with generation / max_gen; n_gen gives max_gen directly.
+ if termination[0] == "n_gen":
+ max_gen = max_evals // pop_size
+ else:
+ max_gen = max(1, int(math.ceil((max_evals - pop_size) / pop_size)))
+
+ ref_dirs = _reference_vectors(self.cfg.get("reference_vectors"), pop_size, n_obj, n_partitions)
+ adapt_interval = None
+ if adapt_freq is not None:
+ adapt_interval = max(1, int(math.ceil(max_gen * float(adapt_freq))))
+ # Periodic reference-vector adaptation
+ if st.adapt_interval is not None and st.generation % st.adapt_interval == 0:
+ scale: np.ndarray[Any, Any] | None = None
+ if st.variant == "platemo":
+ scale = np.ptp(st.F, axis=0)
+ elif st.nadir is not None:
+ scale = st.nadir - st.ideal
+ if scale is not None:
+ st.V = _calc_V(_calc_V(st.ref_dirs) * np.maximum(scale, 1e-64))
+ st.gamma = _calc_gamma(st.V)
+```
+
+**VAMOS 1.5.0:** the population no longer has to be a complete
+lattice. `reference_vectors(path=...)` reads the vectors from a file, such as
+jMetal's `W3D_100.dat` that VAMOS ships, and
+`reference_vectors(divisions=p₁, inner_divisions=p₂)` builds Deb and Jain's
+two-layer lattice (lesson [A2](nsga-iii.md#reference-directions)).
+
+The [RVEA lesson](../../algorithms/rvea.md#interpret-the-result-and-its-limits)
+records a run on DTLZ2 and the changes of VAMOS 1.2.0; the
+[configuration reference](../../reference/api/algorithms/rvea.md) lists every
+builder method. With constraints, RVEA keeps feasible solutions first and
+applies the APD among them; `constraint_handling` accepts the techniques that
+judge one solution at a time (lesson [A5](constrained.md)).
+
+## RVEA, NSGA-III and MOEA/D
+
+| | NSGA-III | RVEA | MOEA/D |
+| --- | --- | --- | --- |
+| Convergence | Non-dominated rank | Distance to the ideal point | Scalarizing function |
+| Diversity | Niche counts per direction | Angle to the vector, penalized more over time | One subproblem per vector |
+| Scales | Normalization every generation | Vectors stretched every f_r · t_max generations | None in the original algorithm |
+| Population | N ≥ H | N = H; can shrink when vectors are empty | N = number of vectors |
+
+**Strengths.** Selection needs no non-dominated sorting, so it stays cheap and
+keeps its selection pressure when almost every solution is non-dominated. The
+schedule makes the balance between convergence and diversity explicit, and the
+vectors can encode preferences.
+
+**Limits.** The schedule needs t_max, so the budget must be known in advance.
+Empty vectors shrink the population, and the returned set can be smaller than
+`pop_size`. RVEA never checks dominance, so a survivor can be dominated by
+another one (`result_mode("non_dominated")`, the default, filters the
+returned set). Like every method with fixed vectors, it suffers on fronts
+whose shape does not match the simplex: degenerate, disconnected or inverted
+fronts [5]. Lesson [A4](agemoea.md) takes the opposite approach and adapts to
+the shape of the front instead.
+
+## Key points
+
+- RVEA keeps one solution per unit reference vector, chosen by the
+ angle-penalized distance APD = (1 + P(θ))·‖f′‖; VAMOS requires
+ `pop_size` to equal the number of vectors.
+- The penalty P(θ) = M·(t/t_max)^α·θ/γ grows during the run: convergence first,
+ alignment with the vectors later; α sets how late.
+- γ, the smallest angle between a vector and its neighbours, makes the penalty
+ relative to the local spacing of the vectors.
+- Every f_r · t_max generations the vectors are stretched to the ranges of the
+ population, which lets RVEA handle objectives of different scales.
+- By default VAMOS follows pymoo where the article differs: M = 1 with two
+ objectives and an ideal point that accumulates across generations;
+ `variant("platemo")` follows the authors' code instead.
+
+**Next:** [A4. AGE-MOEA: adapting to the geometry of the front](agemoea.md).
+
+## References
+
+[1] Cheng, R., Jin, Y., Olhofer, M., and Sendhoff, B. (2016). [A reference vector guided evolutionary algorithm for many-objective optimization](https://doi.org/10.1109/TEVC.2016.2519378). *IEEE Transactions on Evolutionary Computation*, 20(5), 773–791.
+
+[2] Deb, K., and Jain, H. (2014). [An evolutionary many-objective optimization algorithm using reference-point-based nondominated sorting approach, Part I: Solving problems with box constraints](https://doi.org/10.1109/TEVC.2013.2281535). *IEEE Transactions on Evolutionary Computation*, 18(4), 577–601.
+
+[3] Zhang, Q., and Li, H. (2007). [MOEA/D: A multiobjective evolutionary algorithm based on decomposition](https://doi.org/10.1109/TEVC.2007.892759). *IEEE Transactions on Evolutionary Computation*, 11(6), 712–731.
+
+[4] Das, I., and Dennis, J. E. (1998). [Normal-boundary intersection: A new method for generating the Pareto surface in nonlinear multicriteria optimization problems](https://doi.org/10.1137/S1052623496307510). *SIAM Journal on Optimization*, 8(3), 631–657.
+
+[5] Ishibuchi, H., Setoguchi, Y., Masuda, H., and Nojima, Y. (2017). [Performance of decomposition-based many-objective algorithms strongly depends on Pareto front shapes](https://doi.org/10.1109/TEVC.2016.2587749). *IEEE Transactions on Evolutionary Computation*, 21(2), 169–190.
+
+[6] Huband, S., Hingston, P., Barone, L., and While, L. (2006). [A review of multiobjective test problems and a scalable test problem toolkit](https://doi.org/10.1109/TEVC.2005.861417). *IEEE Transactions on Evolutionary Computation*, 10(5), 477–506.
diff --git a/docs/foundations/advanced/top.md b/docs/foundations/advanced/top.md
new file mode 100644
index 000000000..5967a2e7a
--- /dev/null
+++ b/docs/foundations/advanced/top.md
@@ -0,0 +1,416 @@
+---
+description: 'A8. ToP in depth: a first phase that solves a constrained single-objective problem with differential evolution and the feasibility rule, the switch on the feasible share and on delta, a second phase with NSGA-II and constrained domination, and where VAMOS follows PlatEMO and jMetal, with an interactive figure and VAMOS code.'
+search:
+ boost: 0.5
+---
+
+# A8. ToP: two phases
+
+CCMO and C-TAEA (lessons [A6](ccmo.md) and [A7](ctaea.md)) run their
+constrained and their exploring parts side by side for the whole run. The
+**two-phase framework**, ToP, of Liu and Wang [1] runs them one after the
+other. Phase 1 looks for the feasible regions that hold the front by solving a
+simpler problem: a *single-objective* constrained problem whose objective is
+the mean of the objectives. When the population has enough feasible solutions
+and its best ones agree on a region, or when 90% of the budget is spent, phase
+2 starts: NSGA-II with constrained domination spreads the population along the
+front until the end of the run.
+
+Liu and Wang address problems whose constraints act in the decision space as
+well as in the objective space, where the feasible regions can be small and
+scattered. A multi-objective search spreads its effort along the whole front
+from the start; a single-objective search concentrates it. ToP spends the
+first part of the run on that concentration and the rest on the spread.
+
+Compared with NSGA-II, ToP adds a whole phase before it, with its own
+variation (differential evolution), its own selection (one-to-one replacement
+by the feasibility rule) and a switching rule with three thresholds.
+
+In this lesson you will learn:
+
+- the single-objective problem of phase 1 and how its population is replaced;
+- the two quantities that end phase 1, the feasible share Pf and the spread δ,
+ and their thresholds;
+- phase 2, NSGA-II with constrained domination as ToP implements it;
+- where VAMOS follows PlatEMO's implementation through jMetal's port instead of
+ the paper.
+
+## Why two phases
+
+Deb's feasibility rules [2] rank feasible solutions before infeasible ones,
+and NSGA-II [3] uses them to compare solutions inside its non-dominated
+sorting. Both work well once the population sits in the feasible regions that
+matter. The hard part, on problems with small or scattered feasible regions,
+is to get there. The idea of ToP [1] is that a constrained *single-objective*
+problem is easier to search: the feasibility rule then compares two feasible
+solutions on one number, and the population contracts around the best feasible
+region it finds instead of spreading along a front.
+
+ToP therefore splits the run. Phase 1 replaces the m objectives by their
+weighted sum with equal weights, which VAMOS computes as their mean, and solves
+the resulting constrained single-objective problem. Its population does not
+try to cover the front, only to find feasible solutions where the objectives
+are good. Phase 2 starts from that population and solves the original problem.
+
+## Phase 1: one objective and the feasibility rule
+
+Each solution x_i of the population creates one trial vector u_i by
+differential evolution [4], and u_i competes only with x_i:
+
+f̄(x) = ( f₁(x) + … + f_m(x) ) / m (the objective of phase 1)
+u_i replaces x_i ⇔ CV(u_i) < CV(x_i), or CV(u_i) = CV(x_i) and f̄(u_i) < f̄(x_i)
+
+The rule is Deb's feasibility rule applied to one pair: a feasible trial beats
+an infeasible parent, the less violated of two infeasible ones wins, and two
+solutions with the same violation, feasible ones included, are compared by f̄.
+The population never shrinks or grows, and a solution is only ever replaced by
+a better one.
+
+The trial vector comes from one of two DE strategies, chosen with probability
+0.5 each:
+
+DE/current-to-rand/1: v_i = x_i + F (x_r1 − x_i) + F (x_r2 − x_r3) (base vector x_i)
+DE/rand-to-best/1/bin: v_i = x_r1 + F (x_best − x_r1) + F (x_r2 − x_r3) (base vector x_r1)
+u_i: each variable from v_i with probability CR, otherwise from the base vector
+
+x_best is the solution with the lowest f̄, feasible or not, and r1, r2, r3 are
+random members of the population. In VAMOS both mutants go through the
+binomial crossover with their base vector; the trial vector is then clamped to
+the bounds and mutated with polynomial mutation. The defaults are CR = 1.0,
+with which the trial vector is the whole mutant, and F = 0.5.
+
+On CTP2 [5] phase 1 has a simple meaning: f₁ + f₂ is the distance function
+g(x), so f̄ = g/2, and phase 1 minimizes g subject to the constraint. Its lines
+of equal f̄ are parallel to the unconstrained front.
+
+## The switch: Pf and δ
+
+After each generation of phase 1 two quantities are updated from the
+population:
+
+Pf = (number of feasible solutions) / N
+for the n feasible solutions: f̂ = ( f − min ) / ( max − min ) (per objective, min and max over them)
+s₁ ≤ s₂ ≤ … ≤ s_n = the sorted sums f̂₁ + … + f̂_m
+δ = s_⌊n/3⌋ − s₁ (unchanged while fewer than 3 are feasible)
+the next generation is in phase 1 ⇔ ( δ ≥ 0.2 or Pf ≤ 1/3 ) and evaluations ≤ 0.9 · budget
+
+Pf asks whether enough of the population is feasible. δ asks whether the best
+third of the feasible solutions, by the sum of their normalized objectives,
+are close to the best one: a small δ means that the feasible solutions with the
+best objective values agree on a region. Phase 1 ends when both answers are
+yes, or when 90% of the budget is spent. δ and Pf change only in phase 1, so
+once phase 2 starts it lasts until the end. The thresholds are
+`delta_threshold` (0.2), `feasible_ratio_threshold` (1/3) and
+`phase_one_evaluation_fraction` (0.9) in `ToPConfig`.
+
+The normalization uses the feasible solutions of the current population only,
+so δ is scale-free: a population that has contracted to a tiny region still
+has normalized sums between 0 and m, and δ is small only if the best third are
+close *relative to the spread of all feasible solutions*.
+
+## Phase 2: NSGA-II with constrained domination
+
+Phase 2 is NSGA-II (lesson [I5](../intermediate/elitist-survival.md#survival-with-constraints))
+with ToP's constrained dominance:
+
+a ≺ b ⇔ both feasible and a dominates b in the objectives, or CV(a) < CV(b)
+fronts: the feasible solutions by non-dominated sorting, then one front per distinct violation
+survival: whole fronts of P ∪ Q while they fit, the last front by crowding distance
+
+Every infeasible solution is behind every feasible one, and infeasible
+solutions with the same violation share a front whatever their objectives.
+Each offspring is x₁ + F (x₂ − x₃) with binomial crossover (DE/rand/1/bin),
+where x₁ wins a binary tournament on front and crowding distance and x₂, x₃ are
+random; it is then clamped and mutated, as in phase 1.
+
+## Try it: the two phases on the same candidates
+
+The figure shows the 16 CTP2 candidates of lesson
+[A6](ccmo.md#try-it-one-set-of-candidates-two-rules). In phase 1, O1 to O8 are
+the trial vectors of P1 to P8, and each pair is joined by a segment. In phase 2,
+all 16 are the union of population and offspring. Follow the eight pairs of
+phase 1, read Pf and δ under the plot, then switch to phase 2.
+
+
+
+In phase 1 the violation decides six of the eight pairs. O3 has a smaller mean
+objective than P3 (0.505 against 0.548) but is infeasible, so P3 stays; O8 has
+a larger mean than P8 (0.635 against 0.575) but is feasible, so it replaces P8.
+Only O2 and O6 win on the mean objective, against feasible parents. Seven of
+the eight survivors are feasible, so Pf = 0.875, and the best third of them lie
+close together: δ = 0.051. Both tests pass, and the next generation would be in
+phase 2. In phase 2, the six non-dominated feasible candidates fill the first
+front; the second front, P2, O2 and P6, must lose one, and crowding removes O2,
+the middle one. No infeasible candidate survives either phase 2 or, apart from
+P4, phase 1.
+
+## In VAMOS
+
+ToP on CTP2 and on MW3 (15 variables, two constraints), with a population of
+100 and 20,000 evaluations, and on CTP2 a second time with phase 1 limited to
+50% of the budget. The [problem reference](../../reference/problems.md) lists
+both problems.
+
+```python
+import numpy as np
+
+from vamos import optimize
+from vamos.algorithms import ToPConfig
+
+for name, fraction in (("ctp2", 0.9), ("ctp2", 0.5), ("mw3", 0.9)):
+ config = (
+ ToPConfig.builder()
+ .pop_size(100)
+ .crossover("de", cr=1.0, f=0.5)
+ .mutation("pm", prob="1/n", eta=20.0)
+ .phase_one_evaluation_fraction(fraction)
+ .result_mode("population")
+ .build()
+ )
+ result = optimize(name, algorithm="top", algorithm_config=config, max_evaluations=20_000, engine="numpy", seed=1)
+ G = result.data["population"]["G"]
+ feasible = int(np.all(G <= 0.0, axis=1).sum())
+ print(f"{name}, phase 1 for at most {fraction:.0%} of the budget: phase 2 from evaluation {result.data['phase_two_start']}, {feasible} of {len(G)} feasible")
+```
+
+Output:
+
+```text
+ctp2, phase 1 for at most 90% of the budget: phase 2 from evaluation 18100, 100 of 100 feasible
+ctp2, phase 1 for at most 50% of the budget: phase 2 from evaluation 10100, 100 of 100 feasible
+mw3, phase 1 for at most 90% of the budget: phase 2 from evaluation 3400, 100 of 100 feasible
+```
+
+`phase_two_start` is the number of evaluations done when phase 2 started. On
+MW3, Pf and δ pass their thresholds early, and phase 2 starts after 3,400
+evaluations. On CTP2 they never do: a
+random solution of CTP2 has a large g and lies far above the front, where the
+whole objective space is feasible, so the population is feasible from the first
+generation and Pf = 1 throughout (the feasibility rule never replaces a
+feasible solution by an infeasible one). What keeps phase 1 going is δ: while
+DE descends the many local minima of g, the best third of the population stays
+spread relative to the rest, δ stays above 0.2, and phase 1 runs until its
+evaluation limit. The generation that starts at 18,000 evaluations, exactly
+90%, still belongs to phase 1, so phase 2 starts at 18,100; with a limit of
+50% it starts at 10,100. The switch thresholds are therefore problem
+parameters, not constants: `phase_one_evaluation_fraction` bounds what phase 1
+may cost when δ does not fall.
+
+The replacement rule, δ and the switch:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/top/phases.py
+def offspring_replaces_parent(
+ offspring_violation: NDArray[Any],
+ offspring_mean: NDArray[Any],
+ parent_violation: NDArray[Any],
+ parent_mean: NDArray[Any],
+) -> NDArray[np.bool_]:
+ offspring_cv = np.asarray(offspring_violation, dtype=float)
+ parent_cv = np.asarray(parent_violation, dtype=float)
+ smaller_mean = np.asarray(offspring_mean, dtype=float) < np.asarray(parent_mean, dtype=float)
+ return np.asarray((offspring_cv < parent_cv) | ((offspring_cv == parent_cv) & smaller_mean), dtype=bool)
+
+
+def updated_delta(F: NDArray[Any], violation: NDArray[Any], delta: float) -> float:
+ objectives = np.asarray(F, dtype=float)[np.asarray(violation, dtype=float) == 0.0]
+ n = objectives.shape[0]
+ if n < 3:
+ return float(delta)
+ minimum = np.min(objectives, axis=0)
+ maximum = np.max(objectives, axis=0)
+ with np.errstate(divide="ignore", invalid="ignore"):
+ normalized = (objectives - minimum) / (maximum - minimum)
+ sums = np.zeros(n, dtype=float)
+ for j in range(normalized.shape[1]):
+ sums = sums + normalized[:, j]
+ sums = np.sort(sums)
+ return float(sums[n // 3 - 1] - sums[0])
+
+
+def phase_one_continues(
+ delta: float,
+ ratio: float,
+ evaluations: int,
+ max_evaluations: int,
+ *,
+ delta_threshold: float = DELTA_THRESHOLD,
+ feasible_ratio_threshold: float = FEASIBLE_RATIO_THRESHOLD,
+ phase_one_evaluation_fraction: float = PHASE_ONE_EVALUATION_FRACTION,
+) -> bool:
+ searching = delta >= delta_threshold or ratio <= feasible_ratio_threshold
+ return bool(searching and evaluations <= phase_one_evaluation_fraction * max_evaluations)
+```
+
+The comparison is strict, so a trial vector with the same violation and the
+same mean objective does not replace its parent. `sums[n // 3 - 1]` is the
+⌊n/3⌋-th smallest sum. The sums are added objective by objective from zero, as
+jMetal's loops do, so that the floating-point values, and the ties they
+create, are jMetal's. In the switch, a NaN δ, which an objective with a single
+value among the feasible solutions produces, fails `delta >= delta_threshold`;
+the algorithm calls it with the evaluations done when a generation starts.
+
+Phase 2's fronts and survival:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/top/selection.py
+def constrained_front_numbers(F: NDArray[Any], violation: NDArray[Any]) -> IndexArray:
+ objectives = np.asarray(F, dtype=float)
+ cv = np.asarray(violation, dtype=float)
+ fronts = np.zeros(cv.shape[0], dtype=int)
+ feasible = cv == 0.0
+ feasible_fronts = 0
+ if feasible.any():
+ ranks = front_ranks(objectives[feasible])
+ fronts[feasible] = ranks
+ feasible_fronts = int(ranks.max()) + 1
+ if not feasible.all():
+ _, levels = np.unique(cv[~feasible], return_inverse=True)
+ fronts[~feasible] = feasible_fronts + np.asarray(levels, dtype=int).reshape(-1)
+ return fronts
+```
+
+Instead of running a sort with the constrained dominance, the function builds
+its result directly: Pareto fronts for the feasible rows, then `np.unique`
+numbers the distinct violations of the infeasible rows in increasing order,
+one front each. `environmental_selection` then keeps whole fronts while they
+fit and takes the rest of the last front by decreasing crowding distance.
+
+Phase 1 in the algorithm class. The trial vectors:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/top/top.py
+ def _phase_one_offspring(self) -> np.ndarray[Any, Any]:
+ st = self._st
+ X = np.asarray(st.X, dtype=float)
+ n = int(X.shape[0])
+ best = X[index_of_lowest_mean_objective(st.F)]
+ current_to_rand = st.rng.random(n) < CURRENT_TO_RAND_PROBABILITY
+ drawn = st.rng.integers(0, n, size=(n, 3))
+ r1, r2, r3 = X[drawn[:, 0]], X[drawn[:, 1]], X[drawn[:, 2]]
+ choice = current_to_rand[:, None]
+ base = np.where(choice, X, r1)
+ mutant = np.where(choice, current_to_rand_1(X, r1, r2, r3, st.f), rand_to_best_1(best, r1, r2, r3, st.f))
+ return self._trial_vectors(base, mutant)
+```
+
+The random numbers are drawn in blocks: the choice of strategy for every
+solution, then the indices r1, r2 and r3 (with replacement), then, inside
+`_trial_vectors`, the crossover and the mutation. `base` is the vector that
+the crossover starts from: x_i for DE/current-to-rand/1, x_r1 for
+DE/rand-to-best/1/bin. When the evaluated trial vectors come back, `tell`
+replaces the parents and updates Pf and δ:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/top/top.py
+ if st.pending_phase == 1:
+ # Each evaluated trial vector faces the solution at its position; the others are kept.
+ violation = constraint_violation(st.G, st.F.shape[0])
+ replaces = offspring_replaces_parent(
+ constraint_violation(G_off, k), mean_objectives(F_off), violation[:k], mean_objectives(st.F[:k])
+ )
+ rows = np.flatnonzero(replaces)
+ X, F = st.X.copy(), st.F.copy()
+ X[rows], F[rows] = X_off[rows], F_off[rows]
+ st.X, st.F, st.G = X, F, G
+ violation = constraint_violation(st.G, st.F.shape[0])
+ st.feasible_ratio = feasible_ratio(violation)
+ st.delta = updated_delta(st.F, violation, st.delta)
+```
+
+`k` is the number of trial vectors that the budget allowed: a cut last
+generation compares only the first k pairs and keeps the other solutions. The
+violation is computed again after the replacement, so Pf and δ describe the new
+population.
+
+## Where VAMOS differs from the paper
+
+VAMOS follows jMetal's port, which follows PlatEMO's implementation where it
+differs from the paper; the [ToP lesson](../../algorithms/top.md#where-vamos-departs-from-jmetals-port)
+lists the checks against jMetal's classes. Relative to the paper:
+
+- phase 1 draws r1, r2 and r3 with replacement, instead of mutually different
+ and different from i, and uses a fixed F and CR instead of the paper's pools
+ of values;
+- the binomial crossover has no j_rand (no variable is forced from the mutant)
+ and, in DE/rand-to-best/1/bin, the variables that are not crossed come from
+ x_r1 instead of x_i; neither difference matters with CR = 1;
+- the trial vectors of phase 1 are clamped and mutated;
+- δ normalizes with the feasible solutions of the current population instead
+ of all those found, keeps its value with fewer than three feasible solutions,
+ and phase 1 also ends at 90% of the budget;
+- the mean of the objectives replaces their sum, which gives the same
+ comparisons;
+- phase 2 creates its offspring with DE/rand/1/bin and polynomial mutation
+ instead of SBX.
+
+Relative to jMetal's port:
+
+- **Budget:** exact; a cut last generation evaluates the first offspring only,
+ while jMetal can exceed the budget by up to N − 1 evaluations. The phase of a
+ generation is decided when it starts, so the decisions are jMetal's.
+- **Random draws:** in blocks, as described above, while jMetal draws them
+ solution by solution; each draw has jMetal's distribution, but runs with the
+ same seed differ.
+- **Result:** jMetal returns the whole final population, which is
+ `result.data["population"]`; `result.X` and `result.F` follow the configured
+ `result_mode`.
+
+The [ToP lesson](../../algorithms/top.md#agreement-with-jmetals-port-and-the-published-results)
+records the agreement with jMetal and with the published results.
+
+## ToP among the constrained algorithms
+
+| | CCMO, C-TAEA (lessons A6, A7) | ToP |
+| --- | --- | --- |
+| Exploring part | Runs alongside the constrained part all the time | Phase 1, before the constrained part |
+| What it explores with | The problem without constraints | A constrained single-objective problem |
+| Infeasible solutions | Kept by the helper population or the DA | Replaced by a less violated trial vector in phase 1, ranked last in phase 2 |
+| Switching rule | None | δ, Pf and an evaluation limit |
+| Variation | GA (SBX) or DE | DE in both phases |
+
+Strengths:
+
+- **Fast entry into small feasible regions.** A single objective and one-to-one
+ replacement concentrate the population quickly.
+- **Plain NSGA-II afterwards.** Phase 2 is cheap and well understood.
+
+Limits:
+
+- **The switch is a guess about the problem.** On CTP2 above, δ stays high and
+ phase 1 uses 90% of the budget, leaving 2,000 evaluations to spread the
+ population along the front.
+- **One region at a time.** The mean objective rewards one part of the front;
+ the [ToP lesson](../../algorithms/top.md#agreement-with-jmetals-port-and-the-published-results)
+ records MW3 runs whose population converges to one end of the front, and MW1
+ runs that end without a feasible solution.
+- **No exploration after the switch.** Phase 2 ranks every feasible solution
+ first, so infeasible barriers met later are not crossed.
+
+## Key points
+
+- ToP solves a constrained single-objective problem first, the mean of the
+ objectives with the feasibility rule, then the original problem with NSGA-II
+ and constrained dominance.
+- In phase 1 each trial vector faces only its own parent: a smaller violation
+ wins, then a smaller mean objective.
+- Phase 1 lasts while δ ≥ 0.2 or Pf ≤ 1/3, and at most until 90% of the budget;
+ δ measures how close the best third of the feasible solutions are.
+- Phase 2 sorts the feasible solutions into Pareto fronts and puts one front per
+ violation value after them.
+- VAMOS follows PlatEMO's implementation through jMetal's port, with DE in both
+ phases and an exact budget.
+
+**Next:** [A9. CMOEA-MS: two stages](cmoeams.md).
+
+## References
+
+[1] Liu, Z.-Z., and Wang, Y. (2019). [Handling constrained multiobjective optimization problems with constraints in both the decision and objective spaces](https://doi.org/10.1109/TEVC.2019.2894743). *IEEE Transactions on Evolutionary Computation*, 23(5), 870–884.
+
+[2] Deb, K. (2000). [An efficient constraint handling method for genetic algorithms](https://doi.org/10.1016/S0045-7825(99)00389-8). *Computer Methods in Applied Mechanics and Engineering*, 186(2–4), 311–338.
+
+[3] Deb, K., Pratap, A., Agarwal, S., and Meyarivan, T. (2002). [A fast and elitist multiobjective genetic algorithm: NSGA-II](https://doi.org/10.1109/4235.996017). *IEEE Transactions on Evolutionary Computation*, 6(2), 182–197.
+
+[4] Storn, R., and Price, K. (1997). [Differential Evolution – A Simple and Efficient Heuristic for Global Optimization over Continuous Spaces](https://doi.org/10.1023/A:1008202821328). *Journal of Global Optimization*, 11(4), 341–359.
+
+[5] Deb, K., Pratap, A., and Meyarivan, T. (2001). [Constrained test problems for multi-objective evolutionary optimization](https://doi.org/10.1007/3-540-44719-9_20). *Evolutionary Multi-Criterion Optimization – EMO 2001*, Lecture Notes in Computer Science 1993, 284–298.
diff --git a/docs/foundations/basic/multi-objective-problems.md b/docs/foundations/basic/multi-objective-problems.md
new file mode 100644
index 000000000..1ce3ea130
--- /dev/null
+++ b/docs/foundations/basic/multi-objective-problems.md
@@ -0,0 +1,220 @@
+---
+description: 'B1. What a multi-objective optimization problem is: decision and objective spaces, conflicting objectives, why weighted sums are not enough, and why population-based algorithms are used.'
+search:
+ boost: 0.5
+---
+
+# B1. What is a multi-objective problem?
+
+Most real decisions have more than one goal. A bridge should be light **and**
+stiff; a machine-learning model should be accurate **and** small; a production
+plan should be cheap **and** fast **and** clean. When improving one goal makes
+another worse, there is no single best answer, only a set of best
+compromises. Multi-objective optimization finds that set.
+
+In this lesson you will learn:
+
+- how a multi-objective problem is written, and what its two spaces are;
+- why conflicting objectives produce a set of solutions instead of one;
+- why adding the objectives into one weighted sum is not enough;
+- why evolutionary algorithms, which work with a population, fit this task.
+
+## The formal problem
+
+A multi-objective optimization problem with *m* objectives is written as
+
+minimize F(x) = ( f₁(x), f₂(x), …, f_m(x) )
+subject to g_j(x) ≤ 0, j = 1, …, J
+ x ∈ X, for example x_iᴸ ≤ x_i ≤ x_iᵁ, i = 1, …, n
+
+- **x** = (x₁, …, x_n) is a *decision vector*: one candidate design, plan or
+ model. The set X of allowed vectors is the **decision space** (or search
+ space). Each x_i is a *decision variable*; here they are real numbers
+ between bounds, but they can also be integers, bits or permutations.
+- **F(x)** is the *objective vector* of that candidate. The set of all
+ objective vectors is the **objective space**. VAMOS minimizes every
+ objective: an objective to maximize is passed as its negative, −f(x).
+- **g_j(x) ≤ 0** are inequality *constraints*. A candidate that satisfies all
+ of them is *feasible*. VAMOS uses exactly this convention, `G <= 0`; lesson
+ [A5](../advanced/constrained.md) is devoted to constraints.
+
+Problems with two or three objectives are usually called *multi-objective*.
+With four or more, they are called *many-objective*, because, as lesson
+[A1](../advanced/many-objective.md) shows, several mechanisms that work well
+with two objectives stop working.
+
+## Two spaces
+
+The optimizer changes the decision vector, but we judge the result by its
+objective vector. The figure below uses a two-variable relative of the ZDT1
+benchmark [1]:
+
+f₁(x) = x₁
+f₂(x) = g · ( 1 − √(x₁ / g) ), where g = 1 + x₂, 0 ≤ x₁, x₂ ≤ 1
+
+The grey dots are random designs (left) and their objective vectors (right).
+The orange point is a design you control: drag it, or focus it and use the
+arrow keys.
+
+
+
+Three things to notice:
+
+1. **The mapping is not one-to-one.** Moving x₂ upwards moves F(x) upwards
+ without changing f₁: the variable x₂ only adds "distance" from the best
+ trade-offs.
+2. **The best designs form a set.** Every design with x₂ = 0 is a best
+ compromise: you cannot lower f₁ without raising f₂. Those designs are the
+ *Pareto set* (blue segment on the left); their objective vectors form the
+ *Pareto front* (blue curve on the right). Lesson
+ [B2](pareto-dominance.md) defines both precisely.
+3. **The front, not the set, is what a decision maker looks at.** It answers
+ "how much f₂ must I accept to gain this much f₁?". The Pareto set answers
+ "which design gives me that trade-off?".
+
+## Why one optimum is not enough
+
+With one objective, any two candidates can be compared: one is better, or they
+are equal. With two conflicting objectives, a candidate can be better in f₁
+and worse in f₂. Neither is better overall; they are **incomparable**. Along
+the Pareto front every move that improves one objective costs something in
+another, and that cost is called the *trade-off*. The front shows the
+complete menu of trade-offs before anyone has to decide which one is preferred.
+
+## Turning many objectives into one: scalarization
+
+A tempting shortcut is to add the objectives with weights and solve an
+ordinary single-objective problem:
+
+minimize w₁ f₁(x) + w₂ f₂(x) + … + w_m f_m(x), w_i ≥ 0, Σ w_i = 1
+
+With strictly positive weights, the minimizer of a weighted sum is always
+Pareto optimal, and changing the weights moves along the front [2]. But the
+method has two well-known limits:
+
+- **It cannot reach non-convex parts of the front.** The contour lines of a
+ weighted sum are straight. On a front that bulges outwards (non-convex),
+ the straight line always touches the front first at an extreme point. Das
+ and Dennis [3] showed that no choice of weights reaches the interior of
+ such a front, and that evenly spaced weights do not give evenly spaced
+ solutions even on convex fronts.
+- **Weights mix units.** Adding kilograms to millimetres only makes sense once
+ both are scaled, and the result depends on that scaling.
+
+Try both fronts below. Choose the non-convex front, press **Sweep 21 weights**
+and count how many different solutions the weighted sum finds.
+
+
+
+Other scalarizations avoid the first limit. The *ε-constraint* method
+optimizes one objective and turns the others into constraints [4]; the
+*Tchebycheff* scalarization uses a weighted maximum instead of a weighted sum
+and reaches every Pareto-optimal point. Lesson
+[I6](../intermediate/beyond-nsga-ii.md) shows how MOEA/D builds a complete
+algorithm on that idea.
+
+## When do preferences enter?
+
+Somebody eventually picks one solution. Methods are classified by when that
+person, the *decision maker*, states preferences [2, 5]:
+
+- **A priori:** preferences come first, for example as weights, and one
+ solution is computed. Cheap, but the decision maker must know the trade-offs
+ before seeing them.
+- **A posteriori:** a representative approximation of the whole front is
+ computed first, and the decision maker chooses afterwards with the
+ trade-offs in view.
+- **Interactive:** computation and preference statements alternate, focusing
+ the search on the region of interest.
+
+The algorithms in VAMOS, like most evolutionary multi-objective algorithms,
+are *a posteriori* methods. [T03. From a Pareto set to a
+decision](../../tutorials/t03-pareto-decision.md) shows the decision step
+on a real result.
+
+## Why population-based algorithms?
+
+An a posteriori method must return many solutions, spread along the front.
+Evolutionary algorithms keep a *population* of candidates and improve it
+generation after generation, so a single run naturally produces a set. Schaffer's
+VEGA [6] was the first multi-objective genetic algorithm; Goldberg [7]
+proposed ranking the population by Pareto dominance, the idea that NSGA-II,
+the subject of the [Intermediate level](../intermediate/nsga-ii.md), still uses.
+Evolutionary algorithms also need no gradients, so they handle objectives that
+are noisy, discontinuous or computed by a simulator [8, 9].
+
+## In VAMOS
+
+The toy problem of the first figure can be written as a plain Python function
+and solved with NSGA-II. The returned non-dominated solutions should all have
+x₂ close to 0, the Pareto set.
+
+```python
+import numpy as np
+
+from vamos import make_problem, optimize
+
+
+def toy(x):
+ """Two decision variables and two objectives, both minimized."""
+ g = 1.0 + x[1]
+ f1 = x[0]
+ f2 = g * (1.0 - np.sqrt(f1 / g))
+ return [f1, f2]
+
+
+problem = make_problem(toy, n_var=2, n_obj=2, bounds=[(0.0, 1.0), (0.0, 1.0)], encoding="real", name="toy")
+result = optimize(problem, algorithm="nsgaii", pop_size=40, max_evaluations=4_000, engine="numpy", seed=1)
+
+front_F, front_indices = result.front(return_indices=True)
+front_X = result.X[front_indices]
+print(len(front_F), "non-dominated solutions")
+print("largest x2 among them:", round(float(front_X[:, 1].max()), 4))
+print("f1 from", round(float(front_F[:, 0].min()), 3), "to", round(float(front_F[:, 0].max()), 3))
+```
+
+Output:
+
+```text
+40 non-dominated solutions
+largest x2 among them: 0.0166
+f1 from 0.0 to 1.0
+```
+
+`result.X` holds decision vectors and `result.F` the matching objective
+vectors, row by row. The [custom problem guide](../../guide/custom-problem.md)
+explains `make_problem` in full, including constraints and vectorized
+functions.
+
+## Key points
+
+- A multi-objective problem minimizes a vector F(x) = (f₁, …, f_m) over a
+ decision space, usually subject to constraints g_j(x) ≤ 0.
+- Conflicting objectives have no single optimum; the best compromises form the
+ Pareto set (decisions) and the Pareto front (objective values).
+- Weighted sums are simple but miss non-convex parts of the front and depend
+ on scaling.
+- Evolutionary algorithms keep a population and therefore approximate the
+ whole front in one run, leaving the final choice to the decision maker.
+
+**Next:** [B2. Pareto dominance and the Pareto front](pareto-dominance.md).
+
+## References
+
+[1] Zitzler, E., Deb, K., and Thiele, L. (2000). [Comparison of multiobjective evolutionary algorithms: Empirical results](https://doi.org/10.1162/106365600568202). *Evolutionary Computation*, 8(2), 173–195.
+
+[2] Miettinen, K. (1999). [*Nonlinear Multiobjective Optimization*](https://doi.org/10.1007/978-1-4615-5563-6). Kluwer Academic Publishers.
+
+[3] Das, I., and Dennis, J. E. (1997). [A closer look at drawbacks of minimizing weighted sums of objectives for Pareto set generation in multicriteria optimization problems](https://doi.org/10.1007/BF01197559). *Structural Optimization*, 14(1), 63–69.
+
+[4] Haimes, Y. Y., Lasdon, L. S., and Wismer, D. A. (1971). [On a bicriterion formulation of the problems of integrated system identification and system optimization](https://doi.org/10.1109/TSMC.1971.4308298). *IEEE Transactions on Systems, Man, and Cybernetics*, SMC-1(3), 296–297.
+
+[5] Branke, J., Deb, K., Miettinen, K., and Słowiński, R. (Eds.) (2008). [*Multiobjective Optimization: Interactive and Evolutionary Approaches*](https://doi.org/10.1007/978-3-540-88908-3). Lecture Notes in Computer Science 5252, Springer.
+
+[6] Schaffer, J. D. (1985). Multiple objective optimization with vector evaluated genetic algorithms. *Proceedings of the First International Conference on Genetic Algorithms and Their Applications*, 93–100.
+
+[7] Goldberg, D. E. (1989). *Genetic Algorithms in Search, Optimization and Machine Learning*. Addison-Wesley.
+
+[8] Deb, K. (2001). *Multi-Objective Optimization Using Evolutionary Algorithms*. Wiley.
+
+[9] Coello Coello, C. A., Lamont, G. B., and Van Veldhuizen, D. A. (2007). [*Evolutionary Algorithms for Solving Multi-Objective Problems*](https://doi.org/10.1007/978-0-387-36797-2) (2nd ed.). Springer.
diff --git a/docs/foundations/basic/pareto-dominance.md b/docs/foundations/basic/pareto-dominance.md
new file mode 100644
index 000000000..2e75fe584
--- /dev/null
+++ b/docs/foundations/basic/pareto-dominance.md
@@ -0,0 +1,209 @@
+---
+description: 'B2. Pareto dominance, weak dominance and incomparability; the Pareto set and front; non-dominated sets, ideal and nadir points, front shapes and knees, with an interactive dominance explorer.'
+search:
+ boost: 0.5
+---
+
+# B2. Pareto dominance and the Pareto front
+
+Lesson [B1](multi-objective-problems.md) showed that two candidates can be
+incomparable. This lesson makes "better" precise for vectors, defines the
+Pareto set and front, and introduces the reference points used to normalize
+objectives.
+
+In this lesson you will learn:
+
+- the definitions of Pareto dominance, weak dominance and incomparability;
+- what Pareto optimality, the Pareto set and the Pareto front are;
+- the difference between a non-dominated set and the Pareto front;
+- what the ideal and nadir points are and how front shapes differ.
+
+## Comparing objective vectors
+
+Numbers have a total order: for any two of them, one is smaller or they are
+equal. Vectors do not. Is (2, 3) better than (3, 2)? It depends on which
+objective matters more, and that is a preference, not a fact. Pareto
+dominance is the strongest statement that can be made **without** any
+preference, and it is named after Vilfredo Pareto, who used the idea in
+economics [1].
+
+For two objective vectors **a** and **b** of a minimization problem:
+
+a ≺ b (a dominates b) ⇔ a_i ≤ b_i for every i, and a_j < b_j for at least one j
+a ⪯ b (a weakly dominates b) ⇔ a_i ≤ b_i for every i
+a ≺≺ b (a strictly dominates b) ⇔ a_i < b_i for every i
+a ∥ b (incomparable) ⇔ neither a ⪯ b nor b ⪯ a
+
+In words: **a** dominates **b** when it is at least as good in every objective
+and strictly better in at least one. Dominance is transitive (if a ≺ b and
+b ≺ c then a ≺ c) and never holds in both directions, but two vectors may not
+be related at all: it is a *partial* order [2, 3].
+
+Geometrically, a point dominates everything in the box above and to its right,
+and is dominated by everything in the box below and to its left. The other two
+quadrants contain the incomparable points. Explore it below: select a point,
+drag it, or focus it and move it with the arrow keys.
+
+
+
+## Pareto optimality
+
+A feasible decision vector x* is **Pareto optimal** when no feasible x has
+F(x) ≺ F(x*): nothing improves an objective without worsening another [2, 4].
+
+- The **Pareto set** PS is the set of all Pareto-optimal decision vectors.
+- The **Pareto front** PF = { F(x) : x ∈ PS } is their image in objective space.
+
+Two refinements matter in practice:
+
+- **Weak Pareto optimality.** x* is *weakly* Pareto optimal when no x
+ strictly dominates it. Such a point may still be improved in one objective
+ without loss in the others. A flat stretch at the end of a front contains
+ weakly Pareto-optimal points.
+- **Local Pareto optimality.** x* is *locally* Pareto optimal when no
+ dominating vector exists *in a neighbourhood* of x*. Many benchmark problems
+ have local fronts that trap algorithms: in ZDT4, for example, 21⁹ of them [5].
+
+## Non-dominated sets are not the Pareto front
+
+An algorithm only ever sees the finite set of candidates it has evaluated. The
+members of that set that no other member dominates form its **non-dominated
+set**. A set whose members are mutually non-dominated is called an
+**approximation set** [6]. It is the best that run found, but it is the Pareto
+front only if the run found truly Pareto-optimal vectors. Keep the two apart:
+"non-dominated" is relative to a set, "Pareto optimal" is relative to the
+whole problem.
+
+## Ideal and nadir points
+
+Two reference vectors summarize the range of the front:
+
+- the **ideal point** z* has, in each objective, the best value over the Pareto
+ front: z*_i = min { f_i(x) : x ∈ PS };
+- the **nadir point** z^nad has, in each objective, the worst value over the
+ Pareto front: z^nad_i = max { f_i(x) : x ∈ PS }.
+
+The ideal point is usually not attainable (otherwise the objectives would not
+conflict). Together they define the box that contains the front, and they are
+used to **normalize** objectives measured in different units:
+
+f̃_i(x) = ( f_i(x) − z*_i ) / ( z^nad_i − z*_i )
+
+With two objectives, the nadir point is given by the two extremes of the front.
+With three or more, it is hard to estimate because extreme points of the
+non-dominated set can come from dominated regions of the true front [7].
+Enable the option in the figure above to see the ideal and nadir points of the
+current non-dominated set.
+
+## Shapes of Pareto fronts
+
+The geometry of the front affects which methods work:
+
+- **Convex** fronts bulge towards the ideal point (ZDT1). Every point can be
+ found with a weighted sum.
+- **Non-convex** (concave) fronts bulge away from it (ZDT2). Weighted sums only
+ find their extremes, as you saw in [B1](multi-objective-problems.md#turning-many-objectives-into-one-scalarization).
+- **Disconnected** fronts have gaps (ZDT3). Algorithms must keep several
+ separate groups of solutions.
+- **Degenerate** fronts have a lower dimension than m − 1, for example a curve
+ in a three-objective space.
+
+The ZDT problems were designed by Zitzler, Deb and Thiele to isolate these
+features with two objectives [5]; the DTLZ problems scale them to any number of
+objectives [8]. The [problem reference](../../reference/problems.md) lists
+every benchmark that VAMOS ships.
+
+## Choosing one solution: knees
+
+When the decision maker has no strong preference, a common choice is a
+**knee**: a point where a small gain in one objective costs a large loss in
+another, so moving away from it in any direction is a poor bargain [9].
+[T03](../../tutorials/t03-pareto-decision.md) selects a solution from a real
+VAMOS result with explicit preferences.
+
+## In VAMOS
+
+Pareto dominance takes two lines of NumPy. The non-dominated subset of a
+finite set follows directly:
+
+```python
+import numpy as np
+
+
+def dominates(a, b):
+ """True when a Pareto-dominates b; every objective is minimized."""
+ a, b = np.asarray(a), np.asarray(b)
+ return bool(np.all(a <= b) and np.any(a < b))
+
+
+F = np.array([[1.0, 5.0], [2.0, 3.0], [3.0, 4.0], [4.0, 1.0], [2.5, 2.5]])
+print(dominates(F[1], F[2])) # (2, 3) is better than (3, 4) in both objectives
+print(dominates(F[0], F[3])) # (1, 5) and (4, 1) are incomparable
+non_dominated = [i for i in range(len(F)) if not any(dominates(F[j], F[i]) for j in range(len(F)))]
+print(non_dominated)
+```
+
+Output:
+
+```text
+True
+False
+[0, 1, 3, 4]
+```
+
+A VAMOS result does this for you. `OptimizationResult.front()` returns the
+non-dominated rows of `result.F`, and their indices when you also need the
+decision vectors:
+
+```python
+from vamos import optimize
+
+result = optimize("zdt1", algorithm="nsgaii", pop_size=40, max_evaluations=400, engine="numpy", seed=42)
+front_F, front_indices = result.front(return_indices=True)
+print("returned:", result.F.shape, "non-dominated:", front_F.shape)
+print("decisions of the non-dominated rows:", result.X[front_indices].shape)
+```
+
+Output:
+
+```text
+returned: (40, 2) non-dominated: (12, 2)
+decisions of the non-dominated rows: (12, 30)
+```
+
+After only 400 evaluations this non-dominated set is still far from the ZDT1
+front. [Understanding results](../../guide/understanding-results.md#separate-the-returned-set-from-its-non-dominated-subset)
+draws it and explains which set `result.F` holds.
+
+## Key points
+
+- a ≺ b when a is no worse in every objective and better in at least one.
+ Many pairs are incomparable: dominance is a partial order.
+- The Pareto set holds the decisions that nothing dominates; the Pareto front
+ holds their objective vectors.
+- A non-dominated set is relative to the points evaluated; it approximates the
+ front but is not the front.
+- The ideal and nadir points bound the front and are used to normalize the
+ objectives.
+
+**Next:** [B3. What makes a good approximation?](quality-aspects.md)
+
+## References
+
+[1] Pareto, V. (1896). *Cours d'économie politique*. F. Rouge, Lausanne.
+
+[2] Miettinen, K. (1999). [*Nonlinear Multiobjective Optimization*](https://doi.org/10.1007/978-1-4615-5563-6). Kluwer Academic Publishers.
+
+[3] Ehrgott, M. (2005). [*Multicriteria Optimization*](https://doi.org/10.1007/3-540-27659-9) (2nd ed.). Springer.
+
+[4] Deb, K. (2001). *Multi-Objective Optimization Using Evolutionary Algorithms*. Wiley.
+
+[5] Zitzler, E., Deb, K., and Thiele, L. (2000). [Comparison of multiobjective evolutionary algorithms: Empirical results](https://doi.org/10.1162/106365600568202). *Evolutionary Computation*, 8(2), 173–195.
+
+[6] Zitzler, E., Thiele, L., Laumanns, M., Fonseca, C. M., and Grunert da Fonseca, V. (2003). [Performance assessment of multiobjective optimizers: An analysis and review](https://doi.org/10.1109/TEVC.2003.810758). *IEEE Transactions on Evolutionary Computation*, 7(2), 117–132.
+
+[7] Deb, K., Miettinen, K., and Chaudhuri, S. (2010). [Toward an estimation of nadir objective vector using a hybrid of evolutionary and local search approaches](https://doi.org/10.1109/TEVC.2010.2041667). *IEEE Transactions on Evolutionary Computation*, 14(6), 821–841.
+
+[8] Deb, K., Thiele, L., Laumanns, M., and Zitzler, E. (2005). [Scalable test problems for evolutionary multiobjective optimization](https://doi.org/10.1007/1-84628-137-7_6). In A. Abraham, L. Jain and R. Goldberg (Eds.), *Evolutionary Multiobjective Optimization*, 105–145. Springer.
+
+[9] Branke, J., Deb, K., Dierolf, H., and Osswald, M. (2004). [Finding knees in multi-objective optimization](https://doi.org/10.1007/978-3-540-30217-9_73). *Parallel Problem Solving from Nature – PPSN VIII*, Lecture Notes in Computer Science 3242, 722–731.
diff --git a/docs/foundations/basic/quality-aspects.md b/docs/foundations/basic/quality-aspects.md
new file mode 100644
index 000000000..ed900f6b0
--- /dev/null
+++ b/docs/foundations/basic/quality-aspects.md
@@ -0,0 +1,164 @@
+---
+description: 'B3. The quality aspects of an approximation set (convergence, spread, uniformity and cardinality), how sets are compared by dominance, and why no single number can say everything.'
+search:
+ boost: 0.5
+---
+
+# B3. What makes a good approximation?
+
+An algorithm returns an approximation set, not the Pareto front. Two runs, or
+two algorithms, return different sets. Before measuring them with numbers
+(lesson [B4](quality-indicators.md)), we need to agree on **what** a good set
+looks like.
+
+In this lesson you will learn:
+
+- the four quality aspects of an approximation set;
+- how two sets are compared using dominance alone, and why that is often
+ inconclusive;
+- why one number cannot capture every aspect.
+
+## The four quality aspects
+
+Zitzler, Deb and Thiele [1] stated the goals of an a posteriori algorithm as
+three: a small distance to the Pareto front, a good (in most cases uniform)
+distribution of the solutions, and a large extent of the front covered. The
+survey of Li and Yao [2], which reviews about one hundred indicators, groups
+the properties of a set into four aspects:
+
+| Aspect | The question it answers | A set that fails it |
+| --- | --- | --- |
+| **Convergence** | How close are the points to the Pareto front? | A perfectly spread set far from the front. |
+| **Spread** (extent, coverage) | How much of the front's range does the set cover? | A set clustered around one end of the front. |
+| **Uniformity** (evenness) | Are the points evenly distributed along what they cover? | Points bunched together with large gaps between groups. |
+| **Cardinality** | How many non-dominated points does the set offer? | Two excellent points where the decision maker needed choices. |
+
+Spread and uniformity together are often called **diversity**. Convergence
+and diversity pull in different directions: an algorithm that pushes hard
+towards the front tends to lose diversity, and one that preserves diversity
+spends evaluations away from the front. NSGA-II balances them with two
+criteria, ranks and crowding distances (lessons
+[I2](../intermediate/non-dominated-sorting.md) and
+[I3](../intermediate/crowding-distance.md)).
+
+## See the aspects one at a time
+
+The figure builds an approximation set of the ZDT1 front with four sliders,
+one for each aspect: the distance added to every point, the share of the
+front's range covered, how strongly the points cluster towards one end, and
+how many points there are. The table shows how a few indicators react; B4
+defines them.
+
+
+
+Things to try:
+
+1. Set the **convergence gap** to 0 and the **extent** to 20%. GD stays near
+ zero, because every point lies on the front, yet four fifths of the front
+ are missing. IGD and the hypervolume notice it.
+2. Set the extent back to 100% and increase **clustering**. GD barely moves,
+ spacing and IGD grow, and the hypervolume drops slightly.
+3. Reduce the **points** to 2. The hypervolume collapses and IGD grows
+ fivefold, GD hardly changes, and spacing reports a perfect 0, because two
+ points are always evenly spaced. Indicators that each see one aspect can
+ disagree completely.
+
+## Comparing two sets by dominance
+
+Before choosing an indicator, note what dominance alone can say about two
+approximation sets A and B [3]:
+
+A ≺≺ B every b ∈ B is strictly dominated by some a ∈ A
+A ≺ B every b ∈ B is dominated by some a ∈ A
+A ⪯ B A weakly dominates B: every b ∈ B is weakly dominated by some a ∈ A
+A ◁ B A is better than B: A ⪯ B, but not B ⪯ A
+A ∥ B incomparable: neither A ⪯ B nor B ⪯ A
+
+When A ◁ B, A is better than B under **every** preference a decision maker
+could hold. That is the only conclusion free of assumptions, but it is rare:
+two good algorithms usually produce incomparable sets, each better in some
+region of the front. To go further we must add preferences, for example "I
+care about the whole front equally", and that is what a quality indicator
+encodes.
+
+## Why one number cannot say everything
+
+A *unary* quality indicator maps one approximation set to one real number.
+Zitzler et al. [3] proved that no unary indicator, and no finite combination
+of them, can in general detect whether A is better than B; the best an
+indicator can guarantee is that a better value means "not worse". Any single
+number is therefore a summary that weights the aspects in its own way. Three
+practical consequences:
+
+- **Choose indicators for the question.** Convergence-only measures suit a
+ question about convergence; a decision maker who needs the whole front needs
+ an indicator that rewards spread.
+- **Use more than one indicator**, and check that their conclusions agree.
+- **Look at the sets.** For two objectives, a plot of the sets, or of their
+ attainment surfaces (lesson [A10](../advanced/performance-assessment.md)),
+ often shows what the numbers hide.
+
+## Scale matters
+
+Every aspect depends on the units of the objectives. If f₁ is in metres and f₂
+in millimetres, distances are dominated by f₂ and "uniform" means uniform in
+millimetres. Normalize the objectives with fixed bounds, for example the ideal
+and nadir points of a reference front (lesson
+[B2](pareto-dominance.md#ideal-and-nadir-points)), **before** computing
+distances, and use the same bounds for every algorithm you compare.
+
+## In VAMOS
+
+The returned set has a cardinality you can read directly, and its quality
+aspects can be inspected against a known front. For ZDT1 the front is
+f₂ = 1 − √f₁, so the vertical gap of each point is a direct convergence check,
+and the covered range of f₁ measures the spread:
+
+```python
+import numpy as np
+
+from vamos import optimize
+
+result = optimize("zdt1", algorithm="nsgaii", pop_size=100, max_evaluations=10_000, engine="numpy", seed=7)
+front = result.front()
+f1, f2 = front[:, 0], front[:, 1]
+gap = f2 - (1.0 - np.sqrt(f1))
+spacing = np.diff(np.sort(f1))
+
+print("cardinality:", len(front))
+print("convergence, mean vertical gap:", round(float(gap.mean()), 4))
+print("spread, f1 covered:", round(float(f1.min()), 3), "to", round(float(f1.max()), 3))
+print("uniformity, largest / median gap in f1:", round(float(spacing.max() / np.median(spacing)), 1))
+```
+
+Output:
+
+```text
+cardinality: 100
+convergence, mean vertical gap: 0.0261
+spread, f1 covered: 0.0 to 0.995
+uniformity, largest / median gap in f1: 4.2
+```
+
+These ad hoc measures are useful for intuition on a problem whose front is
+known. The next lesson introduces the standard indicators, which work on any
+problem given a reference point or reference set.
+
+## Key points
+
+- Judge an approximation set on convergence, spread, uniformity and
+ cardinality; diversity is spread plus uniformity.
+- Dominance between sets (A ◁ B) is preference-free but often inconclusive.
+- No single unary indicator can establish that one set is better than another;
+ use several, chosen for the question, and look at the sets.
+- Normalize objectives with fixed bounds before measuring distances.
+
+**Next:** [B4. Quality indicators](quality-indicators.md).
+
+## References
+
+[1] Zitzler, E., Deb, K., and Thiele, L. (2000). [Comparison of multiobjective evolutionary algorithms: Empirical results](https://doi.org/10.1162/106365600568202). *Evolutionary Computation*, 8(2), 173–195.
+
+[2] Li, M., and Yao, X. (2019). [Quality evaluation of solution sets in multiobjective optimisation: A survey](https://doi.org/10.1145/3300148). *ACM Computing Surveys*, 52(2), Article 26.
+
+[3] Zitzler, E., Thiele, L., Laumanns, M., Fonseca, C. M., and Grunert da Fonseca, V. (2003). [Performance assessment of multiobjective optimizers: An analysis and review](https://doi.org/10.1109/TEVC.2003.810758). *IEEE Transactions on Evolutionary Computation*, 7(2), 117–132.
diff --git a/docs/foundations/basic/quality-indicators.md b/docs/foundations/basic/quality-indicators.md
new file mode 100644
index 000000000..ae23d9b84
--- /dev/null
+++ b/docs/foundations/basic/quality-indicators.md
@@ -0,0 +1,291 @@
+---
+description: 'B4. Quality indicators for approximation sets: hypervolume, GD, IGD, IGD+, additive epsilon, spacing and spread; Pareto compliance, reference points and reference sets, with interactive figures and MooCore code on a VAMOS result.'
+search:
+ boost: 0.5
+---
+
+# B4. Quality indicators
+
+A quality indicator turns an approximation set into a number, so that runs
+and algorithms can be compared. Lesson [B3](quality-aspects.md) showed that
+any single number weights the quality aspects in its own way. This lesson
+defines the indicators in common use, shows what each one sees, and explains
+the property that matters most when choosing one: Pareto compliance.
+
+In this lesson you will learn:
+
+- the definitions of hypervolume, GD, IGD, IGD+ and the additive ε-indicator;
+- what Pareto compliance is, and which indicators have it;
+- how reference points and reference sets change the results;
+- how to compute the indicators for a VAMOS result.
+
+## What an indicator needs
+
+Every indicator below takes an approximation set A of *m*-dimensional
+objective vectors, all minimized, plus reference data fixed **in advance**:
+
+| Indicator | Reference data | Better | Pareto compliant | Introduced by |
+| --- | --- | --- | --- | --- |
+| Hypervolume (HV) | a reference point r | higher | yes, strictly | Zitzler and Thiele [1, 2] |
+| Generational distance (GD) | a reference set R | lower | no | Van Veldhuizen and Lamont [3] |
+| Inverted generational distance (IGD) | a reference set R | lower | no | Coello Coello and Reyes Sierra [4, 5] |
+| IGD+ | a reference set R | lower | weakly | Ishibuchi et al. [6] |
+| Additive ε-indicator (ε+) | a reference set R | lower | weakly | Zitzler et al. [7] |
+| Spacing | none | lower | no | Schott [8] |
+| Spread Δ | the extremes of the front | lower | no | Deb et al. [9] |
+
+The reference set R is usually a dense sample of the true Pareto front, which
+benchmark problems provide. For a real problem, the non-dominated union of all
+the sets being compared is a common substitute [10].
+
+## Pareto compliance
+
+An indicator I (where higher is better) is
+
+- **strictly Pareto compliant** if A ◁ B implies I(A) > I(B): a better set always
+ scores strictly better;
+- **weakly Pareto compliant** if A ⪯ B implies I(A) ≥ I(B): a better set never
+ scores worse.
+
+(For indicators where lower is better, reverse the inequalities.) An indicator
+that is not compliant can rank a set that dominates another one **below** it.
+That is not a theoretical curiosity; the example further down shows it with
+two points.
+
+## Hypervolume
+
+The hypervolume of A is the size of the region of objective space that A
+dominates and that is bounded by the reference point r [1, 2]:
+
+HV(A; r) = λ( ⋃_{a ∈ A, a ≺ r} [a₁, r₁] × [a₂, r₂] × … × [a_m, r_m] )
+
+where λ is the Lebesgue measure: area with two objectives, volume with three.
+Each point contributes the box between itself and r; overlapping parts count
+once. Drag the five points or the reference point r:
+
+
+
+The hypervolume has unique strengths:
+
+- It is the only commonly used unary indicator known to be **strictly Pareto
+ compliant** [7]. A set of a given size that maximizes it contains only
+ Pareto-optimal points [11].
+- It needs no reference set, only a reference point, so it applies to problems
+ whose front is unknown.
+- It rewards all four aspects at once: convergence, spread, uniformity and
+ cardinality.
+
+And real costs:
+
+- **Computation** is fast for two and three objectives (O(n log n) for n points)
+ but grows exponentially with the number of objectives; the exact problem is
+ #P-hard [12, 13]. Guerreiro, Fonseca and Paquete survey the algorithms [14].
+- **The reference point changes the ranking.** Points beyond r contribute
+ nothing, and r controls how much the extremes are worth. After normalizing
+ each objective to [0, 1], r = (1.1, …, 1.1) is a common choice; Auger et al.
+ [15] and Ishibuchi et al. [16] analyse the bias that the choice introduces.
+- **Scale matters.** Normalize the objectives with fixed bounds first.
+
+The area that only one point dominates is its **exclusive contribution**:
+the hypervolume lost if that point is removed. SMS-EMOA builds its selection on
+it (lesson [I6](../intermediate/beyond-nsga-ii.md)). The contributions are
+measured among the non-dominated points, as VAMOS and MooCore's
+`hv_contributions` measure them by default: a dominated point adds no
+hypervolume, so it contributes 0 and is left out when the contributions of the
+others are measured, and two equal points contribute 0 each, because each one
+covers the area of the other. Drag a point behind another one in the figure to
+see it.
+
+## Distance-based indicators
+
+The other indicators measure distances between A and a reference set R. With
+‖·‖ the Euclidean distance:
+
+GD(A, R) = (1 / |A|) · Σ_{a ∈ A} min_{r ∈ R} ‖a − r‖
+IGD(A, R) = (1 / |R|) · Σ_{r ∈ R} min_{a ∈ A} ‖a − r‖
+IGD+(A, R) = (1 / |R|) · Σ_{r ∈ R} min_{a ∈ A} d⁺(a, r), d⁺(a, r) = √( Σ_i max(a_i − r_i, 0)² )
+ε+(A, R) = max_{r ∈ R} min_{a ∈ A} max_i ( a_i − r_i )
+
+- **GD** looks from A to the front: it only measures convergence. A single
+ well-placed point scores perfectly.
+- **IGD** looks from the front to A: a reference point far from every point of
+ A raises it, so it also measures spread and uniformity.
+- **IGD+** is IGD with a modified distance d⁺ that only counts the objectives in
+ which a is **worse** than r. That change makes it weakly Pareto compliant [6].
+- **ε+** is the smallest amount by which A must be translated towards the
+ origin so that every reference point is weakly dominated. It is a
+ worst-case measure: one uncovered region decides its value [7].
+
+GD and IGD appear in the literature with an exponent p, as
+(Σ dᵖ)^(1/p) / n. Van Veldhuizen and Lamont used p = 2 [3]; the mean distance
+shown here (p = 1) is the version of MooCore and of
+[VAMOS' indicator guide](../../dev/add_metric.md#indicator-contract). Always
+state which one you report. The averaged Hausdorff distance,
+Δ_p = max(GD_p, IGD_p), combines both directions [17].
+
+Select an indicator and drag the points of A to see which distances it uses:
+
+
+
+## Pareto compliance in action
+
+Take a reference set with the two extremes of a linear front, and two
+single-point sets. A = {(0, 0.6)} dominates B = {(0.5, 0.6)}: it is better in f₁
+and equal in f₂. A compliant indicator must not prefer B.
+
+```python
+import moocore
+import numpy as np
+
+reference_set = np.array([[0.0, 1.0], [1.0, 0.0]])
+A = np.array([[0.0, 0.6]])
+B = np.array([[0.5, 0.6]]) # A dominates B: better f1, equal f2
+
+for name, approximation in (("A", A), ("B", B)):
+ igd = moocore.igd(approximation, ref=reference_set)
+ igd_plus = moocore.igd_plus(approximation, ref=reference_set)
+ epsilon = moocore.epsilon_additive(approximation, ref=reference_set)
+ hv = moocore.hypervolume(approximation, ref=[1.1, 1.1])
+ print(f"{name}: IGD {igd:.3f} IGD+ {igd_plus:.3f} eps+ {epsilon:.3f} HV {hv:.3f}")
+```
+
+Output:
+
+```text
+A: IGD 0.783 IGD+ 0.300 eps+ 0.600 HV 0.550
+B: IGD 0.711 IGD+ 0.550 eps+ 0.600 HV 0.300
+```
+
+IGD prefers B, the dominated set, because B happens to lie closer to the
+reference point (1, 0). IGD+ and the hypervolume prefer A. The additive ε gives
+both the same value: weak compliance allows a tie, never a reversal.
+
+## Diversity-only indicators
+
+Two older indicators measure the distribution of A and nothing else:
+
+Spacing(A) = √( 1/(|A| − 1) · Σ_i ( d̄ − d_i )² ), d_i = min_{j ≠ i} Σ_k | a_{i,k} − a_{j,k} |
+Δ(A) = ( d_f + d_l + Σ_{i=1}^{N−1} | d_i − d̄ | ) / ( d_f + d_l + (N − 1) · d̄ )
+
+Schott's **spacing** [8] is the standard deviation of the nearest-neighbour
+distances: 0 for a perfectly even set. Deb's **spread** Δ [9], for two
+objectives, uses the N − 1 distances d_i between consecutive points and the
+distances d_f and d_l from the extremes of the true front to the extremes of
+A: it penalizes both uneven gaps and missing ends. Neither looks at
+convergence, so both must be paired with another indicator.
+
+## All the indicators side by side
+
+The playground of B3 with every indicator of this lesson. Watch which values
+move when you change a single aspect.
+
+
+
+## Choosing and using indicators
+
+1. **Fix the reference data before running anything**: the reference point,
+ the reference set, and the normalization bounds. Choosing them after
+ seeing the results invites bias.
+2. **Normalize** every objective with the same fixed bounds for all the sets
+ compared, for example the ideal and nadir points of the reference front.
+3. **Prefer compliant indicators**: the hypervolume, IGD+ or ε+. Use GD,
+ spacing or spread only as complements that explain *why* a set is good or bad.
+4. **Report more than one** indicator, its direction, and its exact variant
+ (for example IGD with p = 1).
+5. **Measure only feasible, non-dominated points** for a constrained problem,
+ and report the share of feasible runs separately (lesson
+ [A5](../advanced/constrained.md)).
+
+## In VAMOS
+
+Compute the indicators of a VAMOS result with MooCore, using the analytical
+ZDT1 front as reference set, as the
+[quality and budget tutorial](../../tutorials/t07-quality-and-budget.md) does
+for saved studies. ZDT1 is already scaled to [0, 1] in both objectives, so no
+further normalization is needed here.
+
+```python
+import moocore
+import numpy as np
+
+from vamos import optimize
+
+result = optimize("zdt1", algorithm="nsgaii", pop_size=100, max_evaluations=10_000, engine="numpy", seed=7)
+front = result.front()
+
+f1 = np.linspace(0.0, 1.0, 1001)
+reference_set = np.column_stack([f1, 1.0 - np.sqrt(f1)]) # the ZDT1 Pareto front
+reference_point = [1.1, 1.1]
+
+print("HV ", round(moocore.hypervolume(front, ref=reference_point), 4))
+print("HV of the reference front", round(moocore.hypervolume(reference_set, ref=reference_point), 4))
+print("IGD ", round(moocore.igd(front, ref=reference_set), 4))
+print("IGD+", round(moocore.igd_plus(front, ref=reference_set), 4))
+print("eps+", round(moocore.epsilon_additive(front, ref=reference_set), 4))
+```
+
+Output:
+
+```text
+HV 0.8459
+HV of the reference front 0.8762
+IGD 0.0177
+IGD+ 0.0176
+eps+ 0.0241
+```
+
+The exact front has a hypervolume of 1.21 − 1/3 ≈ 0.8767 for this reference
+point; the 1,001-point sample of it reaches 0.8762. This run therefore attains
+about 96.5% of the best possible value after 10,000 evaluations. Durable VAMOS studies record the
+same indicators for every run: see the
+[study lifecycle guide](../../guide/studies.md) and
+[T07](../../tutorials/t07-quality-and-budget.md).
+
+## Key points
+
+- The hypervolume is strictly Pareto compliant and needs only a reference
+ point, but its value depends on that point and on the scaling.
+- IGD+ and ε+ are weakly compliant; GD and IGD are not, and can prefer a
+ dominated set.
+- Fix reference points, reference sets and normalization bounds before
+ running, and report the exact variant of each indicator.
+- Spacing and spread describe the distribution only; pair them with a
+ convergence-aware indicator.
+
+**Next level:** [I1. NSGA-II at a glance](../intermediate/nsga-ii.md).
+
+## References
+
+[1] Zitzler, E., and Thiele, L. (1998). [Multiobjective optimization using evolutionary algorithms – A comparative case study](https://doi.org/10.1007/BFb0056872). *Parallel Problem Solving from Nature – PPSN V*, Lecture Notes in Computer Science 1498, 292–301.
+
+[2] Zitzler, E., and Thiele, L. (1999). [Multiobjective evolutionary algorithms: A comparative case study and the strength Pareto approach](https://doi.org/10.1109/4235.797969). *IEEE Transactions on Evolutionary Computation*, 3(4), 257–271.
+
+[3] Van Veldhuizen, D. A., and Lamont, G. B. (2000). [On measuring multiobjective evolutionary algorithm performance](https://doi.org/10.1109/CEC.2000.870296). *Proceedings of the 2000 Congress on Evolutionary Computation*, 204–211.
+
+[4] Coello Coello, C. A., and Reyes Sierra, M. (2004). [A study of the parallelization of a coevolutionary multi-objective evolutionary algorithm](https://doi.org/10.1007/978-3-540-24694-7_71). *MICAI 2004: Advances in Artificial Intelligence*, Lecture Notes in Computer Science 2972, 688–697.
+
+[5] Coello Coello, C. A., and Cruz Cortés, N. (2005). [Solving multiobjective optimization problems using an artificial immune system](https://doi.org/10.1007/s10710-005-6164-x). *Genetic Programming and Evolvable Machines*, 6(2), 163–190.
+
+[6] Ishibuchi, H., Masuda, H., Tanigaki, Y., and Nojima, Y. (2015). [Modified distance calculation in generational distance and inverted generational distance](https://doi.org/10.1007/978-3-319-15892-1_8). *Evolutionary Multi-Criterion Optimization – EMO 2015*, Lecture Notes in Computer Science 9019, 110–125.
+
+[7] Zitzler, E., Thiele, L., Laumanns, M., Fonseca, C. M., and Grunert da Fonseca, V. (2003). [Performance assessment of multiobjective optimizers: An analysis and review](https://doi.org/10.1109/TEVC.2003.810758). *IEEE Transactions on Evolutionary Computation*, 7(2), 117–132.
+
+[8] Schott, J. R. (1995). *Fault tolerant design using single and multicriteria genetic algorithm optimization*. Master's thesis, Massachusetts Institute of Technology.
+
+[9] Deb, K., Pratap, A., Agarwal, S., and Meyarivan, T. (2002). [A fast and elitist multiobjective genetic algorithm: NSGA-II](https://doi.org/10.1109/4235.996017). *IEEE Transactions on Evolutionary Computation*, 6(2), 182–197.
+
+[10] Knowles, J., Thiele, L., and Zitzler, E. (2006). *A tutorial on the performance assessment of stochastic multiobjective optimizers*. TIK Report 214, Computer Engineering and Networks Laboratory, ETH Zurich.
+
+[11] Fleischer, M. (2003). [The measure of Pareto optima: Applications to multi-objective metaheuristics](https://doi.org/10.1007/3-540-36970-8_37). *Evolutionary Multi-Criterion Optimization – EMO 2003*, Lecture Notes in Computer Science 2632, 519–533.
+
+[12] Beume, N., Fonseca, C. M., López-Ibáñez, M., Paquete, L., and Vahrenhold, J. (2009). [On the complexity of computing the hypervolume indicator](https://doi.org/10.1109/TEVC.2009.2015575). *IEEE Transactions on Evolutionary Computation*, 13(5), 1075–1082.
+
+[13] Bringmann, K., and Friedrich, T. (2010). [Approximating the volume of unions and intersections of high-dimensional geometric objects](https://doi.org/10.1016/j.comgeo.2010.03.004). *Computational Geometry*, 43(6–7), 601–610.
+
+[14] Guerreiro, A. P., Fonseca, C. M., and Paquete, L. (2021). [The hypervolume indicator: Computational problems and algorithms](https://doi.org/10.1145/3453474). *ACM Computing Surveys*, 54(6), Article 119.
+
+[15] Auger, A., Bader, J., Brockhoff, D., and Zitzler, E. (2009). [Theory of the hypervolume indicator: Optimal μ-distributions and the choice of the reference point](https://doi.org/10.1145/1527125.1527138). *Proceedings of the Tenth ACM SIGEVO Workshop on Foundations of Genetic Algorithms (FOGA '09)*, 87–102.
+
+[16] Ishibuchi, H., Imada, R., Setoguchi, Y., and Nojima, Y. (2018). [How to specify a reference point in hypervolume calculation for fair performance comparison](https://doi.org/10.1162/evco_a_00226). *Evolutionary Computation*, 26(3), 411–440.
+
+[17] Schütze, O., Esquivel, X., Lara, A., and Coello Coello, C. A. (2012). [Using the averaged Hausdorff distance as a performance measure in evolutionary multiobjective optimization](https://doi.org/10.1109/TEVC.2011.2161872). *IEEE Transactions on Evolutionary Computation*, 16(4), 504–522.
diff --git a/docs/foundations/index.md b/docs/foundations/index.md
new file mode 100644
index 000000000..b7d3cc83d
--- /dev/null
+++ b/docs/foundations/index.md
@@ -0,0 +1,81 @@
+---
+description: 'Learn multi-objective optimization from the ground up: Pareto dominance, quality indicators, NSGA-II step by step, many-objective and constrained problems, and rigorous comparison, with interactive figures and VAMOS code.'
+---
+
+# Foundations of multi-objective optimization
+
+This learning path explains the ideas behind VAMOS rather than its interface.
+It starts from zero (what it means to optimize several objectives at once)
+and ends with the questions researchers face when they compare algorithms.
+Every lesson has interactive figures you can manipulate, runnable VAMOS code,
+and references to the papers where each idea was introduced.
+
+You need no previous knowledge of optimization. Basic mathematical notation
+(vectors, sums, minimum and maximum) is enough to follow the text; Python is
+only needed to run the code.
+
+## Three levels
+
+| Level | Lessons | After it you can |
+| --- | --- | --- |
+| **Basic** | [B1. What is a multi-objective problem?](basic/multi-objective-problems.md) · [B2. Pareto dominance and the Pareto front](basic/pareto-dominance.md) · [B3. What makes a good approximation?](basic/quality-aspects.md) · [B4. Quality indicators](basic/quality-indicators.md) | Formulate a problem with several objectives, reason with Pareto dominance, judge an approximation set and compute the standard quality indicators. |
+| **Intermediate** | [I1. NSGA-II at a glance](intermediate/nsga-ii.md) · [I2. Fast non-dominated sorting](intermediate/non-dominated-sorting.md) · [I3. Crowding distance and tournament selection](intermediate/crowding-distance.md) · [I4. Variation: SBX and polynomial mutation](intermediate/variation-operators.md) · [I5. Elitist survival and the complete generation](intermediate/elitist-survival.md) · [I6. Beyond NSGA-II](intermediate/beyond-nsga-ii.md) · [I7. SPEA2](intermediate/spea2.md) · [I8. MOEA/D](intermediate/moead.md) · [I9. SMS-EMOA](intermediate/smsemoa.md) · [I10. IBEA](intermediate/ibea.md) · [I11. SMPSO](intermediate/smpso.md) | Explain every step of NSGA-II and the code that implements it in VAMOS, place it among the Pareto-based, decomposition-based and indicator-based families, and explain in the same depth SPEA2, MOEA/D, SMS-EMOA, IBEA and SMPSO. |
+| **Advanced** | [A1. Many-objective optimization](advanced/many-objective.md) · [A2. NSGA-III](advanced/nsga-iii.md) · [A3. RVEA](advanced/rvea.md) · [A4. AGE-MOEA](advanced/agemoea.md) · [A5. Constrained multi-objective optimization](advanced/constrained.md) · [A6. CCMO](advanced/ccmo.md) · [A7. C-TAEA](advanced/ctaea.md) · [A8. ToP](advanced/top.md) · [A9. CMOEA-MS](advanced/cmoeams.md) · [A10. Comparing algorithms rigorously](advanced/performance-assessment.md) | Recognize why four or more objectives and constraints change the problem, explain the many-objective and constrained algorithms of VAMOS, and design a comparison whose conclusions survive scrutiny. |
+
+Read the levels in order the first time. Within a level, each lesson builds
+on the previous one and ends with a link to the next.
+
+## How the interactive figures work
+
+The figures run in your browser. You can drag the points, or focus one with
+Tab and move it with the arrow keys (hold Shift for
+larger steps). Sliders and buttons change the data, and a readout next to
+each figure states the numbers that the picture shows.
+
+The figures use a small JavaScript port of the same algorithms that VAMOS
+implements in Python: non-dominated sorting, crowding distance, simulated
+binary crossover, polynomial mutation and the two-objective quality indicators.
+Their results are checked against VAMOS and MooCore, but they exist to teach;
+use VAMOS itself for real experiments. Without JavaScript the figures do not
+appear, and the text of every lesson remains complete.
+
+## Run the code
+
+Each lesson ends with a short program that uses the public VAMOS interface.
+Install VAMOS first, following the [installation guide](../guide/installation.md):
+
+```bash
+python -m pip install "vamos-optimization==1.5.0"
+```
+
+The quality-indicator examples also use [MooCore](https://multi-objective.github.io/moocore/python/),
+the indicator library that the [quality and budget tutorial](../tutorials/t07-quality-and-budget.md)
+uses as well:
+
+```bash
+python -m pip install moocore
+```
+
+The outputs printed in the lessons come from VAMOS 1.5.0 with the NumPy
+engine. Values computed by an optimization run can differ in their last digits
+in another environment; a seed makes a run repeatable in the same
+environment, not bitwise identical everywhere.
+
+## Where to go next
+
+After the Basic level you can already read a result: [T01. Your first
+meaningful result](../tutorials/t01-first-result.md) applies B2 to a real
+run. After the Intermediate level, the [algorithm lessons](../tutorials/index.md#learn-an-algorithm)
+show each built-in algorithm with its exact configuration. The Advanced level
+leads to the [study tutorials](../tutorials/t06-fair-study.md), where
+comparisons are planned, measured and reported with saved evidence.
+
+## Further reading
+
+These books and tutorials cover the whole path in more depth. Each lesson
+cites the original papers for its own topic.
+
+- Deb, K. (2001). *Multi-Objective Optimization Using Evolutionary Algorithms*. Wiley.
+- Coello Coello, C. A., Lamont, G. B., and Van Veldhuizen, D. A. (2007). [*Evolutionary Algorithms for Solving Multi-Objective Problems*](https://doi.org/10.1007/978-0-387-36797-2) (2nd ed.). Springer.
+- Miettinen, K. (1999). [*Nonlinear Multiobjective Optimization*](https://doi.org/10.1007/978-1-4615-5563-6). Kluwer Academic Publishers.
+- Emmerich, M. T. M., and Deutz, A. H. (2018). [A tutorial on multiobjective optimization: fundamentals and evolutionary methods](https://doi.org/10.1007/s11047-018-9685-y). *Natural Computing*, 17(3), 585–609.
diff --git a/docs/foundations/intermediate/beyond-nsga-ii.md b/docs/foundations/intermediate/beyond-nsga-ii.md
new file mode 100644
index 000000000..f47ec69ee
--- /dev/null
+++ b/docs/foundations/intermediate/beyond-nsga-ii.md
@@ -0,0 +1,157 @@
+---
+description: 'I6. The three families of evolutionary multi-objective algorithms after NSGA-II: Pareto-based (SPEA2), decomposition-based (MOEA/D, Tchebycheff) and indicator-based (IBEA, SMS-EMOA), with interactive figures and the VAMOS algorithms of each family.'
+search:
+ boost: 0.5
+---
+
+# I6. Beyond NSGA-II
+
+NSGA-II answers the question "which solutions survive?" with dominance ranks
+and crowding distances. Other algorithms answer it differently, and the
+answers fall into three families. Knowing them is enough to understand almost
+every algorithm in VAMOS.
+
+In this lesson you will learn:
+
+- the selection principle of Pareto-based, decomposition-based and
+ indicator-based algorithms;
+- how a Tchebycheff scalarization reaches fronts that a weighted sum cannot;
+- how SMS-EMOA uses hypervolume contributions;
+- which VAMOS algorithms belong to each family.
+
+## Pareto-based algorithms
+
+Pareto-based algorithms rank solutions by dominance, then break ties with a
+density estimate. NSGA-II is one; **SPEA2** [1] is the other classic:
+
+- every solution receives a *strength*, the number of solutions it dominates;
+ its raw fitness is the sum of the strengths of the solutions that dominate it
+ (0 for non-dominated solutions);
+- density is estimated from the distance to the k-th nearest neighbour, a finer
+ measure than crowding distance;
+- an external archive of fixed size keeps the best solutions; when it
+ overflows, the solution with the closest neighbours is removed one at a time.
+
+Pareto-based selection works well with two or three objectives and makes no
+assumption about the shape of the front. Its weakness appears with more
+objectives, when nearly every solution is non-dominated (lesson
+[A1](../advanced/many-objective.md)).
+
+## Decomposition-based algorithms
+
+**MOEA/D** [2] decomposes the problem into N single-objective subproblems, one
+per weight vector w¹, …, wᴺ, and optimizes them simultaneously. Each subproblem
+keeps one solution. New solutions are created from *neighbouring* subproblems,
+those with the closest weight vectors, and a child replaces a neighbour's
+solution if it is better **for that neighbour's subproblem**. Neighbours share
+information because their optima are close on the front.
+
+The subproblems are scalarizations. The weighted sum fails on non-convex
+fronts (lesson [B1](../basic/multi-objective-problems.md#turning-many-objectives-into-one-scalarization)).
+The **Tchebycheff** scalarization [3, 4] uses the ideal point z* instead:
+
+g^te(x | w, z*) = max_i w_i · | f_i(x) − z*_i |
+
+Its contour lines are corners, not straight lines, and every Pareto-optimal
+point minimizes it for some weight vector, whatever the shape of the front.
+Compare the two methods on the non-convex front: sweep the weights with each
+method and count the distinct solutions.
+
+
+
+Evenly spaced weights do not give evenly spaced solutions: their spacing
+depends on the shape of the front, and Ishibuchi et al. [5] showed that the
+performance of decomposition-based algorithms depends strongly on how well the
+shape of the front matches the distribution of the weights. NSGA-III and RVEA
+use the same idea of a fixed set of directions with Pareto-based or
+angle-based selection; lesson [A1](../advanced/many-objective.md) explains
+NSGA-III.
+
+## Indicator-based algorithms
+
+If the goal is a set with a high hypervolume (lesson
+[B4](../basic/quality-indicators.md)), why not select for it directly?
+Indicator-based algorithms do exactly that.
+
+- **IBEA** [6] defines the fitness of a solution from a binary indicator,
+ usually the additive ε, computed against every other solution, and removes
+ the worst solution one at a time.
+- **SMS-EMOA** [7] is steady-state: each step creates one offspring, sorts the
+ N + 1 solutions into fronts, and removes the solution of the last front with
+ the **smallest exclusive hypervolume contribution**, the one whose removal
+ loses the least hypervolume.
+
+Drag the points below and watch which one SMS-EMOA would discard:
+
+
+
+Indicator-based selection inherits the Pareto compliance of the hypervolume,
+and it adapts the distribution of points to the front's shape. It also
+inherits its cost: computing contributions becomes expensive with many
+objectives [8].
+
+## The families in VAMOS
+
+| Family | Selection principle | VAMOS algorithms | In-depth lessons |
+| --- | --- | --- | --- |
+| Pareto-based | Dominance rank, then density | [NSGA-II](../../algorithms/nsgaii.md), [SPEA2](../../algorithms/spea2.md) | [I1 NSGA-II](nsga-ii.md), [I7 SPEA2](spea2.md) |
+| Decomposition and reference directions | Scalarized subproblems or directions in objective space | [MOEA/D](../../algorithms/moead.md), [NSGA-III](../../algorithms/nsgaiii.md), [RVEA](../../algorithms/rvea.md) | [I8 MOEA/D](moead.md), [A2 NSGA-III](../advanced/nsga-iii.md), [A3 RVEA](../advanced/rvea.md) |
+| Indicator-based | Contribution to a quality indicator | [SMS-EMOA](../../algorithms/smsemoa.md), [IBEA](../../algorithms/ibea.md) | [I9 SMS-EMOA](smsemoa.md), [I10 IBEA](ibea.md) |
+| Other survival rules | Geometry of the front, particle swarms | [AGE-MOEA](../../algorithms/agemoea.md), [SMPSO](../../algorithms/smpso.md) | [A4 AGE-MOEA](../advanced/agemoea.md), [I11 SMPSO](smpso.md) |
+| Constrained problems | Several populations, archives or stages | [CCMO](../../algorithms/ccmo.md), [C-TAEA](../../algorithms/ctaea.md), [ToP](../../algorithms/top.md), [CMOEA-MS](../../algorithms/cmoeams.md) (lesson [A5](../advanced/constrained.md)) | [A6 CCMO](../advanced/ccmo.md), [A7 C-TAEA](../advanced/ctaea.md), [A8 ToP](../advanced/top.md), [A9 CMOEA-MS](../advanced/cmoeams.md) |
+
+Because every algorithm receives the same problem and budget through
+`optimize`, switching family is a one-word change:
+
+```python
+from vamos import optimize
+
+for algorithm in ("nsgaii", "moead", "smsemoa"):
+ result = optimize("zdt1", algorithm=algorithm, pop_size=100, max_evaluations=10_000, engine="numpy", seed=1)
+ print(f"{algorithm:<8} {result.data['evaluations']} evaluations, {result.F.shape[0]} returned solutions")
+```
+
+Output:
+
+```text
+nsgaii 10000 evaluations, 100 returned solutions
+moead 10000 evaluations, 100 returned solutions
+smsemoa 10000 evaluations, 100 returned solutions
+```
+
+This loop deliberately prints no quality values. One run per algorithm on one
+problem with default settings says little about which algorithm is better:
+lesson [A10](../advanced/performance-assessment.md) explains what a comparison
+needs. Each algorithm's lesson describes its configuration; the
+[capability matrix](../../reference/algorithms.md) lists the encodings,
+constraint handling and engines each one supports.
+
+## Key points
+
+- Pareto-based algorithms select by dominance, then density (NSGA-II, SPEA2).
+- Decomposition-based algorithms solve many scalarized subproblems at once
+ (MOEA/D); the Tchebycheff scalarization reaches non-convex fronts.
+- Indicator-based algorithms select for a quality indicator directly (IBEA,
+ SMS-EMOA), at the price of computing it.
+- In VAMOS all of them share one interface: changing `algorithm=` changes the
+ family.
+
+**Next:** [I7. SPEA2](spea2.md).
+
+## References
+
+[1] Zitzler, E., Laumanns, M., and Thiele, L. (2001). [SPEA2: Improving the strength Pareto evolutionary algorithm](https://tik-db.ee.ethz.ch/db/public/tik/?db=publications&form=report_single_publication&publication_id=1287). TIK Report 103, Computer Engineering and Networks Laboratory, ETH Zurich.
+
+[2] Zhang, Q., and Li, H. (2007). [MOEA/D: A multiobjective evolutionary algorithm based on decomposition](https://doi.org/10.1109/TEVC.2007.892759). *IEEE Transactions on Evolutionary Computation*, 11(6), 712–731.
+
+[3] Steuer, R. E., and Choo, E.-U. (1983). [An interactive weighted Tchebycheff procedure for multiple objective programming](https://doi.org/10.1007/BF02591870). *Mathematical Programming*, 26(3), 326–344.
+
+[4] Miettinen, K. (1999). [*Nonlinear Multiobjective Optimization*](https://doi.org/10.1007/978-1-4615-5563-6). Kluwer Academic Publishers.
+
+[5] Ishibuchi, H., Setoguchi, Y., Masuda, H., and Nojima, Y. (2017). [Performance of decomposition-based many-objective algorithms strongly depends on Pareto front shapes](https://doi.org/10.1109/TEVC.2016.2587749). *IEEE Transactions on Evolutionary Computation*, 21(2), 169–190.
+
+[6] Zitzler, E., and Künzli, S. (2004). [Indicator-based selection in multiobjective search](https://doi.org/10.1007/978-3-540-30217-9_84). *Parallel Problem Solving from Nature – PPSN VIII*, Lecture Notes in Computer Science 3242, 832–842.
+
+[7] Beume, N., Naujoks, B., and Emmerich, M. (2007). [SMS-EMOA: Multiobjective selection based on dominated hypervolume](https://doi.org/10.1016/j.ejor.2006.08.008). *European Journal of Operational Research*, 181(3), 1653–1669.
+
+[8] Bader, J., and Zitzler, E. (2011). [HypE: An algorithm for fast hypervolume-based many-objective optimization](https://doi.org/10.1162/EVCO_a_00009). *Evolutionary Computation*, 19(1), 45–76.
diff --git a/docs/foundations/intermediate/crowding-distance.md b/docs/foundations/intermediate/crowding-distance.md
new file mode 100644
index 000000000..b2347e0fc
--- /dev/null
+++ b/docs/foundations/intermediate/crowding-distance.md
@@ -0,0 +1,227 @@
+---
+description: 'I3. The crowding distance of NSGA-II, its boundary rule and normalization, the crowded-comparison operator and binary tournament selection, with interactive figures and the VAMOS implementation.'
+search:
+ boost: 0.5
+---
+
+# I3. Crowding distance and tournament selection
+
+Ranks push the population towards the front, but all the members of one front
+are equally good by dominance. NSGA-II needs a second criterion to prefer some
+of them, and it should favour solutions in sparsely populated regions so that
+the population spreads along the front. That criterion is the **crowding
+distance** [1].
+
+In this lesson you will learn:
+
+- how the crowding distance is defined and computed;
+- why boundary solutions receive an infinite distance;
+- the crowded-comparison operator and the binary tournament that uses it;
+- the VAMOS implementation, including its rule for objectives without spread.
+
+## From sharing to crowding
+
+NSGA kept diversity with *fitness sharing* [2, 3]: the fitness of a solution
+was divided by the number of neighbours closer than a radius σ_share. The
+result depended strongly on σ_share, and computing it costs O(N²). The crowding
+distance replaces it with a measure that has **no parameter** and adapts to the
+scale of each objective [1].
+
+## Definition
+
+The crowding distance of a solution is computed **within its front**. For
+each objective, sort the front by that objective; the extreme solutions get an
+infinite distance, and every other solution adds the normalized distance
+between its two neighbours:
+
+d_i ← 0 for every solution i of the front
+for each objective m:
+ sort the front by f_m
+ d_first ← ∞, d_last ← ∞
+ for every interior solution i (between its neighbours i − 1 and i + 1 in that order):
+ d_i ← d_i + ( f_m(i + 1) − f_m(i − 1) ) / ( f_m^max − f_m^min )
+
+With two objectives, d_i is the sum of the side lengths of the rectangle, the
+*cuboid*, whose corners are the two neighbours of i, each side divided by the
+range of its objective. A large distance means the neighbours are far away:
+the solution sits in an empty region and should be kept.
+
+- **Boundary solutions** get ∞ so that the extremes of each front, which
+ define its spread, are always preferred.
+- **Normalization** by the range of each objective makes objectives in
+ different units comparable within the front.
+
+Focus or hover a point to see its cuboid and the computation. Then reduce the
+number of places left for this front and see which points NSGA-II would keep:
+
+
+
+Notice that NSGA-II computes the distances **once** and keeps the largest ones.
+It does not recompute them after each removal. When many neighbouring points
+are removed together, a gap can open that the one-shot rule did not
+anticipate; variants that remove one point at a time and recompute
+(Kukkonen and Deb [4]) spread the result more evenly at a higher cost.
+
+## The crowded-comparison operator
+
+Rank and crowding combine into one ordering, the crowded-comparison operator
+≺ₙ [1]:
+
+i ≺ₙ j ⇔ rank_i < rank_j, or ( rank_i = rank_j and d_i > d_j )
+
+A lower rank always wins. Within the same front, the less crowded solution
+wins. NSGA-II uses this operator in two places: to choose parents (below) and
+to truncate the last front during survival (lesson
+[I5](elitist-survival.md)).
+
+## Binary tournament selection
+
+To pick each parent, NSGA-II draws two distinct members of the population at
+random and keeps the one that wins under ≺ₙ; if they tie, a coin decides.
+Tournament selection [5] needs no scaling of fitness values, only a
+comparison, and its *selection pressure* is set by the tournament size: with
+two contestants, the worst solution is never selected, and the best is
+selected about twice per generation on average.
+
+## In VAMOS
+
+The crowding distance of the NumPy kernel follows the definition line by
+line:
+
+```python
+# Excerpt from src/vamos/foundation/kernel/numpy_backend.py
+ for front in fronts:
+ if len(front) == 0:
+ continue
+ front_arr = np.asarray(front, dtype=int)
+ if front_arr.size <= 2:
+ crowding[front_arr] = np.inf
+ continue
+
+ fvals = F[front_arr] # shape (k, n_obj)
+ n_obj = fvals.shape[1]
+ d = np.zeros(front_arr.size, dtype=float)
+
+ for m in range(n_obj):
+ order = np.argsort(fvals[:, m], kind="mergesort")
+ sorted_vals = fvals[order, m]
+
+ span = sorted_vals[-1] - sorted_vals[0]
+ if span <= 0.0:
+ continue
+ d[order[0]] = np.inf
+ d[order[-1]] = np.inf
+
+ contrib = np.zeros_like(sorted_vals)
+ contrib[1:-1] = (sorted_vals[2:] - sorted_vals[:-2]) / span
+ d[order[1:-1]] += contrib[1:-1]
+
+ crowding[front_arr] = d
+```
+
+Two details go beyond the paper and follow jMetal and pymoo:
+
+- a front of one or two solutions gives every member ∞;
+- an objective whose values are all equal in a front (`span <= 0`) is skipped,
+ instead of marking two arbitrary members as boundaries. The
+ [NSGA-II lesson](../../algorithms/nsgaii.md#how-selection-works) records when
+ VAMOS adopted this rule.
+
+The tournament of two (`pressure == 2`) draws the second contestant so that it
+always differs from the first, then compares rank, then crowding, then flips
+a coin:
+
+```python
+# Excerpt from src/vamos/foundation/kernel/numpy_backend.py
+ first = rng.integers(0, N, size=n_parents, dtype=int)
+ second = rng.integers(0, N - 1, size=n_parents, dtype=int)
+ second = second + (second >= first)
+
+ rank_first = ranks[first]
+ rank_second = ranks[second]
+ crowd_first = np.nan_to_num(crowding[first], nan=-np.inf)
+ crowd_second = np.nan_to_num(crowding[second], nan=-np.inf)
+
+ pick_first = rank_first < rank_second
+ pick_second = rank_second < rank_first
+ unresolved = ~(pick_first | pick_second)
+
+ crowd_first_better = crowd_first > crowd_second
+ crowd_second_better = crowd_second > crowd_first
+ pick_first = pick_first | (unresolved & crowd_first_better)
+ pick_second = pick_second | (unresolved & crowd_second_better)
+```
+
+All the tournaments of a generation are resolved at once with array
+operations; there is no Python loop over parents.
+
+The public helper `vamos.select_survivors` returns the crowding distances of
+any set of objective vectors. These are the nine points of the figure, with
+five places to fill:
+
+```python
+import numpy as np
+
+from vamos import select_survivors
+
+f1 = np.array([0.0, 0.04, 0.09, 0.16, 0.38, 0.47, 0.55, 0.80, 1.0])
+front = np.column_stack([f1, 1.0 - np.sqrt(f1)]) # nine points of the ZDT1 front
+selection = select_survivors(front, survivor_count=5)
+
+labels = "ABCDEFGHI"
+for label, distance in zip(labels, selection.crowding_distances):
+ print(label, "inf" if np.isinf(distance) else f"{distance:.3f}")
+print("kept:", ", ".join(labels[i] for i in sorted(selection.selected_indices)))
+```
+
+Output:
+
+```text
+A inf
+B 0.390
+C 0.320
+D 0.606
+E 0.596
+F 0.295
+G 0.539
+H 0.708
+I inf
+kept: A, D, E, H, I
+```
+
+## Known limitations
+
+- **Duplicates.** Identical solutions are neighbours at distance zero; with
+ many duplicates the ranking within a front becomes arbitrary. Fortin and
+ Parizeau [6] discuss corrections.
+- **More than two or three objectives.** The sum of per-objective gaps no
+ longer reflects how crowded a region is, and nearly every solution is a
+ boundary in some objective. NSGA-III replaces crowding with reference
+ directions (lesson [A1](../advanced/many-objective.md)).
+- **Not a distance to the front.** A large crowding distance says nothing
+ about convergence; rank takes care of that.
+
+## Key points
+
+- The crowding distance sums, over the objectives, the normalized gap between
+ the two neighbours of a solution in its front; boundary solutions get ∞.
+- NSGA-II compares solutions by rank first and crowding distance second, the
+ crowded-comparison operator ≺ₙ.
+- Parents are chosen by binary tournaments with ≺ₙ; the last front is truncated
+ by keeping the largest distances, computed once.
+
+**Next:** [I4. Variation: SBX and polynomial mutation](variation-operators.md).
+
+## References
+
+[1] Deb, K., Pratap, A., Agarwal, S., and Meyarivan, T. (2002). [A fast and elitist multiobjective genetic algorithm: NSGA-II](https://doi.org/10.1109/4235.996017). *IEEE Transactions on Evolutionary Computation*, 6(2), 182–197.
+
+[2] Goldberg, D. E., and Richardson, J. (1987). Genetic algorithms with sharing for multimodal function optimization. *Proceedings of the Second International Conference on Genetic Algorithms and Their Application*, 41–49.
+
+[3] Srinivas, N., and Deb, K. (1994). [Multiobjective optimization using nondominated sorting in genetic algorithms](https://doi.org/10.1162/evco.1994.2.3.221). *Evolutionary Computation*, 2(3), 221–248.
+
+[4] Kukkonen, S., and Deb, K. (2006). Improved pruning of non-dominated solutions based on crowding distance for bi-objective optimization problems. *Proceedings of the 2006 IEEE Congress on Evolutionary Computation*, 1179–1186.
+
+[5] Goldberg, D. E., and Deb, K. (1991). [A comparative analysis of selection schemes used in genetic algorithms](https://doi.org/10.1016/B978-0-08-050684-5.50008-2). *Foundations of Genetic Algorithms*, 1, 69–93.
+
+[6] Fortin, F.-A., and Parizeau, M. (2013). [Revisiting the NSGA-II crowding-distance computation](https://doi.org/10.1145/2463372.2463456). *Proceedings of the 15th Annual Conference on Genetic and Evolutionary Computation (GECCO '13)*, 623–630.
diff --git a/docs/foundations/intermediate/elitist-survival.md b/docs/foundations/intermediate/elitist-survival.md
new file mode 100644
index 000000000..9c5a1b203
--- /dev/null
+++ b/docs/foundations/intermediate/elitist-survival.md
@@ -0,0 +1,191 @@
+---
+description: 'I5. Elitist (μ + λ) survival in NSGA-II: merging parents and offspring, filling whole fronts and truncating the last one by crowding distance, step by step and in VAMOS, plus constraints and the steady-state variant.'
+search:
+ boost: 0.5
+---
+
+# I5. Elitist survival and the complete generation
+
+The last step of a generation decides which N of the 2N candidates survive.
+NSGA-II makes parents and offspring compete on equal terms, which guarantees
+that the best solutions found so far are never lost. This property,
+**elitism**, was the third improvement over NSGA [1].
+
+In this lesson you will learn:
+
+- why elitism matters, and how NSGA-II implements it;
+- the survival procedure, step by step;
+- how VAMOS performs it, and how the whole generation fits together;
+- how constraints and the steady-state variant change survival.
+
+## Why elitism
+
+In a non-elitist algorithm the offspring simply replace the parents. A
+Pareto-optimal solution found in one generation can disappear in the next if
+its offspring are worse. Zitzler, Deb and Thiele [2] compared several
+algorithms on the ZDT problems and found elitism to be an important factor of
+performance. NSGA-II uses the simplest elitist scheme, a (μ + λ) selection
+in the terminology of evolution strategies: the N parents and the N offspring
+form one pool, and the best N of the pool survive.
+
+## The procedure
+
+Rₜ ← Pₜ ∪ Qₜ (2N candidates)
+F₁, F₂, … ← fast non-dominated sort of Rₜ (lesson I2)
+Pₜ₊₁ ← ∅, k ← 1
+while |Pₜ₊₁| + |F_k| ≤ N:
+ Pₜ₊₁ ← Pₜ₊₁ ∪ F_k (the whole front fits)
+ k ← k + 1
+compute the crowding distances of F_k (lesson I3)
+add the N − |Pₜ₊₁| members of F_k with the largest distances
+
+Every member of an earlier front survives before any member of a later
+one: convergence first. Only the front that does not fit, the *last front*, is
+cut, and crowding decides the cut: diversity second. The fronts after it are
+discarded without being examined.
+
+Step through one survival with N = 6. Circles are parents, triangles are
+offspring:
+
+
+
+In this example three parents and three offspring survive. Nothing in the
+procedure prefers either group: a parent survives only if it is still among
+the best N.
+
+## In VAMOS
+
+The same twelve candidates, selected with the experimental public helper
+`vamos.select_survivors`, which applies NSGA-II's ranking and crowding:
+
+```python
+import numpy as np
+
+from vamos import select_survivors
+
+parents = np.array([[0.20, 0.30], [0.25, 0.70], [0.40, 0.48], [0.90, 0.12], [0.50, 0.65], [0.95, 0.35]])
+offspring = np.array([[0.45, 0.10], [0.22, 0.90], [0.32, 0.55], [0.60, 0.30], [0.35, 0.90], [0.70, 0.50]])
+candidates = np.vstack([parents, offspring]) # rows 0-5: parents, rows 6-11: offspring
+labels = [f"P{i}" for i in range(1, 7)] + [f"O{i}" for i in range(1, 7)]
+
+selection = select_survivors(candidates, survivor_count=6)
+for label, rank, distance in zip(labels, selection.ranks, selection.crowding_distances):
+ print(f"{label}: front {rank + 1}, crowding {distance:.2f}")
+print("survivors:", ", ".join(labels[i] for i in selection.selected_indices))
+```
+
+Output:
+
+```text
+P1: front 1, crowding inf
+P2: front 2, crowding 0.60
+P3: front 2, crowding 0.73
+P4: front 2, crowding inf
+P5: front 3, crowding 1.31
+P6: front 3, crowding inf
+O1: front 1, crowding inf
+O2: front 2, crowding inf
+O3: front 2, crowding 0.50
+O4: front 2, crowding 1.20
+O5: front 3, crowding inf
+O6: front 3, crowding 1.30
+survivors: P1, O1, P4, O2, O4, P3
+```
+
+The helper orders candidates by rank, then by decreasing crowding distance,
+then by position, and returns the first `survivor_count`. Inside NSGA-II, the
+kernel fills the fronts exactly as in the procedure above:
+
+```python
+# Excerpt from src/vamos/foundation/kernel/numpy_backend.py
+def _select_nsga2(fronts: list[list[int]], crowding: RealArray, pop_size: int) -> IndexArray:
+ """
+ NSGA-II elitist selection based on fronts + crowding.
+ """
+ selected: list[int] = []
+ for front in fronts:
+ if len(front) == 0:
+ continue
+ front_arr = np.asarray(front, dtype=int)
+ if len(selected) + front_arr.size <= pop_size:
+ selected.extend(front_arr.tolist())
+ else:
+ rem = pop_size - len(selected)
+ order = np.argsort(crowding[front_arr])[::-1]
+ selected.extend(front_arr[order[:rem]].tolist())
+ break
+ return np.array(selected, dtype=int)
+```
+
+and the kernel's survival method chains merge, sort, crowding and selection:
+
+```python
+# Excerpt from src/vamos/foundation/kernel/numpy_backend.py
+ X_comb = np.vstack([X, X_off])
+ F_comb = np.vstack([F, F_off])
+ fronts, _ = _fast_non_dominated_sort(F_comb)
+ crowding = _compute_crowding(F_comb, fronts)
+ sel = _select_nsga2(fronts, crowding, pop_size)
+```
+
+## The complete generation
+
+The NSGA-II driver in `src/vamos/engine/algorithm/nsgaii/ask_tell.py`
+organizes each generation as *ask* and *tell*:
+
+1. **Ask.** Compute ranks and crowding distances of the current population
+ (they are cached from the previous survival when possible), pick parents
+ with the binary tournament (lesson [I3](crowding-distance.md)), and apply
+ crossover and mutation (lesson [I4](variation-operators.md)). The result is
+ the offspring decision matrix.
+2. **Evaluate** the offspring, counting every evaluation against the budget.
+3. **Tell.** Merge parents and offspring and run the survival above; update any
+ external archive; check the termination condition.
+
+Two consequences for experiments:
+
+- **The returned set is not the population size.** `result.F` holds, by
+ default, the non-dominated members of the final population, so it can have
+ fewer than N rows ([understanding results](../../guide/understanding-results.md)).
+- **The budget is exact.** The initial population and every offspring count;
+ VAMOS does not overshoot `max_evaluations` silently.
+
+## Survival with constraints
+
+With constraints g_j(x) ≤ 0, VAMOS' default NSGA-II replaces dominance by
+**constrained domination** [3]: a feasible solution beats any infeasible one, two
+infeasible solutions are compared by their total violation, and two feasible
+solutions by Pareto dominance. Sorting, crowding and truncation then proceed as
+above. Lesson [A5](../advanced/constrained.md) shows its effect and the
+alternatives that VAMOS provides.
+
+## Steady-state NSGA-II
+
+The generational scheme creates N offspring before each survival. The
+**steady-state** variant creates one offspring, merges it with the N parents,
+and removes the worst of the N + 1 immediately, so a good offspring can become
+a parent at once. VAMOS enables it with `.steady_state()` in the builder; the
+[NSGA-II lesson](../../algorithms/nsgaii.md#steady-state-nsga-ii) explains the
+budget accounting and when the two variants differ.
+
+## Key points
+
+- NSGA-II is elitist: parents and offspring compete together and the best N of
+ the 2N survive.
+- Survival takes whole fronts while they fit and truncates the first front that
+ does not fit by crowding distance.
+- In VAMOS the kernel's `nsga2_survival` merges, sorts, computes crowding and
+ selects; `vamos.select_survivors` exposes the same ranking for any set of
+ objective vectors.
+- Constraints change the comparison (constrained domination), not the structure
+ of survival.
+
+**Next:** [I6. Beyond NSGA-II](beyond-nsga-ii.md).
+
+## References
+
+[1] Deb, K., Pratap, A., Agarwal, S., and Meyarivan, T. (2002). [A fast and elitist multiobjective genetic algorithm: NSGA-II](https://doi.org/10.1109/4235.996017). *IEEE Transactions on Evolutionary Computation*, 6(2), 182–197.
+
+[2] Zitzler, E., Deb, K., and Thiele, L. (2000). [Comparison of multiobjective evolutionary algorithms: Empirical results](https://doi.org/10.1162/106365600568202). *Evolutionary Computation*, 8(2), 173–195.
+
+[3] Deb, K. (2000). [An efficient constraint handling method for genetic algorithms](https://doi.org/10.1016/S0045-7825(99)00389-8). *Computer Methods in Applied Mechanics and Engineering*, 186(2–4), 311–338.
diff --git a/docs/foundations/intermediate/ibea.md b/docs/foundations/intermediate/ibea.md
new file mode 100644
index 000000000..d5ab3c434
--- /dev/null
+++ b/docs/foundations/intermediate/ibea.md
@@ -0,0 +1,376 @@
+---
+description: 'I10. IBEA in depth: binary quality indicators (additive epsilon and hypervolume difference), the exponential fitness with its scaling c and parameter kappa, objective normalization, iterative removal with fitness updates and binary tournament mating, with an interactive figure and the VAMOS implementation.'
+search:
+ boost: 0.5
+---
+
+# I10. IBEA: indicator-based fitness
+
+SMS-EMOA (lesson [I9](smsemoa.md)) selects with one unary indicator, the
+hypervolume, and pays for exact contributions at every step. The
+Indicator-Based Evolutionary Algorithm of Zitzler and Künzli, IBEA [1], takes a
+more general route. It asks the user for a **binary indicator**, a number that
+says how much better one solution is than another, turns the indicator values
+of all pairs into a fitness, and removes the worst solution until the
+population fits.
+
+IBEA needs no non-dominated sorting, no crowding distance and no density
+estimate: the indicator alone provides both convergence and diversity. With the
+additive ε indicator, the default, the fitness of a population costs O(N² m)
+operations for N solutions and m objectives, whatever m is.
+
+In this lesson you will learn:
+
+- what a binary indicator is, and the two that VAMOS supports: additive ε and
+ hypervolume difference;
+- how IBEA turns indicator values into a fitness, and what the scaling c and
+ the parameter κ do;
+- why VAMOS normalizes the objectives first;
+- how environmental selection removes one solution at a time and updates the
+ others' fitness, and how parents are chosen;
+- how VAMOS implements each step.
+
+## Binary indicators
+
+The indicators of lesson [B4](../basic/quality-indicators.md) are *unary*: they
+give one number to one set. A **binary** indicator I(A, B) compares two sets
+[2]. IBEA applies it to single solutions, I(x₁, x₂), and Zitzler and Künzli
+require it to be **dominance preserving** [1]:
+
+x₁ ≺ x₂ ⇒ I(x₁, x₂) < I(x₂, x₁)
+x₁ ≺ x₂ ⇒ I(x₃, x₁) ≥ I(x₃, x₂) for every x₃
+
+The first condition says that a dominating solution scores better against the
+solution it dominates than the reverse; the second, that the better solution is
+harder for any third solution to cover. VAMOS offers two such indicators.
+
+**Additive ε.** The smallest amount ε by which x₁ must be improved in every
+objective to weakly dominate x₂ (lesson
+[B4](../basic/quality-indicators.md#distance-based-indicators)):
+
+I_ε+(x₁, x₂) = max_i ( f_i(x₁) − f_i(x₂) )
+
+It is ≤ 0 exactly when x₁ weakly dominates x₂, and small and positive when x₁
+almost covers x₂.
+
+**Hypervolume difference.** With H(A) the hypervolume of A
+(lesson [B4](../basic/quality-indicators.md#hypervolume)) [3]:
+
+I_HD(x₁, x₂) = H(x₂) − H(x₁) if x₁ dominates x₂
+I_HD(x₁, x₂) = H({x₁, x₂}) − H(x₁) otherwise
+
+In the second case it is the volume that x₂ dominates and x₁ does not. Select it
+with `.indicator("hypervolume")`; `.indicator("eps")` is the default.
+
+## Fitness from indicator values
+
+The fitness of a solution x of the population P sums one negative term per other
+solution y:
+
+F(x) = Σ_{y ∈ P, y ≠ x} −exp( −I(y, x) / (c · κ) )
+
+The term for y measures how well y covers x:
+
+- If y dominates x, I(y, x) < 0 and the term is below −1; the more y
+ dominates x, and the smaller κ, the larger its magnitude.
+- If y nearly covers x, I(y, x) is small and positive and the term is close
+ to −1. Two close non-dominated solutions penalize each other this way, which is
+ how IBEA rewards spread.
+- If y is far from covering x, I(y, x) is large and the term is close to 0.
+
+F(x) ≤ 0, and a value closer to 0 is better: the solution that the others cover
+the least. Zitzler and Künzli read F(x) as the loss of quality caused by
+removing x [1].
+
+## Normalization, the scaling c and κ
+
+Indicator values depend on the objective units. Zitzler and Künzli's adaptive
+IBEA [1] therefore maps each objective to [0, 1] with the bounds of the
+population, and divides every indicator value by
+
+c = max_{x₁, x₂ ∈ P} | I(x₁, x₂) |
+
+so that I / c lies in [−1, 1] and each exponent in [−1/κ, 1/κ]. VAMOS always
+applies both steps, with either indicator, to the union of population and
+offspring. A positive affine change of the units of any objective then leaves
+the selection unchanged. A solution far from the others widens the
+normalization range, which lowers the resolution among the rest.
+
+κ sets the selection pressure. VAMOS' default is κ = 0.05, the value of
+Zitzler and Künzli [1].
+
+- **Small κ.** The terms of dominating solutions dwarf all others: dominated
+ solutions get a very negative fitness and leave first, and among the
+ non-dominated ones the nearest neighbours decide.
+- **Large κ.** Every term approaches −1 + I(y, x) / (c κ), so the fitness
+ approaches a sum of indicator values. The penalty for being dominated is no
+ longer special, and dominated solutions survive more often.
+
+## Environmental selection
+
+IBEA merges the N parents with the N offspring and removes solutions one at a
+time:
+
+Q ← P ∪ P′ (2N solutions)
+normalize Q, compute I and c, compute F(x) for every x in Q
+while |Q| > N:
+ x* ← the member of Q with the smallest F
+ Q ← Q \ {x*}
+ for every x in Q: F(x) ← F(x) + exp( −I(x*, x) / (c · κ) )
+
+The update removes x\*'s term from the sums of the others, so the fitness of the
+remaining solutions is exactly the one they would have in Q without x\*; nothing
+is recomputed. The normalization and c stay those of the merged set. Removing
+one solution at a time matters for the same reason as in SPEA2 (lesson
+[I7](spea2.md)): when two solutions cover each other, the first removal lifts
+the fitness of the second, which then survives.
+
+## Mating selection
+
+Parents are chosen by binary tournaments on the survivors, comparing their
+updated fitness: the higher fitness wins [1, 4]. Crossover and mutation then
+create the N offspring of the next generation.
+
+## Try it: fitness and removal order
+
+The eight points below are the merged set Q. The table gives each point's
+fitness and the order in which IBEA removes points for the chosen population
+size, with the updated fitness of the survivors. Things to try:
+
+1. With κ = 0.05 and population size 5, P8 and P7, the dominated points, go
+ first, then P3, one of the close pair P2 and P3.
+2. Reduce the population to 4: the next to go is P1, an extreme. IBEA with
+ ε has no rule that protects extremes.
+3. Raise κ to 1 with population size 5: the third removal becomes P4, the only
+ point in the middle of the front, and both P2 and P3 survive.
+4. Switch to the hypervolume-difference indicator and compare the orders.
+
+
+
+## In VAMOS
+
+The figure's default case in NumPy, with the additive ε indicator, κ = 0.05
+and a population of five:
+
+```python
+import numpy as np
+
+F = np.array([[0.05, 0.95], [0.15, 0.60], [0.20, 0.55], [0.40, 0.38], [0.60, 0.20], [0.95, 0.05], [0.50, 0.60], [0.75, 0.45]])
+kappa = 0.05
+Z = (F - F.min(axis=0)) / (F.max(axis=0) - F.min(axis=0)) # each objective mapped to [0, 1]
+eps = np.max(Z[None, :, :] - Z[:, None, :], axis=2) # eps[x, y] = I_eps+(y, x) = max_i (z_i(y) - z_i(x))
+c = np.abs(eps).max() # adaptive scaling: the largest indicator magnitude
+terms = np.exp(-eps / (c * kappa))
+np.fill_diagonal(terms, 0.0) # no term for y = x
+fitness = -terms.sum(axis=1)
+for i, value in enumerate(fitness):
+ print(f"P{i + 1}: F = {value:.3f}")
+
+alive = list(range(len(F)))
+while len(alive) > 5: # population size 5
+ worst = min(alive, key=lambda i: fitness[i]) # the first lowest fitness
+ alive.remove(worst)
+ fitness[alive] += terms[alive, worst] # its terms leave the others' sums
+ print(f"remove P{worst + 1}")
+print("survivors:", ", ".join(f"P{i + 1} ({fitness[i]:.3f})" for i in alive))
+```
+
+Output:
+
+```text
+P1: F = -0.145
+P2: F = -0.334
+P3: F = -0.342
+P4: F = -0.050
+P5: F = -0.023
+P6: F = -0.036
+P7: F = -13.378
+P8: F = -32.961
+remove P8
+remove P7
+remove P3
+survivors: P1 (-0.109), P2 (-0.004), P4 (-0.019), P5 (-0.019), P6 (-0.036)
+```
+
+P7 is dominated by P2, P3 and P4, and P8 by P4 and P5: their fitness is two
+orders of magnitude below the others. P2 and P3 cover each other closely, so both have
+a poor fitness; once P3 is removed, P2's fitness rises from −0.334 to −0.004.
+
+VAMOS builds the indicator matrix in the same orientation, row x and column y
+holding I(y, x), on the normalized objectives:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/ibea/helpers.py
+def epsilon_indicator(F: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
+ # Match jMetalPy: epsilon(i, j) = max_k (f_jk - f_ik)
+ diff = F[None, :, :] - F[:, None, :]
+ return np.asarray(np.max(diff, axis=2), dtype=float)
+
+def _divided_by_largest_magnitude(values: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
+ """``values`` divided by their largest finite magnitude; unchanged when that is 0."""
+ largest = float(np.max(np.abs(values[np.isfinite(values)]), initial=0.0))
+ return values / largest if largest > 0.0 else values
+
+def compute_indicator_matrix(F: np.ndarray[Any, Any], indicator: str) -> np.ndarray[Any, Any]:
+ if F.shape[0] == 0:
+ return np.empty((0, 0), dtype=float)
+ normalized = _normalized_objectives(F)
+ if indicator == "hypervolume":
+ return _divided_by_largest_magnitude(hypervolume_indicator(normalized))
+ return _divided_by_largest_magnitude(epsilon_indicator(normalized))
+```
+
+- `_normalized_objectives` maps each objective to [0, 1] with its minimum and
+ maximum over the finite values; a constant objective maps to 0.
+- `_divided_by_largest_magnitude` divides by c.
+- `hypervolume_indicator` computes I_HD with the reference point max + 1 of the
+ normalized objectives, (2, …, 2) when every objective varies.
+
+The fitness and the removal loop follow the procedure line by line:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/ibea/helpers.py
+def _fitness_exponents(indicator: np.ndarray[Any, Any], kappa: float) -> np.ndarray[Any, Any]:
+ """``-indicator / kappa``, with ``-inf`` (no contribution) on the diagonal and for undefined values.
+
+ ``+inf``, from an infinite indicator or a division that overflows, stays the largest contribution.
+ """
+ with np.errstate(over="ignore"):
+ exponent = -np.asarray(indicator, dtype=float) / kappa
+ exponent[np.isnan(exponent)] = -np.inf
+ np.fill_diagonal(exponent, -np.inf)
+ return exponent
+
+ exponent = _fitness_exponents(indicator_values, kappa)
+ contrib = np.exp(exponent)
+ fitness = np.asarray(-np.sum(contrib, axis=1), dtype=float)
+ fitness = apply_constraint_penalty(fitness, G)
+ active: NDArray[np.int_] = np.arange(F.shape[0], dtype=int)
+ while active.size > pop_size:
+ active_fitness = fitness[active]
+ worst_pos = int(np.argmin(active_fitness))
+ worst = int(active[worst_pos])
+ delta = contrib[active, worst].copy()
+ delta[worst_pos] = 0.0
+ fitness[active] += delta
+ active = np.delete(active, worst_pos)
+
+ return active, fitness[active]
+```
+
+- The diagonal exponent −∞ gives exp(−∞) = 0: no term for y = x.
+- `contrib[x, y]` is the magnitude of y's term in F(x); `contrib[active, worst]`
+ is the column of the removed solution, added back to every survivor.
+- `np.argmin` removes the first of equal lowest values.
+- `apply_constraint_penalty` lowers every infeasible solution below all feasible
+ ones, by one penalty step per rank of its total violation, so infeasible
+ solutions leave first, the most violated first.
+- When κ is so small that an exponent would overflow, VAMOS runs the same loop in
+ the log domain; with `engine="numba"`, a compiled loop gives the same removals.
+
+Mating ranks the survivors by fitness and reuses NSGA-II's tournament kernel
+(lesson [I3](crowding-distance.md#binary-tournament-selection)) with all
+crowding distances set to zero:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/ibea/ibea.py
+ # Higher fitness is better in IBEA (less negative).
+ ranks = np.argsort(np.argsort(-st.fitness))
+ crowd = np.zeros_like(st.fitness, dtype=float)
+ parents_per_group = variation.parents_per_group
+ children_per_group = variation.children_per_group
+ request_size = capped_offspring_size(st.n_eval, self._max_eval, st.offspring_size, "IBEA")
+ parent_count = int(np.ceil(request_size / children_per_group) * parents_per_group)
+
+ sel_method, _ = self.cfg["selection"]
+ mating_pairs = build_mating_pool(self.kernel, ranks, crowd, st.pressure, st.rng, parent_count, parents_per_group, sel_method)
+```
+
+The ranks are all distinct, so the solution with the higher fitness always wins.
+`st.fitness` is the updated fitness that the survivors had at the end of the
+removal loop. SBX creates two children per pair, so N / 2 pairs give the N
+offspring; `capped_offspring_size` shortens the last batch so that the budget is
+never exceeded.
+
+Two runs on ZDT1 that differ only in κ:
+
+```python
+from vamos import optimize
+from vamos.algorithms import IBEAConfig
+from vamos.problems import ZDT1
+
+problem = ZDT1(n_var=30)
+for kappa in (0.05, 1.0):
+ config = (
+ IBEAConfig.builder()
+ .pop_size(100)
+ .crossover("sbx", prob=0.9, eta=20.0)
+ .mutation("pm", prob="1/n", eta=20.0)
+ .selection("tournament")
+ .indicator("eps")
+ .kappa(kappa)
+ .build()
+ )
+ result = optimize(problem, algorithm="ibea", algorithm_config=config, max_evaluations=20_000, engine="numpy", seed=1)
+ print(f"kappa {kappa}: {result.data['evaluations']} evaluations, {result.F.shape[0]} non-dominated of 100 in the final population")
+```
+
+Output:
+
+```text
+kappa 0.05: 20000 evaluations, 97 non-dominated of 100 in the final population
+kappa 1.0: 20000 evaluations, 78 non-dominated of 100 in the final population
+```
+
+By default the result holds the non-dominated members of the final population.
+With κ = 1, dominated solutions are penalized less and more of them survive, as
+the previous section predicts; one seed shows the mechanism, not which value is
+better. The [IBEA lesson](../../algorithms/ibea.md) records a run with its
+figure, and the [configuration reference](../../reference/api/algorithms/ibea.md)
+lists every builder method.
+
+## IBEA compared
+
+- **With NSGA-II and SPEA2.** No fronts and no separate density estimate: one
+ fitness combines convergence and spread. Because the fitness of a dominated
+ solution depends on how far it is dominated, IBEA keeps pushing when nearly
+ every solution is non-dominated. Wagner, Beume and Naujoks [5] found that
+ indicator-based algorithms, IBEA among them, kept converging on many-objective
+ problems where NSGA-II and SPEA2 lost selection pressure (lesson
+ [A1](../advanced/many-objective.md)).
+- **With SMS-EMOA.** Both remove one solution at a time by an indicator.
+ SMS-EMOA measures exact hypervolume contributions, whose cost grows
+ exponentially with m; IBEA with ε needs only pairwise differences.
+- **Distribution.** The figure shows that IBEA with ε does not protect the
+ extremes of the front; the distribution it reaches depends on the indicator, on
+ κ and on the normalization.
+- **When to use it.** Problems with three or more objectives, where Pareto
+ ranking stalls and the hypervolume is too expensive; or whenever a single,
+ parameter-light fitness is preferable to sorting and density estimation.
+
+## Key points
+
+- IBEA turns a binary indicator into a fitness:
+ F(x) = Σ_{y ≠ x} −exp(−I(y, x) / (c κ)); values closer to 0 are better.
+- VAMOS supports the additive ε indicator (default) and the hypervolume
+ difference, always on objectives normalized to [0, 1] and divided by
+ c = max |I|.
+- κ (default 0.05) sets the pressure: small κ punishes dominated solutions
+ strongly, large κ flattens the fitness.
+- Environmental selection removes the lowest fitness one at a time and adds the
+ removed solution's term back to every survivor.
+- Parents come from binary tournaments on the updated fitness.
+
+**Next:** [I11. SMPSO](smpso.md).
+
+## References
+
+[1] Zitzler, E., and Künzli, S. (2004). [Indicator-based selection in multiobjective search](https://doi.org/10.1007/978-3-540-30217-9_84). *Parallel Problem Solving from Nature – PPSN VIII*, Lecture Notes in Computer Science 3242, 832–842.
+
+[2] Zitzler, E., Thiele, L., Laumanns, M., Fonseca, C. M., and Grunert da Fonseca, V. (2003). [Performance assessment of multiobjective optimizers: An analysis and review](https://doi.org/10.1109/TEVC.2003.810758). *IEEE Transactions on Evolutionary Computation*, 7(2), 117–132.
+
+[3] Zitzler, E., and Thiele, L. (1998). [Multiobjective optimization using evolutionary algorithms – A comparative case study](https://doi.org/10.1007/BFb0056872). *Parallel Problem Solving from Nature – PPSN V*, Lecture Notes in Computer Science 1498, 292–301.
+
+[4] Goldberg, D. E., and Deb, K. (1991). [A comparative analysis of selection schemes used in genetic algorithms](https://doi.org/10.1016/B978-0-08-050684-5.50008-2). *Foundations of Genetic Algorithms*, 1, 69–93.
+
+[5] Wagner, T., Beume, N., and Naujoks, B. (2007). Pareto-, aggregation-, and indicator-based methods in many-objective optimization. *Evolutionary Multi-Criterion Optimization – EMO 2007*, Lecture Notes in Computer Science 4403, 742–756.
diff --git a/docs/foundations/intermediate/moead.md b/docs/foundations/intermediate/moead.md
new file mode 100644
index 000000000..652bae8e5
--- /dev/null
+++ b/docs/foundations/intermediate/moead.md
@@ -0,0 +1,499 @@
+---
+description: 'I8. MOEA/D in depth: weight vectors, neighbourhoods, mating with probability δ, differential evolution, the ideal point, replacement limited to n_r solutions and the aggregation functions of VAMOS, with an interactive figure and the VAMOS code.'
+search:
+ boost: 0.5
+---
+
+# I8. MOEA/D: decomposition and neighbourhoods
+
+NSGA-II compares whole solutions by dominance and crowding. MOEA/D, proposed
+by Zhang and Li in 2007 [1], never sorts its population. It *decomposes* the
+problem into N single-objective subproblems, one per weight vector, and solves
+them all at once. Each subproblem keeps exactly one solution, and a new
+solution competes only with the solutions of nearby subproblems, each judged
+by the scalarizing function of **its own** subproblem. Lesson
+[I6](beyond-nsga-ii.md#decomposition-based-algorithms) introduced the idea;
+this lesson takes it apart.
+
+Two things set MOEA/D apart from NSGA-II. Diversity does not come from a
+density estimate but from the weight vectors, which are fixed before the run.
+And the work is local: an offspring is bred from neighbours and compared with
+T neighbours, so one step costs O(T·m) aggregation terms for m objectives
+instead of a sort of the whole population. VAMOS runs MOEA/D steady-state, one
+offspring at a time, with the differential-evolution operator of MOEA/D-DE, the
+variant of Li and Zhang [2].
+
+In this lesson you will learn:
+
+- how weight vectors define the subproblems, and how VAMOS generates them for
+ two and for three or more objectives;
+- what a neighbourhood is, and how mating (probability δ) and replacement
+ (limit n_r) use it;
+- how the ideal point and the aggregation function decide a replacement, and
+ which aggregation functions VAMOS offers;
+- how VAMOS implements and configures MOEA/D, and when to choose it.
+
+## From one weighted problem to many
+
+A scalarization turns a multi-objective problem into a single-objective one
+(lesson [B1](../basic/multi-objective-problems.md#turning-many-objectives-into-one-scalarization)).
+Solving it once gives one Pareto-optimal point; sweeping the weights and
+solving again gives others, one run per point. Zhang and Li [1] observed that
+the optimal solutions of two subproblems with **close weight vectors are
+close** in the objective space, so what one subproblem has found is useful to
+its neighbours. MOEA/D therefore solves all the subproblems together and lets
+neighbours share parents and offspring.
+
+The original algorithm let a good offspring replace every neighbour it
+improved. Two years later, MOEA/D-DE [2] replaced the genetic operators with
+differential evolution [3] and added two measures that protect diversity: with
+probability 1 − δ the parents and the candidates for replacement come from the
+whole population instead of the neighbourhood, and one offspring may replace at
+most n_r solutions. VAMOS implements this version, after jMetal.
+
+## Weight vectors and subproblems
+
+Each subproblem i has a weight vector wⁱ = (wⁱ₁, …, wⁱₘ) with non-negative
+components that add up to 1, and an aggregation function g(x | wⁱ, z\*) to
+minimize, where z\* is the ideal point (below). There is one solution per
+subproblem, so **the population size is the number of weight vectors**.
+VAMOS generates them as jMetal does:
+
+- **Two objectives.** N evenly spaced vectors, for any N:
+
+wᵏ = ( k / (N − 1), 1 − k / (N − 1) ), k = 0, 1, …, N − 1
+
+- **Three or more objectives.** The Das and Dennis simplex lattice [4]
+ explained in lesson [A1](../advanced/many-objective.md#nsga-iii-in-detail):
+ every vector whose components are multiples of 1/p, for p divisions, which
+ gives H = C(p + m − 1, m − 1) vectors. The population must have exactly H
+ members, for example 91 for three objectives and p = 12. When no complete
+ lattice has exactly the requested size, VAMOS uses the weight file that jMetal
+ distributes for that size if it ships one (`W3D_100.dat` gives 100 individuals
+ with three objectives), and otherwise stops with an error: a lattice is never
+ truncated, and the population size is never changed behind your back.
+
+`MOEADConfig.default(...)` chooses the lattice for you when you give no
+population size: 100 vectors with two objectives, 91 with three and the lattice
+with p = 6 beyond that. `weight_vectors(path=...)` reads your own vectors from
+a file instead.
+
+## Neighbourhoods
+
+The neighbourhood B(i) of subproblem i holds the indices of the T weight
+vectors closest to wⁱ in Euclidean distance, i itself included:
+
+B(i) = { the T indices j with the smallest ‖wʲ − wⁱ‖ } i ∈ B(i)
+
+The neighbourhoods are computed once, before the run. VAMOS's default is
+T = 20 (or N if the population is smaller). Lattice weights have many
+equidistant neighbours; VAMOS breaks those ties by index, so a run gives the
+same neighbourhoods, and the same results, on every platform.
+
+T sets how far information travels. With a small T, subproblems cooperate only
+with their immediate neighbours: the search is local and good genes spread
+slowly along the front. With a large T, an offspring competes with many
+subproblems, and a single good solution can take over a large part of the
+population, which is what the limit n_r prevents.
+
+## One step of MOEA/D
+
+VAMOS creates and places one offspring per step:
+
+1. **Choose a subproblem i.** The subproblems are visited in a random
+ permutation, a new one in each cycle of N steps (`subproblem_order`, whose
+ other value, `"cyclic"`, visits 0, 1, …, N − 1).
+2. **Choose the mating pool.** With probability δ (default 0.9) the pool P is
+ the neighbourhood B(i); otherwise it is the whole population.
+3. **Breed.** Draw two distinct parents r₁ and r₂ from P and create one
+ offspring y from them and the current solution xⁱ.
+4. **Evaluate y and update the ideal point** z\*.
+5. **Replace.** Visit the members of P in a random order, and let y replace
+ the solutions it improves, at most n_r of them.
+
+For step 3, VAMOS applies DE rand/1/bin [3] with the current solution xⁱ as the
+base vector, as MOEA/D-DE does, then polynomial mutation (lesson
+[I4](variation-operators.md#polynomial-mutation)):
+
+v = xⁱ + F · ( x^r₁ − x^r₂ )
+y_j = v_j if rand_j < CR or j = j_rand, otherwise y_j = xⁱ_j
+y ← polynomial mutation of y (p_m = 1/n, η_m = 20), then clipped to the bounds
+
+With VAMOS's defaults F = 0.5 and CR = 1.0, every variable comes from v. In
+step 5, whenever y is strictly better than the current solution of
+subproblem j **in subproblem j**, it takes its place, and the loop stops after
+n_r replacements (default 2):
+
+for j in P, in random order:
+ if g(y | wʲ, z*) < g(xʲ | wʲ, z*): xʲ ← y
+ stop after n_r replacements
+
+Notice that the offspring is compared with each neighbour's solution through
+the neighbour's weight vector, not through wⁱ. An offspring that is a poor
+answer to its own subproblem can still be a good answer to the next one.
+
+## The ideal point
+
+The Tchebycheff and PBI functions measure distances from the **ideal point**
+z\*, the best value of each objective (lesson
+[B2](../basic/pareto-dominance.md#ideal-and-nadir-points)). The true ideal
+point is unknown, so MOEA/D estimates it with the best values found so far:
+
+z*_k ← min( z*_k , f_k(y) ) for every objective k
+
+VAMOS starts from the minimum of the initial population and updates z\* with
+each offspring **before** the comparisons of step 5. Every move of z\* shifts
+all the subproblems at once; early in the run, when z\* is a poor estimate, the
+subproblems point at a different part of the front than they will at the end.
+
+## Aggregation functions
+
+The aggregation function decides what "better in subproblem j" means. VAMOS's
+three classic functions are:
+
+Tchebycheff: g(x | w, z*) = max_k w_k · | f_k(x) − z*_k | (a zero weight counts as 10⁻⁴)
+Weighted sum: g(x | w) = Σ_k w_k · f_k(x)
+PBI: g(x | w, z*) = d₁ + θ · d₂
+ d₁ = | (f(x) − z*) · w | / ‖w‖, d₂ = ‖ f(x) − z* − d₁ · w / ‖w‖ ‖
+
+They have different geometries:
+
+- **Tchebycheff** [5] has corner-shaped contour lines. On a continuous
+ two-objective front, the optimum of w lies where w₁(f₁ − z\*₁) = w₂(f₂ − z\*₂),
+ on the ray from z\* with direction (1/w₁, 1/w₂). It reaches every
+ Pareto-optimal point for some weight, whatever the shape of the front.
+- **Weighted sum** has straight contour lines perpendicular to w. It cannot
+ reach the non-convex parts of a front (lesson
+ [I6](beyond-nsga-ii.md#decomposition-based-algorithms)).
+- **PBI** (penalty-based boundary intersection), proposed with MOEA/D [1],
+ measures the progress d₁ along w and penalizes the distance d₂ from the ray
+ through z\* along w, with weight θ (VAMOS: 5). A large θ keeps each subproblem
+ close to its own ray.
+
+The same weight vector therefore asks for different points. With
+w = (0.2, 0.8), Tchebycheff wants f₁ − z\*₁ = 4 (f₂ − z\*₂), towards the
+lower right of a front, and PBI wants f₂ − z\*₂ = 4 (f₁ − z\*₁), towards the upper
+left. VAMOS also offers four more functions, with jMetal's definitions:
+
+| `aggregation(...)` | Definition | Parameter |
+| --- | --- | --- |
+| `"tchebycheff"` | max_k w_k \|f_k − z\*_k\| | none |
+| `"weighted_sum"` | Σ_k w_k f_k | none |
+| `"pbi"` | d₁ + θ d₂ from the ideal point | `theta`, default 5 |
+| `"modified_tchebycheff"` | Tchebycheff + ρ Σ_k w_k \|f_k − z\*_k\| | `rho`, default 10⁻³ |
+| `"augmented_tchebycheff"` | the same formula, jMetal's default [5] | `rho`, default 10⁻⁴ |
+| `"inverse_weight_tchebycheff"` | max_k \|f_k − z\*_k\| / w_k [6] | none |
+| `"inverted_pbi"` | θ d₂ − d₁ measured from the nadir point [7] | `theta`, default 0.1 |
+
+Every function accepts `normalize=True`, which divides each f_k − z\*_k by the
+current range z^nad_k − z\*_k (plus a small ε), with the nadir point estimated
+from the non-dominated solutions found so far. Without it, an objective
+measured in larger units dominates every aggregation. The [MOEA/D
+lesson](../../algorithms/moead.md#what-the-configuration-means) and the
+[configuration reference](../../reference/api/algorithms/moead.md) give the
+details.
+
+## Constraints
+
+With constraints (g_j(x) ≤ 0, lesson [A5](../advanced/constrained.md)), VAMOS's
+replacement follows the feasibility rules by default: a feasible offspring
+replaces an infeasible solution; between two infeasible solutions the smaller
+constraint violation wins; only two feasible solutions are compared by the
+aggregation function. `subproblem_update_criterion(...)` replaces this rule by
+an improved ε method or an adaptive violation threshold, as described in
+[subproblem update criteria](../../reference/constraints.md#moead-subproblem-update-criteria).
+
+## See a replacement
+
+The figure shows 11 subproblems with two objectives, their weight vectors drawn
+as rays from the ideal point, and the current solution of each subproblem.
+Select a subproblem to highlight its T neighbours, then drag the offspring. The
+table compares it with every candidate in the drawn order. Try:
+
+- the default position: the offspring improves three subproblems, but with
+ n_r = 2 it replaces only the first two it meets; shuffle the order, then raise
+ n_r;
+- the same offspring under PBI and under the weighted sum;
+- dragging the offspring left of every solution, so that z\* moves.
+
+
+
+## In VAMOS
+
+`MOEADConfig.default(...)` gives VAMOS's default configuration; `variant="de"`
+gives MOEA/D-DE as jMetal configures it, with the Tchebycheff function. The
+default factory also chooses the population from the lattice:
+
+```python
+from vamos.algorithms import MOEADConfig
+
+config = MOEADConfig.default(pop_size=100, n_var=30, n_obj=2)
+print("neighbourhood T:", config.neighbor_size)
+print("delta:", config.delta, " n_r:", config.replace_limit)
+print("crossover:", config.crossover)
+print("mutation:", config.mutation[0], "eta", config.mutation[1]["eta"])
+print("aggregation:", config.aggregation)
+print("variant 'de':", MOEADConfig.default(pop_size=100, n_var=30, n_obj=2, variant="de").aggregation)
+
+for n_obj in (2, 3, 5):
+ default = MOEADConfig.default(n_var=12, n_obj=n_obj)
+ print(f"{n_obj} objectives: pop_size {default.pop_size}, weight vectors {default.weight_vectors}")
+```
+
+Output:
+
+```text
+neighbourhood T: 20
+delta: 0.9 n_r: 2
+crossover: ('de', {'cr': 1.0, 'f': 0.5})
+mutation: pm eta 20.0
+aggregation: ('pbi', {'theta': 5.0})
+variant 'de': ('tchebycheff', {})
+2 objectives: pop_size 100, weight vectors {'path': None, 'divisions': 99}
+3 objectives: pop_size 91, weight vectors {'path': None, 'divisions': 12}
+5 objectives: pop_size 210, weight vectors {'path': None, 'divisions': 6}
+```
+
+Without `variant`, VAMOS pairs MOEA/D-DE's operators with PBI, its own choice;
+the [MOEA/D lesson](../../algorithms/moead.md#what-the-configuration-means)
+records this and the planned change of default.
+
+The weight vectors are built by a function that follows jMetal. With two
+objectives it is a `linspace`; with more, it tries the packaged jMetal file
+when no complete lattice has the requested size, and otherwise generates the
+lattice with exactly `pop_size` vectors (`strict=True`), or raises an error:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/components/weight_vectors.py
+def _load_or_generate_jmetalpy_weights(
+ pop_size: int, n_obj: int, path: str | None, divisions: int | None, sha256: str | None = None
+) -> FloatArray:
+ if n_obj == 2:
+ vals = np.linspace(0.0, 1.0, pop_size, dtype=float)
+ return np.column_stack([vals, 1.0 - vals])
+
+ weight_path = _resolve_jmetalpy_weight_path(path, n_obj, pop_size)
+ if weight_path is None and divisions is None and _exact_divisions(pop_size, n_obj) is None:
+ # No complete lattice has pop_size vectors: use the jMetal weights VAMOS ships for it, if any.
+ packaged = _packaged_weights(n_obj, pop_size)
+ if packaged is not None:
+ return packaged
+ weights = _generate_weights(pop_size, n_obj, divisions=divisions, strict=True)
+```
+
+The neighbourhoods are the first T columns of the sorted distance matrix
+between weight vectors. The stable sort puts the subproblem itself first
+(distance 0) and breaks ties by index:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/moead/neighborhood.py
+def compute_neighbors(weights: np.ndarray[Any, Any], neighbor_size: int) -> np.ndarray[Any, Any]:
+ """Compute neighborhood indices based on weight vector distances."""
+ dist = np.linalg.norm(weights[:, None, :] - weights[None, :, :], axis=2)
+ # Lattice weights have many equidistant neighbours; a stable sort breaks those ties by index, so the
+ # neighbourhoods, and the trajectory, are the same on every platform.
+ order = np.argsort(dist, axis=1, kind="stable")
+ return order[:, :neighbor_size]
+```
+
+`ask()` performs steps 1 to 3. `use_neighbors` is the draw against δ; the
+parents of the DE crossover are the random parents followed by the current
+solution of the subproblem, `st.X[active]`, which serves as the base vector
+and as the source of the variables that the crossover does not take from the
+mutant:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/moead/moead.py
+ active = self._next_active_indices(st, batch_size)
+ use_neighbors = st.rng.random(batch_size) < st.delta
+
+ parent_pairs = self._sample_parent_pairs(st, active, use_neighbors)
+
+ n_var = st.X.shape[1]
+ if self._cross_is_de:
+ # (random parents..., current solution): jMetal's MOEADDEBuilder, or Evolver's pool and the current one.
+ width = parent_pairs.shape[1]
+ parents = np.empty((batch_size, width + 1, n_var), dtype=st.X.dtype)
+ for slot in range(width):
+ parents[:, slot, :] = st.X[parent_pairs[:, slot]]
+ parents[:, width, :] = st.X[active]
+ offspring = st.crossover_fn(parents, st.rng)
+ children = offspring[:, 0, :].copy()
+ else:
+ parents = st.X[parent_pairs.reshape(-1)].reshape(batch_size, 2, n_var)
+ offspring = st.crossover_fn(parents, st.rng)
+ children = offspring[:, 0, :].copy()
+
+ children = st.mutation_fn(children, st.rng)
+```
+
+`batch_size` is 1 by default, which makes the algorithm steady-state. `tell()`
+then updates the ideal point with `st.ideal = np.minimum(st.ideal, F_child.min(axis=0))`
+and draws the order of the candidates, `st.rng.permutation(st.neighbors[active[0]])`
+or `st.rng.permutation(pop_size)`, depending on the same δ draw. The replacement
+loop is the heart of MOEA/D. VAMOS runs a compiled copy of it when Numba is
+installed; this is the pure-Python version, which performs the same comparisons:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/moead/neighborhood_kernels.py
+ replacements = 0
+ for idx in range(candidate_length):
+ k = int(candidate_order[idx])
+
+ diff_current = np.abs(F[k] - ideal)
+ diff_child = np.abs(child_f - ideal)
+
+ if normalize == 1 or agg_id in {AGG_INVERTED_PBI, AGG_INVERSE_WEIGHT_TCHEBYCHEFF}:
+ args = (k, weights, weights_safe, weights_unit, ideal, nadir, agg_id, agg_theta, agg_rho, agg_epsilon, normalize)
+ current_val = _scalar_aggregation(F[k], *args)
+ child_val = _scalar_aggregation(child_f, *args)
+ elif agg_id == AGG_TCHEBYCHEFF:
+ current_val = float(np.max(weights_safe[k] * diff_current))
+ child_val = float(np.max(weights_safe[k] * diff_child))
+ elif agg_id == AGG_WEIGHTED_SUM:
+ current_val = float(np.dot(weights[k], F[k]))
+ child_val = float(np.dot(weights[k], child_f))
+
+ replace = False
+ if use_constraints == 1:
+ current_cv = cv[k]
+ feas_child = child_cv <= 0.0
+ feas_curr = current_cv <= 0.0
+ if (not feas_curr) and feas_child:
+ replace = True
+ elif feas_child and feas_curr:
+ replace = child_val < current_val
+ else:
+ replace = child_cv < current_cv
+ else:
+ replace = child_val < current_val
+
+ if not replace:
+ continue
+
+ X[k] = child
+ F[k] = child_f
+ if use_constraints == 1:
+ G[k] = child_g
+ cv[k] = child_cv
+ replacements += 1
+ if replacements >= replace_limit:
+ break
+```
+
+Line by line: `k` is the next candidate in the random order; both values are
+computed with the weights of `k`. `weights_safe` is the weight matrix with
+every zero replaced by 10⁻⁴, the rule for zero weights in the Tchebycheff
+formula. The branches for PBI and the modified Tchebycheff, skipped here,
+follow the formulas above. Without constraints a replacement needs a strictly
+smaller value (`child_val < current_val`); with constraints the feasibility
+rules come first. The counter stops the loop at `replace_limit`, the n_r of
+the formulas.
+
+The aggregation function matters most when the front is not convex. ZDT2 [8]
+has the concave front f₂ = 1 − f₁². With the same operators and budget,
+Tchebycheff spreads the 50 subproblems along the front, while the weighted sum
+can only reach its two ends:
+
+```python
+import numpy as np
+
+from vamos import optimize
+from vamos.algorithms import MOEADConfig
+from vamos.problems import ZDT2
+
+problem = ZDT2(n_var=10) # concave Pareto front: f2 = 1 - f1^2
+for aggregation in ("tchebycheff", "weighted_sum"):
+ config = (
+ MOEADConfig.builder()
+ .pop_size(50)
+ .neighbor_size(10)
+ .delta(0.9)
+ .replace_limit(2)
+ .crossover("de", cr=1.0, f=0.5)
+ .mutation("pm", prob="1/n", eta=20.0)
+ .aggregation(aggregation)
+ .result_mode("population")
+ .build()
+ )
+ result = optimize(problem, algorithm="moead", algorithm_config=config, max_evaluations=4000, engine="numpy", seed=1)
+ distinct = np.unique(np.round(result.F, 2), axis=0)
+ print(f"{aggregation:<13} {result.data['evaluations']} evaluations, {len(result.F)} subproblems, {len(distinct)} distinct objective vectors")
+```
+
+Output:
+
+```text
+tchebycheff 4000 evaluations, 50 subproblems, 50 distinct objective vectors
+weighted_sum 4000 evaluations, 50 subproblems, 3 distinct objective vectors
+```
+
+`result_mode("population")` returns one solution per subproblem. With the
+weighted sum, many subproblems hold the same solution: nothing in MOEA/D
+prevents two subproblems from sharing one, and on a concave front the weighted
+sum gives them every reason to.
+
+## MOEA/D, NSGA-II and the decomposition family
+
+| | NSGA-II | MOEA/D |
+| --- | --- | --- |
+| Selection | Rank and crowding over parents and offspring | Scalar comparison within a neighbourhood |
+| Source of diversity | Crowding distance, measured each generation | Weight vectors, fixed before the run |
+| Offspring | N per generation | One per step (steady-state) |
+| Work per offspring | A share of the sort of 2N solutions | T aggregation values |
+| Population size | Free | The number of weight vectors |
+
+**Strengths.** Each step is cheap and local. Any single-objective operator,
+such as DE, plugs in directly, and Li and Zhang [2] showed that MOEA/D-DE
+handles problems whose Pareto sets have complicated shapes. Selection does not
+depend on dominance, so it keeps its pressure when most solutions are mutually
+non-dominated, which matters with many objectives (lesson
+[A1](../advanced/many-objective.md)).
+
+**Limits.** The weight vectors fix the distribution of the final solutions,
+and evenly spaced weights give evenly spaced solutions only when the front has
+the matching shape; Ishibuchi et al. [9] showed how strongly performance
+depends on that match. Objectives with different scales need `normalize=True`.
+Subproblems can share a solution, as the example shows, and with three or more
+objectives the population size is tied to the lattice.
+
+**When to use it.** MOEA/D-DE is a strong choice for two or three objectives
+with continuous variables, especially when the Pareto set is complicated; its
+descendants NSGA-III and RVEA (lessons [A2](../advanced/nsga-iii.md) and
+[A3](../advanced/rvea.md)) keep the idea of fixed
+directions for many objectives.
+
+## Key points
+
+- MOEA/D solves N scalar subproblems at once, one weight vector and one
+ solution each; the population size is the number of weight vectors.
+- Neighbourhoods are the T closest weight vectors. With probability δ mating
+ and replacement use the neighbourhood, otherwise the whole population.
+- An offspring replaces a solution only if it is better **in that solution's
+ subproblem**, and at most n_r solutions per offspring.
+- Tchebycheff, weighted sum and PBI define different subproblems for the same
+ weight vector; the weighted sum cannot reach non-convex parts of a front.
+- VAMOS's default uses DE and polynomial mutation, T = 20, δ = 0.9, n_r = 2
+ and PBI; `variant="de"` gives MOEA/D-DE with Tchebycheff.
+
+**Next:** [I9. SMS-EMOA: selection by hypervolume contribution](smsemoa.md).
+
+## References
+
+[1] Zhang, Q., and Li, H. (2007). [MOEA/D: A Multiobjective Evolutionary Algorithm Based on Decomposition](https://doi.org/10.1109/TEVC.2007.892759). *IEEE Transactions on Evolutionary Computation*, 11(6), 712–731.
+
+[2] Li, H., and Zhang, Q. (2009). [Multiobjective Optimization Problems With Complicated Pareto Sets, MOEA/D and NSGA-II](https://doi.org/10.1109/TEVC.2008.925798). *IEEE Transactions on Evolutionary Computation*, 13(2), 284–302.
+
+[3] Storn, R., and Price, K. (1997). [Differential Evolution – A Simple and Efficient Heuristic for Global Optimization over Continuous Spaces](https://doi.org/10.1023/A:1008202821328). *Journal of Global Optimization*, 11(4), 341–359.
+
+[4] Das, I., and Dennis, J. E. (1998). [Normal-boundary intersection: A new method for generating the Pareto surface in nonlinear multicriteria optimization problems](https://doi.org/10.1137/S1052623496307510). *SIAM Journal on Optimization*, 8(3), 631–657.
+
+[5] Steuer, R. E., and Choo, E.-U. (1983). [An interactive weighted Tchebycheff procedure for multiple objective programming](https://doi.org/10.1007/BF02591870). *Mathematical Programming*, 26(3), 326–344.
+
+[6] Qi, Y., Ma, X., Liu, F., Jiao, L., Sun, J., and Wu, J. (2014). [MOEA/D with Adaptive Weight Adjustment](https://doi.org/10.1162/EVCO_a_00109). *Evolutionary Computation*, 22(2), 231–264.
+
+[7] Sato, H. (2014). [Inverted PBI in MOEA/D and its impact on the search performance on multi and many-objective optimization](https://doi.org/10.1145/2576768.2598297). *Proceedings of the 2014 Annual Conference on Genetic and Evolutionary Computation (GECCO '14)*, 645–652.
+
+[8] Zitzler, E., Deb, K., and Thiele, L. (2000). [Comparison of multiobjective evolutionary algorithms: Empirical results](https://doi.org/10.1162/106365600568202). *Evolutionary Computation*, 8(2), 173–195.
+
+[9] Ishibuchi, H., Setoguchi, Y., Masuda, H., and Nojima, Y. (2017). [Performance of decomposition-based many-objective algorithms strongly depends on Pareto front shapes](https://doi.org/10.1109/TEVC.2016.2587749). *IEEE Transactions on Evolutionary Computation*, 21(2), 169–190.
diff --git a/docs/foundations/intermediate/non-dominated-sorting.md b/docs/foundations/intermediate/non-dominated-sorting.md
new file mode 100644
index 000000000..3c62b1794
--- /dev/null
+++ b/docs/foundations/intermediate/non-dominated-sorting.md
@@ -0,0 +1,218 @@
+---
+description: 'I2. Fast non-dominated sorting step by step: domination counters and dominated sets, its O(MN²) cost, an interactive stepper, and the vectorized implementation in VAMOS.'
+search:
+ boost: 0.5
+---
+
+# I2. Fast non-dominated sorting
+
+The first criterion of NSGA-II is the **rank** of each solution: the index of
+the non-dominated front it belongs to. Computing ranks is the most expensive
+step of the algorithm, and NSGA-II owes the "fast" in its title to the way it
+does it [1].
+
+In this lesson you will learn:
+
+- what non-domination fronts are;
+- the fast non-dominated sorting algorithm, its bookkeeping and its cost;
+- how VAMOS implements it with NumPy, and the faster method it uses for two
+ objectives.
+
+## Fronts and ranks
+
+Sort a population into layers:
+
+- **Front 1** (F₁) holds the solutions that no other solution dominates;
+- **Front 2** (F₂) holds those that no solution dominates once F₁ is removed;
+- and so on, until every solution has a front.
+
+The rank of a solution is the number of its front. Rank 1 is best. Every
+member of F₂ is dominated by at least one member of F₁, and solutions in the
+same front are mutually non-dominated. Goldberg [2] proposed this layering;
+Srinivas and Deb's NSGA [3] used it as fitness.
+
+**VAMOS numbers ranks from 0.** In its arrays, front 1 has rank 0.
+
+## The naive method and its cost
+
+The obvious approach finds F₁ by checking every solution against every other
+one (O(M N²) comparisons for N solutions and M objectives), removes it, and
+repeats on the rest. With up to N fronts, the worst case is O(M N³), the cost
+of the original NSGA [1].
+
+## The fast method
+
+NSGA-II compares every pair **once** and remembers the result in two
+structures per solution p [1]:
+
+- **n_p**, the *domination counter*: how many solutions dominate p;
+- **S_p**, the *dominated set*: the solutions that p dominates.
+
+for each p: S_p ← ∅, n_p ← 0
+for each pair (p, q):
+ if p ≺ q: add q to S_p
+ if q ≺ p: n_p ← n_p + 1
+F₁ ← { p : n_p = 0 }
+k ← 1
+while F_k is not empty:
+ F_{k+1} ← ∅
+ for each p in F_k:
+ for each q in S_p:
+ n_q ← n_q − 1
+ if n_q = 0: add q to F_{k+1}
+ k ← k + 1
+
+When a front is removed, only the counters of the solutions it dominates
+change, and a solution joins the next front at the moment its counter reaches
+zero: every solution that dominated it has already been placed. Step through
+it below. The number after each letter is the current counter n_p; focus or
+hover a point to draw its dominated set S_p.
+
+
+
+**Cost.** The pairwise comparisons cost O(M N²). Peeling the fronts visits each
+pair (p, q ∈ S_p) once, O(N²) in total. The memory for the sets S_p is O(N²).
+Since NSGA-II sorts the 2N solutions of the merged population every
+generation, this step dominates the cost of the algorithm [1].
+
+## In VAMOS
+
+VAMOS does not keep Python lists for S_p. Its NumPy kernel builds the complete
+dominance matrix with broadcasting (`dom_matrix[p, q]` is true when p
+dominates q) and derives every counter from it at once. Each loop iteration
+then extracts a whole front:
+
+```python
+# Excerpt from src/vamos/foundation/kernel/numpy_backend.py
+def _fast_non_dominated_sort_dense(F: RealArray) -> tuple[list[list[int]], IndexArray]:
+ """Dense vectorized fast non-dominated sort for moderate population sizes."""
+ N = F.shape[0]
+ less_equal = F[:, None, :] <= F[None, :, :]
+ strictly_less = F[:, None, :] < F[None, :, :]
+ dom_matrix = np.logical_and(
+ np.all(less_equal, axis=2),
+ np.any(strictly_less, axis=2),
+ )
+
+ dominated_count = dom_matrix.sum(axis=0).astype(np.int64)
+ rank = np.empty(N, dtype=int)
+ fronts: list[list[int]] = []
+
+ current = np.flatnonzero(dominated_count == 0)
+ level = 0
+ while current.size > 0:
+ fronts.append(current.tolist())
+ rank[current] = level
+ dom_contrib = dom_matrix[current].sum(axis=0)
+ dominated_count -= dom_contrib
+ dominated_count[current] = -1
+ dom_matrix[current] = False
+ level += 1
+ current = np.flatnonzero(dominated_count == 0)
+
+ return fronts, rank
+```
+
+Read it against the pseudo-code:
+
+- the row `dom_matrix[p]` is S_p, and the column sum `dominated_count[q]` is n_q;
+- `dom_matrix[current].sum(axis=0)` counts, for every q, how many members of the
+ current front dominate it: one subtraction updates all the counters;
+- setting the counters of the extracted front to −1 removes it, so it is never
+ selected again.
+
+The matrix has N² entries per objective. For very large populations the
+kernel switches to `_fast_non_dominated_sort_blocked`, which processes the
+comparisons in blocks of rows to bound memory.
+
+**Two objectives.** With M = 2, VAMOS uses a different algorithm in O(N log N):
+it visits the points by increasing f₁ and finds the rank of each one with a
+binary search over the last point of each front, in the spirit of the
+efficient methods of Kung, Luccio and Preparata [4] and Jensen [5]. It returns
+the same ranks as the dense sort:
+
+```python
+# Excerpt from src/vamos/foundation/kernel/numpy_backend.py
+ order = np.lexsort((F[:, 1], F[:, 0]))
+ f1 = F[order, 0].tolist()
+ f2 = F[order, 1].tolist()
+ last_rows: list[tuple[float, float]] = []
+ sorted_ranks: list[int] = []
+ for key in zip(f2, f1):
+ rank = bisect_left(last_rows, key)
+ if rank == len(last_rows):
+ last_rows.append(key)
+ else:
+ last_rows[rank] = key
+ sorted_ranks.append(rank)
+```
+
+You can obtain the ranks of any set of objective vectors through the
+experimental public helper `vamos.select_survivors`, which applies the NSGA-II
+ranking and crowding of the NumPy kernel. These are the twelve points of the
+figure above:
+
+```python
+import numpy as np
+
+from vamos import select_survivors
+
+points = np.array(
+ [
+ [0.08, 0.78], [0.20, 0.50], [0.45, 0.30], [0.80, 0.10],
+ [0.18, 0.92], [0.32, 0.62], [0.55, 0.45], [0.90, 0.30],
+ [0.45, 0.85], [0.66, 0.62], [0.95, 0.55], [0.75, 0.90],
+ ]
+)
+selection = select_survivors(points, survivor_count=len(points))
+labels = "ABCDEFGHIJKL"
+for rank in range(max(selection.ranks) + 1):
+ members = [labels[i] for i, r in enumerate(selection.ranks) if r == rank]
+ print(f"front {rank + 1} (rank {rank}):", ", ".join(members))
+```
+
+Output:
+
+```text
+front 1 (rank 0): A, B, C, D
+front 2 (rank 1): E, F, G, H
+front 3 (rank 2): I, J, K
+front 4 (rank 3): L
+```
+
+`select_survivors` is exported by `vamos` but is **experimental**: it is not
+covered by the [1.x stability policy](../../project/stability-and-versioning.md).
+
+## Details that matter
+
+- **Duplicates.** Two identical objective vectors do not dominate each other,
+ so they share a front. Crowding distance then has to separate them
+ (lesson [I3](crowding-distance.md)).
+- **Constraints.** With constraints, VAMOS' default NSGA-II sorts with
+ *constrained domination* instead of plain dominance: a feasible solution
+ beats an infeasible one. Lesson [A5](../advanced/constrained.md) explains it.
+- **Many objectives.** As M grows, almost every solution lands in F₁, and the
+ rank stops discriminating. Lesson [A1](../advanced/many-objective.md) shows
+ why and what replaces it.
+
+## Key points
+
+- Fronts layer a population by dominance; the rank of a solution is its front.
+- Fast non-dominated sorting compares every pair once and stores a counter n_p
+ and a set S_p per solution: O(M N²) time and O(N²) memory.
+- VAMOS vectorizes it with a dominance matrix and uses an O(N log N) method for
+ two objectives.
+
+**Next:** [I3. Crowding distance and tournament selection](crowding-distance.md).
+
+## References
+
+[1] Deb, K., Pratap, A., Agarwal, S., and Meyarivan, T. (2002). [A fast and elitist multiobjective genetic algorithm: NSGA-II](https://doi.org/10.1109/4235.996017). *IEEE Transactions on Evolutionary Computation*, 6(2), 182–197.
+
+[2] Goldberg, D. E. (1989). *Genetic Algorithms in Search, Optimization and Machine Learning*. Addison-Wesley.
+
+[3] Srinivas, N., and Deb, K. (1994). [Multiobjective optimization using nondominated sorting in genetic algorithms](https://doi.org/10.1162/evco.1994.2.3.221). *Evolutionary Computation*, 2(3), 221–248.
+
+[4] Kung, H. T., Luccio, F., and Preparata, F. P. (1975). [On finding the maxima of a set of vectors](https://doi.org/10.1145/321906.321910). *Journal of the ACM*, 22(4), 469–476.
+
+[5] Jensen, M. T. (2003). [Reducing the run-time complexity of multiobjective EAs: The NSGA-II and other algorithms](https://doi.org/10.1109/TEVC.2003.817234). *IEEE Transactions on Evolutionary Computation*, 7(5), 503–515.
diff --git a/docs/foundations/intermediate/nsga-ii.md b/docs/foundations/intermediate/nsga-ii.md
new file mode 100644
index 000000000..e1458338b
--- /dev/null
+++ b/docs/foundations/intermediate/nsga-ii.md
@@ -0,0 +1,181 @@
+---
+description: 'I1. NSGA-II at a glance: why it was proposed, its generational loop, a live NSGA-II running in the page, and the same configuration in VAMOS.'
+search:
+ boost: 0.5
+---
+
+# I1. NSGA-II at a glance
+
+NSGA-II, the *Non-dominated Sorting Genetic Algorithm II* of Deb, Pratap,
+Agarwal and Meyarivan [1], is the most widely used evolutionary
+multi-objective algorithm. It is the default reference point in almost every
+comparison, and its two selection criteria, Pareto rank and crowding
+distance, reappear in many later algorithms. The Intermediate level takes it
+apart: this lesson gives the whole picture, and lessons I2 to I5 explain each
+step in detail together with the VAMOS code that implements it.
+
+In this lesson you will learn:
+
+- which problems of its predecessor NSGA-II solved;
+- the structure of one NSGA-II generation;
+- how a population converges to the front, by watching it happen;
+- how to run the same configuration in VAMOS.
+
+## Where NSGA-II comes from
+
+Goldberg [2] suggested ranking a population by Pareto dominance. Srinivas and
+Deb [3] turned the idea into NSGA, which sorted the population into
+non-dominated fronts and used *fitness sharing* to keep diversity inside each
+front. NSGA worked, but had three weaknesses that the NSGA-II paper lists
+explicitly [1]:
+
+| Weakness of NSGA | Answer in NSGA-II | Lesson |
+| --- | --- | --- |
+| Sorting cost O(M N³) for N solutions and M objectives | **Fast non-dominated sorting**, O(M N²) | [I2](non-dominated-sorting.md) |
+| A sharing parameter σ_share that had to be tuned | **Crowding distance**, which has no parameter | [I3](crowding-distance.md) |
+| No elitism: good solutions could be lost | **Elitist survival**: parents and offspring compete together | [I5](elitist-survival.md) |
+
+## One generation
+
+NSGA-II keeps a population P of N solutions. Each generation creates N
+offspring, merges them with the parents, and keeps the best N:
+
+
+
+In pseudo-code, following the paper [1]:
+
+P₀ ← N random solutions; evaluate them; sort P₀ into fronts and compute crowding distances
+for t = 0, 1, 2, … while the evaluation budget lasts:
+ Qₜ ← N offspring of Pₜ: binary tournament on (rank, crowding) → SBX crossover → polynomial mutation
+ evaluate Qₜ
+ Rₜ ← Pₜ ∪ Qₜ (2N solutions)
+ F₁, F₂, … ← fast non-dominated sort of Rₜ
+ Pₜ₊₁ ← whole fronts F₁, F₂, … while they fit in N places;
+ fill the remaining places from the next front, largest crowding distance first
+
+Two criteria drive everything: **rank** (the front a solution belongs to)
+pushes the population towards the Pareto front, and **crowding distance**
+spreads it along the front. Rank always comes first; crowding only breaks ties
+between solutions of the same front.
+
+## Watch it converge
+
+The figure runs NSGA-II with VAMOS' default real-coded settings on ZDT1, ZDT2
+or ZDT3 with 30 variables: binary tournament, SBX with probability 0.9 and
+η_c = 20, polynomial mutation with probability 1/30 and η_m = 20. Press
+**Play**, or advance one generation at a time. Blue points are the first front
+of the current population; grey points are dominated.
+
+
+
+What to look for:
+
+1. **Two phases.** For the first generations the population moves down
+ towards the front (convergence); the first front holds few points. Later
+ almost every solution is non-dominated and the work shifts to spreading
+ them evenly (diversity).
+2. **Diminishing returns.** The hypervolume curve rises steeply, then slowly.
+ Each additional percent costs more evaluations than the previous one.
+3. **Population size.** With 20 solutions the front is reached sooner per
+ evaluation but covered sparsely; with 100 it takes longer but the coverage
+ is dense. Neither is "right": it depends on how many alternatives the
+ decision maker needs and on the budget.
+4. **Shape.** On ZDT3 the population splits into the five disconnected pieces
+ of the front, without any parameter telling it to.
+
+This figure runs a compact JavaScript port of the algorithm, written for
+teaching. VAMOS runs the same steps in Python with vectorized NumPy kernels.
+
+## The same run in VAMOS
+
+The configuration of the figure, written with the explicit builder, run for
+an increasing number of generations. Every run uses the same seed. The *mean
+gap* is the average vertical distance of the non-dominated points to the ZDT1
+front f₂ = 1 − √f₁.
+
+```python
+import numpy as np
+
+from vamos import optimize
+from vamos.algorithms import NSGAIIConfig
+from vamos.problems import ZDT1
+
+problem = ZDT1(n_var=30)
+config = (
+ NSGAIIConfig.builder()
+ .pop_size(100)
+ .crossover("sbx", prob=0.9, eta=20.0)
+ .mutation("pm", prob="1/n", eta=20.0)
+ .selection("tournament", size=2)
+ .build()
+)
+print("generations evaluations non-dominated mean gap")
+for generations in (1, 10, 50, 100, 200):
+ result = optimize(problem, algorithm="nsgaii", algorithm_config=config, termination=("n_gen", generations), engine="numpy", seed=1)
+ front = result.front()
+ gap = np.mean(front[:, 1] - (1.0 - np.sqrt(front[:, 0])))
+ print(f"{generations:>11} {result.data['evaluations']:>11} {len(front):>13} {gap:>8.4f}")
+```
+
+Output:
+
+```text
+generations evaluations non-dominated mean gap
+ 1 100 11 3.1383
+ 10 1000 13 1.4859
+ 50 5000 69 0.2758
+ 100 10000 100 0.0253
+ 200 20000 100 0.0029
+```
+
+One generation means the random initial population only: the budget of a run
+always includes it. `NSGAIIConfig.default(pop_size=100, n_var=30)` produces
+exactly this configuration. The [NSGA-II lesson](../../algorithms/nsgaii.md)
+covers the remaining options, such as the steady-state variant and external
+archives, and the [configuration reference](../../reference/api/algorithms/nsgaii.md)
+lists every field.
+
+## Where each step lives in VAMOS
+
+| Step | Lesson | VAMOS source |
+| --- | --- | --- |
+| Generation loop (ask, evaluate, tell) | [I5](elitist-survival.md) | `src/vamos/engine/algorithm/nsgaii/ask_tell.py` |
+| Fast non-dominated sorting | [I2](non-dominated-sorting.md) | `_fast_non_dominated_sort` in `src/vamos/foundation/kernel/numpy_backend.py` |
+| Crowding distance | [I3](crowding-distance.md) | `_compute_crowding` in the same file |
+| Binary tournament | [I3](crowding-distance.md) | `NumPyKernel.tournament_selection` in the same file |
+| SBX and polynomial mutation | [I4](variation-operators.md) | `src/vamos/foundation/kernel/operator_primitives.py` |
+| Elitist survival | [I5](elitist-survival.md) | `_select_nsga2` and `NumPyKernel.nsga2_survival` in `numpy_backend.py` |
+
+The NumPy kernel is the reference implementation. The Numba and MooCore
+engines implement the same kernel interface and are tested against it; see
+[algorithms and backends](../../reference/algorithms.md).
+
+## Cost of one generation
+
+Sorting 2N solutions with M objectives costs O(M N²) comparisons, which
+dominates everything else; crowding costs O(M N log N) [1]. Jensen [4] showed
+that sorting can be done in O(N log^(M−1) N). For two objectives VAMOS uses an
+O(N log N) sort (lesson [I2](non-dominated-sorting.md#in-vamos)). In practice,
+for expensive problems the evaluations cost far more than the algorithm.
+
+## Key points
+
+- NSGA-II added fast sorting, a parameter-free diversity measure and elitism
+ to NSGA.
+- Each generation creates N offspring, merges them with the N parents, and keeps
+ the best N by rank, then by crowding distance.
+- Rank drives convergence; crowding distance drives spread. Rank always has
+ priority.
+- The budget counts every evaluation, including the initial population.
+
+**Next:** [I2. Fast non-dominated sorting](non-dominated-sorting.md).
+
+## References
+
+[1] Deb, K., Pratap, A., Agarwal, S., and Meyarivan, T. (2002). [A fast and elitist multiobjective genetic algorithm: NSGA-II](https://doi.org/10.1109/4235.996017). *IEEE Transactions on Evolutionary Computation*, 6(2), 182–197.
+
+[2] Goldberg, D. E. (1989). *Genetic Algorithms in Search, Optimization and Machine Learning*. Addison-Wesley.
+
+[3] Srinivas, N., and Deb, K. (1994). [Multiobjective optimization using nondominated sorting in genetic algorithms](https://doi.org/10.1162/evco.1994.2.3.221). *Evolutionary Computation*, 2(3), 221–248.
+
+[4] Jensen, M. T. (2003). [Reducing the run-time complexity of multiobjective EAs: The NSGA-II and other algorithms](https://doi.org/10.1109/TEVC.2003.817234). *IEEE Transactions on Evolutionary Computation*, 7(5), 503–515.
diff --git a/docs/foundations/intermediate/smpso.md b/docs/foundations/intermediate/smpso.md
new file mode 100644
index 000000000..28a791b9c
--- /dev/null
+++ b/docs/foundations/intermediate/smpso.md
@@ -0,0 +1,406 @@
+---
+description: 'I11. SMPSO in depth: particle swarm basics, the velocity update with inertia, C1, C2, r1 and r2, the constriction coefficient and the speed constraint, the leaders archive with crowding distance, personal bests and polynomial-mutation turbulence, with an interactive figure and the VAMOS code.'
+search:
+ boost: 0.5
+---
+
+# I11. SMPSO: multi-objective particle swarm optimization
+
+Every algorithm so far breeds children from parents with crossover and
+mutation. Particle swarm optimization (PSO), introduced by Kennedy and
+Eberhart in 1995 [2], works differently: a *swarm* of particles flies through
+the decision space, and each particle moves according to its own best position
+so far and the best position known to the swarm. Nothing is recombined; every
+particle is updated in place.
+
+SMPSO, the *speed-constrained multi-objective PSO* of Nebro et al. [1], adapts
+this idea to several objectives. The best position known to the swarm is
+replaced by an archive of non-dominated **leaders**, from which every particle
+picks its guide, and the velocity of each particle is bounded so that it
+cannot jump erratically between the bounds of the variables. Unlike NSGA-II,
+the swarm itself is not elitist: the archive keeps the best solutions, and it
+is what VAMOS returns.
+
+In this lesson you will learn:
+
+- how a particle moves: position, velocity, personal best and leader;
+- the velocity update with the inertia w and the coefficients C₁, C₂, r₁ and r₂;
+- the constriction coefficient χ and the speed constraint that define SMPSO;
+- how the leaders archive, leader selection, personal bests and turbulence
+ work, and how VAMOS implements and configures them.
+
+## From bird flocks to multi-objective swarms
+
+Kennedy and Eberhart [2] modelled a population that shares information like a
+flock of birds: each particle keeps its position x, its velocity v and the best
+position it has visited, its *personal best* p, and it is also attracted by the
+best position found by the swarm, the *leader* g. Two later additions became
+standard: an **inertia weight** w that scales the previous velocity, proposed by
+Shi and Eberhart [3], and a **constriction coefficient** χ that scales the
+whole update, derived by Clerc and Kennedy [4] from a stability analysis of the
+particle's trajectory.
+
+With several objectives there is no single best position. Multi-objective PSOs
+keep the non-dominated positions found so far in an archive and let each
+particle choose its leader there; how the archive is bounded and how a leader
+is chosen decide the spread of the result. Nebro et al. [1] observed that in
+some problems the velocities grow so large that particles move erratically,
+from one bound of a variable to the other, and they proposed SMPSO with a
+**speed constraint** on every variable.
+
+## A particle and its velocity
+
+At each iteration every particle computes a new velocity from three terms and
+moves:
+
+v ← w · v + C₁ r₁ (p − x) + C₂ r₂ (g − x)
+x ← x + v
+
+- **Inertia** w · v keeps part of the previous movement. VAMOS uses w = 0.1, a
+ small value: the particle has little momentum.
+- **The cognitive term** C₁ r₁ (p − x) pulls the particle towards its own
+ personal best.
+- **The social term** C₂ r₂ (g − x) pulls it towards its leader.
+
+r₁ and r₂ are random numbers in [0, 1] that vary the strength of the two pulls;
+C₁ and C₂ set their scale. VAMOS, like jMetal, draws one r₁, one r₂, one C₁ and
+one C₂ per particle and iteration, shared by all its variables, with C₁ and C₂
+uniform in [c1, c1 + 1] and [c2, c2 + 1]: [1.5, 2.5] with the defaults. The
+pulls change length from one iteration to the next, never direction.
+
+## Constriction and the speed constraint
+
+SMPSO then scales the new velocity by the constriction coefficient, which
+depends on φ = C₁ + C₂:
+
+φ = C₁ + C₂
+χ = 2 / ( 2 − φ − √(φ² − 4φ) ) if φ > 4, χ = 1 otherwise
+v ← χ · ( w · v + C₁ r₁ (p − x) + C₂ r₂ (g − x) )
+
+and clamps every component of the velocity to a fraction of the range of its
+variable, the **speed constraint** that gives SMPSO its name:
+
+δ_j = vmax_fraction · ( x_j^U − x_j^L ) (VAMOS default: vmax_fraction = 0.5)
+v_j ← min( max( v_j, −δ_j ), δ_j )
+x_j ← x_j + v_j
+if x_j < x_j^L: x_j ← x_j^L, v_j ← −v_j if x_j > x_j^U: x_j ← x_j^U, v_j ← −v_j
+
+With the default, no step can be longer than half the range of a variable. A
+particle that crosses a bound stops on it, and that component of its velocity
+changes sign.
+
+Look closely at the sign of χ. For φ > 4 the denominator 2 − φ − √(φ² − 4φ) is
+negative, and VAMOS evaluates the expression as written, as in jMetal (see the
+[SMPSO lesson](../../algorithms/smpso.md#understand-the-configuration)), so
+χ lies between −1 and 0: about −0.73 for φ = 4.1 and −0.38 for φ = 5. Clerc and
+Kennedy's coefficient [4] is the absolute value of this number, 0.73 for
+φ = 4.1. With the default draws, φ is the sum of two uniform values in
+[1.5, 2.5], so φ > 4 in half of the updates; in those, the step points in the
+opposite direction of the combined pull, before the speed constraint bounds it.
+In the other half, χ = 1 and the speed constraint alone limits the step.
+
+## See one velocity update
+
+The figure shows one particle in a two-variable decision space with bounds
+[0, 1], its current velocity, its personal best and its leader. The arrows are
+the three terms of the update; their sum is the unconstrained new velocity,
+which the figure then constricts and clamps. Try:
+
+- the default C₁ = 2.0 and C₂ = 1.9: φ = 3.9, χ = 1, and the speed constraint
+ cuts the first component of the step from 0.95 to 0.5;
+- C₁ + C₂ above 4, for example 2.2 and 2.3: χ = −0.5, the step reverses and the
+ particle stops on the lower bounds;
+- resampling r₁ and r₂ several times.
+
+
+
+## Leaders, personal bests and turbulence
+
+**The leaders archive.** SMPSO keeps the non-dominated positions found so far
+in an archive of bounded size, by default the swarm size. VAMOS inserts the
+particles one at a time, as jMetal does: a particle that a leader dominates, or
+equals, is rejected; leaders that the particle dominates leave; and when the
+archive overflows, the leader with the smallest crowding distance (lesson
+[I3](crowding-distance.md)) is removed. Crowding distance [5] keeps the leaders
+spread along the front, with the boundary leaders always kept.
+
+**Choosing a leader.** For each particle, two distinct leaders are drawn at
+random and the one with the larger crowding distance wins; a tie is decided by
+a coin. Leaders in sparse regions are chosen more often, so the swarm is drawn
+towards the gaps of the front. While the archive holds at most two leaders,
+VAMOS gives every particle the first one.
+
+**The personal best.** After evaluation, each particle compares its new
+position with its personal best. The new position replaces the personal best
+**unless the personal best dominates it**:
+
+p ← x unless f(p) ≺ f(x)
+
+So a new position that is better, or merely incomparable, becomes the new
+personal best. With constraints, a feasible personal best is kept against an
+infeasible position, and between two infeasible ones the smaller violation
+wins.
+
+**Turbulence.** PSO has no mutation of its own. SMPSO adds polynomial mutation
+(lesson [I4](variation-operators.md#polynomial-mutation), [6]) to part of the
+swarm, a *turbulence* that helps particles leave local optima. VAMOS mutates
+every sixth particle (indices 0, 6, 12, …) after it moves, with p_m = 1/n and
+η_m = 20 by default.
+
+One iteration of VAMOS's SMPSO therefore runs: choose a leader for every
+particle, update velocities and positions, apply the turbulence, evaluate the
+swarm, update the personal bests, and insert the new positions into the
+leaders archive. The swarm starts at random positions with zero velocity, and
+each personal best starts at its particle's initial position.
+
+## In VAMOS
+
+`SMPSOConfig.default(...)` gives the default configuration:
+
+```python
+from vamos.algorithms import SMPSOConfig
+
+config = SMPSOConfig.default(n_var=30)
+name, params = config.mutation
+print("swarm:", config.pop_size, " leaders archive:", config.archive_size)
+print("inertia w:", config.inertia)
+print("C1 drawn from", [config.c1, config.c1 + 1.0], " C2 drawn from", [config.c2, config.c2 + 1.0])
+print("speed constraint: vmax_fraction", config.vmax_fraction)
+print("turbulence:", name, "prob", round(params["prob"], 4), "eta", params["eta"])
+print("result:", config.result_mode)
+```
+
+Output:
+
+```text
+swarm: 100 leaders archive: 100
+inertia w: 0.1
+C1 drawn from [1.5, 2.5] C2 drawn from [1.5, 2.5]
+speed constraint: vmax_fraction 0.5
+turbulence: polynomial prob 0.0333 eta 20.0
+result: non_dominated
+```
+
+`result_mode` `non_dominated` returns the leaders archive; `population`
+returns the final swarm. The velocity update in `SMPSO.ask()` follows the
+formulas above, for the whole swarm at once:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/smpso/smpso.py
+ # PSO velocity update (SMPSO with constriction)
+ pop_size, n_var = st.X.shape
+ # Drawn per particle and used as drawn, as in jMetal (jMetalPy rounds them to one decimal).
+ r1 = st.rng.uniform(st.r1_min, st.r1_max, size=(pop_size, 1))
+ r2 = st.rng.uniform(st.r2_min, st.r2_max, size=(pop_size, 1))
+ c1 = st.rng.uniform(st.c1_min, st.c1_max, size=(pop_size, 1))
+ c2 = st.rng.uniform(st.c2_min, st.c2_max, size=(pop_size, 1))
+ rho = c1 + c2
+ disc = np.maximum(rho * rho - 4.0 * rho, 0.0)
+ constriction = np.where(
+ rho <= 4.0,
+ 1.0,
+ 2.0 / (2.0 - rho - np.sqrt(disc)),
+ )
+ velocity = constriction * (st.max_weight * st.velocity + c1 * r1 * (st.pbest_X - st.X) + c2 * r2 * (leaders - st.X))
+ velocity = np.clip(velocity, st.delta_min, st.delta_max)
+
+ # Position update
+ X_new = st.X + velocity
+ low_mask = X_new < st.xl
+ if np.any(low_mask):
+ X_new = np.where(low_mask, st.xl, X_new)
+ velocity[low_mask] *= st.change_velocity1
+ high_mask = X_new > st.xu
+ if np.any(high_mask):
+ X_new = np.where(high_mask, st.xu, X_new)
+ velocity[high_mask] *= st.change_velocity2
+
+ # Apply mutation (turbulence)
+ if st.mutation_op is not None:
+ if st.mutation_every <= 1:
+ X_new = st.mutation_op(X_new, st.rng)
+ else:
+ mask = (np.arange(pop_size) % st.mutation_every) == 0
+ if np.any(mask):
+ X_new[mask] = st.mutation_op(X_new[mask], st.rng)
+```
+
+Line by line: the four random factors have shape `(pop_size, 1)`, one value
+per particle that broadcasts over its variables. `rho` is φ, and `disc` guards
+the square root when φ ≤ 4, where `np.where` returns 1. `st.max_weight` is the
+inertia w, and `leaders` holds one leader per particle. `st.delta_min` and
+`st.delta_max` are ∓δ, computed once from the bounds and `vmax_fraction`.
+`change_velocity1` and `change_velocity2` are −1, the reversal at the bounds.
+The last block is the turbulence: `mutation_every` is 6.
+
+The leader of each particle comes from a binary tournament on the crowding
+distances of the archive, computed once per iteration:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/smpso/smpso.py
+ size = arch_X.shape[0]
+ if size == 0:
+ raise ValueError("Archive is empty.")
+ if size <= 2:
+ leaders = np.repeat(arch_X[:1], n_select, axis=0)
+ leader_idx = np.zeros(n_select, dtype=int)
+ return leaders, leader_idx
+
+ first = rng.integers(0, size, size=n_select, dtype=int)
+ second = rng.integers(0, size - 1, size=n_select, dtype=int)
+ second += second >= first
+ crowding_first = np.nan_to_num(crowding[first], nan=-np.inf)
+ crowding_second = np.nan_to_num(crowding[second], nan=-np.inf)
+
+ leader_idx = np.empty(n_select, dtype=int)
+ better_first = crowding_first > crowding_second
+ better_second = crowding_second > crowding_first
+ leader_idx[better_first] = first[better_first]
+ leader_idx[better_second] = second[better_second]
+
+ tied = ~(better_first | better_second)
+ if tied.any():
+ flip = rng.integers(0, 2, size=int(tied.sum()), dtype=int)
+ leader_idx[tied] = np.where(flip == 0, first[tied], second[tied])
+
+ leaders = arch_X[leader_idx]
+ return leaders, leader_idx
+```
+
+The second draw skips the first index, so the two contestants always differ,
+the same trick as the parent tournament of NSGA-II (lesson
+[I3](crowding-distance.md#in-vamos)). The personal bests are updated after
+evaluation:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/smpso/helpers.py
+ if technique is not None and constraint_mode != "none" and G is not None and pbest_G is not None:
+ from vamos.engine.algorithm.components.constraint_handling import preferred
+
+ update_idx = ~preferred(technique, pbest_F, pbest_G, F, G)
+ elif constraint_mode and constraint_mode != "none" and G is not None and pbest_G is not None:
+ feas_new = is_feasible(G)
+ feas_old = is_feasible(pbest_G)
+ cv_new = compute_violation(G)
+ cv_old = compute_violation(pbest_G)
+
+ both_infeasible = ~feas_new & ~feas_old
+ same_violation = (feas_new & feas_old) | (both_infeasible & (cv_new == cv_old))
+ old_better = (feas_old & ~feas_new) | (both_infeasible & (cv_old < cv_new)) | (same_violation & dominates(pbest_F, F))
+ update_idx = ~old_better
+ else:
+ # Without constraints, update if current is not dominated by personal best
+ update_idx = ~dominates(pbest_F, F)
+
+ pbest_X[update_idx] = X[update_idx]
+ pbest_F[update_idx] = F[update_idx]
+ if pbest_G is not None and G is not None:
+ pbest_G[update_idx] = G[update_idx]
+```
+
+The first branch applies a constraint-handling technique chosen with
+`constraint_handling(...)` (see the [constraint
+reference](../../reference/constraints.md#choose-a-constraint-handling-technique)).
+The second is the default with constraints: the personal best survives only
+when it is better, that is feasible against infeasible, less violated, or
+dominating at equal violation. Without constraints only dominance counts.
+
+The speed constraint is what makes SMPSO work on multimodal problems. ZDT4 [7]
+has many local Pareto fronts; its distance function g equals 1 only on the
+global front. With the default constraint, almost every leader reaches the
+global front within 10,000 evaluations; with `vmax_fraction(10.0)`, which lets
+a step span ten times the range of a variable, none does:
+
+```python
+import numpy as np
+
+from vamos import optimize
+from vamos.algorithms import SMPSOConfig
+from vamos.problems import ZDT4
+
+problem = ZDT4(n_var=10) # x1 in [0, 1], x2..x10 in [-5, 5]
+for vmax_fraction in (0.5, 10.0):
+ config = (
+ SMPSOConfig.builder()
+ .pop_size(100)
+ .archive_size(100)
+ .mutation("pm", prob="1/n", eta=20.0)
+ .vmax_fraction(vmax_fraction)
+ .build()
+ )
+ result = optimize(problem, algorithm="smpso", algorithm_config=config, max_evaluations=10_000, engine="numpy", seed=2)
+ X = result.X # the leaders archive
+ g = 1 + 10 * (problem.n_var - 1) + np.sum(X[:, 1:] ** 2 - 10 * np.cos(4 * np.pi * X[:, 1:]), axis=1)
+ print(f"vmax_fraction {vmax_fraction}: {len(X)} leaders, {int(np.sum(g < 1.01))} on the global front (g < 1.01)")
+```
+
+Output:
+
+```text
+vmax_fraction 0.5: 100 leaders, 96 on the global front (g < 1.01)
+vmax_fraction 10.0: 12 leaders, 0 on the global front (g < 1.01)
+```
+
+This is one seed, but not a lucky one: over seeds 1 to 10 the default put
+between 91 and 100 leaders on the global front, and `vmax_fraction` 1.0 or
+more put none. The [SMPSO lesson](../../algorithms/smpso.md) records a run
+with a smaller budget and the changes VAMOS 1.2.0 made to follow jMetal.
+
+## SMPSO compared with NSGA-II and MOEA/D
+
+| | NSGA-II | MOEA/D | SMPSO |
+| --- | --- | --- | --- |
+| New solutions | SBX and polynomial mutation | DE and polynomial mutation | Velocity update, turbulence on every sixth particle |
+| Memory | The population | One solution per subproblem | Personal bests and the leaders archive |
+| Elitism | Survival of the best N of 2N | Replacement only by better solutions | Only in the archive; the swarm always moves |
+| Diversity | Crowding distance | Weight vectors | Crowding distance in the archive and in leader selection |
+| Encodings in VAMOS | All | All, with suitable operators | Real and mixed |
+
+**Strengths.** The velocity update is cheap and vectorized, and the particles
+follow directed trajectories with memory instead of random recombination. The
+speed constraint makes SMPSO robust on multimodal problems such as ZDT4, as
+the example shows.
+
+**Limits.** SMPSO needs a velocity, so VAMOS rejects binary, integer and
+permutation problems. The archive is bounded with crowding distance, which
+degrades with many objectives (lesson [A1](../advanced/many-objective.md)).
+The swarm is not elitist: the final swarm can be far worse than the archive,
+which is why the archive is the default result.
+
+**When to use it.** Continuous problems with two or three objectives,
+especially multimodal ones, and cheap evaluations where many iterations are
+affordable.
+
+## Key points
+
+- A particle moves with a velocity that combines inertia, a pull towards its
+ personal best and a pull towards a leader, scaled by the random C₁ r₁ and
+ C₂ r₂.
+- SMPSO scales the velocity by the constriction coefficient χ when
+ C₁ + C₂ > 4, then clamps each component to vmax_fraction of the variable's
+ range: the speed constraint. In VAMOS, χ is negative when C₁ + C₂ > 4.
+- Leaders come from a bounded archive of non-dominated positions, truncated by
+ crowding distance and sampled by a crowding tournament; the archive is the
+ result.
+- A personal best is replaced unless it dominates the new position; polynomial
+ mutation on every sixth particle adds turbulence.
+- VAMOS's defaults: w = 0.1, C₁ and C₂ in [1.5, 2.5], vmax_fraction 0.5,
+ archive and swarm of 100.
+
+**Next level:** [A1. Many-objective optimization](../advanced/many-objective.md).
+
+## References
+
+[1] Nebro, A. J., Durillo, J. J., García-Nieto, J., Coello Coello, C. A., Luna, F., and Alba, E. (2009). [SMPSO: A new PSO-based metaheuristic for multi-objective optimization](https://doi.org/10.1109/MCDM.2009.4938830). *IEEE Symposium on Computational Intelligence in Multi-Criteria Decision-Making*, 66–73.
+
+[2] Kennedy, J., and Eberhart, R. (1995). [Particle swarm optimization](https://doi.org/10.1109/ICNN.1995.488968). *Proceedings of ICNN'95 – International Conference on Neural Networks*, 4, 1942–1948.
+
+[3] Shi, Y., and Eberhart, R. (1998). [A modified particle swarm optimizer](https://doi.org/10.1109/ICEC.1998.699146). *Proceedings of the 1998 IEEE International Conference on Evolutionary Computation*, 69–73.
+
+[4] Clerc, M., and Kennedy, J. (2002). [The particle swarm – explosion, stability, and convergence in a multidimensional complex space](https://doi.org/10.1109/4235.985692). *IEEE Transactions on Evolutionary Computation*, 6(1), 58–73.
+
+[5] Deb, K., Pratap, A., Agarwal, S., and Meyarivan, T. (2002). [A fast and elitist multiobjective genetic algorithm: NSGA-II](https://doi.org/10.1109/4235.996017). *IEEE Transactions on Evolutionary Computation*, 6(2), 182–197.
+
+[6] Deb, K., and Goyal, M. (1996). A combined genetic adaptive search (GeneAS) for engineering design. *Computer Science and Informatics*, 26(4), 30–45.
+
+[7] Zitzler, E., Deb, K., and Thiele, L. (2000). [Comparison of multiobjective evolutionary algorithms: Empirical results](https://doi.org/10.1162/106365600568202). *Evolutionary Computation*, 8(2), 173–195.
diff --git a/docs/foundations/intermediate/smsemoa.md b/docs/foundations/intermediate/smsemoa.md
new file mode 100644
index 000000000..258f309e7
--- /dev/null
+++ b/docs/foundations/intermediate/smsemoa.md
@@ -0,0 +1,421 @@
+---
+description: 'I9. SMS-EMOA in depth: the steady-state (μ + 1) loop, non-dominated sorting of the N + 1 solutions, removal of the least hypervolume contributor of the last front, the reference point, special cases and cost, with interactive figures and the VAMOS implementation.'
+search:
+ boost: 0.5
+---
+
+# I9. SMS-EMOA: selection by hypervolume contribution
+
+Lesson [B4](../basic/quality-indicators.md#hypervolume) showed that the
+hypervolume rewards convergence, spread and uniformity at once, and lesson
+[I6](beyond-nsga-ii.md#indicator-based-algorithms) asked why an algorithm
+should not select for it directly. SMS-EMOA, the *S-metric selection*
+evolutionary multi-objective algorithm of Emmerich, Beume and Naujoks [1, 2],
+does exactly that, in the simplest possible way: create one offspring, and
+remove the solution whose loss costs the least hypervolume.
+
+SMS-EMOA keeps NSGA-II's non-dominated sorting for convergence and replaces the
+crowding distance with the **exclusive hypervolume contribution** for
+diversity. Because it removes a single solution per step, its contributions
+always describe the current set; NSGA-II, which cuts a whole front with
+distances computed once (lesson [I3](crowding-distance.md)), has no such
+guarantee.
+
+In this lesson you will learn:
+
+- the steady-state (μ + 1) loop and what it changes;
+- how the N + 1 solutions are sorted, and which front loses a member;
+- how the exclusive hypervolume contribution is computed, and how the reference
+ point changes it;
+- what VAMOS does when the last front has one point, with more than two
+ objectives and with constraints;
+- what the selection costs, and when to use SMS-EMOA.
+
+## From an indicator to a selection rule
+
+The hypervolume, or S metric, was introduced to compare the results of
+multi-objective algorithms [3]. A set of a given size that maximizes it
+contains only Pareto-optimal points [4], so an algorithm whose population never
+loses hypervolume moves towards the front. Emmerich, Beume and Naujoks turned
+that observation into a selection operator [2], and Beume, Naujoks and Emmerich
+evaluated the resulting algorithm on two- and three-objective benchmarks and on
+aeronautical design problems [1].
+
+## The steady-state loop
+
+SMS-EMOA is a (μ + 1) algorithm, in the terminology of evolution strategies:
+μ = N parents create one offspring, and the worst of the N + 1 solutions
+leaves.
+
+P ← N random solutions, evaluated
+repeat until the evaluation budget is spent:
+ choose two parents in P
+ q ← mutation( first child of crossover(parents) ), evaluate q
+ Q ← P ∪ {q} (N + 1 solutions)
+ F₁, …, F_v ← non-dominated sort of Q (lesson I2)
+ r ← the member s of F_v with the smallest ΔS(s, F_v)
+ P ← Q \ {r}
+
+Each evaluation changes the population, so a good child can become a parent
+at once, as in steady-state NSGA-II (lesson
+[I5](elitist-survival.md#steady-state-nsga-ii)). The child competes on equal
+terms: if it is the worst of the N + 1, it is the one removed, and the
+population does not change.
+
+Parent selection is not part of the method. VAMOS draws both parents uniformly
+at random by default, `selection("random")`, and `selection("tournament")`
+uses NSGA-II's tournament on rank and crowding distance instead.
+
+## Sorting the N + 1 solutions
+
+The N + 1 solutions are sorted into fronts exactly as in NSGA-II (lesson
+[I2](non-dominated-sorting.md)). Only the **last front** F_v can lose a member;
+every earlier front is safe. Early in a run, F_v often holds dominated
+solutions or the child alone. Later, all N + 1 solutions are often mutually
+non-dominated, v = 1, and the hypervolume alone decides.
+
+VAMOS does not sort from scratch at every step. It keeps the fronts of the
+population and inserts the child: the child joins the first front whose members
+do not dominate it, and the members it dominates move down one front, possibly
+pushing others further. The result is the same set of fronts as a full sort.
+
+Beume et al. [1] also describe a cheaper rule for a population with more than
+one front: remove the member of the last front that the most solutions
+dominate. VAMOS does not use it; it always measures hypervolume contributions.
+
+## The exclusive hypervolume contribution
+
+With S(A) the hypervolume of a set A with respect to a reference point r
+(lesson [B4](../basic/quality-indicators.md#hypervolume)), the exclusive
+contribution of s to the last front is the hypervolume lost if s leaves:
+
+ΔS(s, F_v) = S(F_v) − S(F_v \ {s})
+
+With two objectives it is a rectangle. Sort F_v by f₁, so that s₁, …, s_n have
+increasing f₁ and decreasing f₂; each point's rectangle reaches to the next
+point along f₁ and to the previous point along f₂, and the two extremes reach
+the reference point:
+
+ΔS(sᵢ) = ( f₁(sᵢ₊₁) − f₁(sᵢ) ) · ( f₂(sᵢ₋₁) − f₂(sᵢ) ), with f₂(s₀) = r₂ and f₁(sₙ₊₁) = r₁
+
+A point squeezed between close neighbours has a thin rectangle and leaves
+first, so the removals thin out crowded regions. Drag the points of the figure
+and watch which one SMS-EMOA would discard:
+
+
+
+## The reference point
+
+The two extremes' contributions extend to r, so r decides how much they are
+worth. Too close, and the extremes contribute almost nothing and are removed
+first; far away, and they are always kept. VAMOS offers three rules through
+`SMSEMOAConfig.builder().reference_point(...)`:
+
+"relative" (default): r = nadir + offset · (nadir − ideal) offset = 1.0, recomputed at every step
+"jmetal": rᵢ = 1.1 · max fᵢ, or max fᵢ / 1.1 when max fᵢ < 0, recomputed at every step
+vector=[…]: a fixed r given by the user
+
+Ideal and nadir are the best and worst value of each objective over **all
+N + 1 solutions**, not only the last front (lesson
+[B2](../basic/pareto-dominance.md#ideal-and-nadir-points)). The default places r
+one objective range beyond the worst values, so rescaling an objective rescales
+r with it and the selection does not depend on the units. jMetal's rule lies
+close to the worst values. A fixed vector suits an objective space whose
+bounds are known; points outside its box contribute 0 and are removed before any
+point inside it with a positive contribution. The
+[SMS-EMOA lesson](../../algorithms/smsemoa.md#understand-the-configuration)
+compares the rules and records when VAMOS introduced them. Auger et al. [5]
+showed how r shapes the distribution that maximizes the hypervolume, and
+Ishibuchi et al. [6] how to choose it.
+
+## Special cases in VAMOS
+
+- **The last front has one solution.** It is removed at once, and no
+ hypervolume is computed. If that solution is the child, the population does
+ not change.
+- **Ties.** The first of the equal smallest contributions is removed, in the
+ order of the population with the child last. Duplicated points contribute 0.
+- **More than two objectives.** The contributions are exact: MooCore's
+ `hv_contributions` when MooCore is installed, otherwise an exact sweep for two
+ objectives and, for three or more, one exact hypervolume of the front for each
+ point left out. VAMOS uses no approximation.
+- **Constraints.** With the default `constraint_mode="feasibility"`, while any of
+ the N + 1 solutions is infeasible, the one with the largest total violation is
+ removed (the last one on ties), and no hypervolume is computed. A
+ `constraint_handling(...)` technique ranks the N + 1 solutions instead, and the
+ least contributor of its last front leaves; see
+ [choose a constraint-handling technique](../../reference/constraints.md#choose-a-constraint-handling-technique).
+- **Duplicates.** With `eliminate_duplicates(True)`, a child that repeats a
+ decision vector or an objective vector of the population is discarded.
+
+## Step through one selection
+
+Six parents, P1 to P6, and one child C. Press the step buttons: sort into
+fronts, identify the last front, compute its contributions, remove the worst.
+Things to try:
+
+1. In the default scenario, the child is dominated by P3 and P4. It is alone in
+ the last front, so VAMOS removes it without computing any hypervolume.
+2. Switch to the second scenario, or drag C below the front, and step again. All
+ seven points form one front; P4, squeezed between P3 and C, has the smallest
+ contribution and leaves.
+3. Lower the reference offset to 0. The extremes P1 and P6 now contribute
+ nothing, and P1, the first of them, is removed: the population starts losing
+ its spread.
+
+
+
+## In VAMOS
+
+The contributions of the second scenario, with MooCore and VAMOS' default
+reference point:
+
+```python
+import moocore
+import numpy as np
+
+parents = np.array([[0.08, 0.90], [0.20, 0.62], [0.35, 0.45], [0.40, 0.40], [0.62, 0.22], [0.90, 0.06]])
+child = np.array([[0.50, 0.30]])
+candidates = np.vstack([parents, child]) # the N + 1 solutions, here a single front
+nadir, ideal = candidates.max(axis=0), candidates.min(axis=0)
+reference = nadir + 1.0 * (nadir - ideal) # VAMOS' default reference point, offset 1.0
+contributions = moocore.hv_contributions(candidates, ref=reference)
+
+labels = ["P1", "P2", "P3", "P4", "P5", "P6", "C"]
+print("reference point:", reference.round(3))
+for label, (f1, f2), value in zip(labels, candidates, contributions):
+ print(f"{label} ({f1:.2f}, {f2:.2f}): contribution {value:.4f}")
+print("SMS-EMOA removes", labels[int(np.argmin(contributions))])
+```
+
+Output:
+
+```text
+reference point: [1.72 1.74]
+P1 (0.08, 0.90): contribution 0.1008
+P2 (0.20, 0.62): contribution 0.0420
+P3 (0.35, 0.45): contribution 0.0085
+P4 (0.40, 0.40): contribution 0.0050
+P5 (0.62, 0.22): contribution 0.0224
+P6 (0.90, 0.06): contribution 0.1312
+C (0.50, 0.30): contribution 0.0120
+SMS-EMOA removes P4
+```
+
+The large margin of the default reference point gives the extremes the two
+largest contributions. In the algorithm, one step generates a single child,
+evaluates it, counts the evaluation and runs the survival:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/smsemoa/smsemoa.py
+ def _reference_step(
+ self, st: SMSEMOAState, problem: ProblemProtocol, eval_strategy: EvaluationBackend
+ ) -> tuple[NDArray[Any], NDArray[np.float64], NDArray[np.float64] | None]:
+ """Generate, evaluate and insert one child (the reference for ``CompiledSteadyStep``).
+
+ Returns the evaluated child as ``(X, F, G)`` rows.
+ """
+ X_child = self._generate_offspring(st)
+ F_child, G_child = self._evaluate_offspring(problem, X_child, eval_strategy, st.constraint_mode)
+ # A constraint-handling technique follows the evaluations before the child's.
+ progress = run_progress(st.n_eval, st.max_evals)
+ st.n_eval += X_child.shape[0]
+ survival_selection(st, X_child, F_child, G_child, self.kernel, progress)
+ return X_child, F_child, G_child
+```
+
+`_generate_offspring` draws the two parents (with replacement under random
+selection), applies the crossover, and mutates and keeps only its first child.
+Without constraints, the survival works on a buffer `F_work` that holds the N
+parents and the child in its last row:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/smsemoa/helpers.py
+ F_work = _ensure_objective_buffer(st, pop_n, st.F.shape[1])
+ F_work[:pop_n] = st.F
+ F_work[pop_n] = F_child[0]
+
+ if st.ref_adaptive:
+ st.ref_point = update_reference_point(st.ref_point, F_work, st.ref_offset, st.ref_rule)
+
+ fronts = [list(front) for front in st.fronts]
+ ranks = np.empty(pop_n + 1, dtype=int)
+ ranks[:pop_n] = st.ranks
+ ranks[pop_n] = -1
+ incremental_insert_fronts(fronts, ranks, F_work, pop_n)
+
+ worst_front = np.asarray(fronts[-1], dtype=int)
+ if worst_front.size == 1:
+ remove_idx = int(worst_front[0])
+ else:
+ remove_idx = int(worst_front[least_contributor(kernel, F_work[worst_front], st.ref_point)])
+
+ if remove_idx == pop_n:
+ return
+
+ _write_child_survivor(st, X_child, F_child, G_child, pop_n, remove_idx)
+```
+
+- The adaptive reference point is updated from all N + 1 rows before anything is
+ removed.
+- `incremental_insert_fronts` inserts row `pop_n`, the child, into the cached
+ fronts.
+- A last front of one member is removed directly; otherwise
+ `least_contributor` picks the member to remove.
+- `remove_idx == pop_n` means the child itself lost: the population is left
+ unchanged. Otherwise the child takes the place of the removed member, and the
+ cached fronts, ranks and crowding distances are updated for the next parent
+ selection.
+
+`least_contributor` measures the contributions inside the reference box only:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/smsemoa/helpers.py
+def least_contributor(kernel: KernelBackend, points: FloatArray, ref_point: FloatArray) -> int:
+ """Row of ``points`` with the smallest hypervolume contribution (the first on ties).
+
+ Points outside the reference box (a fixed user reference) contribute 0; the
+ others are measured among themselves with the kernel's contribution hook.
+ """
+ inside = np.all(points <= ref_point, axis=1)
+ if bool(inside.all()):
+ contributions = kernel.hypervolume_contributions(points, ref_point)
+ else:
+ contributions = np.zeros(points.shape[0], dtype=float)
+ if bool(inside.any()):
+ contributions[inside] = kernel.hypervolume_contributions(points[inside], ref_point)
+ return int(np.argmin(contributions))
+```
+
+With the adaptive rules, every point lies inside the box; only a fixed vector
+can leave some outside. `np.argmin` returns the first smallest value, the tie
+rule above. The default reference point is computed by:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/components/hv_reference.py
+def relative_reference_point(F: ArrayLike, offset: float) -> NDArray[np.float64]:
+ """``nadir + offset * (nadir - ideal)`` of the rows of ``F``, objective by objective.
+
+ The point is the reference ``1 + offset`` of the objectives normalized to
+ ``[0, 1]`` by the ideal and the nadir of ``F``, expressed in the original units.
+ Rescaling an objective rescales the reference with it, so the order of the
+ hypervolume contributions, and any selection that follows it, does not depend
+ on the objective units. An objective with no spread uses a range of 1: all
+ points then share that factor of their contributions.
+ """
+ values = np.asarray(F, dtype=float)
+ top = np.max(values, axis=0)
+ span = top - np.min(values, axis=0)
+ span = np.where(span > 0.0, span, 1.0)
+ return np.asarray(top + offset * span, dtype=np.float64)
+```
+
+A complete run on ZDT1 with the default reference point written out:
+
+```python
+from vamos import optimize
+from vamos.algorithms import SMSEMOAConfig
+from vamos.problems import ZDT1
+
+problem = ZDT1(n_var=30)
+config = (
+ SMSEMOAConfig.builder()
+ .pop_size(50)
+ .crossover("sbx", prob=0.9, eta=20.0)
+ .mutation("pm", prob="1/n", eta=20.0)
+ .selection("random")
+ .reference_point(offset=1.0, adaptive=True)
+ .build()
+)
+result = optimize(problem, algorithm="smsemoa", algorithm_config=config, max_evaluations=5_000, engine="numpy", seed=1)
+
+F = result.F
+print("evaluations:", result.data["evaluations"], "| generations of 50 children:", result.data["generation"])
+print("returned:", F.shape, "| f1 from", round(float(F[:, 0].min()), 3), "to", round(float(F[:, 0].max()), 3))
+print("reference point of the last step:", result.data["reference_point"].round(3))
+```
+
+Output:
+
+```text
+evaluations: 5000 | generations of 50 children: 99
+returned: (50, 2) | f1 from 0.0 to 0.991
+reference point of the last step: [1.982 2.118]
+```
+
+After the 50 initial evaluations, 4,950 children were created, one per step;
+VAMOS counts a generation every 50 children. The returned set spans nearly the
+whole range of f₁, because the extremes carry large contributions. The
+[SMS-EMOA lesson](../../algorithms/smsemoa.md) records a run with a fixed
+reference point, and the
+[configuration reference](../../reference/api/algorithms/smsemoa.md) lists every
+builder method.
+
+## Cost
+
+Each evaluation is followed by one contributions computation on the last front.
+With two objectives, a sort of that front suffices, O(n log n) for n points. The
+cost of the exact hypervolume, and of exact contributions, grows exponentially
+with the number of objectives [7, 8]; Guerreiro, Fonseca and Paquete [9] survey
+the exact and approximate algorithms. A run of E evaluations computes E sets of
+contributions, where NSGA-II computes E / N sets of crowding distances.
+
+With `engine="numba"` and a supported configuration (real encoding with SBX
+and polynomial mutation, among others), VAMOS compiles the whole step, including
+the two-objective contributions, and reproduces the NumPy path. For many objectives,
+HypE [10] estimates the contributions by Monte Carlo sampling, and
+reference-direction algorithms avoid them altogether (lesson
+[A1](../advanced/many-objective.md)).
+
+## SMS-EMOA compared
+
+- **With NSGA-II.** Same sorting; the hypervolume contribution replaces the
+ crowding distance, and one child per step replaces N. The contributions
+ account for the shape of the front and are recomputed after every removal.
+- **With SPEA2** (lesson [I7](spea2.md)). Both remove one solution at a time;
+ SPEA2 measures distances to neighbours, SMS-EMOA measures the volume a point
+ adds, so its distribution depends on the shape of the front and on the
+ reference point [5].
+- **With IBEA** (lesson [I10](ibea.md)). IBEA also selects by an indicator but
+ needs only pairwise indicator values, which stay cheap with many objectives.
+- **When to use it.** Two or three objectives, when the hypervolume is the
+ measure that matters, and especially when evaluations are expensive enough
+ that the per-step selection cost does not matter.
+
+## Key points
+
+- SMS-EMOA is steady-state: each step creates one child and removes one of the
+ N + 1 solutions.
+- Only the last front loses a member: the one with the smallest exclusive
+ hypervolume contribution ΔS(s, F_v) = S(F_v) − S(F_v \ {s}).
+- The reference point sets the contributions of the extremes; VAMOS' default
+ is nadir + 1.0 · (nadir − ideal) of the N + 1 solutions, recomputed at every
+ step.
+- VAMOS removes a single-member last front directly, computes exact
+ contributions for any number of objectives, and handles constraints by
+ violation first.
+- The cost of exact contributions limits SMS-EMOA to few objectives.
+
+**Next:** [I10. IBEA: indicator-based fitness](ibea.md).
+
+## References
+
+[1] Beume, N., Naujoks, B., and Emmerich, M. (2007). [SMS-EMOA: Multiobjective selection based on dominated hypervolume](https://doi.org/10.1016/j.ejor.2006.08.008). *European Journal of Operational Research*, 181(3), 1653–1669.
+
+[2] Emmerich, M., Beume, N., and Naujoks, B. (2005). An EMO algorithm using the hypervolume measure as selection criterion. *Evolutionary Multi-Criterion Optimization – EMO 2005*, Lecture Notes in Computer Science 3410, 62–76.
+
+[3] Zitzler, E., and Thiele, L. (1998). [Multiobjective optimization using evolutionary algorithms – A comparative case study](https://doi.org/10.1007/BFb0056872). *Parallel Problem Solving from Nature – PPSN V*, Lecture Notes in Computer Science 1498, 292–301.
+
+[4] Fleischer, M. (2003). [The measure of Pareto optima: Applications to multi-objective metaheuristics](https://doi.org/10.1007/3-540-36970-8_37). *Evolutionary Multi-Criterion Optimization – EMO 2003*, Lecture Notes in Computer Science 2632, 519–533.
+
+[5] Auger, A., Bader, J., Brockhoff, D., and Zitzler, E. (2009). [Theory of the hypervolume indicator: Optimal μ-distributions and the choice of the reference point](https://doi.org/10.1145/1527125.1527138). *Proceedings of the Tenth ACM SIGEVO Workshop on Foundations of Genetic Algorithms (FOGA '09)*, 87–102.
+
+[6] Ishibuchi, H., Imada, R., Setoguchi, Y., and Nojima, Y. (2018). [How to specify a reference point in hypervolume calculation for fair performance comparison](https://doi.org/10.1162/evco_a_00226). *Evolutionary Computation*, 26(3), 411–440.
+
+[7] Beume, N., Fonseca, C. M., López-Ibáñez, M., Paquete, L., and Vahrenhold, J. (2009). [On the complexity of computing the hypervolume indicator](https://doi.org/10.1109/TEVC.2009.2015575). *IEEE Transactions on Evolutionary Computation*, 13(5), 1075–1082.
+
+[8] Bringmann, K., and Friedrich, T. (2010). [Approximating the volume of unions and intersections of high-dimensional geometric objects](https://doi.org/10.1016/j.comgeo.2010.03.004). *Computational Geometry*, 43(6–7), 601–610.
+
+[9] Guerreiro, A. P., Fonseca, C. M., and Paquete, L. (2021). [The hypervolume indicator: Computational problems and algorithms](https://doi.org/10.1145/3453474). *ACM Computing Surveys*, 54(6), Article 119.
+
+[10] Bader, J., and Zitzler, E. (2011). [HypE: An algorithm for fast hypervolume-based many-objective optimization](https://doi.org/10.1162/EVCO_a_00009). *Evolutionary Computation*, 19(1), 45–76.
diff --git a/docs/foundations/intermediate/spea2.md b/docs/foundations/intermediate/spea2.md
new file mode 100644
index 000000000..1d2f7f100
--- /dev/null
+++ b/docs/foundations/intermediate/spea2.md
@@ -0,0 +1,414 @@
+---
+description: 'I7. SPEA2 in depth: strength and raw fitness, k-th nearest-neighbour density, environmental selection into a fixed-size archive, the truncation operator and mating selection, with an interactive figure and the VAMOS implementation.'
+search:
+ boost: 0.5
+---
+
+# I7. SPEA2: strength, density and archive truncation
+
+NSGA-II sorts the population into fronts and breaks ties within a front by
+crowding distance. SPEA2, the second version of the Strength Pareto
+Evolutionary Algorithm by Zitzler, Laumanns and Thiele [1], answers the same two
+questions, convergence and spread, in a different way: every solution receives
+one number, its **fitness**, that counts the dominance relations it takes part
+in and adds a small density term, and the best solutions are kept in an
+**archive** of fixed size.
+
+When the archive overflows with non-dominated solutions, SPEA2 does not cut
+it in one shot as NSGA-II does with crowding distances (lesson
+[I3](crowding-distance.md)). It removes one solution at a time, always the one
+whose neighbours are closest, and measures the distances again after every
+removal. It is the second classic of the Pareto-based family of lesson
+[I6](beyond-nsga-ii.md#pareto-based-algorithms).
+
+In this lesson you will learn:
+
+- how strength and raw fitness turn dominance into a number;
+- how the distance to the k-th nearest neighbour estimates density, and the k
+ that VAMOS uses;
+- how the archive is filled, and how the truncation operator chooses which
+ solutions to remove;
+- how parents are chosen, and how VAMOS implements each step.
+
+## From SPEA to SPEA2
+
+The first SPEA [2] already kept an external archive of non-dominated solutions.
+An archive member's *strength* was the share of the population it dominated, the
+fitness of a population member was computed from the strengths of the archive
+members that dominated it, and clustering reduced the archive when it grew too
+large. Zitzler, Laumanns and Thiele [1] identified three weaknesses:
+
+- **Coarse fitness.** Solutions dominated by the same archive members had the
+ same fitness. With a single archive member, the whole population had one
+ fitness value, whether its members dominated each other or not.
+- **No density information** when many solutions are mutually non-dominated, as
+ the dominance relation alone cannot order them.
+- **Lost extremes.** Clustering could remove the outer solutions of the front.
+
+SPEA2 fixes them with a finer fitness, a nearest-neighbour density estimate and
+a new truncation operator, and keeps the archive at a constant size.
+
+## Strength and raw fitness
+
+SPEA2 assigns fitness to the union of the archive Aₜ and the current population
+Pₜ, M = N_A + N solutions in total. The **strength** of a solution is the number
+of solutions it dominates, and its **raw fitness** sums the strengths of the
+solutions that dominate it (≺ is Pareto dominance, lesson
+[B2](../basic/pareto-dominance.md)):
+
+S(i) = | { j ∈ Aₜ ∪ Pₜ : i ≺ j } |
+R(i) = Σ_{j ∈ Aₜ ∪ Pₜ, j ≺ i} S(j)
+
+Raw fitness is minimized. R(i) = 0 means that no solution dominates i. A
+dominated solution is penalized more when it has many dominators and when they
+are strong, that is, when they dominate many other solutions as well. Unlike
+SPEA, dominators are counted in the whole union, archive and population alike,
+so even a dominated solution contributes its strength.
+
+## Density from the k-th nearest neighbour
+
+Raw fitness cannot separate mutually non-dominated solutions, which all have
+R = 0. SPEA2 adds a density term based on σᵢᵏ, the Euclidean distance in
+objective space from i to its k-th nearest neighbour among all M solutions, a
+classical density estimator [3]:
+
+D(i) = 1 / ( σᵢᵏ + 2 )
+F(i) = R(i) + D(i)
+
+The constant 2 keeps D(i) in (0, 0.5], so D(i) < 1. Because R is an integer,
+density only orders solutions of equal raw fitness, and every non-dominated
+solution has F(i) < 1. A solution with a close k-th neighbour sits in a
+crowded region and has a larger D, a worse fitness.
+
+The paper uses k = √M, the square root of the sample size [1]. VAMOS follows
+jMetal instead: `k_neighbors` defaults to **1**, the nearest neighbour, and
+`SPEA2Config.builder().k_neighbors(k)` sets another value. The distances use the
+objective values as they are, without normalization, so an objective with a much
+larger range dominates them; scale such objectives in the problem definition.
+
+## Environmental selection
+
+Each generation, the new archive is built from the union, in two cases:
+
+Q ← Aₜ ∪ Pₜ (M solutions)
+compute S, R, D and F for every member of Q
+Aₜ₊₁ ← { i ∈ Q : R(i) = 0 } (the non-dominated, F(i) < 1)
+if |Aₜ₊₁| > N_A: remove members with the truncation operator until |Aₜ₊₁| = N_A
+if |Aₜ₊₁| < N_A: add the N_A − |Aₜ₊₁| dominated members of Q with the lowest F
+
+Early in a run, few solutions are non-dominated and the archive is completed
+with the best dominated ones. Later, more than N_A solutions are usually
+non-dominated, and the truncation operator decides.
+
+## The truncation operator
+
+Let σᵢˡ now denote the distance from i to its l-th nearest neighbour **among the
+members still in the archive**. The truncation removes, one at a time, a member
+i that satisfies i ≤_d j for every other member j, where
+
+i ≤_d j ⇔ σᵢˡ = σⱼˡ for every l,
+ or there is a k with σᵢˡ = σⱼˡ for every l < k, and σᵢᵏ < σⱼᵏ
+
+In words: remove the member with the closest nearest neighbour; on a tie,
+compare the second-closest neighbours, then the third, and so on. This is a
+**lexicographic** comparison of the sorted neighbour distances, and it is
+recomputed after every removal. Two consequences:
+
+- **The closest pair always ties.** Its two members share the same nearest
+ distance, so the second neighbour decides which of them goes: the one whose
+ other neighbours are also close.
+- **Boundary solutions are protected.** An extreme solution has neighbours on one
+ side only, so its second-nearest distance is usually larger than its
+ neighbour's, and its neighbour is removed instead. Zitzler, Laumanns and
+ Thiele designed the operator for this purpose [1].
+
+The cost is higher than one crowding computation: each removal examines the
+distances among all remaining members.
+
+## Mating selection
+
+Only archive members become parents. SPEA2 fills the mating pool with binary
+tournaments on the archive, comparing fitness F [1, 4]. The population of the
+next generation consists of the N offspring created from that pool, so SPEA2 is
+elitist through its archive: a solution survives only while it stays in Aₜ.
+
+## Try it: fitness and truncation
+
+The ten points below play the union Aₜ ∪ Pₜ. The table gives each point's
+strength, raw fitness, k-th neighbour distance, density and fitness, and the
+archive-size control applies environmental selection. Things to try:
+
+1. Keep archive size 5. Seven points are non-dominated, so two must go: P5
+ leaves first, then P2. P5 and P6 form the closest pair; P5 goes because its
+ second neighbour, P4, is closer than P6's.
+2. Set the archive size to 8 and 9. P8 and P10 are dominated with the same
+ R = 2; P10 sits next to P6, so its density is higher and P8 enters first.
+3. Drag a point onto another one and watch S, R and the truncation order change.
+ Switch k from 1 to 3 (√10 ≈ 3, the paper's rule for ten points).
+
+
+
+## In VAMOS
+
+The definitions above fit in a few lines of NumPy. These are the ten points of
+the figure, with VAMOS' default k = 1 and an archive of five:
+
+```python
+import numpy as np
+
+F = np.array([[0.05, 0.92], [0.12, 0.70], [0.16, 0.64], [0.30, 0.45], [0.45, 0.33],
+ [0.50, 0.30], [0.85, 0.08], [0.40, 0.62], [0.70, 0.55], [0.55, 0.32]]) # P1 ... P10
+dominates = np.all(F[:, None] <= F[None, :], axis=2) & np.any(F[:, None] < F[None, :], axis=2)
+S = dominates.sum(axis=1) # strength: how many points each point dominates
+R = dominates.T.astype(int) @ S # raw fitness: the strengths of its dominators
+distances = np.linalg.norm(F[:, None] - F[None, :], axis=2)
+k = 1 # VAMOS' default k_neighbors
+sigma_k = np.sort(distances, axis=1)[:, k] # column 0 is the distance to itself
+D = 1.0 / (sigma_k + 2.0)
+for i in range(len(F)):
+ print(f"P{i + 1}: S={S[i]} R={R[i]} D={D[i]:.4f} F={R[i] + D[i]:.4f}")
+
+archive = [int(i) for i in np.flatnonzero(R == 0)] # the non-dominated points
+while len(archive) > 5: # archive size 5: truncate
+ sub = distances[np.ix_(archive, archive)]
+ np.fill_diagonal(sub, np.inf)
+ neighbours = np.sort(sub, axis=1) # each row: distances to the others, nearest first
+ worst = min(range(len(archive)), key=lambda i: tuple(neighbours[i]))
+ print(f"truncation removes P{archive.pop(worst) + 1}")
+print("archive:", ", ".join(f"P{i + 1}" for i in archive))
+```
+
+Output:
+
+```text
+P1: S=0 R=0 D=0.4483 F=0.4483
+P2: S=0 R=0 D=0.4826 F=0.4826
+P3: S=0 R=0 D=0.4826 F=0.4826
+P4: S=2 R=0 D=0.4562 F=0.4562
+P5: S=1 R=0 D=0.4858 F=0.4858
+P6: S=2 R=0 D=0.4869 F=0.4869
+P7: S=0 R=0 D=0.4194 F=0.4194
+P8: S=0 R=2 D=0.4551 F=2.4551
+P9: S=0 R=6 D=0.4396 F=6.4396
+P10: S=1 R=2 D=0.4869 F=2.4869
+truncation removes P5
+truncation removes P2
+archive: P1, P3, P4, P6, P7
+```
+
+P9 is dominated by P4, P5, P6 and P10, so R(P9) = 2 + 1 + 2 + 1 = 6. P6's
+nearest neighbour is the dominated P10: the density uses all M solutions,
+dominated ones included, while the truncation only measures distances among
+the non-dominated.
+
+VAMOS computes strength and raw fitness from a boolean dominance matrix
+(`dom[i, j]` is true when i dominates j), and the k-th neighbour distance with
+a partial sort:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/spea2/helpers.py
+def strength_raw_fitness(dom: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
+ """Compute SPEA2 raw fitness (strength ranking) from dominance matrix."""
+ n = dom.shape[0]
+ if n == 0:
+ return np.empty(0, dtype=float)
+ strength = dom.sum(axis=1, dtype=np.int64)
+ raw = (dom.T @ strength).astype(float, copy=False)
+ return np.asarray(raw, dtype=float)
+
+def _kth_neighbour_distance(dist: np.ndarray[Any, Any], k: int) -> np.ndarray[Any, Any]:
+ n = dist.shape[0]
+ if n == 0:
+ return np.empty(0, dtype=float)
+ if n == 1:
+ return np.full(1, np.inf, dtype=float)
+ k = min(max(int(k), 1), n - 1)
+ # Each row's zero self-distance sorts first, so position k is the k-th neighbour.
+ return np.asarray(np.partition(dist, kth=k, axis=1)[:, k], dtype=float)
+```
+
+`dom.sum(axis=1)` counts the solutions each one dominates, S; `dom.T @ strength`
+adds, for each solution, the strengths of the rows that dominate it, R. With
+constraints (the default `constraint_mode="feasibility"`), `dom` holds
+constrained domination instead (lesson [A5](../advanced/constrained.md)), so
+feasible solutions dominate infeasible ones.
+
+Environmental selection follows the two cases of the procedure:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/spea2/helpers.py
+ n = F.shape[0]
+ dist = np.linalg.norm(F[:, None, :] - F[None, :, :], axis=2)
+ kth_distance = _kth_neighbour_distance(dist, int(k_neighbors) if k_neighbors is not None else 1)
+ dom, _, _ = dominance_matrix(F, G, constraint_mode)
+ raw_fitness = strength_raw_fitness(dom)
+
+ nondominated = np.flatnonzero(raw_fitness == 0.0)
+ if n <= archive_size:
+ selected: NDArray[np.int_] = np.arange(n, dtype=int)
+ elif nondominated.size > archive_size:
+ keep = truncate_lexicographic(dist[np.ix_(nondominated, nondominated)], archive_size, selection_kernels)
+ selected = nondominated[keep]
+ else:
+ dominated = np.flatnonzero(raw_fitness > 0.0)
+ fitness = raw_fitness[dominated] + 1.0 / (kth_distance[dominated] + 2.0)
+ fill = dominated[np.argsort(fitness, kind="stable")[: archive_size - nondominated.size]]
+ selected = np.concatenate([nondominated, fill])
+
+ return selected, raw_fitness[selected], kth_distance[selected]
+```
+
+- `n <= archive_size` happens only at the start, when the initial population
+ fits in the archive.
+- The fill sorts the dominated solutions by F = R + 1 / (σᵏ + 2) with a stable
+ sort, so equal fitness keeps the input order.
+- The function also returns R and σᵏ of each survivor, measured in the union;
+ the mating tournament reuses them.
+
+The truncation operator removes one row per iteration:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/spea2/helpers.py
+ active: NDArray[np.int_] = np.arange(n, dtype=int)
+ while active.size > keep:
+ sub = dist[np.ix_(active, active)]
+ np.fill_diagonal(sub, np.inf)
+ nearest = sub.min(axis=1)
+ candidates = np.flatnonzero(nearest == nearest.min())
+ if candidates.size > 1:
+ # The self-distance sorts last in every row, so it never decides the order.
+ rows = np.sort(sub[candidates], axis=1)
+ candidates = candidates[np.lexsort(rows.T[::-1])]
+ active = np.delete(active, int(candidates[0]))
+
+ return active
+```
+
+The candidates are the members with the smallest nearest distance. When there
+are several, their rows of sorted distances are ordered lexicographically with
+`np.lexsort`, which sorts by the last key given, hence the reversed `rows.T`.
+`np.lexsort` is stable, so identical rows remove the first member. With
+`engine="numba"`, a compiled loop gives the same result for finite distances.
+
+Mating uses a binary tournament between two distinct archive members. It
+compares raw fitness first and, on a tie, the k-th neighbour distance, where
+the larger distance wins:
+
+```python
+# Excerpt from src/vamos/engine/algorithm/spea2/spea2.py
+ fa = raw_fitness[first]
+ fb = raw_fitness[second]
+ da = density[first]
+ db = density[second]
+
+ winners = np.empty(n_parents, dtype=int)
+ better_first = fa < fb
+ better_second = fb < fa
+ winners[better_first] = first[better_first]
+ winners[better_second] = second[better_second]
+
+ tied = ~(better_first | better_second)
+ if tied.any():
+ tied_first = first[tied]
+ tied_second = second[tied]
+ tied_density_first = da[tied]
+ tied_density_second = db[tied]
+
+ density_first = tied_density_first > tied_density_second
+ density_second = tied_density_second > tied_density_first
+```
+
+Since D = 1 / (σᵏ + 2) is below 1 and decreases with σᵏ, comparing R and then
+σᵏ is the same as comparing F. A remaining tie is decided by a coin. The
+contestants are drawn as in NSGA-II's tournament (lesson
+[I3](crowding-distance.md#binary-tournament-selection)). Each generation forms
+N pairs of winners, and each pair produces one offspring: VAMOS keeps the first
+child of the crossover and mutates it.
+
+A complete run on ZDT1, with an archive smaller than the population and the
+default k written out:
+
+```python
+import numpy as np
+
+from vamos import optimize
+from vamos.algorithms import SPEA2Config
+from vamos.problems import ZDT1
+
+problem = ZDT1(n_var=30)
+config = (
+ SPEA2Config.builder()
+ .pop_size(100)
+ .archive_size(60)
+ .k_neighbors(1)
+ .crossover("sbx", prob=0.9, eta=20.0)
+ .mutation("pm", prob="1/n", eta=20.0)
+ .selection("tournament")
+ .build()
+)
+result = optimize(problem, algorithm="spea2", algorithm_config=config, max_evaluations=20_000, engine="numpy", seed=1)
+
+gap = np.abs(result.F[:, 1] - (1.0 - np.sqrt(result.F[:, 0]))) # ZDT1 front: f2 = 1 - sqrt(f1)
+print("evaluations:", result.data["evaluations"])
+print("returned:", result.F.shape)
+print("largest vertical gap to the front:", round(float(gap.max()), 3))
+```
+
+Output:
+
+```text
+evaluations: 20000
+returned: (60, 2)
+largest vertical gap to the front: 0.013
+```
+
+Each generation creates 100 offspring and keeps 60 solutions; the result holds
+the non-dominated members of the final archive, here all 60. With the paper's
+rule, k would be √160 ≈ 13. The [SPEA2 lesson](../../algorithms/spea2.md)
+records a run with its figure, and the
+[configuration reference](../../reference/api/algorithms/spea2.md) lists every
+builder method.
+
+## SPEA2, NSGA-II and when to use it
+
+- **Same family, different estimators.** Both are elitist and Pareto-based.
+ NSGA-II ranks fronts and uses one crowding computation per front; SPEA2 uses a
+ scalar fitness, a k-nearest-neighbour density and an iterative truncation that
+ spreads the archive more evenly, at a higher cost: M² distances per
+ generation, and a truncation that re-examines them after every removal.
+- **Archive and population are decoupled.** `archive_size` sets how many
+ solutions survive and are returned; `pop_size` sets how many offspring each
+ generation evaluates.
+- **Many objectives.** When nearly every solution is non-dominated, R = 0 for
+ all of them and selection is decided by density alone, which rewards spread,
+ not convergence. Ishibuchi, Tsukamoto and Nojima [5] showed this loss of
+ selection pressure for NSGA-II and SPEA2 (lesson
+ [A1](../advanced/many-objective.md)).
+- **When to use it.** Two or three objectives, when an evenly spread set of a
+ given size matters, and the population is small enough for M² distances.
+
+## Key points
+
+- Strength S(i) counts the solutions that i dominates; raw fitness R(i) sums the
+ strengths of the solutions that dominate i, and is 0 for non-dominated ones.
+- Density D(i) = 1 / (σᵢᵏ + 2) is below 1, so F = R + D orders by dominance
+ first and density second. VAMOS uses k = 1 by default; the paper uses √M.
+- The archive keeps every non-dominated solution if they fit, completes it with
+ the best dominated ones if they do not fill it, and otherwise truncates.
+- The truncation removes, one at a time, the member whose sorted neighbour
+ distances are lexicographically smallest, which tends to keep the extremes.
+- Parents come from the archive through binary tournaments on fitness.
+
+**Next:** [I8. MOEA/D](moead.md).
+
+## References
+
+[1] Zitzler, E., Laumanns, M., and Thiele, L. (2001). [SPEA2: Improving the strength Pareto evolutionary algorithm](https://tik-db.ee.ethz.ch/db/public/tik/?db=publications&form=report_single_publication&publication_id=1287). TIK Report 103, Computer Engineering and Networks Laboratory, ETH Zurich.
+
+[2] Zitzler, E., and Thiele, L. (1999). [Multiobjective evolutionary algorithms: A comparative case study and the strength Pareto approach](https://doi.org/10.1109/4235.797969). *IEEE Transactions on Evolutionary Computation*, 3(4), 257–271.
+
+[3] Silverman, B. W. (1986). *Density Estimation for Statistics and Data Analysis*. Chapman and Hall.
+
+[4] Goldberg, D. E., and Deb, K. (1991). [A comparative analysis of selection schemes used in genetic algorithms](https://doi.org/10.1016/B978-0-08-050684-5.50008-2). *Foundations of Genetic Algorithms*, 1, 69–93.
+
+[5] Ishibuchi, H., Tsukamoto, N., and Nojima, Y. (2008). [Evolutionary many-objective optimization: A short review](https://doi.org/10.1109/CEC.2008.4631121). *Proceedings of the 2008 IEEE Congress on Evolutionary Computation*, 2419–2426.
diff --git a/docs/foundations/intermediate/variation-operators.md b/docs/foundations/intermediate/variation-operators.md
new file mode 100644
index 000000000..d13751097
--- /dev/null
+++ b/docs/foundations/intermediate/variation-operators.md
@@ -0,0 +1,237 @@
+---
+description: 'I4. How NSGA-II creates offspring for real variables: simulated binary crossover (SBX) and polynomial mutation, their distribution indices and bounded forms, interactive offspring distributions and the VAMOS implementation.'
+search:
+ boost: 0.5
+---
+
+# I4. Variation: SBX and polynomial mutation
+
+Selection decides **who** reproduces; variation decides **what** the children
+look like. For real-valued decision variables, NSGA-II uses simulated binary
+crossover (SBX) and polynomial mutation, both designed by Deb and co-authors.
+Their behaviour is governed by one number each, the *distribution index* η.
+
+In this lesson you will learn:
+
+- how SBX generates two children from two parents, and what η_c controls;
+- how polynomial mutation perturbs a variable, and what η_m controls;
+- how both operators respect the variable bounds;
+- how VAMOS implements and configures them, and which alternatives it offers.
+
+## Exploration and exploitation
+
+Offspring close to their parents *exploit* what the parents already found;
+offspring far from them *explore* new regions. Early in a run exploration
+helps to locate the front; later exploitation refines it. SBX and polynomial
+mutation make this trade-off with a probability distribution centred on the
+parents, whose width is controlled by η and, for SBX, by the distance between
+the parents themselves.
+
+## Simulated binary crossover (SBX)
+
+Before real-coded algorithms became common, genetic algorithms encoded real
+variables as bit strings and used single-point crossover. Deb and Agrawal [1]
+derived the distribution of children that single-point crossover produces on
+such strings and reproduced it directly on real numbers, hence *simulated
+binary* crossover.
+
+For one variable with parent values p₁ ≤ p₂, draw u uniformly in [0, 1] and
+compute a *spread factor* β_q:
+
+β_q = (2u)^(1/(η_c + 1)) if u ≤ 0.5
+β_q = (1 / (2(1 − u)))^(1/(η_c + 1)) otherwise
+
+c₁ = ½ [ (p₁ + p₂) − β_q (p₂ − p₁) ]
+c₂ = ½ [ (p₁ + p₂) + β_q (p₂ − p₁) ]
+
+Its key properties:
+
+- **The children are symmetric around the parents' mean**, so crossover does
+ not bias the population in any direction.
+- **The spread is proportional to the distance between the parents.** When
+ the population is diverse, children are diverse; when it converges, children
+ stay close. This makes SBX *self-adaptive*.
+- **η_c sets the shape.** A large η_c (20 is the usual default) gives children
+ near their parents; a small η_c (2 to 5) spreads them widely.
+
+The formula above ignores the bounds of the variable. NSGA-II's reference
+implementation, and VAMOS, use a **bounded** version that rescales the
+distribution so that no child falls outside [x^L, x^U]. For each child, the
+probability mass that would fall beyond the nearer bound is removed: β_q is
+computed from αu instead of 2u, with the threshold 1/α instead of 0.5, where
+α = 2 − β^−(η_c+1), β = 1 + 2 (p₁ − x^L)/(p₂ − p₁) for c₁ and
+β = 1 + 2 (x^U − p₂)/(p₂ − p₁) for c₂.
+
+In NSGA-II each pair of parents is crossed with probability 0.9 (VAMOS'
+default). Within a crossed pair, each variable is recombined with probability
+0.5, and the two children swap the variable with probability 0.5.
+
+Move the parents and change η_c. The histogram shows where 40,000 children of
+those two parents land, for one variable bounded by [0, 1]:
+
+
+
+Try placing both parents close to a bound (for example 0.02 and 0.08) with a
+small η_c: the bounded version squeezes the distribution instead of producing
+values outside [0, 1].
+
+## Polynomial mutation
+
+Mutation perturbs single variables of a child. Polynomial mutation [2] draws
+the perturbation from a polynomial distribution centred on the current value,
+again controlled by a distribution index η_m. The bounded form used by
+NSGA-II's reference code, and VAMOS, scales the perturbation by the distance
+to each bound [3]. With y the current value in [y^L, y^U],
+δ₁ = (y − y^L)/(y^U − y^L), δ₂ = (y^U − y)/(y^U − y^L) and u uniform in [0, 1]:
+
+δ_q = [ 2u + (1 − 2u)(1 − δ₁)^(η_m+1) ]^(1/(η_m+1)) − 1 if u ≤ 0.5
+δ_q = 1 − [ 2(1 − u) + 2(u − 0.5)(1 − δ₂)^(η_m+1) ]^(1/(η_m+1)) otherwise
+
+y' = y + δ_q (y^U − y^L)
+
+Each variable is mutated with probability p_m. The usual choice,
+p_m = 1/n for n variables, mutates one variable per child on average; VAMOS
+writes it as `prob="1/n"`.
+
+
+
+## In VAMOS
+
+The builder selects the operators by name and sets their parameters; these are
+the values of `NSGAIIConfig.default(...)` for real variables:
+
+```python
+from vamos.algorithms import NSGAIIConfig, available_crossover_methods, available_mutation_methods
+
+config = (
+ NSGAIIConfig.builder()
+ .pop_size(100)
+ .crossover("sbx", prob=0.9, eta=20.0)
+ .mutation("pm", prob="1/n", eta=20.0)
+ .selection("tournament", size=2)
+ .build()
+)
+print(config.crossover)
+print(config.mutation)
+print("crossovers:", ", ".join(available_crossover_methods()))
+print("mutations:", ", ".join(available_mutation_methods()))
+```
+
+Output:
+
+```text
+('sbx', {'prob': 0.9, 'eta': 20.0})
+('pm', {'prob': '1/n', 'eta': 20.0})
+crossovers: arithmetic, blx_alpha, blx_alpha_beta, de, fuzzy, laplace, pcx, sbx, simplex, undx, whole_arithmetic
+mutations: cauchy, gaussian, levy_flight, linked_polynomial, non_uniform, pm, polynomial, power_law, uniform, uniform_reset
+```
+
+The arithmetic of both operators lives in
+`src/vamos/foundation/kernel/operator_primitives.py`. SBX works on a tensor of
+parent pairs, so every pair and every variable of a generation is processed by
+the same array expressions. This excerpt computes the first child, c₁, with
+the bounded spread factor:
+
+```python
+# Excerpt from src/vamos/foundation/kernel/operator_primitives.py
+ pair_mask = rng.random(n_pairs) <= prob_crossover
+ idx = np.flatnonzero(pair_mask)
+ if idx.size == 0:
+ return offspring
+
+ parent1 = offspring[idx, 0, :]
+ parent2 = offspring[idx, 1, :]
+ base1 = parent1.copy()
+ base2 = parent2.copy()
+ eps = 1.0e-14
+
+ y1 = np.minimum(parent1, parent2)
+ y2 = np.maximum(parent1, parent2)
+ diff = y2 - y1
+ valid = diff > eps
+ if prob_var >= 1.0:
+ active = valid
+ else:
+ active = valid & (rng.random(parent1.shape) <= prob_var)
+ if not np.any(active):
+ return offspring
+
+ xl = lower_arr.reshape(1, -1)
+ xu = upper_arr.reshape(1, -1)
+ rand = rng.random(parent1.shape)
+ betaq = np.empty_like(parent1)
+
+ beta_valid = 1.0 + (2.0 * (y1 - xl) / diff.clip(min=eps))
+ beta_valid = np.maximum(beta_valid, eps)
+ alpha = 2.0 - np.power(beta_valid, -(eta + 1.0))
+ alpha = np.maximum(alpha, eps)
+ term = rand <= (1.0 / alpha)
+ inv_eta = 1.0 / (eta + 1.0)
+ betaq[term] = np.power(rand[term] * alpha[term], inv_eta)
+ betaq[~term] = np.power(1.0 / (2.0 - rand[~term] * alpha[~term]), inv_eta)
+ c1 = 0.5 * ((y1 + y2) - betaq * diff)
+```
+
+`pair_mask` applies the crossover probability per pair, `active` the
+per-variable probability (`prob_var`, 0.5), and a variable whose parents are
+equal is left unchanged (`valid`). The second child uses the upper bound in the
+same way, and a final mask swaps the children's values with probability 0.5.
+
+Polynomial mutation follows the two branches of the formula:
+
+```python
+# Excerpt from src/vamos/foundation/kernel/operator_primitives.py
+ delta1 = (y - yl) / span
+ delta2 = (yu - y) / span
+ deltaq = np.empty_like(y)
+ mut_pow = 1.0 / (eta + 1.0)
+
+ lower_branch = rnd <= 0.5
+ if np.any(lower_branch):
+ rnd_low = rnd[lower_branch]
+ xy_low = 1.0 - delta1[lower_branch]
+ val_low = 2.0 * rnd_low + (1.0 - 2.0 * rnd_low) * np.power(xy_low, eta + 1.0)
+ deltaq[lower_branch] = np.power(val_low, mut_pow) - 1.0
+
+ upper_branch = ~lower_branch
+ if np.any(upper_branch):
+ rnd_high = rnd[upper_branch]
+ xy_high = 1.0 - delta2[upper_branch]
+ val_high = 2.0 * (1.0 - rnd_high) + 2.0 * (rnd_high - 0.5) * np.power(xy_high, eta + 1.0)
+ deltaq[upper_branch] = 1.0 - np.power(val_high, mut_pow)
+
+ mutated = y + deltaq * span
+ np.clip(mutated, yl, yu, out=mutated)
+```
+
+With `engine="numba"`, compiled kernels perform the same arithmetic and must
+draw the random numbers in the same order and shape; the
+[backend guide](../../dev/add_backend.md) states that contract.
+
+## Other encodings
+
+SBX and polynomial mutation are for real variables. Binary, integer,
+permutation and mixed problems need operators that produce valid values of
+their type, such as bit-flip mutation, order crossover or swap mutation.
+`NSGAIIConfig.default(..., encoding=...)` chooses suitable ones, and
+[Decision representations](../../tutorials/encodings.md) shows each encoding
+at work.
+
+## Key points
+
+- SBX produces two children symmetric around their parents; their spread grows
+ with the distance between the parents and shrinks as η_c grows.
+- Polynomial mutation perturbs a variable with a spread controlled by η_m;
+ with p_m = 1/n it changes one variable per child on average.
+- The bounded forms of both operators keep every value inside its bounds.
+- VAMOS' defaults are SBX (0.9, η_c = 20) and polynomial mutation (1/n, η_m = 20).
+
+**Next:** [I5. Elitist survival and the complete generation](elitist-survival.md).
+
+## References
+
+[1] Deb, K., and Agrawal, R. B. (1995). Simulated binary crossover for continuous search space. *Complex Systems*, 9(2), 115–148.
+
+[2] Deb, K., and Goyal, M. (1996). A combined genetic adaptive search (GeneAS) for engineering design. *Computer Science and Informatics*, 26(4), 30–45.
+
+[3] Deb, K., and Deb, D. (2014). [Analysing mutation schemes for real-parameter genetic algorithms](https://doi.org/10.1504/IJAISC.2014.059280). *International Journal of Artificial Intelligence and Soft Computing*, 4(1), 1–28.
diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md
index 0de9c37f8..3e8ed3fae 100644
--- a/docs/guide/getting-started.md
+++ b/docs/guide/getting-started.md
@@ -10,6 +10,8 @@ Choose the shortest route that matches what you want to accomplish. Installation
4. Use the [API reference](../reference/api_reference.md) when you need exact signatures rather than tutorial guidance.
If Python itself is still new to you, begin with the [Minimal Python Track](minimal-python.md).
+If multi-objective optimization is new to you, the [Foundations](../foundations/index.md) path
+explains Pareto dominance, quality indicators and NSGA-II with interactive figures.
## Solve your own problem
diff --git a/docs/javascripts/foundations.js b/docs/javascripts/foundations.js
new file mode 100644
index 000000000..bcfa1a370
--- /dev/null
+++ b/docs/javascripts/foundations.js
@@ -0,0 +1,4125 @@
+/* Interactive figures for the Foundations learning path.
+
+ Dependency-free DOM and SVG. Every figure is a progressive enhancement: the
+ lesson text explains the idea without JavaScript, and each container keeps a
+ short fallback paragraph until its figure is drawn. The algorithms below
+ follow the NumPy reference implementation of VAMOS
+ (src/vamos/foundation/kernel/numpy_backend.py and operator_primitives.py,
+ and src/vamos/foundation/quality_indicators/hypervolume.py).
+ tests/docs/test_foundations.py checks that every figure a lesson uses is
+ implemented here and, when Node.js is installed, runs the non-dominated
+ sorting, crowding distance, hypervolume and hypervolume contributions
+ against VAMOS. The distance indicators and the Das-Dennis lattices were
+ checked by hand against MooCore and VAMOS when the path was added. */
+(function (root) {
+ "use strict";
+
+ /* ------------------------------------------------------------------ */
+ /* Pure algorithms */
+ /* ------------------------------------------------------------------ */
+
+ function mulberry32(seed) {
+ let a = seed >>> 0;
+ return function () {
+ a = (a + 0x6d2b79f5) >>> 0;
+ let t = a;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+ }
+
+ function gaussian(rand) {
+ const u = Math.max(rand(), 1e-12);
+ const v = rand();
+ return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
+ }
+
+ /** a Pareto-dominates b (minimization): no worse everywhere, better somewhere. */
+ function dominates(a, b) {
+ let better = false;
+ for (let i = 0; i < a.length; i++) {
+ if (a[i] > b[i]) return false;
+ if (a[i] < b[i]) better = true;
+ }
+ return better;
+ }
+
+ /** Fast non-dominated sorting (Deb et al., 2002) with its bookkeeping. */
+ function nonDominatedSort(F, relation) {
+ const better = relation || dominates;
+ const n = F.length;
+ const S = [];
+ const count = new Array(n).fill(0);
+ for (let p = 0; p < n; p++) S.push([]);
+ for (let p = 0; p < n; p++) {
+ for (let q = 0; q < n; q++) {
+ if (p === q) continue;
+ if (better(F[p], F[q], p, q)) S[p].push(q);
+ else if (better(F[q], F[p], q, p)) count[p] += 1;
+ }
+ }
+ const rank = new Array(n).fill(-1);
+ const fronts = [];
+ const remaining = count.slice();
+ let current = [];
+ for (let p = 0; p < n; p++) if (remaining[p] === 0) current.push(p);
+ let level = 0;
+ while (current.length) {
+ fronts.push(current);
+ const next = [];
+ for (const p of current) rank[p] = level;
+ for (const p of current) {
+ for (const q of S[p]) {
+ remaining[q] -= 1;
+ if (remaining[q] === 0) next.push(q);
+ }
+ }
+ next.sort((a, b) => a - b);
+ current = next;
+ level += 1;
+ }
+ return { fronts, rank, count, dominatedSets: S };
+ }
+
+ /** Crowding distance of the rows listed in `front`, aligned with `front`. */
+ function crowdingDistance(F, front) {
+ const k = front.length;
+ const d = new Array(k).fill(0);
+ if (k === 0) return d;
+ if (k <= 2) return d.fill(Infinity);
+ const m = F[front[0]].length;
+ for (let j = 0; j < m; j++) {
+ const order = front.map((_, i) => i).sort((a, b) => F[front[a]][j] - F[front[b]][j] || a - b);
+ const lo = F[front[order[0]]][j];
+ const hi = F[front[order[k - 1]]][j];
+ const span = hi - lo;
+ if (!(span > 0)) continue;
+ d[order[0]] = Infinity;
+ d[order[k - 1]] = Infinity;
+ for (let i = 1; i < k - 1; i++) {
+ d[order[i]] += (F[front[order[i + 1]]][j] - F[front[order[i - 1]]][j]) / span;
+ }
+ }
+ return d;
+ }
+
+ /** Ranks and crowding distances of every row, as VAMOS' nsga2_ranking. */
+ function rankAndCrowding(F, relation) {
+ const sorted = nonDominatedSort(F, relation);
+ const crowding = new Array(F.length).fill(0);
+ for (const front of sorted.fronts) {
+ const d = crowdingDistance(F, front);
+ front.forEach((row, i) => {
+ crowding[row] = d[i];
+ });
+ }
+ return { rank: sorted.rank, crowding, fronts: sorted.fronts };
+ }
+
+ /** vamos.select_survivors: lower rank, then larger crowding, then lower index. */
+ function selectSurvivors(F, count) {
+ const r = rankAndCrowding(F);
+ const order = F.map((_, i) => i).sort((a, b) => r.rank[a] - r.rank[b] || cmpDesc(r.crowding[a], r.crowding[b]) || a - b);
+ return { selected: order.slice(0, count), rank: r.rank, crowding: r.crowding, fronts: r.fronts };
+ }
+
+ function cmpDesc(a, b) {
+ if (a === b) return 0;
+ return a > b ? -1 : 1;
+ }
+
+ function nonDominatedIndices(F) {
+ const out = [];
+ for (let i = 0; i < F.length; i++) {
+ let dominated = false;
+ for (let j = 0; j < F.length && !dominated; j++) {
+ if (j !== i && dominates(F[j], F[i])) dominated = true;
+ }
+ if (!dominated) out.push(i);
+ }
+ return out;
+ }
+
+ /** Exact two-objective hypervolume; points outside the reference box are ignored. */
+ function hypervolume2d(points, ref) {
+ const inside = points.filter((p) => p[0] < ref[0] && p[1] < ref[1]).sort((a, b) => a[0] - b[0] || a[1] - b[1]);
+ let area = 0;
+ let ceiling = ref[1];
+ for (const p of inside) {
+ if (p[1] < ceiling) {
+ area += (ref[0] - p[0]) * (ceiling - p[1]);
+ ceiling = p[1];
+ }
+ }
+ return area;
+ }
+
+ /** Exclusive hypervolume contributions, as VAMOS's hypervolume_contributions and MooCore's
+ hv_contributions (ignore_dominated) compute them: points outside the reference box are
+ left out, a dominated point gives 0 and is left out of the others' contributions, and
+ equal points give 0 each while still covering their neighbours. */
+ function hvContributions2d(points, ref) {
+ const out = new Array(points.length).fill(0);
+ const boxes = new Array(points.length).fill(null);
+ const groups = new Map();
+ points.forEach((p, i) => {
+ if (!(p[0] < ref[0] && p[1] < ref[1])) return;
+ const key = p[0] + "," + p[1];
+ if (!groups.has(key)) groups.set(key, { p, members: [] });
+ groups.get(key).members.push(i);
+ });
+ const unique = [...groups.values()].sort((a, b) => a.p[0] - b.p[0] || a.p[1] - b.p[1]);
+ const front = [];
+ let lowest = Infinity;
+ for (const group of unique) {
+ if (group.p[1] < lowest) {
+ front.push(group);
+ lowest = group.p[1];
+ }
+ }
+ front.forEach((group, k) => {
+ if (group.members.length > 1) return;
+ const p = group.p;
+ const right = k + 1 < front.length ? front[k + 1].p[0] : ref[0];
+ const top = k > 0 ? front[k - 1].p[1] : ref[1];
+ out[group.members[0]] = (right - p[0]) * (top - p[1]);
+ boxes[group.members[0]] = [p[0], p[1], right, top];
+ });
+ return { contributions: out, boxes };
+ }
+
+ /** The contour max(w·f₁, (1 − w)·f₂) = c of the Tchebycheff scalarization with the ideal point at the origin:
+ the upper and right edges of the rectangle where the value is at most c, which meet at (c / w, c / (1 − w)). */
+ function tchebycheffContour(w, c) {
+ const cx = w > 1e-9 ? c / w : 3;
+ const cy = 1 - w > 1e-9 ? c / (1 - w) : 3;
+ return [[0, cy], [cx, cy], [cx, 0]];
+ }
+
+ function euclidean(a, b) {
+ let s = 0;
+ for (let i = 0; i < a.length; i++) s += (a[i] - b[i]) * (a[i] - b[i]);
+ return Math.sqrt(s);
+ }
+
+ function dPlus(a, r) {
+ let s = 0;
+ for (let i = 0; i < a.length; i++) {
+ const v = Math.max(a[i] - r[i], 0);
+ s += v * v;
+ }
+ return Math.sqrt(s);
+ }
+
+ function nearest(from, to, distance) {
+ let best = Infinity;
+ let index = -1;
+ to.forEach((t, i) => {
+ const d = distance(t, from);
+ if (d < best) {
+ best = d;
+ index = i;
+ }
+ });
+ return { distance: best, index };
+ }
+
+ /** GD with p = 1: mean distance from each approximation point to the reference set. */
+ function generationalDistance(A, R) {
+ return A.reduce((sum, a) => sum + nearest(a, R, (r, x) => euclidean(x, r)).distance, 0) / A.length;
+ }
+
+ /** IGD with p = 1: mean distance from each reference point to the approximation set. */
+ function igd(A, R) {
+ return R.reduce((sum, r) => sum + nearest(r, A, (a, x) => euclidean(a, x)).distance, 0) / R.length;
+ }
+
+ /** IGD+ (Ishibuchi et al., 2015): only the objectives where a is worse than r count. */
+ function igdPlus(A, R) {
+ return R.reduce((sum, r) => sum + nearest(r, A, (a, x) => dPlus(a, x)).distance, 0) / R.length;
+ }
+
+ /** Additive epsilon: smallest shift that makes A weakly dominate every point of R. */
+ function epsilonAdditive(A, R) {
+ let worst = -Infinity;
+ for (const r of R) {
+ let best = Infinity;
+ for (const a of A) {
+ let shift = -Infinity;
+ for (let i = 0; i < a.length; i++) shift = Math.max(shift, a[i] - r[i]);
+ best = Math.min(best, shift);
+ }
+ worst = Math.max(worst, best);
+ }
+ return worst;
+ }
+
+ /** Schott's spacing: standard deviation of nearest-neighbour L1 distances. */
+ function spacing(A) {
+ if (A.length < 2) return NaN;
+ const d = A.map((a, i) => {
+ let best = Infinity;
+ A.forEach((b, j) => {
+ if (i === j) return;
+ let s = 0;
+ for (let k = 0; k < a.length; k++) s += Math.abs(a[k] - b[k]);
+ best = Math.min(best, s);
+ });
+ return best;
+ });
+ const mean = d.reduce((s, v) => s + v, 0) / d.length;
+ return Math.sqrt(d.reduce((s, v) => s + (v - mean) * (v - mean), 0) / (d.length - 1));
+ }
+
+ /** Deb's spread Delta for two objectives, given the extremes of the true front. */
+ function spreadDelta(A, extremes) {
+ if (A.length < 2) return NaN;
+ const P = A.slice().sort((a, b) => a[0] - b[0]);
+ const gaps = [];
+ for (let i = 0; i + 1 < P.length; i++) gaps.push(euclidean(P[i], P[i + 1]));
+ const mean = gaps.reduce((s, v) => s + v, 0) / gaps.length;
+ const df = euclidean(extremes[0], P[0]);
+ const dl = euclidean(extremes[1], P[P.length - 1]);
+ const dev = gaps.reduce((s, v) => s + Math.abs(v - mean), 0);
+ return (df + dl + dev) / (df + dl + gaps.length * mean);
+ }
+
+ function sbxPair(p1, p2, lower, upper, eta, probVar, rand) {
+ const c1 = p1.slice();
+ const c2 = p2.slice();
+ const inv = 1 / (eta + 1);
+ for (let j = 0; j < p1.length; j++) {
+ const y1 = Math.min(p1[j], p2[j]);
+ const y2 = Math.max(p1[j], p2[j]);
+ const diff = y2 - y1;
+ if (!(diff > 1e-14)) continue;
+ if (probVar < 1 && !(rand() <= probVar)) continue;
+ const u = rand();
+ let beta = Math.max(1 + (2 * (y1 - lower)) / diff, 1e-14);
+ let alpha = Math.max(2 - Math.pow(beta, -(eta + 1)), 1e-14);
+ let bq = u <= 1 / alpha ? Math.pow(u * alpha, inv) : Math.pow(1 / (2 - u * alpha), inv);
+ let a = 0.5 * (y1 + y2 - bq * diff);
+ beta = Math.max(1 + (2 * (upper - y2)) / diff, 1e-14);
+ alpha = Math.max(2 - Math.pow(beta, -(eta + 1)), 1e-14);
+ bq = u <= 1 / alpha ? Math.pow(u * alpha, inv) : Math.pow(1 / (2 - u * alpha), inv);
+ let b = 0.5 * (y1 + y2 + bq * diff);
+ if (rand() <= 0.5) {
+ const t = a;
+ a = b;
+ b = t;
+ }
+ c1[j] = a;
+ c2[j] = b;
+ }
+ return [c1, c2];
+ }
+
+ function polynomialMutation(x, lower, upper, prob, eta, rand) {
+ const span = upper - lower;
+ const power = 1 / (eta + 1);
+ for (let j = 0; j < x.length; j++) {
+ if (!(rand() <= prob)) continue;
+ const y = x[j];
+ const u = rand();
+ let dq;
+ if (u <= 0.5) {
+ const val = 2 * u + (1 - 2 * u) * Math.pow(1 - (y - lower) / span, eta + 1);
+ dq = Math.pow(val, power) - 1;
+ } else {
+ const val = 2 * (1 - u) + 2 * (u - 0.5) * Math.pow(1 - (upper - y) / span, eta + 1);
+ dq = 1 - Math.pow(val, power);
+ }
+ x[j] = Math.min(upper, Math.max(lower, y + dq * span));
+ }
+ return x;
+ }
+
+ function zdtG(x) {
+ let s = 0;
+ for (let i = 1; i < x.length; i++) s += x[i];
+ return 1 + (9 * s) / (x.length - 1);
+ }
+
+ const PROBLEMS = {
+ zdt1: {
+ label: "ZDT1 (convex)",
+ evaluate: (x) => {
+ const g = zdtG(x);
+ return [x[0], g * (1 - Math.sqrt(x[0] / g))];
+ },
+ curve: (t) => 1 - Math.sqrt(t),
+ },
+ zdt2: {
+ label: "ZDT2 (non-convex)",
+ evaluate: (x) => {
+ const g = zdtG(x);
+ return [x[0], g * (1 - (x[0] / g) * (x[0] / g))];
+ },
+ curve: (t) => 1 - t * t,
+ },
+ zdt3: {
+ label: "ZDT3 (disconnected)",
+ evaluate: (x) => {
+ const g = zdtG(x);
+ const r = x[0] / g;
+ return [x[0], g * (1 - Math.sqrt(r) - r * Math.sin(10 * Math.PI * x[0]))];
+ },
+ curve: (t) => 1 - Math.sqrt(t) - t * Math.sin(10 * Math.PI * t),
+ },
+ };
+
+ function sampledFront(problem, n) {
+ const pts = [];
+ for (let i = 0; i < n; i++) {
+ const t = i / (n - 1);
+ pts.push([t, problem.curve(t)]);
+ }
+ return nonDominatedIndices(pts).map((i) => pts[i]);
+ }
+
+ function nsga2Truncate(F, count) {
+ const r = rankAndCrowding(F);
+ const selected = [];
+ for (const front of r.fronts) {
+ if (selected.length + front.length <= count) {
+ selected.push(...front);
+ if (selected.length === count) break;
+ } else {
+ const rest = front.slice().sort((a, b) => cmpDesc(r.crowding[a], r.crowding[b]) || a - b);
+ selected.push(...rest.slice(0, count - selected.length));
+ break;
+ }
+ }
+ return selected;
+ }
+
+ /** A compact NSGA-II with VAMOS' default real-coded operators. */
+ function createNSGAII(problem, popSize, nVar, seed) {
+ const rand = mulberry32(seed);
+ const st = { X: [], F: [], generation: 1, evaluations: 0 };
+ for (let i = 0; i < popSize; i++) {
+ const x = [];
+ for (let j = 0; j < nVar; j++) x.push(rand());
+ st.X.push(x);
+ st.F.push(problem.evaluate(x));
+ }
+ st.evaluations = popSize;
+ let metrics = rankAndCrowding(st.F);
+ st.rank = metrics.rank;
+ function tournament() {
+ const n = st.X.length;
+ const a = Math.floor(rand() * n);
+ let b = Math.floor(rand() * (n - 1));
+ if (b >= a) b += 1;
+ if (metrics.rank[a] !== metrics.rank[b]) return metrics.rank[a] < metrics.rank[b] ? a : b;
+ if (metrics.crowding[a] !== metrics.crowding[b]) return metrics.crowding[a] > metrics.crowding[b] ? a : b;
+ return rand() < 0.5 ? a : b;
+ }
+ st.step = function () {
+ const offspring = [];
+ while (offspring.length < popSize) {
+ const p1 = st.X[tournament()];
+ const p2 = st.X[tournament()];
+ const children = rand() <= 0.9 ? sbxPair(p1, p2, 0, 1, 20, 0.5, rand) : [p1.slice(), p2.slice()];
+ for (const child of children) {
+ polynomialMutation(child, 0, 1, 1 / nVar, 20, rand);
+ offspring.push(child);
+ }
+ }
+ const offF = offspring.map((x) => problem.evaluate(x));
+ const allX = st.X.concat(offspring);
+ const allF = st.F.concat(offF);
+ const keep = nsga2Truncate(allF, popSize);
+ st.X = keep.map((i) => allX[i]);
+ st.F = keep.map((i) => allF[i]);
+ st.generation += 1;
+ st.evaluations += offspring.length;
+ metrics = rankAndCrowding(st.F);
+ st.rank = metrics.rank;
+ };
+ return st;
+ }
+
+ /* CTP2 of Deb, Pratap and Meyarivan (2001), written in objective space. */
+ const CTP2 = { theta: -0.2 * Math.PI, a: 0.2, b: 10, c: 1, d: 6, e: 1 };
+
+ function ctpViolation(f, p) {
+ const prm = p || CTP2;
+ const lhs = Math.cos(prm.theta) * (f[1] - prm.e) - Math.sin(prm.theta) * f[0];
+ const inner = Math.sin(prm.theta) * (f[1] - prm.e) + Math.cos(prm.theta) * f[0];
+ const rhs = prm.a * Math.pow(Math.abs(Math.sin(prm.b * Math.PI * Math.pow(inner, prm.c))), prm.d);
+ return Math.max(0, rhs - lhs);
+ }
+
+ /** Constrained domination (Deb, 2000), with violations passed alongside. */
+ function constrainedDominates(cv) {
+ return function (a, b, i, j) {
+ const fa = cv[i] <= 0;
+ const fb = cv[j] <= 0;
+ if (fa && !fb) return true;
+ if (!fa && fb) return false;
+ if (!fa && !fb) return cv[i] < cv[j];
+ return dominates(a, b);
+ };
+ }
+
+ function binomial(n, k) {
+ let r = 1;
+ for (let i = 1; i <= k; i++) r = (r * (n - k + i)) / i;
+ return Math.round(r);
+ }
+
+ function dasDennis(m, p) {
+ const out = [];
+ const rec = (prefix, left, depth) => {
+ if (depth === m - 1) {
+ out.push(prefix.concat([left / p]));
+ return;
+ }
+ for (let i = 0; i <= left; i++) rec(prefix.concat([i / p]), left - i, depth + 1);
+ };
+ rec([], p, 0);
+ return out;
+ }
+
+ /** Points z attained by at least k of the runs, as a 2-D staircase. */
+ function attainmentSurface(runs, k) {
+ const xs = Array.from(new Set(runs.flat().map((p) => p[0]))).sort((a, b) => a - b);
+ return xs.map((u) => {
+ const heights = runs
+ .map((run) => run.reduce((best, p) => (p[0] <= u ? Math.min(best, p[1]) : best), Infinity))
+ .sort((a, b) => a - b);
+ return [u, heights[k - 1]];
+ });
+ }
+
+ function normalCdf(z) {
+ const t = 1 / (1 + 0.3275911 * Math.abs(z) / Math.SQRT2);
+ const y = 1 - ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * Math.exp(-(z * z) / 2);
+ return z >= 0 ? 0.5 * (1 + y) : 0.5 * (1 - y);
+ }
+
+ /** Two-sided Mann-Whitney U test with the normal approximation. */
+ function mannWhitney(a, b) {
+ const all = a.map((v) => [v, 0]).concat(b.map((v) => [v, 1])).sort((x, y) => x[0] - y[0]);
+ const ranks = new Array(all.length);
+ for (let i = 0; i < all.length; ) {
+ let j = i;
+ while (j + 1 < all.length && all[j + 1][0] === all[i][0]) j += 1;
+ for (let k = i; k <= j; k++) ranks[k] = (i + j) / 2 + 1;
+ i = j + 1;
+ }
+ let r1 = 0;
+ all.forEach((item, i) => {
+ if (item[1] === 0) r1 += ranks[i];
+ });
+ const n1 = a.length;
+ const n2 = b.length;
+ const u = r1 - (n1 * (n1 + 1)) / 2;
+ const mean = (n1 * n2) / 2;
+ const sd = Math.sqrt((n1 * n2 * (n1 + n2 + 1)) / 12);
+ const z = (Math.abs(u - mean) - 0.5) / sd;
+ return { u, p: Math.min(1, 2 * (1 - normalCdf(Math.max(z, 0)))) };
+ }
+
+ /** Lexicographic comparison of two ascending distance lists. */
+ function lexLess(a, b) {
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
+ if (Math.abs(a[i] - b[i]) > 1e-12) return a[i] < b[i];
+ }
+ return false;
+ }
+
+ /** SPEA2 strength S, raw fitness R, density D = 1 / (σᵏ + 2) and fitness F = R + D. */
+ function spea2Fitness(F, k) {
+ const n = F.length;
+ const S = F.map((a) => F.filter((b) => dominates(a, b)).length);
+ const R = F.map((b, i) => F.reduce((sum, a, j) => (j !== i && dominates(a, b) ? sum + S[j] : sum), 0));
+ const kk = Math.max(1, Math.min(n - 1, k || Math.floor(Math.sqrt(n))));
+ const D = F.map((a, i) => {
+ const d = F.map((b, j) => (j === i ? Infinity : euclidean(a, b))).sort((x, y) => x - y);
+ return 1 / (d[kk - 1] + 2);
+ });
+ return { S, R, D, fitness: R.map((r, i) => r + D[i]), k: kk };
+ }
+
+ /** SPEA2 environmental selection: non-dominated first, then truncation by nearest neighbours. */
+ function spea2Select(F, size, k) {
+ const fit = spea2Fitness(F, k);
+ const nd = F.map((_, i) => i).filter((i) => fit.R[i] === 0);
+ let archive = nd.slice();
+ let filled = [];
+ if (F.length <= size) archive = F.map((_, i) => i);
+ else if (archive.length < size) {
+ const rest = F.map((_, i) => i)
+ .filter((i) => fit.R[i] > 0)
+ .sort((a, b) => fit.fitness[a] - fit.fitness[b] || a - b);
+ filled = rest.slice(0, size - archive.length);
+ archive = archive.concat(filled);
+ }
+ const removed = [];
+ while (archive.length > size) {
+ const lists = archive.map((i) =>
+ archive
+ .filter((j) => j !== i)
+ .map((j) => euclidean(F[i], F[j]))
+ .sort((a, b) => a - b)
+ );
+ let worst = 0;
+ for (let a = 1; a < archive.length; a++) if (lexLess(lists[a], lists[worst])) worst = a;
+ removed.push(archive[worst]);
+ archive.splice(worst, 1);
+ }
+ return { kept: archive, removed, filled, nd, ...fit };
+ }
+
+ /** Additive epsilon indicator I(a, b): smallest shift of a that weakly dominates b. */
+ function epsilonPair(a, b) {
+ let m = -Infinity;
+ for (let i = 0; i < a.length; i++) m = Math.max(m, a[i] - b[i]);
+ return m;
+ }
+
+ /** IBEA environmental selection (VAMOS' ibea/helpers.py): additive epsilon or hypervolume difference. */
+ function ibeaSelect(F, size, kappa, indicator) {
+ const m = F[0].length;
+ const lo = [];
+ const hi = [];
+ for (let j = 0; j < m; j++) {
+ lo.push(Math.min(...F.map((f) => f[j])));
+ hi.push(Math.max(...F.map((f) => f[j])));
+ }
+ const Z = F.map((f) => f.map((v, j) => (hi[j] > lo[j] ? (v - lo[j]) / (hi[j] - lo[j]) : 0)));
+ let M;
+ if (indicator === "hv") {
+ const ref = Z[0].map((_, j) => Math.max(...Z.map((z) => z[j])) + 1);
+ const H = (p) => p.reduce((prod, v, j) => prod * Math.max(ref[j] - v, 0), 1);
+ const Hc = (p, q) => p.reduce((prod, v, j) => prod * Math.max(ref[j] - Math.max(v, q[j]), 0), 1);
+ M = Z.map((x, i) => Z.map((y, k) => (i === k ? 0 : dominates(y, x) ? H(x) - H(y) : H(x) - Hc(x, y))));
+ } else {
+ M = Z.map((x) => Z.map((y) => epsilonPair(y, x)));
+ }
+ let c = 0;
+ M.forEach((row) => row.forEach((v) => (c = Math.max(c, Math.abs(v)))));
+ if (c > 0) M = M.map((row) => row.map((v) => v / c));
+ const T = M.map((row, x) => row.map((v, y) => (x === y ? 0 : Math.exp(-v / kappa))));
+ const fitness = T.map((row) => -row.reduce((sum, v) => sum + v, 0));
+ const initial = fitness.slice();
+ const alive = Z.map((_, i) => i);
+ const removed = [];
+ while (alive.length > size) {
+ let worst = alive[0];
+ for (const i of alive) if (fitness[i] < fitness[worst]) worst = i;
+ alive.splice(alive.indexOf(worst), 1);
+ removed.push(worst);
+ for (const x of alive) fitness[x] += T[x][worst];
+ }
+ return { fitness: initial, final: fitness, kept: alive, removed, c: c || 1, terms: T };
+ }
+
+ /** RVEA angle-penalized distance of translated objectives Fp against unit reference vectors V. */
+ function rveaSelect(Fp, V, progress, alpha, penaltyM) {
+ const M = penaltyM || V[0].length;
+ const norm = (a) => Math.max(1e-64, Math.sqrt(a.reduce((s, v) => s + v * v, 0)));
+ const cosine = (a, b) => a.reduce((s, v, i) => s + v * b[i], 0) / (norm(a) * norm(b) || 1);
+ const gamma = V.map((v, j) => Math.min(...V.map((u, k) => (k === j ? Infinity : Math.acos(Math.min(1, cosine(v, u)))))));
+ const assoc = [];
+ const theta = [];
+ const apd = [];
+ Fp.forEach((f) => {
+ let best = 0;
+ V.forEach((v, j) => {
+ if (cosine(f, v) > cosine(f, V[best])) best = j;
+ });
+ const t = Math.acos(Math.min(1, cosine(f, V[best])));
+ assoc.push(best);
+ theta.push(t);
+ apd.push((1 + M * Math.pow(progress, alpha) * (t / gamma[best])) * norm(f));
+ });
+ const selected = V.map((_, j) => {
+ let pick = -1;
+ Fp.forEach((_, i) => {
+ if (assoc[i] === j && (pick < 0 || apd[i] < apd[pick])) pick = i;
+ });
+ return pick;
+ });
+ return { assoc, theta, apd, gamma, selected };
+ }
+
+ /** MOEA/D weights for two objectives, as numpy.linspace builds them. */
+ function moeadWeights(n) {
+ const step = 1 / (n - 1);
+ return Array.from({ length: n }, (_, k) => {
+ const v = k === n - 1 ? 1 : k * step;
+ return [v, 1 - v];
+ });
+ }
+
+ /** Neighbourhoods: the T closest weight vectors (stable argsort of Euclidean distances). */
+ function moeadNeighbours(W, T) {
+ return W.map((w) =>
+ W.map((u, j) => [Math.sqrt(w.reduce((sum, v, m) => sum + (v - u[m]) * (v - u[m]), 0)), j])
+ .sort((a, b) => a[0] - b[0] || a[1] - b[1])
+ .slice(0, T)
+ .map((e) => e[1])
+ );
+ }
+
+ /** MOEA/D aggregation functions of VAMOS: Tchebycheff, weighted sum and PBI. */
+ function moeadAggregate(mode, f, w, z, theta) {
+ if (mode === "ws") return f.reduce((sum, v, m) => sum + w[m] * v, 0);
+ if (mode === "pbi") {
+ const norm = Math.sqrt(w.reduce((sum, v) => sum + v * v, 0));
+ const u = w.map((v) => v / norm);
+ const d = f.map((v, m) => v - z[m]);
+ const d1 = Math.abs(d.reduce((sum, v, m) => sum + v * u[m], 0));
+ const d2 = Math.sqrt(d.reduce((sum, v, m) => sum + (v - d1 * u[m]) * (v - d1 * u[m]), 0));
+ return d1 + (theta === undefined ? 5 : theta) * d2;
+ }
+ return Math.max(...f.map((v, m) => (w[m] === 0 ? 1e-4 : w[m]) * Math.abs(v - z[m])));
+ }
+
+ /** One MOEA/D replacement step: strict improvement, at most nr replacements, in the given order. */
+ function moeadReplace(current, W, y, order, nr, mode, theta) {
+ const z = current[0].map((_, m) => Math.min(y[m], ...current.map((f) => f[m])));
+ let replaced = 0;
+ const rows = order.map((j) => {
+ const gx = moeadAggregate(mode, current[j], W[j], z, theta);
+ const gy = moeadAggregate(mode, y, W[j], z, theta);
+ let result = "kept";
+ if (gy < gx) {
+ if (replaced < nr) {
+ result = "replaced";
+ replaced += 1;
+ } else result = "better (limit n_r reached)";
+ }
+ return { j, gx, gy, result };
+ });
+ return { z, rows, replaced };
+ }
+
+ /** NSGA-III association: the direction of largest cosine and the perpendicular distance to it. */
+ function nsga3Associate(f, W) {
+ const norm = Math.sqrt(f.reduce((s2, v) => s2 + v * v, 0));
+ let best = 0;
+ let bestCos = -Infinity;
+ W.forEach((w, j) => {
+ const wn = Math.sqrt(w.reduce((s2, v) => s2 + v * v, 0));
+ const c = norm > 0 ? f.reduce((s2, v, m) => s2 + (v / norm) * (w[m] / wn), 0) : 0;
+ if (c > bestCos) {
+ bestCos = c;
+ best = j;
+ }
+ });
+ return { dir: best, dperp: norm * Math.sqrt(Math.max(0, 1 - bestCos * bestCos)) };
+ }
+
+ /** NSGA-III niche preservation, returning every pick with its round and reason. */
+ function nsga3Niching(rho0, candidates, K, rand) {
+ const rho = rho0.slice();
+ const left = candidates.slice();
+ const picks = [];
+ let round = 0;
+ const shuffle = (a) => {
+ for (let i = a.length - 1; i > 0; i--) {
+ const j = Math.floor(rand() * (i + 1));
+ [a[i], a[j]] = [a[j], a[i]];
+ }
+ return a;
+ };
+ while (picks.length < K) {
+ round += 1;
+ const J = rho.map((_, j) => j).filter((j) => left.some((c) => c.dir === j));
+ if (!J.length) break;
+ const low = Math.min(...J.map((j) => rho[j]));
+ const Jmin = shuffle(J.filter((j) => rho[j] === low)).slice(0, K - picks.length);
+ for (const j of Jmin) {
+ const C = shuffle(left.filter((c) => c.dir === j));
+ let chosen = C[0];
+ if (rho[j] === 0) for (const c of C) if (c.dperp < chosen.dperp) chosen = c;
+ picks.push({ id: chosen.id, dir: j, round, count: rho[j], low, Jmin: Jmin.slice(), closest: rho[j] === 0 });
+ left.splice(left.indexOf(chosen), 1);
+ rho[j] += 1;
+ if (picks.length >= K) break;
+ }
+ }
+ return { picks, rho };
+ }
+
+ /** One SMPSO velocity and position update, as VAMOS computes it (bounds [lower, upper] per variable). */
+ function smpsoStep(o) {
+ const phi = o.c1 + o.c2;
+ const chi = phi <= 4 ? 1 : 2 / (2 - phi - Math.sqrt(phi * phi - 4 * phi));
+ const inertia = o.v.map((v) => o.w * v);
+ const cognitive = o.x.map((x, j) => o.c1 * o.r1 * (o.p[j] - x));
+ const social = o.x.map((x, j) => o.c2 * o.r2 * (o.g[j] - x));
+ const raw = o.x.map((_, j) => inertia[j] + cognitive[j] + social[j]);
+ const constricted = raw.map((v) => chi * v);
+ const delta = o.x.map((_, j) => o.vmax * (o.upper[j] - o.lower[j]));
+ const clamped = constricted.map((v, j) => (o.clamp === false ? v : Math.min(delta[j], Math.max(-delta[j], v))));
+ const tentative = o.x.map((x, j) => x + clamped[j]);
+ const hit = [];
+ const position = tentative.slice();
+ const velocity = clamped.slice();
+ tentative.forEach((x, j) => {
+ if (x < o.lower[j]) {
+ position[j] = o.lower[j];
+ velocity[j] = -velocity[j];
+ hit.push([j, "lower"]);
+ } else if (x > o.upper[j]) {
+ position[j] = o.upper[j];
+ velocity[j] = -velocity[j];
+ hit.push([j, "upper"]);
+ }
+ });
+ return { phi, chi, inertia, cognitive, social, raw, constricted, clamped, tentative, position, velocity, delta, hit };
+ }
+
+ function solveLinear(A, b) {
+ const n = b.length;
+ const M = A.map((row, i) => row.concat([b[i]]));
+ for (let c = 0; c < n; c++) {
+ let piv = c;
+ for (let r = c + 1; r < n; r++) if (Math.abs(M[r][c]) > Math.abs(M[piv][c])) piv = r;
+ if (Math.abs(M[piv][c]) < 1e-14) return null;
+ [M[c], M[piv]] = [M[piv], M[c]];
+ for (let r = 0; r < n; r++) {
+ if (r === c) continue;
+ const k = M[r][c] / M[c][c];
+ for (let q = c; q <= n; q++) M[r][q] -= k * M[c][q];
+ }
+ }
+ return M.map((row, i) => row[n] / row[i]);
+ }
+
+ /** AGE-MOEA geometry estimate and greedy survival score of one front (VAMOS' geometry.py). */
+ function agemoeaSurvival(F, forceP) {
+ const m = F[0].length;
+ const z = F[0].map((_, i) => Math.min(...F.map((f) => f[i])));
+ const T = F.map((f) => f.map((v, i) => Math.round((v - z[i]) * 1e12) / 1e12));
+ const dot = (a, b) => a.reduce((s2, v, i) => s2 + v * b[i], 0);
+ const corners = [];
+ for (let i = 0; i < m; i++) {
+ const d = F[0].map((_, k) => (k === i ? 1 : 0) + 1e-6);
+ const dd = dot(d, d);
+ let best = -1;
+ let bestDist = Infinity;
+ T.forEach((t, s2) => {
+ if (corners.includes(s2)) return;
+ const dist = dot(t, t) - (dot(t, d) * dot(t, d)) / dd;
+ if (dist < bestDist) {
+ bestDist = dist;
+ best = s2;
+ }
+ });
+ corners.push(best);
+ }
+ let a = null;
+ if (new Set(corners).size === m) {
+ const b = solveLinear(corners.map((c) => T[c]), corners.map(() => 1));
+ if (b && b.every((v) => Number.isFinite(v) && v > 0)) a = b.map((v) => 1 / v);
+ }
+ if (!a) a = F[0].map((_, i) => Math.max(...T.map((t) => t[i])) || 1);
+ const Nf = T.map((t) => t.map((v, i) => v / a[i]));
+ let central = -1;
+ let centralDist = Infinity;
+ Nf.forEach((t, s2) => {
+ if (corners.includes(s2)) return;
+ const dist = dot(t, t) - (t.reduce((x, v) => x + v, 0) ** 2) / m;
+ if (dist < centralDist) {
+ centralDist = dist;
+ central = s2;
+ }
+ });
+ let p = 1;
+ if (central >= 0) {
+ const mean = Nf[central].reduce((x, v) => x + v, 0) / m;
+ if (mean > 0) {
+ const est = Math.log(m) / Math.log(1 / mean);
+ p = !Number.isFinite(est) || est <= 0.1 ? 1 : Math.min(est, 20);
+ }
+ }
+ const estimated = p;
+ if (forceP) p = forceP;
+ const lp = (v) => Math.pow(v.reduce((x, u) => x + Math.pow(Math.abs(u), p), 0), 1 / p);
+ const proximity = Nf.map((t) => {
+ const v = lp(t);
+ return v < 1e-8 ? 1 : v;
+ });
+ const dist = (s2, q) => Math.max(1e-8, lp(Nf[s2].map((v, i) => v - Nf[q][i]))) / proximity[s2];
+ const score = new Array(F.length).fill(0);
+ const selected = [];
+ const order = [];
+ corners
+ .slice()
+ .sort((x, y) => x - y)
+ .forEach((c) => {
+ score[c] = Infinity;
+ selected.push(c);
+ order.push(c);
+ });
+ while (selected.length < F.length) {
+ let best = -1;
+ let bestScore = -Infinity;
+ F.forEach((_, s2) => {
+ if (selected.includes(s2)) return;
+ const ds = selected.map((q) => dist(s2, q)).sort((x, y) => x - y);
+ const sc = ds.length === 1 ? ds[0] : ds[0] + ds[1];
+ if (sc > bestScore) {
+ bestScore = sc;
+ best = s2;
+ }
+ });
+ score[best] = bestScore;
+ selected.push(best);
+ order.push(best);
+ }
+ return { p, estimated, central, corners, normalized: Nf, intercepts: a, proximity, score, order };
+ }
+
+ /** The N survivors of a last front by survival score (descending; later index first on ties). */
+ function agemoeaCut(score, N) {
+ return score
+ .map((v, i) => i)
+ .sort((x, y) => (score[y] === score[x] ? y - x : score[y] > score[x] ? 1 : -1))
+ .slice(0, N);
+ }
+
+ /* ---- Constrained algorithms: shared candidates and the selection rules of CCMO, C-TAEA, ToP, CMOEA-MS ---- */
+
+ const CS_CANDIDATES = [
+ ["P1", 0.15, 0.88],
+ ["P2", 0.2, 1.25],
+ ["P3", 0.32, 0.775],
+ ["P4", 0.45, 0.6],
+ ["P5", 0.565, 0.6],
+ ["P6", 0.7, 0.8],
+ ["P7", 0.81, 0.42],
+ ["P8", 0.95, 0.2],
+ ["O1", 0.08, 0.95],
+ ["O2", 0.3, 1.1],
+ ["O3", 0.25, 0.76],
+ ["O4", 0.52, 0.5],
+ ["O5", 0.6, 0.42],
+ ["O6", 0.645, 0.54],
+ ["O7", 0.88, 0.15],
+ ["O8", 0.97, 0.3],
+ ];
+
+ /** Strength-based fitness R + density with a custom dominance relation. */
+ function strengthFitness(n, dom, density) {
+ const S = [];
+ for (let i = 0; i < n; i++) {
+ let s2 = 0;
+ for (let j = 0; j < n; j++) if (i !== j && dom(i, j)) s2 += 1;
+ S.push(s2);
+ }
+ const R = [];
+ const by = [];
+ for (let j = 0; j < n; j++) {
+ let r = 0;
+ const d = [];
+ for (let i = 0; i < n; i++)
+ if (i !== j && dom(i, j)) {
+ r += S[i];
+ d.push(i);
+ }
+ R.push(r);
+ by.push(d);
+ }
+ const D = Array.from({ length: n }, (_, i) => density(i));
+ return { S, R, D, by, fitness: R.map((r, i) => r + D[i]) };
+ }
+
+ function kthOther(row, i, k) {
+ return row.filter((_, j) => j !== i).sort((a, b) => a - b)[k - 1];
+ }
+
+ /** Keep fitness < 1; fill with the lowest fitness (stable) or truncate by lexicographic distance lists. */
+ function strengthSelect(fitness, n, dist) {
+ const idx = fitness.map((_, i) => i);
+ let keep = idx.filter((i) => fitness[i] < 1);
+ if (keep.length < n) {
+ keep = idx.slice().sort((a, b) => (Number.isNaN(fitness[a]) ? 1 : 0) - (Number.isNaN(fitness[b]) ? 1 : 0) || fitness[a] - fitness[b] || a - b).slice(0, n);
+ } else {
+ while (keep.length > n) {
+ const lists = keep.map((i) =>
+ keep
+ .filter((j) => j !== i)
+ .map((j) => dist(i, j))
+ .sort((a, b) => a - b)
+ );
+ let worst = 0;
+ for (let a = 1; a < keep.length; a++) if (lexLess(lists[a], lists[worst])) worst = a;
+ keep.splice(worst, 1);
+ }
+ }
+ return keep;
+ }
+
+ /** CCMO: SPEA2 fitness with violation-first dominance (population 1) or zero violations (population 2). */
+ function ccmoSelect(F, cv, n) {
+ const m = F.length;
+ const dist = (i, j) => euclidean(F[i], F[j]);
+ const k = Math.floor(Math.sqrt(m));
+ const dk = F.map((_, i) => kthOther(F.map((_, j) => dist(i, j)), i, k));
+ const dom = (i, j) => cv[i] < cv[j] || (cv[i] === cv[j] && dominates(F[i], F[j]));
+ const fit = strengthFitness(m, dom, (i) => 1 / (dk[i] + 2));
+ return { ...fit, dk, k, kept: strengthSelect(fit.fitness, n, dist) };
+ }
+
+ const CTAEA_W = (count) =>
+ Array.from({ length: count }, (_, k) => {
+ const a = k / (count - 1);
+ return [Math.max(a, 1e-6), Math.max(1 - a, 1e-6)];
+ });
+
+ function ctaeaAssociate(f, W) {
+ const nf = Math.hypot(...f) || 1;
+ let best = 0;
+ let bestCos = -Infinity;
+ W.forEach((w, k) => {
+ const c = (f[0] * w[0] + f[1] * w[1]) / (nf * Math.hypot(...w));
+ if (c > bestCos) {
+ bestCos = c;
+ best = k;
+ }
+ });
+ return best;
+ }
+
+ function ctaeaTchebycheff(rows, W) {
+ const z = [0, 1].map((j) => Math.min(...rows.map((f) => f[j])));
+ return rows.map((f) => {
+ const w = W[ctaeaAssociate(f, W)];
+ return Math.max(...f.map((v, j) => Math.abs(v - z[j]) / w[j]));
+ });
+ }
+
+ /** C-TAEA convergence archive and diversity archive updates (ctaea/archives.py). */
+ function ctaeaSelect(F, cv, n) {
+ const W = CTAEA_W(n);
+ const idx = F.map((_, i) => i);
+ const feasible = idx.filter((i) => cv[i] <= 0);
+ const ca = { removals: [], fronts: null, normalized: null };
+ let CA;
+ if (feasible.length === n) CA = feasible.slice();
+ else if (feasible.length > n) {
+ const sorted = nonDominatedSort(feasible.map((i) => F[i]));
+ ca.fronts = sorted.fronts.map((f) => f.map((r) => feasible[r]));
+ CA = [];
+ for (const front of ca.fronts) {
+ if (CA.length >= n) break;
+ CA.push(...front);
+ }
+ while (CA.length > n) {
+ const rows = CA.map((i) => F[i]);
+ const lo = [0, 1].map((j) => Math.min(...rows.map((f) => f[j])));
+ const hi = [0, 1].map((j) => Math.max(...rows.map((f) => f[j])));
+ const norm = rows.map((f) => f.map((v, j) => (hi[j] > lo[j] ? (v - lo[j]) / (hi[j] - lo[j]) : 0)));
+ const region = norm.map((f) => ctaeaAssociate(f, W));
+ const counts = W.map((_, k) => region.filter((r) => r === k).length);
+ const crowded = counts.indexOf(Math.max(...counts));
+ const members = CA.filter((_, a) => region[a] === crowded);
+ let dmin = Infinity;
+ members.forEach((i) => members.forEach((j) => i !== j && euclidean(F[i], F[j]) > 0 && (dmin = Math.min(dmin, euclidean(F[i], F[j])))));
+ const closest = members.filter((i) => members.some((j) => j !== i && Math.abs(euclidean(F[i], F[j]) - dmin) < 1e-15));
+ const tch = ctaeaTchebycheff(
+ closest.map((i) => F[i]),
+ W
+ );
+ let worst = 0;
+ tch.forEach((v, a) => {
+ if (v > tch[worst]) worst = a;
+ });
+ ca.normalized = ca.normalized || CA.map((i, a) => ({ i, f: norm[a], region: region[a] }));
+ ca.removals.push({ counts, crowded, closest, tch, removed: closest[worst], ideal: [0, 1].map((j) => Math.min(...closest.map((i) => F[i][j]))) });
+ CA.splice(CA.indexOf(closest[worst]), 1);
+ }
+ } else {
+ const infeasible = idx.filter((i) => cv[i] > 0);
+ const tch = ctaeaTchebycheff(
+ infeasible.map((i) => F[i]),
+ W
+ );
+ const fronts = nonDominatedSort(infeasible.map((i, a) => [cv[i], tch[a]])).fronts.map((f) => f.map((r) => infeasible[r]));
+ CA = feasible.slice();
+ for (const front of fronts) {
+ if (CA.length >= n) break;
+ if (CA.length + front.length <= n) CA.push(...front);
+ else
+ CA.push(
+ ...front
+ .slice()
+ .sort((a, b) => cv[a] - cv[b] || a - b)
+ .slice(0, n - CA.length)
+ );
+ }
+ }
+ const regions = F.map((f) => ctaeaAssociate(f, W));
+ const caCounts = W.map((_, k) => CA.filter((i) => regions[i] === k).length);
+ const left = W.map((_, k) => regions.filter((r) => r === k).length);
+ const available = new Set(idx);
+ const DA = [];
+ const trace = [];
+ let iteration = 1;
+ while (DA.length < n && available.size) {
+ for (let r = 0; r < W.length; r++) {
+ if (DA.length >= n) break;
+ for (let q = 0; q < iteration - caCounts[r]; q++) {
+ if (!left[r]) break;
+ const cands = idx.filter((i) => available.has(i) && regions[i] === r);
+ const nd = cands.filter((i) => !cands.some((j) => j !== i && dominates(F[j], F[i])));
+ const tch = ctaeaTchebycheff(
+ nd.map((i) => F[i]),
+ W
+ );
+ let best = 0;
+ tch.forEach((v, a) => {
+ if (v < tch[best]) best = a;
+ });
+ available.delete(nd[best]);
+ left[r] -= 1;
+ if (DA.length < n) {
+ DA.push(nd[best]);
+ trace.push({ iteration, region: r, ca: caCounts[r], cands, nd, tch, chosen: nd[best] });
+ }
+ }
+ }
+ iteration += 1;
+ }
+ return { W, CA, DA, ca, caCounts, regions, trace, feasible };
+ }
+
+ /** ToP phase 1 (pairwise replacement on the mean objective) and phase 2 (constrained NSGA-II survival). */
+ function topSelect(F, cv, n) {
+ const mean = (f) => f.reduce((s2, v) => s2 + v, 0) / f.length;
+ const pairs = [];
+ const next = [];
+ for (let i = 0; i < n; i++) {
+ const p = i;
+ const o = i + n;
+ const wins = cv[o] < cv[p] || (cv[o] === cv[p] && mean(F[o]) < mean(F[p]));
+ pairs.push({ p, o, winner: wins ? o : p, pm: mean(F[p]), om: mean(F[o]) });
+ next.push(wins ? o : p);
+ }
+ const feas = next.filter((i) => cv[i] <= 0);
+ const Pf = feas.length / n;
+ let delta = 1;
+ if (feas.length >= 3) {
+ const lo = [0, 1].map((j) => Math.min(...feas.map((i) => F[i][j])));
+ const hi = [0, 1].map((j) => Math.max(...feas.map((i) => F[i][j])));
+ const sums = feas.map((i) => F[i].reduce((s2, v, j) => s2 + (v - lo[j]) / (hi[j] - lo[j]), 0)).sort((a, b) => a - b);
+ delta = sums[Math.floor(feas.length / 3) - 1] - sums[0];
+ }
+ const idx = F.map((_, i) => i);
+ const feasible = idx.filter((i) => cv[i] <= 0);
+ const fronts = nonDominatedSort(feasible.map((i) => F[i])).fronts.map((f) => f.map((r) => feasible[r]));
+ const infeasible = idx.filter((i) => cv[i] > 0);
+ Array.from(new Set(infeasible.map((i) => cv[i])))
+ .sort((a, b) => a - b)
+ .forEach((v) => fronts.push(infeasible.filter((i) => cv[i] === v)));
+ const crowd = new Array(F.length).fill(0);
+ fronts.forEach((front) => {
+ const d = crowdingDistance(F, front);
+ front.forEach((i, a) => (crowd[i] = d[a]));
+ });
+ const kept = [];
+ for (const front of fronts) {
+ if (kept.length + front.length <= n) kept.push(...front);
+ else {
+ kept.push(
+ ...front
+ .slice()
+ .sort((a, b) => cmpDesc(crowd[a], crowd[b]) || a - b)
+ .slice(0, n - kept.length)
+ );
+ break;
+ }
+ if (kept.length === n) break;
+ }
+ return { pairs, next, Pf, delta, phaseOneContinues: delta >= 0.2 || Pf <= 1 / 3, fronts, crowd, kept: kept.sort((a, b) => a - b) };
+ }
+
+ /** CMOEA-MS stage A and stage B fitness and selection (cmoeams/fitness.py, selection.py). */
+ function cmoeamsSelect(F, cv, n) {
+ const m = F.length;
+ const top = Math.max(...cv);
+ const cvn = cv.map((v) => (top > 0 ? Math.max(v, 0) / top : 0));
+ const lo = [0, 1].map((j) => Math.min(...F.map((f) => f[j])));
+ const hi = [0, 1].map((j) => Math.max(...F.map((f) => f[j])));
+ const Fn = F.map((f) => f.map((v, j) => (hi[j] > lo[j] ? (v - lo[j]) / (hi[j] - lo[j]) : 0)));
+ const kk = Math.floor(Math.sqrt(m));
+ const dSde = Fn.map((fi) =>
+ Fn.map((fj) => Math.hypot(...fi.map((v, t) => v - Math.max(fj[t], v))))
+ .sort((a, b) => a - b)[kk]
+ );
+ const sde = dSde.map((d) => 1 / (d + 2));
+ const cosd = (a, b) => {
+ const na = Math.hypot(...a);
+ const nb = Math.hypot(...b);
+ return na && nb ? 1 - (a[0] * b[0] + a[1] * b[1]) / (na * nb) : 1;
+ };
+ const fitnessOf = (points, viol) => {
+ const dom = (i, j) => viol[i] < viol[j] || (viol[i] === viol[j] && dominates(points[i], points[j]));
+ const dcos = points.map((p, i) => kthOther(points.map((q) => cosd(p, q)), i, kk));
+ const fit = strengthFitness(m, dom, (i) => 1 / (dcos[i] + 2));
+ return { ...fit, dcos, kept: strengthSelect(fit.fitness, n, (i, j) => cosd(F[i], F[j])).sort((a, b) => a - b) };
+ };
+ const zeros = new Array(m).fill(0);
+ const A = fitnessOf(
+ sde.map((v, i) => [v, cvn[i]]),
+ zeros
+ );
+ const B = fitnessOf(F, cvn);
+ const share = cvn.filter((v) => v <= 0).length / m;
+ return { cvn, dSde, sde, A, B, share };
+ }
+
+ const algorithms = {
+ ccmoSelect,
+ ctaeaSelect,
+ topSelect,
+ cmoeamsSelect,
+ CS_CANDIDATES,
+ agemoeaSurvival,
+ agemoeaCut,
+ smpsoStep,
+ nsga3Associate,
+ nsga3Niching,
+ moeadWeights,
+ moeadNeighbours,
+ moeadAggregate,
+ moeadReplace,
+ spea2Fitness,
+ spea2Select,
+ epsilonPair,
+ ibeaSelect,
+ rveaSelect,
+ mulberry32,
+ dominates,
+ nonDominatedSort,
+ crowdingDistance,
+ rankAndCrowding,
+ selectSurvivors,
+ nonDominatedIndices,
+ hypervolume2d,
+ hvContributions2d,
+ tchebycheffContour,
+ generationalDistance,
+ igd,
+ igdPlus,
+ epsilonAdditive,
+ spacing,
+ spreadDelta,
+ sbxPair,
+ polynomialMutation,
+ nsga2Truncate,
+ createNSGAII,
+ ctpViolation,
+ constrainedDominates,
+ binomial,
+ dasDennis,
+ attainmentSurface,
+ mannWhitney,
+ PROBLEMS,
+ };
+ root.VamosFoundations = algorithms;
+
+ if (typeof document === "undefined") return;
+
+ /* ------------------------------------------------------------------ */
+ /* DOM and SVG helpers */
+ /* ------------------------------------------------------------------ */
+
+ const SVG_NS = "http://www.w3.org/2000/svg";
+ const LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+ const RANK_CLASSES = ["vf-r0", "vf-r1", "vf-r2", "vf-r3", "vf-r4"];
+ const reducedMotion = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
+ let uid = 0;
+
+ function s(tag, attrs, parent) {
+ const node = document.createElementNS(SVG_NS, tag);
+ if (attrs) for (const key of Object.keys(attrs)) node.setAttribute(key, attrs[key]);
+ if (parent) parent.appendChild(node);
+ return node;
+ }
+
+ function h(tag, attrs, parent, text) {
+ const node = document.createElement(tag);
+ if (attrs) for (const key of Object.keys(attrs)) node.setAttribute(key, attrs[key]);
+ if (text !== undefined) node.textContent = text;
+ if (parent) parent.appendChild(node);
+ return node;
+ }
+
+ function txt(parent, x, y, content, attrs) {
+ const node = s("text", Object.assign({ x, y }, attrs || {}), parent);
+ node.textContent = content;
+ return node;
+ }
+
+ function clear(node) {
+ while (node.firstChild) node.removeChild(node.firstChild);
+ }
+
+ function fmt(value, digits) {
+ if (value === Infinity) return "∞";
+ if (value === -Infinity) return "−∞";
+ if (!Number.isFinite(value)) return "–";
+ return value.toFixed(digits === undefined ? 3 : digits);
+ }
+
+ function pair(p, digits) {
+ return "(" + fmt(p[0], digits === undefined ? 2 : digits) + ", " + fmt(p[1], digits === undefined ? 2 : digits) + ")";
+ }
+
+ function rankClass(rank) {
+ return RANK_CLASSES[Math.min(rank, RANK_CLASSES.length - 1)];
+ }
+
+ function niceTicks(lo, hi, count) {
+ const span = hi - lo;
+ const raw = span / count;
+ const mag = Math.pow(10, Math.floor(Math.log10(raw)));
+ const err = raw / mag;
+ const step = (err >= 7.5 ? 10 : err >= 3.5 ? 5 : err >= 1.5 ? 2 : 1) * mag;
+ const ticks = [];
+ for (let v = Math.ceil(lo / step - 1e-9) * step; v <= hi + step * 1e-9; v += step) ticks.push(+v.toFixed(10));
+ return ticks;
+ }
+
+ function tickFormat(v) {
+ if (v === 0) return "0";
+ if (Math.abs(v) >= 1000) return v.toLocaleString("en-US");
+ return String(+v.toFixed(3));
+ }
+
+ function marker(layer, shape, x, y, r, cls) {
+ if (shape === "triangle") {
+ const k = r * 1.3;
+ return s("path", { d: `M${x},${y - k}L${x + k * 0.866},${y + k * 0.5}L${x - k * 0.866},${y + k * 0.5}Z`, class: cls }, layer);
+ }
+ if (shape === "square") {
+ return s("rect", { x: x - r * 0.88, y: y - r * 0.88, width: r * 1.76, height: r * 1.76, rx: 1.5, class: cls }, layer);
+ }
+ if (shape === "diamond") {
+ const k = r * 1.25;
+ return s("path", { d: `M${x},${y - k}L${x + k},${y}L${x},${y + k}L${x - k},${y}Z`, class: cls }, layer);
+ }
+ if (shape === "cross") {
+ return s("path", { d: `M${x - r},${y - r}L${x + r},${y + r}M${x - r},${y + r}L${x + r},${y - r}`, class: cls }, layer);
+ }
+ return s("circle", { cx: x, cy: y, r, class: cls }, layer);
+ }
+
+ function legend(parent, items) {
+ const list = h("ul", { class: "vf-legend" }, parent);
+ for (const item of items) {
+ const li = h("li", {}, list);
+ const icon = s("svg", { viewBox: "0 0 14 14", "aria-hidden": "true" }, li);
+ if (item.shape === "line") s("line", { x1: 1, y1: 7, x2: 13, y2: 7, class: item.cls }, icon);
+ else if (item.shape === "region") s("rect", { x: 1, y: 1, width: 12, height: 12, rx: 2, class: item.cls }, icon);
+ else marker(icon, item.shape, 7, 7, 4.2, item.cls);
+ h("span", {}, li, item.label);
+ }
+ return list;
+ }
+
+ function controls(parent) {
+ return h("div", { class: "vf-controls" }, parent);
+ }
+
+ function button(parent, label, onClick, primary) {
+ const b = h("button", { type: "button", class: "vf-button" + (primary ? " vf-button--primary" : "") }, parent, label);
+ b.addEventListener("click", onClick);
+ return b;
+ }
+
+ function slider(parent, o) {
+ const label = h("label", {}, parent);
+ h("span", {}, label, o.label);
+ const input = h("input", { type: "range", min: o.min, max: o.max, step: o.step }, label);
+ input.value = o.value;
+ const show = (v) => (o.format ? o.format(v) : String(v));
+ const out = h("output", {}, label, show(o.value));
+ input.addEventListener("input", () => {
+ const v = parseFloat(input.value);
+ out.textContent = show(v);
+ o.onInput(v);
+ });
+ return {
+ input,
+ set(v) {
+ input.value = v;
+ out.textContent = show(v);
+ },
+ };
+ }
+
+ function select(parent, o) {
+ const label = h("label", {}, parent);
+ h("span", {}, label, o.label);
+ const node = h("select", {}, label);
+ for (const [value, text] of o.options) {
+ const opt = h("option", { value: String(value) }, node, text);
+ if (String(value) === String(o.value)) opt.selected = true;
+ }
+ node.addEventListener("change", () => o.onChange(node.value));
+ return node;
+ }
+
+ function checkbox(parent, o) {
+ const label = h("label", {}, parent);
+ const box = h("input", { type: "checkbox" }, label);
+ box.checked = !!o.checked;
+ h("span", {}, label, o.label);
+ box.addEventListener("change", () => o.onChange(box.checked));
+ return box;
+ }
+
+ function createPlot(parent, o) {
+ const W = o.width || 360;
+ const H = o.height || 280;
+ const m = Object.assign({ l: 50, r: 14, t: 12, b: 42 }, o.margin || {});
+ const wrap = h("div", { class: "vf-plot-wrap" }, parent);
+ if (o.title) h("p", { class: "vf-title" }, wrap, o.title);
+ const svg = s("svg", { viewBox: `0 0 ${W} ${H}`, class: "vf-plot", role: "group", "aria-label": o.label || o.title || "" }, wrap);
+ const clipId = "vf-clip-" + ++uid;
+ const clipRect = s("rect", {}, s("clipPath", { id: clipId }, s("defs", {}, svg)));
+ const axes = s("g", { "aria-hidden": "true" }, svg);
+ const clipped = s("g", { "clip-path": `url(#${clipId})` }, svg);
+ const plot = { svg, wrap, W, H, m, xd: o.x, yd: o.y, pw: W - m.l - m.r, ph: H - m.t - m.b };
+ plot.layers = {
+ back: s("g", {}, clipped),
+ mid: s("g", {}, clipped),
+ marks: s("g", {}, svg),
+ points: s("g", {}, svg),
+ top: s("g", {}, svg),
+ };
+ plot.x = (v) => m.l + ((v - plot.xd[0]) / (plot.xd[1] - plot.xd[0])) * plot.pw;
+ plot.y = (v) => m.t + plot.ph - ((v - plot.yd[0]) / (plot.yd[1] - plot.yd[0])) * plot.ph;
+ plot.xi = (px) => plot.xd[0] + ((px - m.l) / plot.pw) * (plot.xd[1] - plot.xd[0]);
+ plot.yi = (py) => plot.yd[0] + ((m.t + plot.ph - py) / plot.ph) * (plot.yd[1] - plot.yd[0]);
+ plot.drawAxes = function () {
+ clear(axes);
+ clipRect.setAttribute("x", m.l);
+ clipRect.setAttribute("y", m.t);
+ clipRect.setAttribute("width", plot.pw);
+ clipRect.setAttribute("height", plot.ph);
+ if (o.axes === false) return;
+ const xt = o.xTicks || niceTicks(plot.xd[0], plot.xd[1], o.xCount || 5);
+ const yt = o.yTicks || niceTicks(plot.yd[0], plot.yd[1], o.yCount || 5);
+ for (const v of xt) {
+ if (v < plot.xd[0] - 1e-9 || v > plot.xd[1] + 1e-9) continue;
+ const px = plot.x(v);
+ s("line", { x1: px, x2: px, y1: m.t, y2: m.t + plot.ph, class: "vf-grid-line" }, axes);
+ txt(axes, px, m.t + plot.ph + 15, o.xFormat ? o.xFormat(v) : tickFormat(v), { "text-anchor": "middle" });
+ }
+ for (const v of yt) {
+ if (v < plot.yd[0] - 1e-9 || v > plot.yd[1] + 1e-9) continue;
+ const py = plot.y(v);
+ s("line", { x1: m.l, x2: m.l + plot.pw, y1: py, y2: py, class: "vf-grid-line" }, axes);
+ txt(axes, m.l - 6, py + 4, o.yFormat ? o.yFormat(v) : tickFormat(v), { "text-anchor": "end" });
+ }
+ s("path", { d: `M${m.l},${m.t}V${m.t + plot.ph}H${m.l + plot.pw}`, class: "vf-axis-line" }, axes);
+ if (o.xLabel) txt(axes, m.l + plot.pw / 2, H - 6, o.xLabel, { "text-anchor": "middle", class: "vf-axis-label" });
+ if (o.yLabel) {
+ txt(axes, 0, 0, o.yLabel, {
+ "text-anchor": "middle",
+ class: "vf-axis-label",
+ transform: `translate(12 ${m.t + plot.ph / 2}) rotate(-90)`,
+ });
+ }
+ };
+ plot.setDomain = function (x, y) {
+ plot.xd = x;
+ plot.yd = y;
+ plot.drawAxes();
+ };
+ plot.pointer = function (evt) {
+ const ctm = svg.getScreenCTM();
+ if (!ctm) return null;
+ const pt = svg.createSVGPoint();
+ pt.x = evt.clientX;
+ pt.y = evt.clientY;
+ const p = pt.matrixTransform(ctm.inverse());
+ return { x: plot.xi(p.x), y: plot.yi(p.y) };
+ };
+ plot.line = function (layer, points, cls) {
+ const d = points.map((p, i) => (i ? "L" : "M") + plot.x(p[0]).toFixed(2) + "," + plot.y(p[1]).toFixed(2)).join("");
+ return s("path", { d, class: cls }, layer);
+ };
+ plot.rect = function (layer, x0, y0, x1, y1, cls) {
+ const xa = plot.x(Math.min(x0, x1));
+ const xb = plot.x(Math.max(x0, x1));
+ const ya = plot.y(Math.max(y0, y1));
+ const yb = plot.y(Math.min(y0, y1));
+ return s("rect", { x: xa, y: ya, width: Math.max(0, xb - xa), height: Math.max(0, yb - ya), class: cls }, layer);
+ };
+ plot.drawAxes();
+ return plot;
+ }
+
+ function tooltip(plot) {
+ const tip = h("div", { class: "vf-tooltip", "aria-hidden": "true" }, plot.wrap);
+ tip.hidden = true;
+ return {
+ show(content, px, py) {
+ tip.textContent = content;
+ tip.hidden = false;
+ const box = plot.svg.getBoundingClientRect();
+ const outer = plot.wrap.getBoundingClientRect();
+ const scale = box.width / plot.W || 1;
+ const x = box.left - outer.left + px * scale;
+ let left = x + 12;
+ if (left + tip.offsetWidth > plot.wrap.clientWidth) left = Math.max(0, x - tip.offsetWidth - 12);
+ tip.style.left = left + "px";
+ tip.style.top = Math.max(0, box.top - outer.top + py * scale - 34) + "px";
+ },
+ hide() {
+ tip.hidden = true;
+ },
+ };
+ }
+
+ function attachTip(node, tip, content, px, py) {
+ node.addEventListener("pointerenter", () => tip.show(typeof content === "function" ? content() : content, px, py));
+ node.addEventListener("pointerleave", () => tip.hide());
+ }
+
+ /** A focusable point the reader can drag with a pointer or move with the arrow keys. */
+ function handle(plot, o) {
+ const g = s("g", { class: "vf-handle", tabindex: "0", role: "button", "aria-roledescription": "draggable point" }, plot.layers.points);
+ s("circle", { r: 15, class: "vf-hit" }, g);
+ s("circle", { r: (o.r || 6) + 4, class: "vf-focus" }, g);
+ const mark = marker(g, o.shape || "circle", 0, 0, o.r || 6, o.cls);
+ const bx = o.boundsX || plot.xd;
+ const by = o.boundsY || plot.yd;
+ const clamp = (v, b) => Math.min(b[1], Math.max(b[0], v));
+ let dragging = false;
+ const api = {
+ node: g,
+ mark,
+ place() {
+ const p = o.get();
+ g.setAttribute("transform", `translate(${plot.x(p[0]).toFixed(2)} ${plot.y(p[1]).toFixed(2)})`);
+ g.setAttribute("aria-label", (o.label ? o.label() : "Point") + " at " + pair(p) + ". Use the arrow keys to move it.");
+ },
+ setClass(cls) {
+ mark.setAttribute("class", cls);
+ },
+ };
+ g.addEventListener("pointerdown", (e) => {
+ if (e.button !== undefined && e.button !== 0) return;
+ e.preventDefault();
+ dragging = true;
+ if (g.setPointerCapture) g.setPointerCapture(e.pointerId);
+ if (g.focus) g.focus({ preventScroll: true });
+ if (o.onSelect) o.onSelect();
+ });
+ g.addEventListener("pointermove", (e) => {
+ if (!dragging) return;
+ const p = plot.pointer(e);
+ if (!p) return;
+ o.set(clamp(p.x, bx), clamp(p.y, by));
+ });
+ const stop = () => {
+ dragging = false;
+ };
+ g.addEventListener("pointerup", stop);
+ g.addEventListener("pointercancel", stop);
+ g.addEventListener("focus", () => {
+ if (o.onSelect) o.onSelect();
+ });
+ g.addEventListener("keydown", (e) => {
+ const keys = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, 1], ArrowDown: [0, -1] };
+ const move = keys[e.key];
+ if (!move) return;
+ e.preventDefault();
+ const p = o.get();
+ const factor = e.shiftKey ? 0.1 : 0.02;
+ o.set(clamp(p[0] + move[0] * factor * (bx[1] - bx[0]), bx), clamp(p[1] + move[1] * factor * (by[1] - by[0]), by));
+ });
+ api.place();
+ return api;
+ }
+
+ function table(parent, headers, rows, numeric) {
+ const t = h("table", {}, h("div", { class: "vf-table-wrap" }, parent));
+ const tr = h("tr", {}, h("thead", {}, t));
+ headers.forEach((label, i) => h("th", numeric && numeric[i] ? { class: "vf-num" } : {}, tr, label));
+ const body = h("tbody", {}, t);
+ for (const row of rows) {
+ const r = h("tr", {}, body);
+ row.forEach((cell, i) => h("td", numeric && numeric[i] ? { class: "vf-num" } : {}, r, cell));
+ }
+ return t;
+ }
+
+ /** Draw a sampled front, breaking the line where the front is disconnected. */
+ function drawFront(plot, layer, pts, cls, maxGap) {
+ let seg = [];
+ const gap = maxGap || 3 / Math.max(pts.length, 2);
+ pts.forEach((p, i) => {
+ if (i && p[0] - pts[i - 1][0] > gap) {
+ if (seg.length > 1) plot.line(layer, seg, cls);
+ seg = [];
+ }
+ seg.push(p);
+ });
+ if (seg.length > 1) plot.line(layer, seg, cls);
+ }
+
+ /** Make a mark keyboard-focusable and give it back focus after a re-render. */
+ function focusable(mark, label, state, index) {
+ mark.setAttribute("tabindex", "0");
+ mark.setAttribute("class", mark.getAttribute("class") + " vf-focusable");
+ mark.setAttribute("aria-label", label);
+ if (state.refocus === index) {
+ state.refocus = -1;
+ mark.focus({ preventScroll: true });
+ }
+ }
+
+ function frontPoints(curve, lo, hi, n) {
+ const pts = [];
+ for (let i = 0; i < n; i++) {
+ const t = lo + ((hi - lo) * i) / (n - 1);
+ pts.push([t, curve(t)]);
+ }
+ return pts;
+ }
+
+ /* ------------------------------------------------------------------ */
+ /* Figures */
+ /* ------------------------------------------------------------------ */
+
+ const widgets = {};
+
+ /* B1: one design in decision space and its image in objective space. */
+ widgets["decision-map"] = function (node) {
+ const toy = (x1, x2) => {
+ const g = 1 + x2;
+ return [x1, g * (1 - Math.sqrt(x1 / g))];
+ };
+ const rand = mulberry32(7);
+ const cloud = Array.from({ length: 260 }, () => [rand(), rand()]);
+ const state = { x: [0.3, 0.6] };
+ const ctl = controls(node);
+ const body = h("div", { class: "vf-body vf-body--two" }, node);
+ const dec = createPlot(body, { title: "Decision space", x: [0, 1], y: [-0.04, 1], xLabel: "x₁", yLabel: "x₂", label: "Decision space with a draggable design" });
+ const obj = createPlot(body, { title: "Objective space", x: [0, 1], y: [0, 2], xLabel: "f₁(x)", yLabel: "f₂(x)", label: "Objective space showing the image of the design" });
+ for (const c of cloud) {
+ s("circle", { cx: dec.x(c[0]), cy: dec.y(c[1]), r: 1.8, class: "vf-cloud" }, dec.layers.back);
+ const f = toy(c[0], c[1]);
+ s("circle", { cx: obj.x(f[0]), cy: obj.y(f[1]), r: 1.8, class: "vf-cloud" }, obj.layers.back);
+ }
+ dec.line(dec.layers.mid, [[0, 0], [1, 0]], "vf-line-1");
+ obj.line(obj.layers.mid, frontPoints((t) => 1 - Math.sqrt(t), 0, 1, 101), "vf-line-1");
+ const readout = h("div", { class: "vf-readout" }, node);
+ legend(node, [
+ { label: "Random designs and their images", shape: "circle", cls: "vf-cloud" },
+ { label: "Pareto set (left) and Pareto front (right)", shape: "line", cls: "vf-line-1" },
+ { label: "Your design x and F(x)", shape: "circle", cls: "vf-pt vf-pt-2" },
+ { label: "Same x₁ with x₂ = 0", shape: "circle", cls: "vf-pt-hollow" },
+ ]);
+ const hd = handle(dec, {
+ cls: "vf-pt vf-pt-2",
+ r: 7,
+ label: () => "Design x",
+ get: () => state.x,
+ set: (a, b) => {
+ state.x = [Math.max(0, Math.min(1, a)), Math.max(0, Math.min(1, b))];
+ render();
+ },
+ boundsY: [0, 1],
+ });
+ function render() {
+ hd.place();
+ clear(obj.layers.marks);
+ clear(dec.layers.top);
+ const f = toy(state.x[0], state.x[1]);
+ const best = toy(state.x[0], 0);
+ if (state.x[1] > 0.005) {
+ s("line", { x1: obj.x(f[0]), y1: obj.y(f[1]), x2: obj.x(best[0]), y2: obj.y(best[1]), class: "vf-line-thin vf-dashed" }, obj.layers.marks);
+ marker(obj.layers.marks, "circle", obj.x(best[0]), obj.y(best[1]), 5, "vf-pt-hollow");
+ marker(dec.layers.top, "circle", dec.x(state.x[0]), dec.y(0), 5, "vf-pt-hollow");
+ }
+ marker(obj.layers.marks, "circle", obj.x(f[0]), obj.y(f[1]), 7, "vf-pt vf-pt-2");
+ txt(obj.layers.marks, obj.x(f[0]) + 10, obj.y(f[1]) - 8, "F(x)", { class: "vf-mark-label" });
+ clear(readout);
+ h("p", {}, readout, `x = ${pair(state.x)} → F(x) = ${pair(f)}.`);
+ if (state.x[1] > 0.005) {
+ h(
+ "p",
+ {},
+ readout,
+ `The design (${fmt(state.x[0], 2)}, 0.00) reaches F = ${pair(best)}: the same f₁ and a lower f₂. ` +
+ "So x is dominated. Every design with x₂ > 0 is dominated in this way, which is why the Pareto set is the segment x₂ = 0."
+ );
+ } else {
+ h("p", {}, readout, "x lies in the Pareto set: no other design lowers one objective without raising the other.");
+ }
+ }
+ button(ctl, "Move to the Pareto set", () => {
+ state.x = [state.x[0], 0];
+ render();
+ });
+ button(ctl, "Random design", () => {
+ state.x = [Math.round(Math.random() * 100) / 100, Math.round(Math.random() * 100) / 100];
+ render();
+ });
+ render();
+ };
+
+ /* B1 and I6: weighted sum versus Tchebycheff scalarization. */
+ widgets.scalarization = function (node) {
+ const modes = (node.dataset.modes || "ws").split(",");
+ const shapes = { convex: (t) => 1 - Math.sqrt(t), concave: (t) => 1 - t * t };
+ const state = { shape: node.dataset.shape || "concave", mode: modes[0], w: 0.5, trail: [] };
+ const ctl = controls(node);
+ select(ctl, {
+ label: "Front",
+ options: [
+ ["convex", "Convex (ZDT1)"],
+ ["concave", "Non-convex (ZDT2)"],
+ ],
+ value: state.shape,
+ onChange: (v) => {
+ state.shape = v;
+ state.trail = [];
+ render();
+ },
+ });
+ if (modes.length > 1) {
+ select(ctl, {
+ label: "Method",
+ options: [
+ ["ws", "Weighted sum"],
+ ["tch", "Tchebycheff"],
+ ],
+ value: state.mode,
+ onChange: (v) => {
+ state.mode = v;
+ state.trail = [];
+ render();
+ },
+ });
+ }
+ slider(ctl, {
+ label: "Weight w₁",
+ min: 0,
+ max: 1,
+ step: 0.01,
+ value: state.w,
+ format: (v) => v.toFixed(2),
+ onInput: (v) => {
+ state.w = v;
+ render();
+ },
+ });
+ const sweepButton = button(ctl, "Sweep 21 weights", sweep, true);
+ const body = h("div", { class: "vf-body vf-body--side" }, node);
+ const plot = createPlot(body, { x: [0, 1.15], y: [0, 1.15], xLabel: "f₁", yLabel: "f₂", label: "Pareto front and the solution selected by a weight vector" });
+ const readout = h("div", { class: "vf-readout" }, body);
+ legend(node, [
+ { label: "Pareto front", shape: "line", cls: "vf-front" },
+ { label: "Contour of the scalarized objective", shape: "line", cls: "vf-line-2" },
+ { label: "Selected solution", shape: "circle", cls: "vf-pt vf-pt-2" },
+ { label: "Solutions found by the sweep", shape: "circle", cls: "vf-pt vf-pt-1" },
+ ]);
+ function front() {
+ return frontPoints(shapes[state.shape], 0, 1, 401);
+ }
+ function solve(w, mode, pts) {
+ let best = Infinity;
+ let arg = null;
+ for (const p of pts) {
+ const v = mode === "ws" ? w * p[0] + (1 - w) * p[1] : Math.max(w * p[0], (1 - w) * p[1]);
+ if (v < best - 1e-12) {
+ best = v;
+ arg = p;
+ }
+ }
+ return { value: best, point: arg };
+ }
+ function render() {
+ clear(plot.layers.mid);
+ clear(plot.layers.marks);
+ const pts = front();
+ plot.line(plot.layers.mid, pts, "vf-front");
+ const w = state.w;
+ const sol = solve(w, state.mode, pts);
+ const c = sol.value;
+ if (state.mode === "ws") {
+ if (1 - w > 1e-9) {
+ const yAt = (x) => (c - w * x) / (1 - w);
+ plot.line(plot.layers.mid, [[-0.5, yAt(-0.5)], [2, yAt(2)]], "vf-line-2");
+ } else {
+ plot.line(plot.layers.mid, [[c / w, -1], [c / w, 3]], "vf-line-2");
+ }
+ } else {
+ const contour = tchebycheffContour(w, c);
+ const [cx, cy] = contour[1];
+ plot.line(plot.layers.mid, contour, "vf-line-2");
+ plot.line(plot.layers.mid, [[0, 0], [cx * 3, cy * 3]], "vf-line-thin vf-dashed");
+ }
+ for (const p of state.trail) marker(plot.layers.marks, "circle", plot.x(p[0]), plot.y(p[1]), 4.5, "vf-pt vf-pt-1");
+ marker(plot.layers.marks, "circle", plot.x(sol.point[0]), plot.y(sol.point[1]), 7, "vf-pt vf-pt-2");
+ clear(readout);
+ const name = state.mode === "ws" ? "weighted sum w₁f₁ + w₂f₂" : "Tchebycheff max(w₁f₁, w₂f₂)";
+ h("p", {}, readout, `Minimizing the ${name} with w = (${w.toFixed(2)}, ${(1 - w).toFixed(2)}) selects f = ${pair(sol.point)}.`);
+ if (state.trail.length) {
+ const distinct = new Set(state.trail.map((p) => p[0].toFixed(3))).size;
+ h("p", {}, readout, `21 evenly spaced weights found ${distinct} distinct Pareto-optimal solution${distinct === 1 ? "" : "s"}.`);
+ if (state.mode === "ws" && state.shape === "concave") {
+ h("p", {}, readout, "On a non-convex front the weighted sum only ever returns the two extremes: the interior points are never minimizers (Das and Dennis, 1997).");
+ }
+ } else {
+ h("p", {}, readout, "Move the weight, or sweep 21 weights to see which part of the front a scalarizing method can reach.");
+ }
+ }
+ function sweep() {
+ const weights = Array.from({ length: 21 }, (_, i) => i / 20);
+ const pts = front();
+ state.trail = [];
+ if (reducedMotion) {
+ state.trail = weights.map((w) => solve(w, state.mode, pts).point);
+ render();
+ return;
+ }
+ sweepButton.disabled = true;
+ let i = 0;
+ const tick = () => {
+ state.w = weights[i];
+ state.trail.push(solve(state.w, state.mode, pts).point);
+ render();
+ i += 1;
+ if (i < weights.length) setTimeout(tick, 90);
+ else sweepButton.disabled = false;
+ };
+ tick();
+ }
+ render();
+ };
+
+ /* B2: Pareto dominance explorer. */
+ widgets.dominance = function (node) {
+ const preset = [
+ [0.1, 0.9],
+ [0.22, 0.62],
+ [0.35, 0.7],
+ [0.4, 0.4],
+ [0.55, 0.52],
+ [0.62, 0.28],
+ [0.75, 0.45],
+ [0.86, 0.14],
+ [0.3, 0.95],
+ [0.68, 0.8],
+ ];
+ const state = { P: preset.map((p) => p.slice()), selected: 3, showFront: false };
+ const ctl = controls(node);
+ const picker = select(ctl, {
+ label: "Selected point",
+ options: state.P.map((_, i) => [i, LETTERS[i]]),
+ value: state.selected,
+ onChange: (v) => {
+ state.selected = +v;
+ render();
+ },
+ });
+ checkbox(ctl, {
+ label: "Show the non-dominated set, ideal and nadir points",
+ checked: false,
+ onChange: (v) => {
+ state.showFront = v;
+ render();
+ },
+ });
+ button(ctl, "Random points", () => {
+ state.P = state.P.map(() => [0.05 + Math.random() * 0.9, 0.05 + Math.random() * 0.9]);
+ render();
+ });
+ const body = h("div", { class: "vf-body vf-body--side" }, node);
+ const plot = createPlot(body, { x: [0, 1], y: [0, 1], xLabel: "f₁ (minimize)", yLabel: "f₂ (minimize)", label: "Ten objective vectors; drag them or move them with the arrow keys" });
+ const tip = tooltip(plot);
+ const readout = h("div", { class: "vf-readout" }, body);
+ legend(node, [
+ { label: "Region dominated by the selected point", shape: "region", cls: "vf-region-1" },
+ { label: "Region that dominates it", shape: "region", cls: "vf-region-2" },
+ { label: "Dominated by the selected point", shape: "circle", cls: "vf-pt vf-pt-1" },
+ { label: "Dominates the selected point", shape: "circle", cls: "vf-pt vf-pt-2" },
+ { label: "Incomparable", shape: "circle", cls: "vf-pt vf-pt-muted" },
+ ]);
+ const handles = state.P.map((_, i) =>
+ handle(plot, {
+ cls: "vf-pt vf-pt-muted",
+ label: () => "Point " + LETTERS[i],
+ get: () => state.P[i],
+ set: (a, b) => {
+ state.P[i] = [a, b];
+ render();
+ },
+ onSelect: () => {
+ if (state.selected !== i) {
+ state.selected = i;
+ picker.value = String(i);
+ render();
+ }
+ },
+ })
+ );
+ handles.forEach((hd, i) => {
+ hd.node.addEventListener("pointerenter", () => {
+ const p = state.P[i];
+ tip.show(`${LETTERS[i]} ${pair(p)}`, plot.x(p[0]), plot.y(p[1]));
+ });
+ hd.node.addEventListener("pointerleave", () => tip.hide());
+ });
+ function render() {
+ clear(plot.layers.back);
+ clear(plot.layers.mid);
+ clear(plot.layers.top);
+ const P = state.P;
+ const sel = P[state.selected];
+ plot.rect(plot.layers.back, sel[0], sel[1], 1.5, 1.5, "vf-region-1");
+ plot.rect(plot.layers.back, -0.5, -0.5, sel[0], sel[1], "vf-region-2");
+ const dominatedBy = [];
+ const dominating = [];
+ const incomparable = [];
+ P.forEach((p, i) => {
+ const hd = handles[i];
+ hd.place();
+ hd.node.classList.toggle("vf-selected", i === state.selected);
+ if (i === state.selected) {
+ hd.setClass("vf-pt vf-pt-ink");
+ return;
+ }
+ if (dominates(sel, p)) {
+ dominatedBy.push(LETTERS[i]);
+ hd.setClass("vf-pt vf-pt-1");
+ } else if (dominates(p, sel)) {
+ dominating.push(LETTERS[i]);
+ hd.setClass("vf-pt vf-pt-2");
+ } else {
+ incomparable.push(LETTERS[i]);
+ hd.setClass("vf-pt vf-pt-muted");
+ }
+ });
+ P.forEach((p, i) => txt(plot.layers.top, plot.x(p[0]) + 9, plot.y(p[1]) - 7, LETTERS[i], { class: "vf-mark-label" }));
+ const nd = nonDominatedIndices(P);
+ if (state.showFront) {
+ const F = nd.map((i) => P[i]).sort((a, b) => a[0] - b[0]);
+ const stair = [[F[0][0], 1.5]];
+ F.forEach((p, k) => {
+ stair.push([p[0], p[1]]);
+ stair.push([k + 1 < F.length ? F[k + 1][0] : 1.5, p[1]]);
+ });
+ plot.line(plot.layers.mid, stair, "vf-line-1");
+ const ideal = [Math.min(...F.map((p) => p[0])), Math.min(...F.map((p) => p[1]))];
+ const nadir = [Math.max(...F.map((p) => p[0])), Math.max(...F.map((p) => p[1]))];
+ marker(plot.layers.top, "cross", plot.x(ideal[0]), plot.y(ideal[1]), 5, "vf-line-ink");
+ txt(plot.layers.top, plot.x(ideal[0]) + 8, plot.y(ideal[1]) - 6, "ideal", { class: "vf-mark-label" });
+ marker(plot.layers.top, "cross", plot.x(nadir[0]), plot.y(nadir[1]), 5, "vf-line-ink");
+ txt(plot.layers.top, plot.x(nadir[0]) + 8, plot.y(nadir[1]) - 6, "nadir", { class: "vf-mark-label" });
+ }
+ clear(readout);
+ const name = LETTERS[state.selected];
+ h("p", {}, readout, `${name} = ${pair(sel)}.`);
+ h("p", {}, readout, `${name} dominates: ${dominatedBy.join(", ") || "none"}.`);
+ h("p", {}, readout, `${name} is dominated by: ${dominating.join(", ") || "none"}.`);
+ h("p", {}, readout, `Incomparable with ${name}: ${incomparable.join(", ") || "none"}.`);
+ h("p", {}, readout, `Non-dominated set: ${nd.map((i) => LETTERS[i]).join(", ")}.`);
+ }
+ render();
+ };
+
+ const QUALITY_INFO = {
+ hv: { name: "HV ↑", better: "higher", aspects: "all four aspects" },
+ igd: { name: "IGD ↓", better: "lower", aspects: "convergence, spread, uniformity" },
+ igdp: { name: "IGD+ ↓", better: "lower", aspects: "convergence, spread, uniformity" },
+ gd: { name: "GD ↓", better: "lower", aspects: "convergence only" },
+ eps: { name: "Additive ε ↓", better: "lower", aspects: "convergence, worst-case spread" },
+ spacing: { name: "Spacing ↓", better: "lower", aspects: "uniformity only" },
+ spread: { name: "Spread Δ ↓", better: "lower", aspects: "spread and uniformity" },
+ n: { name: "Points", better: "context", aspects: "cardinality" },
+ };
+
+ /* B3 and B4: approximation sets with controllable quality aspects. */
+ widgets.quality = function (node) {
+ const keys = (node.dataset.indicators || "hv,igd,igdp,gd,eps,spacing,spread,n").split(",");
+ const curve = (t) => 1 - Math.sqrt(t);
+ const R = frontPoints(curve, 0, 1, 201);
+ const ref = [1.1, 1.1];
+ const hvTrue = hypervolume2d(R, ref);
+ const state = { gap: 0.05, extent: 1, cluster: 0, n: 12 };
+ const ctl = controls(node);
+ slider(ctl, { label: "Convergence gap", min: 0, max: 0.5, step: 0.01, value: state.gap, format: (v) => v.toFixed(2), onInput: (v) => ((state.gap = v), render()) });
+ slider(ctl, { label: "Extent covered", min: 0.1, max: 1, step: 0.05, value: state.extent, format: (v) => Math.round(v * 100) + "%", onInput: (v) => ((state.extent = v), render()) });
+ slider(ctl, { label: "Clustering", min: 0, max: 1, step: 0.05, value: state.cluster, format: (v) => v.toFixed(2), onInput: (v) => ((state.cluster = v), render()) });
+ slider(ctl, { label: "Points", min: 2, max: 40, step: 1, value: state.n, format: (v) => String(v), onInput: (v) => ((state.n = v), render()) });
+ const body = h("div", { class: "vf-body vf-body--two" }, node);
+ const plot = createPlot(body, { x: [0, 1.6], y: [0, 1.6], xLabel: "f₁", yLabel: "f₂", label: "Approximation set compared with the ZDT1 Pareto front" });
+ const readout = h("div", { class: "vf-readout" }, body);
+ legend(node, [
+ { label: "Pareto front (ZDT1)", shape: "line", cls: "vf-front" },
+ { label: "Approximation set A", shape: "circle", cls: "vf-pt vf-pt-1" },
+ { label: "HV reference point r = (1.1, 1.1)", shape: "cross", cls: "vf-line-ink" },
+ { label: "Region dominated by A inside r", shape: "region", cls: "vf-region-1" },
+ ]);
+ plot.line(plot.layers.mid, R, "vf-front");
+ function approximation() {
+ const A = [];
+ const start = (1 - state.extent) / 2;
+ for (let i = 0; i < state.n; i++) {
+ const t = state.n === 1 ? 0.5 : i / (state.n - 1);
+ const warped = Math.pow(t, 1 + 4 * state.cluster);
+ const f1 = start + state.extent * warped;
+ A.push([f1 + state.gap, curve(f1) + state.gap]);
+ }
+ return A;
+ }
+ function render() {
+ clear(plot.layers.back);
+ clear(plot.layers.marks);
+ const A = approximation();
+ const inside = A.filter((p) => p[0] < ref[0] && p[1] < ref[1]).sort((a, b) => a[0] - b[0]);
+ if (inside.length) {
+ const poly = [[inside[0][0], ref[1]]];
+ inside.forEach((p, k) => {
+ poly.push(p);
+ poly.push([k + 1 < inside.length ? inside[k + 1][0] : ref[0], p[1]]);
+ });
+ poly.push([ref[0], ref[1]]);
+ plot.line(plot.layers.back, poly, "vf-region-1");
+ }
+ marker(plot.layers.marks, "cross", plot.x(ref[0]), plot.y(ref[1]), 5, "vf-line-ink");
+ txt(plot.layers.marks, plot.x(ref[0]) + 8, plot.y(ref[1]) - 6, "r", { class: "vf-mark-label" });
+ for (const p of A) marker(plot.layers.marks, "circle", plot.x(p[0]), plot.y(p[1]), 4.5, "vf-pt vf-pt-1");
+ const values = {
+ hv: `${fmt(hypervolume2d(A, ref))} (${fmt((100 * hypervolume2d(A, ref)) / hvTrue, 1)}%)`,
+ igd: fmt(igd(A, R)),
+ igdp: fmt(igdPlus(A, R)),
+ gd: fmt(generationalDistance(A, R)),
+ eps: fmt(epsilonAdditive(A, R)),
+ spacing: fmt(spacing(A)),
+ spread: fmt(spreadDelta(A, [[0, 1], [1, 0]])),
+ n: String(A.length),
+ };
+ clear(readout);
+ table(
+ readout,
+ ["Indicator", "Value", "Reacts to"],
+ keys.map((k) => [QUALITY_INFO[k].name, values[k], QUALITY_INFO[k].aspects]),
+ [false, true, false]
+ );
+ h("p", {}, readout, "↑ higher is better, ↓ lower is better. The HV percentage is relative to the hypervolume of the Pareto front itself.");
+ }
+ render();
+ };
+
+ /* B4 and I6: hypervolume and exclusive contributions. */
+ widgets.hypervolume = function (node) {
+ const smsemoa = node.dataset.smsemoa === "true";
+ const state = {
+ P: [
+ [0.1, 0.85],
+ [0.3, 0.52],
+ [0.42, 0.44],
+ [0.65, 0.22],
+ [0.9, 0.08],
+ ],
+ ref: [1.05, 1.05],
+ active: -1,
+ };
+ const names = state.P.map((_, i) => "P" + (i + 1));
+ const body = h("div", { class: "vf-body vf-body--side" }, node);
+ const plot = createPlot(body, { x: [0, 1.2], y: [0, 1.2], xLabel: "f₁", yLabel: "f₂", label: "Hypervolume of five draggable points and a draggable reference point" });
+ const tip = tooltip(plot);
+ const readout = h("div", { class: "vf-readout" }, body);
+ legend(node, [
+ { label: "Dominated region (the hypervolume)", shape: "region", cls: "vf-region-1" },
+ { label: "Exclusive contribution of the focused point", shape: "region", cls: "vf-region-strong" },
+ { label: "Point", shape: "circle", cls: "vf-pt vf-pt-1" },
+ { label: "Contributes nothing", shape: "circle", cls: "vf-pt-hollow" },
+ { label: "Reference point r", shape: "diamond", cls: "vf-pt vf-pt-3" },
+ ]);
+ const handles = state.P.map((_, i) =>
+ handle(plot, {
+ cls: "vf-pt vf-pt-1",
+ label: () => names[i],
+ get: () => state.P[i],
+ set: (a, b) => {
+ state.P[i] = [a, b];
+ render();
+ },
+ onSelect: () => {
+ state.active = i;
+ render();
+ },
+ })
+ );
+ handles.forEach((hd, i) => {
+ hd.node.addEventListener("pointerenter", () => {
+ state.active = i;
+ render();
+ const p = state.P[i];
+ tip.show(`${names[i]}: contribution ${fmt(hvContributions2d(state.P, state.ref).contributions[i])}`, plot.x(p[0]), plot.y(p[1]));
+ });
+ hd.node.addEventListener("pointerleave", () => tip.hide());
+ });
+ const refHandle = handle(plot, {
+ cls: "vf-pt vf-pt-3",
+ shape: "diamond",
+ r: 6,
+ label: () => "Reference point r",
+ get: () => state.ref,
+ set: (a, b) => {
+ state.ref = [a, b];
+ render();
+ },
+ });
+ function render() {
+ clear(plot.layers.back);
+ clear(plot.layers.mid);
+ clear(plot.layers.top);
+ const ref = state.ref;
+ const inside = state.P.filter((p) => p[0] < ref[0] && p[1] < ref[1]).sort((a, b) => a[0] - b[0] || a[1] - b[1]);
+ const nd = inside.filter((p) => !inside.some((q) => dominates(q, p)));
+ if (nd.length) {
+ const poly = [[nd[0][0], ref[1]]];
+ nd.forEach((p, k) => {
+ poly.push(p);
+ poly.push([k + 1 < nd.length ? nd[k + 1][0] : ref[0], p[1]]);
+ });
+ poly.push([ref[0], ref[1]]);
+ plot.line(plot.layers.back, poly, "vf-region-1");
+ }
+ const contrib = hvContributions2d(state.P, ref);
+ if (state.active >= 0 && contrib.boxes[state.active]) {
+ const b = contrib.boxes[state.active];
+ plot.rect(plot.layers.mid, b[0], b[1], b[2], b[3], "vf-region-strong");
+ }
+ handles.forEach((hd, i) => {
+ hd.place();
+ hd.setClass(contrib.contributions[i] > 0 ? "vf-pt vf-pt-1" : "vf-pt-hollow");
+ hd.node.classList.toggle("vf-selected", i === state.active);
+ const p = state.P[i];
+ txt(plot.layers.top, plot.x(p[0]) + 9, plot.y(p[1]) - 7, names[i], { class: "vf-mark-label" });
+ });
+ refHandle.place();
+ txt(plot.layers.top, plot.x(ref[0]) + 9, plot.y(ref[1]) - 7, "r", { class: "vf-mark-label" });
+ clear(readout);
+ h("p", {}, readout, `HV = ${fmt(hypervolume2d(state.P, ref))} with r = ${pair(ref)}.`);
+ table(
+ readout,
+ ["Point", "Objectives", "Exclusive contribution"],
+ state.P.map((p, i) => [names[i], pair(p), fmt(contrib.contributions[i])]),
+ [false, true, true]
+ );
+ if (smsemoa) {
+ let worst = 0;
+ contrib.contributions.forEach((c, i) => {
+ if (c < contrib.contributions[worst]) worst = i;
+ });
+ h("p", {}, readout, `SMS-EMOA would discard ${names[worst]}: removing it loses the least hypervolume (${fmt(contrib.contributions[worst])}).`);
+ } else {
+ h("p", {}, readout, "Focus or hover a point to see the area that only it dominates. Drag r to see how the reference point changes the value and the weight of the extreme points.");
+ }
+ }
+ render();
+ };
+
+ /* B4: GD, IGD, IGD+ and additive epsilon drawn as distances. */
+ widgets["distance-indicators"] = function (node) {
+ const R = frontPoints((t) => 1 - Math.sqrt(t), 0, 1, 11);
+ const state = {
+ A: [
+ [0.06, 0.9],
+ [0.3, 0.6],
+ [0.52, 0.42],
+ [0.85, 0.2],
+ ],
+ mode: "igd",
+ };
+ const ctl = controls(node);
+ select(ctl, {
+ label: "Indicator",
+ options: [
+ ["gd", "GD: from A to the reference set"],
+ ["igd", "IGD: from the reference set to A"],
+ ["igdp", "IGD+: only where A is worse"],
+ ["eps", "Additive ε: shift needed"],
+ ],
+ value: state.mode,
+ onChange: (v) => {
+ state.mode = v;
+ render();
+ },
+ });
+ const body = h("div", { class: "vf-body vf-body--side" }, node);
+ const plot = createPlot(body, { x: [0, 1.2], y: [0, 1.2], xLabel: "f₁", yLabel: "f₂", label: "Distance-based indicators between a draggable approximation set and a reference set" });
+ const readout = h("div", { class: "vf-readout" }, body);
+ legend(node, [
+ { label: "Reference set R (11 points of the ZDT1 front)", shape: "diamond", cls: "vf-pt vf-pt-3" },
+ { label: "Approximation set A", shape: "circle", cls: "vf-pt vf-pt-1" },
+ { label: "Distance used by the indicator", shape: "line", cls: "vf-line-2" },
+ { label: "A shifted by ε", shape: "circle", cls: "vf-pt-hollow" },
+ ]);
+ const handles = state.A.map((_, i) =>
+ handle(plot, {
+ cls: "vf-pt vf-pt-1",
+ label: () => "Approximation point a" + (i + 1),
+ get: () => state.A[i],
+ set: (a, b) => {
+ state.A[i] = [a, b];
+ render();
+ },
+ })
+ );
+ function render() {
+ clear(plot.layers.mid);
+ clear(plot.layers.marks);
+ const A = state.A;
+ const seg = (p, q) => s("line", { x1: plot.x(p[0]), y1: plot.y(p[1]), x2: plot.x(q[0]), y2: plot.y(q[1]), class: "vf-line-2" }, plot.layers.mid);
+ let value;
+ let text;
+ if (state.mode === "gd") {
+ A.forEach((a) => seg(a, R[nearest(a, R, (r, x) => euclidean(x, r)).index]));
+ value = generationalDistance(A, R);
+ text = "GD averages, over the points of A, the distance to the nearest reference point. A set with one well-converged point scores well even if it misses most of the front.";
+ } else if (state.mode === "igd") {
+ R.forEach((r) => seg(r, A[nearest(r, A, (a, x) => euclidean(a, x)).index]));
+ value = igd(A, R);
+ text = "IGD averages, over the reference points, the distance to the nearest point of A. Gaps in A leave some reference points far away.";
+ } else if (state.mode === "igdp") {
+ R.forEach((r) => {
+ const a = A[nearest(r, A, (x, y) => dPlus(x, y)).index];
+ seg(r, [r[0] + Math.max(a[0] - r[0], 0), r[1] + Math.max(a[1] - r[1], 0)]);
+ });
+ value = igdPlus(A, R);
+ text = "IGD+ measures, from each reference point, only how much the nearest point of A is worse. A point that is better than a reference point adds nothing.";
+ } else {
+ value = epsilonAdditive(A, R);
+ A.forEach((a) => {
+ const shifted = [a[0] - value, a[1] - value];
+ seg(a, shifted);
+ marker(plot.layers.marks, "circle", plot.x(shifted[0]), plot.y(shifted[1]), 4, "vf-pt-hollow");
+ });
+ text = "Additive ε is the smallest amount every point of A must be moved towards the origin so that each reference point is weakly dominated. It is a worst-case measure.";
+ }
+ for (const r of R) marker(plot.layers.marks, "diamond", plot.x(r[0]), plot.y(r[1]), 4, "vf-pt vf-pt-3");
+ handles.forEach((hd) => hd.place());
+ clear(readout);
+ h("p", {}, readout, `${QUALITY_INFO[state.mode].name.replace(" ↓", "")} = ${fmt(value)} (lower is better).`);
+ h("p", {}, readout, text);
+ h("p", {}, readout, "Drag the points of A, or focus one and use the arrow keys.");
+ }
+ render();
+ };
+
+ /* I1: NSGA-II running in the page. */
+ widgets["nsga2-live"] = function (node) {
+ const state = { problem: "zdt1", pop: 100, seed: 2026, playing: false, timer: null, history: [] };
+ const nVar = 30;
+ const maxGenerations = 250;
+ const ref = [1.1, 1.1];
+ let algo;
+ let hvTrue;
+ const ctl = controls(node);
+ select(ctl, {
+ label: "Problem",
+ options: Object.keys(PROBLEMS).map((k) => [k, PROBLEMS[k].label]),
+ value: state.problem,
+ onChange: (v) => {
+ state.problem = v;
+ reset();
+ },
+ });
+ select(ctl, {
+ label: "Population",
+ options: [
+ [20, "20"],
+ [50, "50"],
+ [100, "100"],
+ ],
+ value: state.pop,
+ onChange: (v) => {
+ state.pop = +v;
+ reset();
+ },
+ });
+ const playButton = button(ctl, "Play", () => (state.playing ? pause() : play()), true);
+ button(ctl, "One generation", () => {
+ pause();
+ advance();
+ });
+ button(ctl, "Reset", () => reset());
+ button(ctl, "New seed", () => {
+ state.seed = Math.floor(Math.random() * 1e6);
+ reset();
+ });
+ const body = h("div", { class: "vf-body vf-body--two" }, node);
+ const plot = createPlot(body, { title: "Population in objective space", x: [0, 1], y: [0, 6], xLabel: "f₁", yLabel: "f₂", label: "NSGA-II population in objective space" });
+ const hvPlot = createPlot(body, {
+ title: "Hypervolume relative to the true front",
+ x: [0, maxGenerations * 100],
+ y: [0, 1],
+ xLabel: "Evaluations",
+ yLabel: "HV / HV(front)",
+ xCount: 4,
+ yFormat: (v) => Math.round(v * 100) + "%",
+ label: "Hypervolume of the non-dominated population as a share of the hypervolume of the true front",
+ });
+ const readout = h("div", { class: "vf-readout" }, node);
+ legend(node, [
+ { label: "Pareto front", shape: "line", cls: "vf-front" },
+ { label: "Rank 1 (non-dominated)", shape: "circle", cls: "vf-pt vf-r0" },
+ { label: "Ranks 2 and higher", shape: "circle", cls: "vf-pt vf-pt-muted" },
+ { label: "Hypervolume ratio", shape: "line", cls: "vf-line-1" },
+ ]);
+ function hvRatio() {
+ const F = algo.F.filter((_, i) => algo.rank[i] === 0);
+ return hypervolume2d(F, ref) / hvTrue;
+ }
+ const fronts = {};
+ function trueFront() {
+ if (!fronts[state.problem]) fronts[state.problem] = sampledFront(PROBLEMS[state.problem], 2001);
+ return fronts[state.problem];
+ }
+ function reset() {
+ pause();
+ algo = createNSGAII(PROBLEMS[state.problem], state.pop, nVar, state.seed);
+ hvTrue = hypervolume2d(trueFront(), ref);
+ plot.yd = [0, 0];
+ hvPlot.setDomain([0, maxGenerations * state.pop], [0, 1]);
+ state.history = [[algo.evaluations, hvRatio()]];
+ draw();
+ }
+ function draw() {
+ const ymin = state.problem === "zdt3" ? -1 : 0;
+ const top = Math.max(...algo.F.map((f) => f[1]));
+ const ymax = top > 1.5 ? Math.min(8, Math.ceil(top * 1.05)) : 1.5;
+ if (ymax !== plot.yd[1] || ymin !== plot.yd[0]) {
+ plot.setDomain([0, 1], [ymin, ymax]);
+ clear(plot.layers.mid);
+ drawFront(plot, plot.layers.mid, trueFront(), "vf-front");
+ }
+ clear(plot.layers.marks);
+ algo.F.forEach((f, i) => {
+ if (algo.rank[i] > 0 && f[1] <= ymax) marker(plot.layers.marks, "circle", plot.x(f[0]), plot.y(f[1]), 3.5, "vf-pt vf-pt-muted");
+ });
+ algo.F.forEach((f, i) => {
+ if (algo.rank[i] === 0 && f[1] <= ymax) marker(plot.layers.marks, "circle", plot.x(f[0]), plot.y(f[1]), 4, "vf-pt vf-r0");
+ });
+ clear(hvPlot.layers.mid);
+ hvPlot.line(hvPlot.layers.mid, [[0, 1], [maxGenerations * state.pop, 1]], "vf-front");
+ if (state.history.length > 1) hvPlot.line(hvPlot.layers.mid, state.history, "vf-line-1");
+ const last = state.history[state.history.length - 1];
+ clear(hvPlot.layers.marks);
+ marker(hvPlot.layers.marks, "circle", hvPlot.x(last[0]), hvPlot.y(last[1]), 4, "vf-pt vf-pt-1");
+ const nd = algo.rank.filter((r) => r === 0).length;
+ clear(readout);
+ h(
+ "p",
+ {},
+ readout,
+ `Generation ${algo.generation}: ${algo.evaluations.toLocaleString("en-US")} evaluations, ${nd} of ${state.pop} solutions in the first front, ` +
+ `hypervolume ${fmt(100 * last[1], 1)}% of the true front's (r = (1.1, 1.1)). Seed ${state.seed}.`
+ );
+ }
+ function advance() {
+ if (algo.generation >= maxGenerations) {
+ pause();
+ return;
+ }
+ algo.step();
+ state.history.push([algo.evaluations, hvRatio()]);
+ draw();
+ }
+ function play() {
+ if (algo.generation >= maxGenerations) reset();
+ state.playing = true;
+ playButton.textContent = "Pause";
+ const loop = () => {
+ if (!state.playing) return;
+ advance();
+ if (state.playing) state.timer = setTimeout(loop, 70);
+ };
+ loop();
+ }
+ function pause() {
+ state.playing = false;
+ playButton.textContent = "Play";
+ if (state.timer) clearTimeout(state.timer);
+ state.timer = null;
+ }
+ reset();
+ };
+
+ function randomFrontSet(rand, n, offsets) {
+ const pts = [];
+ for (let i = 0; i < n; i++) {
+ const level = offsets[i % offsets.length];
+ const t = 0.03 + 0.94 * rand();
+ pts.push([+(t + level * 0.6).toFixed(2), +(1 - Math.sqrt(t) + level + 0.04 * rand()).toFixed(2)]);
+ }
+ return pts.map((p) => [Math.min(0.98, p[0]), Math.min(0.98, Math.max(0.02, p[1]))]);
+ }
+
+ /* I2: fast non-dominated sorting, one bookkeeping step at a time. */
+ widgets.sorting = function (node) {
+ const preset = [
+ [0.08, 0.78],
+ [0.2, 0.5],
+ [0.45, 0.3],
+ [0.8, 0.1],
+ [0.18, 0.92],
+ [0.32, 0.62],
+ [0.55, 0.45],
+ [0.9, 0.3],
+ [0.45, 0.85],
+ [0.66, 0.62],
+ [0.95, 0.55],
+ [0.75, 0.9],
+ ];
+ const state = { P: preset, step: 0, focus: -1, refocus: -1 };
+ let steps = [];
+ const ctl = controls(node);
+ const back = button(ctl, "Back", () => go(state.step - 1));
+ const next = button(ctl, "Next step", () => go(state.step + 1), true);
+ button(ctl, "Restart", () => go(0));
+ button(ctl, "New points", () => {
+ const rand = mulberry32(Math.floor(Math.random() * 1e6));
+ state.P = randomFrontSet(rand, 12, [0, 0.15, 0.3]);
+ build();
+ go(0);
+ });
+ const body = h("div", { class: "vf-body vf-body--side" }, node);
+ const plot = createPlot(body, { x: [0, 1], y: [0, 1], xLabel: "f₁", yLabel: "f₂", label: "Twelve points sorted into non-domination fronts" });
+ const tip = tooltip(plot);
+ const readout = h("div", { class: "vf-readout" }, body);
+ legend(node, [
+ { label: "Front 1, 2, 3, … (darker is better)", shape: "circle", cls: "vf-pt vf-r1" },
+ { label: "Not yet assigned", shape: "circle", cls: "vf-pt-hollow" },
+ { label: "Front being extracted", shape: "circle", cls: "vf-ring" },
+ { label: "S_p: points dominated by the focused point", shape: "line", cls: "vf-line-thin" },
+ ]);
+ function build() {
+ const sorted = nonDominatedSort(state.P);
+ const counts = sorted.count.slice();
+ const rank = new Array(state.P.length).fill(-1);
+ steps = [
+ {
+ counts: counts.slice(),
+ rank: rank.slice(),
+ current: [],
+ text: "Compare every pair once. For each point p, n_p (the number next to it) counts the points that dominate p, and S_p stores the points that p dominates. Focus a point to see its S_p.",
+ },
+ ];
+ sorted.fronts.forEach((front, k) => {
+ front.forEach((p) => {
+ rank[p] = k;
+ });
+ steps.push({
+ counts: counts.slice(),
+ rank: rank.slice(),
+ current: front,
+ text: `Front ${k + 1}: the unassigned points with n_p = 0 are ${front.map((p) => LETTERS[p]).join(", ")}. Nothing left dominates them.`,
+ });
+ for (const p of front) for (const q of sorted.dominatedSets[p]) counts[q] -= 1;
+ const last = k === sorted.fronts.length - 1;
+ steps.push({
+ counts: counts.slice(),
+ rank: rank.slice(),
+ current: [],
+ text: last
+ ? `Done: ${sorted.fronts.length} fronts. Each pair was compared once, so the cost is O(M N²) for N points and M objectives.`
+ : `Remove front ${k + 1}: for each of its points p, decrease n_q by one for every q in S_p. The points that reach 0 form front ${k + 2}.`,
+ });
+ });
+ state.dominated = sorted.dominatedSets;
+ }
+ function go(i) {
+ state.step = Math.max(0, Math.min(steps.length - 1, i));
+ render();
+ }
+ function render() {
+ const st = steps[state.step];
+ back.disabled = state.step === 0;
+ next.disabled = state.step === steps.length - 1;
+ clear(plot.layers.mid);
+ clear(plot.layers.marks);
+ clear(plot.layers.top);
+ if (state.focus >= 0) {
+ const p = state.P[state.focus];
+ for (const q of state.dominated[state.focus]) {
+ s("line", { x1: plot.x(p[0]), y1: plot.y(p[1]), x2: plot.x(state.P[q][0]), y2: plot.y(state.P[q][1]), class: "vf-line-thin" }, plot.layers.mid);
+ }
+ }
+ state.P.forEach((p, i) => {
+ const px = plot.x(p[0]);
+ const py = plot.y(p[1]);
+ const assigned = st.rank[i] >= 0;
+ const hit = s("circle", { cx: px, cy: py, r: 13, class: "vf-hit" }, plot.layers.marks);
+ const mark = marker(plot.layers.marks, "circle", px, py, 6, assigned ? "vf-pt " + rankClass(st.rank[i]) : "vf-pt-hollow");
+ const show = (fromKeyboard) => {
+ tip.show(`${LETTERS[i]} ${pair(p)} · dominates ${state.dominated[i].map((q) => LETTERS[q]).join(", ") || "nothing"}`, px, py);
+ if (state.focus !== i) {
+ state.focus = i;
+ if (fromKeyboard) state.refocus = i;
+ render();
+ }
+ };
+ hit.addEventListener("pointerenter", () => show(false));
+ hit.addEventListener("pointerleave", () => tip.hide());
+ mark.addEventListener("pointerenter", () => show(false));
+ mark.addEventListener("focus", () => show(true));
+ mark.addEventListener("blur", () => tip.hide());
+ focusable(mark, `${LETTERS[i]} ${pair(p)}, n_p = ${st.counts[i]}${assigned ? ", front " + (st.rank[i] + 1) : ""}, dominates ${state.dominated[i].map((q) => LETTERS[q]).join(", ") || "nothing"}`, state, i);
+ if (st.current.includes(i)) marker(plot.layers.marks, "circle", px, py, 10, "vf-ring");
+ const counter = assigned && !st.current.includes(i) ? "" : " · " + st.counts[i];
+ txt(plot.layers.top, px + 10, py - 8, LETTERS[i] + counter, { class: "vf-mark-label" });
+ });
+ clear(readout);
+ h("p", { class: "vf-step-text" }, readout, `Step ${state.step + 1} of ${steps.length}. ${st.text}`);
+ const fronts = [];
+ st.rank.forEach((r, i) => {
+ if (r < 0) return;
+ (fronts[r] = fronts[r] || []).push(LETTERS[i]);
+ });
+ if (fronts.length) table(readout, ["Front", "Points"], fronts.map((f, k) => [String(k + 1), f.join(", ")]));
+ }
+ build();
+ go(0);
+ };
+
+ /* I3: crowding distance and one-shot truncation. */
+ widgets.crowding = function (node) {
+ const curve = (t) => 1 - Math.sqrt(t);
+ const preset = [0, 0.04, 0.09, 0.16, 0.38, 0.47, 0.55, 0.8, 1].map((t) => [t, curve(t)]);
+ const state = { P: preset, focus: 4, keep: 9, refocus: -1 };
+ const ctl = controls(node);
+ const keepSlider = slider(ctl, {
+ label: "Places left for this front",
+ min: 2,
+ max: 9,
+ step: 1,
+ value: 9,
+ format: (v) => String(v),
+ onInput: (v) => {
+ state.keep = v;
+ render();
+ },
+ });
+ button(ctl, "New front", () => {
+ const rand = mulberry32(Math.floor(Math.random() * 1e6));
+ const ts = [0, 1].concat(Array.from({ length: 7 }, () => +rand().toFixed(2))).sort((a, b) => a - b);
+ state.P = ts.map((t) => [t, curve(t)]);
+ state.keep = 9;
+ keepSlider.set(9);
+ render();
+ });
+ const body = h("div", { class: "vf-body vf-body--side" }, node);
+ const plot = createPlot(body, { x: [-0.05, 1.08], y: [-0.05, 1.08], xLabel: "f₁", yLabel: "f₂", label: "Crowding distance in one front" });
+ const readout = h("div", { class: "vf-readout" }, body);
+ legend(node, [
+ { label: "Kept", shape: "circle", cls: "vf-pt vf-pt-1" },
+ { label: "Discarded by crowding", shape: "circle", cls: "vf-pt-hollow" },
+ { label: "Cuboid of the focused point", shape: "region", cls: "vf-region-2" },
+ ]);
+ function render() {
+ const P = state.P;
+ const front = P.map((_, i) => i);
+ const d = crowdingDistance(P, front);
+ const order = front.slice().sort((a, b) => cmpDesc(d[a], d[b]) || a - b);
+ const kept = new Set(order.slice(0, state.keep));
+ clear(plot.layers.back);
+ clear(plot.layers.marks);
+ clear(plot.layers.top);
+ const byF1 = front.slice().sort((a, b) => P[a][0] - P[b][0] || a - b);
+ const pos = byF1.indexOf(state.focus);
+ const f1span = P[byF1[byF1.length - 1]][0] - P[byF1[0]][0];
+ const f2span = Math.max(...P.map((p) => p[1])) - Math.min(...P.map((p) => p[1]));
+ let detail;
+ if (pos > 0 && pos < byF1.length - 1) {
+ const a = P[byF1[pos - 1]];
+ const b = P[byF1[pos + 1]];
+ plot.rect(plot.layers.back, a[0], a[1], b[0], b[1], "vf-region-2");
+ const c1 = (b[0] - a[0]) / f1span;
+ const c2 = (a[1] - b[1]) / f2span;
+ detail = `${LETTERS[state.focus]}: (${fmt(b[0], 2)} − ${fmt(a[0], 2)}) / ${fmt(f1span, 2)} + (${fmt(a[1], 2)} − ${fmt(b[1], 2)}) / ${fmt(f2span, 2)} = ${fmt(c1)} + ${fmt(c2)} = ${fmt(c1 + c2)}.`;
+ } else {
+ detail = `${LETTERS[state.focus]} is a boundary point: its distance is ∞, so the extremes of the front are always kept.`;
+ }
+ P.forEach((p, i) => {
+ const px = plot.x(p[0]);
+ const py = plot.y(p[1]);
+ const hit = s("circle", { cx: px, cy: py, r: 13, class: "vf-hit" }, plot.layers.marks);
+ const mark = marker(plot.layers.marks, "circle", px, py, 6, kept.has(i) ? "vf-pt vf-pt-1" : "vf-pt-hollow");
+ const pick = (fromKeyboard) => {
+ if (state.focus !== i) {
+ state.focus = i;
+ if (fromKeyboard) state.refocus = i;
+ render();
+ }
+ };
+ hit.addEventListener("pointerenter", () => pick(false));
+ mark.addEventListener("pointerenter", () => pick(false));
+ mark.addEventListener("focus", () => pick(true));
+ focusable(mark, `${LETTERS[i]}, crowding distance ${fmt(d[i])}${kept.has(i) ? ", kept" : ", discarded"}`, state, i);
+ if (i === state.focus) marker(plot.layers.marks, "circle", px, py, 10, "vf-ring");
+ txt(plot.layers.top, px + 9, py - 8, LETTERS[i], { class: "vf-mark-label" });
+ });
+ clear(readout);
+ h("p", { class: "vf-step-text" }, readout, detail);
+ table(
+ readout,
+ ["Point", "Crowding distance", "Status"],
+ order.map((i) => [LETTERS[i], fmt(d[i]), kept.has(i) ? "kept" : "discarded"]),
+ [false, true, false]
+ );
+ }
+ render();
+ };
+
+ /* I4: offspring distributions of SBX and polynomial mutation. */
+ widgets.variation = function (node) {
+ const mode = node.dataset.mode || "sbx";
+ const state = { p1: 0.3, p2: 0.6, x: 0.3, eta: 20 };
+ const samples = 20000;
+ const bins = 50;
+ const ctl = controls(node);
+ if (mode === "sbx") {
+ slider(ctl, { label: "Parent 1", min: 0, max: 1, step: 0.01, value: state.p1, format: (v) => v.toFixed(2), onInput: (v) => ((state.p1 = v), render()) });
+ slider(ctl, { label: "Parent 2", min: 0, max: 1, step: 0.01, value: state.p2, format: (v) => v.toFixed(2), onInput: (v) => ((state.p2 = v), render()) });
+ } else {
+ slider(ctl, { label: "Parent", min: 0, max: 1, step: 0.01, value: state.x, format: (v) => v.toFixed(2), onInput: (v) => ((state.x = v), render()) });
+ }
+ slider(ctl, {
+ label: mode === "sbx" ? "Distribution index η_c" : "Distribution index η_m",
+ min: 0,
+ max: 100,
+ step: 1,
+ value: state.eta,
+ format: (v) => String(v),
+ onInput: (v) => ((state.eta = v), render()),
+ });
+ const body = h("div", { class: "vf-body vf-body--side" }, node);
+ const plot = createPlot(body, {
+ x: [0, 1],
+ y: [0, 1],
+ xLabel: "Value of the variable (bounds [0, 1])",
+ yLabel: "Share of offspring",
+ yFormat: (v) => Math.round(v * 100) + "%",
+ label: mode === "sbx" ? "Distribution of SBX offspring" : "Distribution of polynomial mutation results",
+ });
+ const readout = h("div", { class: "vf-readout" }, body);
+ legend(node, [
+ { label: mode === "sbx" ? "Offspring (20,000 crossovers)" : "Mutated values (20,000 mutations)", shape: "region", cls: "vf-bar-1" },
+ { label: mode === "sbx" ? "Parents" : "Parent", shape: "line", cls: "vf-line-2" },
+ ]);
+ function render() {
+ const rand = mulberry32(11);
+ const counts = new Array(bins).fill(0);
+ const parents = mode === "sbx" ? [state.p1, state.p2] : [state.x];
+ let near = 0;
+ for (let i = 0; i < samples; i++) {
+ const values = mode === "sbx" ? sbxPair([state.p1], [state.p2], 0, 1, state.eta, 1, rand).map((c) => c[0]) : [polynomialMutation([state.x], 0, 1, 1, state.eta, rand)[0]];
+ for (const v of values) {
+ counts[Math.min(bins - 1, Math.max(0, Math.floor(v * bins)))] += 1;
+ if (parents.some((p) => Math.abs(v - p) <= 0.05)) near += 1;
+ }
+ }
+ const total = samples * (mode === "sbx" ? 2 : 1);
+ const shares = counts.map((c) => c / total);
+ const top = Math.max(0.05, Math.ceil(Math.max(...shares) * 20) / 20);
+ plot.setDomain([0, 1], [0, top]);
+ clear(plot.layers.mid);
+ clear(plot.layers.top);
+ shares.forEach((v, i) => {
+ if (v <= 0) return;
+ const x0 = plot.x(i / bins) + 0.5;
+ const x1 = plot.x((i + 1) / bins) - 0.5;
+ s("rect", { x: x0, y: plot.y(v), width: Math.max(0.5, x1 - x0), height: plot.y(0) - plot.y(v), class: "vf-bar-1" }, plot.layers.mid);
+ });
+ parents.forEach((p, k) => {
+ s("line", { x1: plot.x(p), x2: plot.x(p), y1: plot.y(0), y2: plot.y(top), class: "vf-line-2" }, plot.layers.top);
+ txt(plot.layers.top, plot.x(p) + 4, plot.m.t + 12 + 14 * k, mode === "sbx" ? "p" + (k + 1) : "parent", { class: "vf-mark-label" });
+ });
+ clear(readout);
+ h("p", {}, readout, `${fmt((100 * near) / total, 1)}% of the ${mode === "sbx" ? "offspring" : "mutated values"} lie within ±0.05 of ${mode === "sbx" ? "a parent" : "the parent"} (η = ${state.eta}).`);
+ h(
+ "p",
+ {},
+ readout,
+ mode === "sbx"
+ ? "A large η_c keeps children close to their parents; a small η_c spreads them out. The spread also scales with the distance between the parents, and the bounded version never leaves [0, 1]."
+ : "A large η_m makes small perturbations; a small η_m makes large jumps. Near a bound the distribution is squeezed so that the result stays inside it."
+ );
+ }
+ render();
+ };
+
+ /* I5: one generation of elitist survival, step by step. */
+ widgets.survival = function (node) {
+ const preset = {
+ parents: [
+ [0.2, 0.3],
+ [0.25, 0.7],
+ [0.4, 0.48],
+ [0.9, 0.12],
+ [0.5, 0.65],
+ [0.95, 0.35],
+ ],
+ offspring: [
+ [0.45, 0.1],
+ [0.22, 0.9],
+ [0.32, 0.55],
+ [0.6, 0.3],
+ [0.35, 0.9],
+ [0.7, 0.5],
+ ],
+ };
+ const state = { data: preset, step: 0 };
+ let steps = [];
+ const ctl = controls(node);
+ const back = button(ctl, "Back", () => go(state.step - 1));
+ const next = button(ctl, "Next step", () => go(state.step + 1), true);
+ button(ctl, "Restart", () => go(0));
+ button(ctl, "New candidates", () => {
+ const rand = mulberry32(Math.floor(Math.random() * 1e6));
+ const pts = randomFrontSet(rand, 12, [0, 0.12, 0.24, 0.06, 0.18, 0.3]);
+ state.data = { parents: pts.slice(0, 6), offspring: pts.slice(6) };
+ build();
+ go(0);
+ });
+ const body = h("div", { class: "vf-body vf-body--side" }, node);
+ const plot = createPlot(body, { x: [0, 1], y: [0, 1], xLabel: "f₁", yLabel: "f₂", label: "Parents and offspring competing for the next population" });
+ const readout = h("div", { class: "vf-readout" }, body);
+ legend(node, [
+ { label: "Parent (P)", shape: "circle", cls: "vf-pt vf-pt-muted" },
+ { label: "Offspring (O)", shape: "triangle", cls: "vf-pt vf-pt-muted" },
+ { label: "Front 1, 2, 3 … (darker is better)", shape: "circle", cls: "vf-pt vf-r1" },
+ { label: "Survivor", shape: "circle", cls: "vf-ring" },
+ ]);
+ const N = 6;
+ function build() {
+ const F = state.data.parents.concat(state.data.offspring);
+ const names = state.data.parents.map((_, i) => "P" + (i + 1)).concat(state.data.offspring.map((_, i) => "O" + (i + 1)));
+ const r = rankAndCrowding(F);
+ const survivors = nsga2Truncate(F, N);
+ const list = (rows) => rows.map((i) => names[i]).join(", ");
+ steps = [];
+ steps.push({ F, names, rank: null, kept: [], crowd: null, faded: [], text: `Parents P (circles) and offspring O (triangles): ${F.length} candidates compete for N = ${N} places. Both groups are treated alike: this is what makes NSGA-II elitist.` });
+ steps.push({
+ F,
+ names,
+ rank: r.rank,
+ kept: [],
+ crowd: null,
+ faded: [],
+ text: "Sort the merged population into fronts: " + r.fronts.map((f, k) => `front ${k + 1} = {${list(f)}}`).join("; ") + ".",
+ });
+ const kept = [];
+ let k = 0;
+ for (; k < r.fronts.length; k++) {
+ const front = r.fronts[k];
+ if (kept.length + front.length > N) break;
+ kept.push(...front);
+ steps.push({ F, names, rank: r.rank, kept: kept.slice(), crowd: null, faded: [], text: `Front ${k + 1} fits entirely: ${kept.length} of ${N} places are now used.` });
+ if (kept.length === N) break;
+ }
+ if (kept.length < N && k < r.fronts.length) {
+ const front = r.fronts[k];
+ const left = N - kept.length;
+ steps.push({
+ F,
+ names,
+ rank: r.rank,
+ kept: kept.slice(),
+ crowd: front,
+ faded: [],
+ text: `Front ${k + 1} has ${front.length} points but only ${left} place${left === 1 ? "" : "s"} remain. Compute the crowding distance inside front ${k + 1} (shown next to each point).`,
+ });
+ const chosen = front.filter((i) => survivors.includes(i));
+ const dropped = front.filter((i) => !survivors.includes(i));
+ steps.push({
+ F,
+ names,
+ rank: r.rank,
+ kept: survivors.slice(),
+ crowd: front,
+ faded: dropped,
+ text: `Keep the ${left} largest distances: ${list(chosen)}. Discard ${list(dropped)}, the most crowded.`,
+ });
+ }
+ const parentsKept = survivors.filter((i) => i < 6).length;
+ steps.push({
+ F,
+ names,
+ rank: r.rank,
+ kept: survivors.slice(),
+ crowd: null,
+ faded: F.map((_, i) => i).filter((i) => !survivors.includes(i)),
+ text: `New population: ${list(survivors.slice().sort((a, b) => a - b))}. ${parentsKept} parent${parentsKept === 1 ? "" : "s"} and ${N - parentsKept} offspring survive; later fronts were never needed.`,
+ });
+ state.crowding = r.crowding;
+ }
+ function go(i) {
+ state.step = Math.max(0, Math.min(steps.length - 1, i));
+ render();
+ }
+ function render() {
+ const st = steps[state.step];
+ back.disabled = state.step === 0;
+ next.disabled = state.step === steps.length - 1;
+ clear(plot.layers.marks);
+ clear(plot.layers.top);
+ st.F.forEach((p, i) => {
+ const px = plot.x(p[0]);
+ const py = plot.y(p[1]);
+ const cls = (st.rank ? "vf-pt " + rankClass(st.rank[i]) : "vf-pt vf-pt-muted") + (st.faded.includes(i) ? " vf-faded" : "");
+ marker(plot.layers.marks, i < 6 ? "circle" : "triangle", px, py, 6, cls);
+ if (st.kept.includes(i)) marker(plot.layers.marks, "circle", px, py, 10.5, "vf-ring");
+ let label = st.names[i];
+ if (st.crowd && st.crowd.includes(i)) label += " · " + fmt(state.crowding[i], 2);
+ txt(plot.layers.top, px + 10, py - 8, label, { class: "vf-mark-label" });
+ });
+ clear(readout);
+ h("p", { class: "vf-step-text" }, readout, `Step ${state.step + 1} of ${steps.length}. ${st.text}`);
+ }
+ build();
+ go(0);
+ };
+
+ /* A1: the share of non-dominated points as objectives are added. */
+ widgets["dominance-resistance"] = function (node) {
+ const state = { n: 100, results: [], token: 0 };
+ const ms = Array.from({ length: 14 }, (_, i) => i + 2);
+ const ctl = controls(node);
+ select(ctl, {
+ label: "Random points",
+ options: [
+ [50, "50"],
+ [100, "100"],
+ [200, "200"],
+ ],
+ value: state.n,
+ onChange: (v) => {
+ state.n = +v;
+ compute();
+ },
+ });
+ const body = h("div", { class: "vf-body vf-body--side" }, node);
+ const plot = createPlot(body, {
+ x: [2, 15],
+ y: [0, 1],
+ xLabel: "Number of objectives m",
+ yLabel: "Non-dominated share",
+ yFormat: (v) => Math.round(v * 100) + "%",
+ xTicks: [2, 4, 6, 8, 10, 12, 14],
+ label: "Share of mutually non-dominated points among uniform random points as the number of objectives grows",
+ });
+ const tip = tooltip(plot);
+ const readout = h("div", { class: "vf-readout" }, body);
+ function compute() {
+ const token = ++state.token;
+ state.results = [];
+ const trials = 10;
+ let index = 0;
+ const work = () => {
+ if (token !== state.token) return;
+ const m = ms[index];
+ const rand = mulberry32(1000 + m);
+ let share = 0;
+ for (let t = 0; t < trials; t++) {
+ const P = Array.from({ length: state.n }, () => Array.from({ length: m }, rand));
+ share += nonDominatedIndices(P).length / state.n;
+ }
+ state.results.push([m, share / trials]);
+ render();
+ index += 1;
+ if (index < ms.length) setTimeout(work, 0);
+ };
+ work();
+ }
+ function render() {
+ clear(plot.layers.mid);
+ clear(plot.layers.marks);
+ if (state.results.length > 1) plot.line(plot.layers.mid, state.results, "vf-line-1");
+ state.results.forEach((r) => {
+ const mark = marker(plot.layers.marks, "circle", plot.x(r[0]), plot.y(r[1]), 4, "vf-pt vf-pt-1");
+ const hit = s("circle", { cx: plot.x(r[0]), cy: plot.y(r[1]), r: 12, class: "vf-hit" }, plot.layers.marks);
+ attachTip(hit, tip, `m = ${r[0]}: ${fmt(100 * r[1], 1)}% non-dominated`, plot.x(r[0]), plot.y(r[1]));
+ mark.setAttribute("aria-hidden", "true");
+ });
+ clear(readout);
+ h("p", {}, readout, `Average over 10 samples of ${state.n} points drawn uniformly in [0, 1]^m.`);
+ const pick = state.results.filter((r) => [2, 3, 5, 8, 10, 15].includes(r[0]));
+ table(readout, ["m", "Non-dominated"], pick.map((r) => [String(r[0]), fmt(100 * r[1], 1) + "%"]), [false, true]);
+ }
+ compute();
+ };
+
+ /* A1: Das and Dennis reference directions. */
+ widgets["reference-directions"] = function (node) {
+ const state = { m: 3, p: 12 };
+ const ctl = controls(node);
+ select(ctl, {
+ label: "Objectives m",
+ options: Array.from({ length: 9 }, (_, i) => [i + 2, String(i + 2)]),
+ value: state.m,
+ onChange: (v) => {
+ state.m = +v;
+ render();
+ },
+ });
+ slider(ctl, { label: "Divisions p", min: 1, max: 30, step: 1, value: state.p, format: (v) => String(v), onInput: (v) => ((state.p = v), render()) });
+ const body = h("div", { class: "vf-body vf-body--side" }, node);
+ const holder = h("div", {}, body);
+ const readout = h("div", { class: "vf-readout" }, body);
+ function render() {
+ clear(holder);
+ const H = binomial(state.p + state.m - 1, state.m - 1);
+ if (state.m === 2) {
+ const plot = createPlot(holder, { x: [0, 1.05], y: [0, 1.05], xLabel: "w₁", yLabel: "w₂", label: "Reference directions for two objectives" });
+ for (const w of dasDennis(2, state.p)) {
+ plot.line(plot.layers.mid, [[0, 0], [w[0] * 1.5, w[1] * 1.5]], "vf-line-thin");
+ marker(plot.layers.marks, "circle", plot.x(w[0]), plot.y(w[1]), 4, "vf-pt vf-pt-1");
+ }
+ } else if (state.m === 3) {
+ const plot = createPlot(holder, { x: [-0.08, 1.08], y: [-0.1, 0.95], axes: false, margin: { l: 10, r: 10, t: 10, b: 10 }, width: 340, height: 300, label: "Reference points on the unit simplex for three objectives" });
+ const V = [
+ [0, 0],
+ [1, 0],
+ [0.5, 0.866],
+ ];
+ plot.line(plot.layers.mid, [V[0], V[1], V[2], V[0]], "vf-line-ink");
+ ["w₁ = 1", "w₂ = 1", "w₃ = 1"].forEach((label, i) => txt(plot.layers.top, plot.x(V[i][0]) + (i === 1 ? -36 : i === 0 ? 0 : 8), plot.y(V[i][1]) + (i === 2 ? 4 : 16), label, { class: "vf-mark-label" }));
+ for (const w of dasDennis(3, state.p)) {
+ const x = w[0] * V[0][0] + w[1] * V[1][0] + w[2] * V[2][0];
+ const y = w[0] * V[0][1] + w[1] * V[1][1] + w[2] * V[2][1];
+ marker(plot.layers.marks, "circle", plot.x(x), plot.y(y), state.p > 20 ? 2.5 : 3.5, "vf-pt vf-pt-1");
+ }
+ } else {
+ h("p", { class: "vf-fallback" }, holder, `With ${state.m} objectives the simplex cannot be drawn in the plane; the table gives the number of directions.`);
+ }
+ clear(readout);
+ h("p", {}, readout, `H = C(p + m − 1, m − 1) = C(${state.p + state.m - 1}, ${state.m - 1}) = ${H.toLocaleString("en-US")} reference directions.`);
+ h("p", {}, readout, `NSGA-III in VAMOS needs a population of at least H = ${H.toLocaleString("en-US")} so that every direction can keep a solution.`);
+ const rows = [1, 2, 3, 4, 6, 8, 12].map((p) => [String(p), binomial(p + state.m - 1, state.m - 1).toLocaleString("en-US")]);
+ table(readout, ["p", `H for m = ${state.m}`], rows, [false, true]);
+ }
+ render();
+ };
+
+ /** CTP2 background: infeasible region, unconstrained front and constrained front. */
+ function drawCtp2(plot) {
+ const cols = 120;
+ for (let c = 0; c < cols; c++) {
+ const f1 = (c + 0.5) / cols;
+ let start = null;
+ const step = 0.004;
+ for (let f2 = Math.max(0, 1 - f1); f2 <= 1.6 + step; f2 += step) {
+ const bad = f2 <= 1.6 && ctpViolation([f1, f2]) > 0;
+ if (bad && start === null) start = f2;
+ if (!bad && start !== null) {
+ plot.rect(plot.layers.back, c / cols, start, (c + 1) / cols + 0.0005, f2, "vf-region-2");
+ start = null;
+ }
+ }
+ }
+ plot.line(plot.layers.back, [[0, 1], [1, 0]], "vf-front");
+ const lowest = [];
+ for (let i = 0; i <= 1000; i++) {
+ const f1 = i / 1000;
+ for (let f2 = 1 - f1; f2 <= 1.6; f2 += 0.0005) {
+ if (ctpViolation([f1, f2]) <= 0) {
+ lowest.push([f1, f2]);
+ break;
+ }
+ }
+ }
+ const constrainedFront = nonDominatedIndices(lowest).map((i) => lowest[i]);
+ constrainedFront.forEach((p) => marker(plot.layers.back, "circle", plot.x(p[0]), plot.y(p[1]), 1.6, "vf-pt-1"));
+ drawFront(plot, plot.layers.back, constrainedFront, "vf-line-1", 0.0015);
+ }
+
+ /* A2: constrained domination on CTP2. */
+ widgets.constraints = function (node) {
+ const state = { rule: "cdp", seed: 5, pop: [] };
+ const ctl = controls(node);
+ select(ctl, {
+ label: "Ranking rule",
+ options: [
+ ["cdp", "Constrained domination (Deb, 2000)"],
+ ["pareto", "Pareto dominance, constraints ignored"],
+ ],
+ value: state.rule,
+ onChange: (v) => {
+ state.rule = v;
+ render();
+ },
+ });
+ button(ctl, "New population", () => {
+ state.seed = Math.floor(Math.random() * 1e6);
+ sample();
+ render();
+ });
+ const body = h("div", { class: "vf-body vf-body--side" }, node);
+ const plot = createPlot(body, { x: [0, 1], y: [0, 1.6], xLabel: "f₁", yLabel: "f₂", label: "CTP2 objective space with its infeasible regions and a ranked population" });
+ const tip = tooltip(plot);
+ const readout = h("div", { class: "vf-readout" }, body);
+ legend(node, [
+ { label: "Infeasible region", shape: "region", cls: "vf-region-2" },
+ { label: "Unconstrained front f₂ = 1 − f₁", shape: "line", cls: "vf-front" },
+ { label: "Constrained Pareto front", shape: "line", cls: "vf-line-1" },
+ { label: "Feasible solution (colour = front)", shape: "circle", cls: "vf-pt vf-r1" },
+ { label: "Infeasible solution (colour = front)", shape: "square", cls: "vf-pt vf-r1" },
+ ]);
+ drawCtp2(plot);
+ function sample() {
+ const rand = mulberry32(state.seed);
+ state.pop = Array.from({ length: 24 }, () => {
+ const f1 = rand();
+ const g = 1 + 0.55 * rand();
+ return [f1, g - f1];
+ });
+ }
+ function render() {
+ clear(plot.layers.marks);
+ const F = state.pop;
+ const cv = F.map((f) => ctpViolation(f));
+ const sorted = nonDominatedSort(F, state.rule === "cdp" ? constrainedDominates(cv) : null);
+ F.forEach((f, i) => {
+ const px = plot.x(f[0]);
+ const py = plot.y(f[1]);
+ marker(plot.layers.marks, cv[i] > 0 ? "square" : "circle", px, py, 5.5, "vf-pt " + rankClass(sorted.rank[i]));
+ const hit = s("circle", { cx: px, cy: py, r: 11, class: "vf-hit" }, plot.layers.marks);
+ attachTip(hit, tip, `f = ${pair(f)} · violation ${fmt(cv[i])} · front ${sorted.rank[i] + 1}`, px, py);
+ });
+ const feasible = cv.filter((v) => v <= 0).length;
+ const first = sorted.fronts[0];
+ const firstFeasible = first.filter((i) => cv[i] <= 0).length;
+ clear(readout);
+ h("p", {}, readout, `${feasible} of ${F.length} solutions are feasible. Front 1 has ${first.length} solution${first.length === 1 ? "" : "s"}, ${firstFeasible} of them feasible.`);
+ h(
+ "p",
+ {},
+ readout,
+ state.rule === "cdp"
+ ? "Under constrained domination every feasible solution beats every infeasible one, infeasible solutions are ordered by their violation, and Pareto dominance only decides between feasible solutions."
+ : "Ignoring the constraints, infeasible solutions close to the unconstrained front take the best ranks: selection would push the population into regions it can never use."
+ );
+ }
+ sample();
+ render();
+ };
+
+ /* A3: empirical attainment surfaces and a per-run indicator. */
+ widgets.attainment = function (node) {
+ const curve = (t) => 1 - Math.sqrt(t);
+ const ref = [1.1, 1.1];
+ const runsPerAlgorithm = 11;
+ const state = { seed: 31, show: "median", runs: { A: [], B: [] } };
+ const profiles = {
+ A: { gap: [0.08, 0.025], extent: [0.92, 1] },
+ B: { gap: [0.02, 0.01], extent: [0.45, 0.7] },
+ };
+ const ctl = controls(node);
+ select(ctl, {
+ label: "Surfaces",
+ options: [
+ ["median", "Median (6 of 11 runs)"],
+ ["A", "Algorithm A: best, median, worst"],
+ ["B", "Algorithm B: best, median, worst"],
+ ],
+ value: state.show,
+ onChange: (v) => {
+ state.show = v;
+ render();
+ },
+ });
+ button(ctl, "New runs", () => {
+ state.seed = Math.floor(Math.random() * 1e6);
+ generate();
+ render();
+ });
+ const body = h("div", { class: "vf-body vf-body--two" }, node);
+ const plot = createPlot(body, { title: "Attainment surfaces", x: [0, 1.15], y: [0, 1.15], xLabel: "f₁", yLabel: "f₂", label: "Empirical attainment surfaces of two algorithms" });
+ const strip = createPlot(body, {
+ title: "Hypervolume of each run",
+ x: [0, 3],
+ y: [0.6, 0.9],
+ xTicks: [1, 2],
+ xFormat: (v) => (v === 1 ? "A" : "B"),
+ xLabel: "Algorithm",
+ yLabel: "HV (r = 1.1, 1.1)",
+ label: "Hypervolume of every run of each algorithm",
+ });
+ const tip = tooltip(strip);
+ const readout = h("div", { class: "vf-readout" }, node);
+ legend(node, [
+ { label: "Algorithm A", shape: "line", cls: "vf-line-1" },
+ { label: "Algorithm B", shape: "line", cls: "vf-line-2" },
+ { label: "Best and worst surfaces (thin)", shape: "line", cls: "vf-line-thin" },
+ { label: "Pareto front", shape: "line", cls: "vf-front" },
+ ]);
+ function generate() {
+ const rand = mulberry32(state.seed);
+ for (const key of ["A", "B"]) {
+ const prof = profiles[key];
+ state.runs[key] = Array.from({ length: runsPerAlgorithm }, () => {
+ const gap = Math.max(0.002, prof.gap[0] + prof.gap[1] * gaussian(rand));
+ const extent = prof.extent[0] + (prof.extent[1] - prof.extent[0]) * rand();
+ const start = key === "A" ? rand() * (1 - extent) * 0.5 : 0.1 + rand() * (0.9 - extent);
+ const pts = Array.from({ length: 10 }, (_, i) => {
+ const t = Math.min(1, start + (extent * (i + 0.2 * rand())) / 9);
+ return [t + 0.2 * gap * rand(), curve(t) + gap * (0.5 + rand())];
+ });
+ return nonDominatedIndices(pts).map((i) => pts[i]);
+ });
+ }
+ }
+ function stairs(surface) {
+ const pts = [];
+ let prev = 3;
+ for (const [u, v] of surface) {
+ if (!Number.isFinite(v)) continue;
+ pts.push([u, Math.min(prev, 3)]);
+ pts.push([u, v]);
+ prev = v;
+ }
+ if (pts.length) pts.push([3, prev]);
+ return pts;
+ }
+ function render() {
+ clear(plot.layers.mid);
+ plot.line(plot.layers.mid, frontPoints(curve, 0, 1, 101), "vf-front");
+ const median = Math.ceil(runsPerAlgorithm / 2);
+ const keys = state.show === "median" ? ["A", "B"] : [state.show];
+ for (const key of keys) {
+ const cls = key === "A" ? "vf-line-1" : "vf-line-2";
+ if (state.show !== "median") {
+ plot.line(plot.layers.mid, stairs(attainmentSurface(state.runs[key], 1)), "vf-line-thin");
+ plot.line(plot.layers.mid, stairs(attainmentSurface(state.runs[key], runsPerAlgorithm)), "vf-line-thin vf-dashed");
+ }
+ plot.line(plot.layers.mid, stairs(attainmentSurface(state.runs[key], median)), cls);
+ }
+ const hv = { A: state.runs.A.map((r) => hypervolume2d(r, ref)), B: state.runs.B.map((r) => hypervolume2d(r, ref)) };
+ const all = hv.A.concat(hv.B);
+ const lo = Math.floor(Math.min(...all) * 20) / 20 - 0.025;
+ const hi = Math.ceil(Math.max(...all) * 20) / 20 + 0.025;
+ strip.setDomain([0, 3], [lo, hi]);
+ clear(strip.layers.mid);
+ clear(strip.layers.marks);
+ const med = (v) => {
+ const sorted = v.slice().sort((a, b) => a - b);
+ return sorted[Math.floor(sorted.length / 2)];
+ };
+ const jitter = mulberry32(3);
+ ["A", "B"].forEach((key, k) => {
+ const cx = k + 1;
+ hv[key].forEach((v, i) => {
+ const x = cx + (jitter() - 0.5) * 0.5;
+ marker(strip.layers.marks, "circle", strip.x(x), strip.y(v), 4.5, "vf-pt " + (key === "A" ? "vf-pt-1" : "vf-pt-2"));
+ const hit = s("circle", { cx: strip.x(x), cy: strip.y(v), r: 10, class: "vf-hit" }, strip.layers.marks);
+ attachTip(hit, tip, `${key}, run ${i + 1}: HV ${fmt(v)}`, strip.x(x), strip.y(v));
+ });
+ strip.line(strip.layers.mid, [[cx - 0.35, med(hv[key])], [cx + 0.35, med(hv[key])]], "vf-line-ink");
+ });
+ const test = mannWhitney(hv.A, hv.B);
+ clear(readout);
+ h("p", {}, readout, `Median HV: A ${fmt(med(hv.A))}, B ${fmt(med(hv.B))}. Mann–Whitney U = ${fmt(test.u, 1)}, two-sided p ≈ ${fmt(test.p, 3)} (normal approximation, ${runsPerAlgorithm} runs each).`);
+ h(
+ "p",
+ {},
+ readout,
+ "The data are synthetic: A covers the whole front but converges less, B converges closer on part of it. The surfaces show where each one is better; a single indicator value cannot."
+ );
+ }
+ generate();
+ render();
+ };
+
+ /** Shared scaffold: draggable labelled points, a plot and a readout. */
+ function pointSetFigure(node, o) {
+ const state = { P: o.points.map((p) => p.slice()), active: -1 };
+ const ctl = controls(node);
+ const body = h("div", { class: "vf-body " + (o.layout === undefined ? "vf-body--side" : o.layout) }, node);
+ const plot = createPlot(body, { x: o.x || [0, 1], y: o.y || [0, 1], xLabel: o.xLabel || "f₁", yLabel: o.yLabel || "f₂", label: o.label });
+ const readout = h("div", { class: "vf-readout" }, body);
+ if (o.legend) legend(node, o.legend);
+ const fig = { state, ctl, plot, readout, render: () => {} };
+ fig.name = (i) => (o.names ? o.names[i] : LETTERS[i]);
+ fig.handles = state.P.map((_, i) =>
+ handle(plot, {
+ cls: "vf-pt vf-pt-1",
+ label: () => "Point " + fig.name(i),
+ get: () => state.P[i],
+ set: (a, b) => {
+ state.P[i] = [a, b];
+ fig.render();
+ },
+ onSelect: () => {
+ if (state.active !== i) {
+ state.active = i;
+ fig.render();
+ }
+ },
+ })
+ );
+ fig.labels = () => {
+ clear(plot.layers.top);
+ state.P.forEach((p, i) => txt(plot.layers.top, plot.x(p[0]) + 9, plot.y(p[1]) - 7, fig.name(i), { class: "vf-mark-label" }));
+ };
+ return fig;
+ }
+
+ /* I7: SPEA2 strength, raw fitness, density and archive truncation. */
+ widgets["spea2-fitness"] = function (node) {
+ const defaults = [
+ [0.05, 0.92],
+ [0.12, 0.7],
+ [0.16, 0.64],
+ [0.3, 0.45],
+ [0.45, 0.33],
+ [0.5, 0.3],
+ [0.85, 0.08],
+ [0.4, 0.62],
+ [0.7, 0.55],
+ [0.55, 0.32],
+ ];
+ const names = defaults.map((_, i) => "P" + (i + 1));
+ const fig = pointSetFigure(node, {
+ points: defaults,
+ names,
+ layout: "",
+ label: "Ten draggable points with their SPEA2 fitness and the archive built by environmental selection",
+ legend: [
+ { label: "Non-dominated, in the archive", shape: "circle", cls: "vf-pt vf-pt-1" },
+ { label: "Dominated, added by fitness", shape: "square", cls: "vf-pt vf-pt-1" },
+ { label: "Removed by truncation (order shown)", shape: "circle", cls: "vf-pt vf-pt-2" },
+ { label: "Rejected", shape: "circle", cls: "vf-pt-hollow" },
+ { label: "Distance to the k-th neighbour of the focused point", shape: "line", cls: "vf-line-thin vf-dashed" },
+ ],
+ });
+ const state = fig.state;
+ state.size = 5;
+ state.k = 1;
+ const ordinal = (n) => n + (n === 1 ? "st" : n === 2 ? "nd" : n === 3 ? "rd" : "th");
+ slider(fig.ctl, { label: "Archive size", min: 1, max: 10, step: 1, value: state.size, format: (v) => String(v), onInput: (v) => ((state.size = v), fig.render()) });
+ select(fig.ctl, {
+ label: "k",
+ options: [
+ [1, "1, VAMOS default"],
+ [2, "2"],
+ [3, "3 ≈ √10, the paper"],
+ ],
+ value: 1,
+ onChange: (v) => ((state.k = +v), fig.render()),
+ });
+ button(fig.ctl, "Reset", () => {
+ defaults.forEach((p, i) => (state.P[i] = p.slice()));
+ fig.render();
+ });
+ fig.render = function () {
+ const P = state.P;
+ const sel = spea2Select(P, state.size, state.k);
+ const kept = new Set(sel.kept);
+ clear(fig.plot.layers.mid);
+ fig.labels();
+ const sigma = (i) => 1 / sel.D[i] - 2;
+ if (state.active >= 0) {
+ const a = P[state.active];
+ const r = sigma(state.active);
+ s("ellipse", { cx: fig.plot.x(a[0]), cy: fig.plot.y(a[1]), rx: fig.plot.x(a[0] + r) - fig.plot.x(a[0]), ry: fig.plot.y(a[1]) - fig.plot.y(a[1] + r), class: "vf-line-thin vf-dashed" }, fig.plot.layers.mid);
+ }
+ const status = (i) => {
+ const order = sel.removed.indexOf(i);
+ if (order >= 0) return "removed " + ordinal(order + 1);
+ const fill = sel.filled.indexOf(i);
+ if (fill >= 0) return `added by F (${ordinal(fill + 1)})`;
+ return kept.has(i) ? "kept" : "rejected (dominated)";
+ };
+ P.forEach((p, i) => {
+ const hd = fig.handles[i];
+ hd.place();
+ hd.node.classList.toggle("vf-selected", i === state.active);
+ const order = sel.removed.indexOf(i);
+ hd.setClass(kept.has(i) ? "vf-pt vf-pt-1" : order >= 0 ? "vf-pt vf-pt-2" : "vf-pt-hollow");
+ if (sel.filled.includes(i)) hd.setClass("vf-pt vf-pt-1 vf-faded");
+ if (order >= 0) txt(fig.plot.layers.top, fig.plot.x(p[0]) - 6, fig.plot.y(p[1]) + 20, "×" + (order + 1), { class: "vf-mark-label" });
+ });
+ clear(fig.readout);
+ const ndn = sel.nd.length;
+ let summary;
+ if (P.length <= state.size) summary = `${P.length} points for ${state.size} places: every point is kept.`;
+ else if (ndn > state.size) summary = `${ndn} non-dominated points for ${state.size} places: the truncation removes ${sel.removed.map((i) => names[i]).join(", then ")}.`;
+ else if (ndn < state.size) summary = `${ndn} non-dominated points for ${state.size} places: the archive is completed with ${sel.filled.map((i) => names[i]).join(" and ")}, the dominated points with the lowest F.`;
+ else summary = `Exactly ${ndn} non-dominated points for ${ndn} places.`;
+ h("p", {}, fig.readout, summary);
+ if (state.active >= 0) {
+ const i = state.active;
+ const doms = P.map((_, j) => j).filter((j) => j !== i && dominates(P[j], P[i]));
+ h("p", {}, fig.readout, doms.length ? `${names[i]} is dominated by ${doms.map((j) => names[j]).join(", ")}: R = ${doms.map((j) => sel.S[j]).join(" + ")} = ${sel.R[i]}.` : `${names[i]} is non-dominated: R = 0, and its strength is S = ${sel.S[i]}.`);
+ }
+ table(
+ fig.readout,
+ ["Point", "S", "R", "σ_k", "D", "F", "Status"],
+ P.map((_, i) => [names[i], String(sel.S[i]), String(sel.R[i]), fmt(sigma(i), 4), fmt(sel.D[i], 4), fmt(sel.fitness[i], 4), status(i)]),
+ [false, true, true, true, true, true, false]
+ );
+ };
+ fig.render();
+ };
+
+ /* I10: IBEA fitness with the additive epsilon indicator. */
+ widgets["ibea-fitness"] = function (node) {
+ const defaults = [
+ [0.05, 0.95],
+ [0.15, 0.6],
+ [0.2, 0.55],
+ [0.4, 0.38],
+ [0.6, 0.2],
+ [0.95, 0.05],
+ [0.5, 0.6],
+ [0.75, 0.45],
+ ];
+ const names = defaults.map((_, i) => "P" + (i + 1));
+ const fig = pointSetFigure(node, {
+ points: defaults,
+ names,
+ layout: "",
+ label: "Eight draggable points with their IBEA fitness and the order in which environmental selection removes them",
+ legend: [
+ { label: "Survives", shape: "circle", cls: "vf-pt vf-pt-1" },
+ { label: "Removed (order shown)", shape: "circle", cls: "vf-pt-hollow" },
+ ],
+ });
+ const state = fig.state;
+ state.kappa = 0.05;
+ state.size = 5;
+ state.indicator = "eps";
+ const ordinal = (n) => n + (n === 1 ? "st" : n === 2 ? "nd" : n === 3 ? "rd" : "th");
+ const kappaOf = (t) => +(0.01 * Math.pow(200, t)).toPrecision(2);
+ slider(fig.ctl, { label: "κ (log scale)", min: 0, max: 1, step: 0.01, value: Math.log(0.05 / 0.01) / Math.log(200), format: (t) => String(kappaOf(t)), onInput: (t) => ((state.kappa = kappaOf(t)), fig.render()) });
+ select(fig.ctl, {
+ label: "Indicator",
+ options: [
+ ["eps", "Additive ε (default)"],
+ ["hv", "Hypervolume difference"],
+ ],
+ value: "eps",
+ onChange: (v) => ((state.indicator = v), fig.render()),
+ });
+ slider(fig.ctl, { label: "Population size", min: 1, max: 7, step: 1, value: state.size, format: (v) => String(v), onInput: (v) => ((state.size = v), fig.render()) });
+ button(fig.ctl, "Reset", () => {
+ defaults.forEach((p, i) => (state.P[i] = p.slice()));
+ fig.render();
+ });
+ const big = (v) => (Math.abs(v) >= 1e6 ? v.toExponential(3) : fmt(v));
+ fig.render = function () {
+ const P = state.P;
+ const sel = ibeaSelect(P, state.size, state.kappa, state.indicator);
+ const kept = new Set(sel.kept);
+ fig.labels();
+ P.forEach((p, i) => {
+ const hd = fig.handles[i];
+ hd.place();
+ hd.node.classList.toggle("vf-selected", i === state.active);
+ const order = sel.removed.indexOf(i);
+ hd.setClass(kept.has(i) ? "vf-pt vf-pt-1" : "vf-pt-hollow");
+ if (order >= 0) txt(fig.plot.layers.top, fig.plot.x(p[0]) - 6, fig.plot.y(p[1]) + 20, "×" + (order + 1), { class: "vf-mark-label" });
+ });
+ clear(fig.readout);
+ h("p", {}, fig.readout, `Population size ${state.size}: IBEA removes ${sel.removed.map((i) => names[i]).join(", then ") || "nothing"}. c = ${fmt(sel.c)} (largest |I| on normalized objectives), κ = ${state.kappa}.`);
+ if (state.active >= 0) {
+ const x = state.active;
+ const terms = sel.terms[x]
+ .map((v, y) => [y, -v])
+ .filter(([y]) => y !== x)
+ .sort((a, b) => a[1] - b[1])
+ .slice(0, 3);
+ h("p", {}, fig.readout, `${names[x]}: ${terms.map(([y, v]) => `${names[y]} contributes ${big(v)}`).join(", ")}.`);
+ }
+ table(
+ fig.readout,
+ ["Point", "f₁", "f₂", "Fitness (initial)", "Status", "Fitness after selection"],
+ P.map((p, i) => {
+ const order = sel.removed.indexOf(i);
+ return [names[i], fmt(p[0], 2), fmt(p[1], 2), big(sel.fitness[i]), kept.has(i) ? "survives" : "removed " + ordinal(order + 1), kept.has(i) ? big(sel.final[i]) : "–"];
+ }),
+ [false, true, true, true, false, true]
+ );
+ };
+ fig.render();
+ };
+
+ /* A3: RVEA angle-penalized distance. */
+ widgets["rvea-apd"] = function (node) {
+ const V = [0, 1, 2, 3, 4].map((k) => {
+ const w = [k / 4, 1 - k / 4];
+ const n = Math.hypot(w[0], w[1]);
+ return [w[0] / n, w[1] / n];
+ });
+ const F = [
+ [0.2, 1.2],
+ [0.305, 1.095],
+ [0.387, 0.98],
+ [0.494, 1.004],
+ [0.688, 1.196],
+ [0.576, 0.806],
+ [0.862, 0.452],
+ [1.197, 0.565],
+ [1.046, 0.408],
+ [1.031, 0.277],
+ [1.246, 0.192],
+ [1.6, 0.1],
+ ];
+ const z = [Math.min(...F.map((f) => f[0])), Math.min(...F.map((f) => f[1]))];
+ const Fp = F.map((f) => [f[0] - z[0], f[1] - z[1]]);
+ const state = { progress: 0, alpha: 2, M: 1, focus: -1 };
+ const ctl = controls(node);
+ slider(ctl, { label: "t / t_max", min: 0, max: 1, step: 0.005, value: 0, format: (v) => v.toFixed(3), onInput: (v) => ((state.progress = v), render()) });
+ slider(ctl, { label: "α", min: 0.5, max: 10, step: 0.5, value: 2, format: (v) => v.toFixed(1), onInput: (v) => ((state.alpha = v), render()) });
+ checkbox(ctl, { label: "M = 2, as in the article", checked: false, onChange: (v) => ((state.M = v ? 2 : 1), render()) });
+ const body = h("div", { class: "vf-body" }, node);
+ const plot = createPlot(body, { x: [0, 1.8], y: [0, 1.4], xLabel: "f₁", yLabel: "f₂", width: 400, height: 320, label: "RVEA reference vectors from the ideal point and the solution each one keeps" });
+ const tip = tooltip(plot);
+ const readout = h("div", { class: "vf-readout" }, body);
+ legend(node, [
+ { label: "Reference vector (from z)", shape: "line", cls: "vf-line-ink" },
+ { label: "Kept by its vector", shape: "circle", cls: "vf-pt vf-pt-2" },
+ { label: "Not kept", shape: "circle", cls: "vf-pt-hollow" },
+ { label: "Radius stretched by the penalty, ‖f′‖·(1 + P(θ))", shape: "line", cls: "vf-line-thin vf-dashed" },
+ ]);
+ function render() {
+ const sel = rveaSelect(Fp, V, state.progress, state.alpha, state.M);
+ clear(plot.layers.mid);
+ clear(plot.layers.marks);
+ clear(plot.layers.top);
+ plot.line(plot.layers.mid, [[z[0], 3], [z[0], z[1]], [3, z[1]]], "vf-line-thin");
+ V.forEach((v, j) => {
+ plot.line(plot.layers.mid, [z, [z[0] + 3 * v[0], z[1] + 3 * v[1]]], "vf-line-ink");
+ const t = Math.min((1.75 - z[0]) / (v[0] || 1e-9), (1.36 - z[1]) / (v[1] || 1e-9));
+ txt(plot.layers.top, plot.x(z[0] + t * v[0]) - (j === 4 ? 18 : 4), plot.y(z[1] + t * v[1]) + (j === 4 ? -6 : 12), "v" + (j + 1), { class: "vf-mark-label" });
+ });
+ F.forEach((f, i) => {
+ const nrm = Math.hypot(Fp[i][0], Fp[i][1]);
+ const ghost = [z[0] + (sel.apd[i] * Fp[i][0]) / nrm, z[1] + (sel.apd[i] * Fp[i][1]) / nrm];
+ if (nrm > 0) plot.line(plot.layers.mid, [f, ghost], "vf-line-thin vf-dashed");
+ const winner = sel.selected.includes(i);
+ const px = plot.x(f[0]);
+ const py = plot.y(f[1]);
+ const hit = s("circle", { cx: px, cy: py, r: 11, class: "vf-hit" }, plot.layers.marks);
+ marker(plot.layers.marks, "circle", px, py, winner ? 6.5 : 5, winner ? "vf-pt vf-pt-2" : "vf-pt-hollow");
+ attachTip(hit, tip, `${i + 1} · v${sel.assoc[i] + 1} · θ ${fmt((sel.theta[i] * 180) / Math.PI, 1)}° · APD ${fmt(sel.apd[i])}`, px, py);
+ txt(plot.layers.top, px + 8, py - 6, String(i + 1), { class: "vf-mark-label" });
+ });
+ marker(plot.layers.marks, "cross", plot.x(z[0]), plot.y(z[1]), 4, "vf-line-ink");
+ clear(readout);
+ const sv = Math.pow(state.progress, state.alpha);
+ const kept = sel.selected.filter((i) => i >= 0).map((i) => i + 1);
+ const empty = sel.selected.map((i, j) => (i < 0 ? "v" + (j + 1) : null)).filter(Boolean);
+ h("p", {}, readout, `s = (t/t_max)^α = ${fmt(sv)} · M = ${state.M}. Survivors: ${kept.join(", ")}${empty.length ? ` (${empty.join(", ")} ${empty.length === 1 ? "has" : "have"} no solution)` : ""}.`);
+ const rows = F.map((_, i) => i).sort((a, b) => sel.assoc[a] - sel.assoc[b] || a - b);
+ table(
+ readout,
+ ["Point", "Vector", "θ (°)", "‖f′‖", "P(θ)", "APD", "Kept"],
+ rows.map((i) => {
+ const pen = state.M * sv * (sel.theta[i] / sel.gamma[sel.assoc[i]]);
+ return [String(i + 1), "v" + (sel.assoc[i] + 1), fmt((sel.theta[i] * 180) / Math.PI, 1), fmt(Math.hypot(Fp[i][0], Fp[i][1])), fmt(pen), fmt(sel.apd[i]), sel.selected.includes(i) ? "✓" : ""];
+ }),
+ [true, false, true, true, true, true, false]
+ );
+ }
+ render();
+ };
+
+ /* I8: MOEA/D neighbourhoods and replacement. */
+ widgets["moead-neighbourhood"] = function (node) {
+ const N = 11;
+ const W = moeadWeights(N);
+ const P = [
+ [1.1, 0.1],
+ [0.925, 0.192],
+ [0.786, 0.272],
+ [0.671, 0.345],
+ [0.571, 0.414],
+ [0.482, 0.482],
+ [0.401, 0.551],
+ [0.325, 0.625],
+ [0.252, 0.71],
+ [0.18, 0.818],
+ [0.1, 1.1],
+ ];
+ const state = { i: 5, T: 5, nr: 2, mode: "tch", pool: "neighbourhood", y: [0.39, 0.39], order: [6, 3, 5, 7, 4] };
+ const ctl = controls(node);
+ const pick = select(ctl, { label: "Subproblem", options: W.map((_, k) => [k, String(k)]), value: state.i, onChange: (v) => ((state.i = +v), resetOrder(), render()) });
+ slider(ctl, { label: "T", min: 2, max: 11, step: 1, value: state.T, format: (v) => String(v), onInput: (v) => ((state.T = v), resetOrder(), render()) });
+ slider(ctl, { label: "n_r", min: 1, max: 5, step: 1, value: state.nr, format: (v) => String(v), onInput: (v) => ((state.nr = v), render()) });
+ select(ctl, {
+ label: "Aggregation",
+ options: [
+ ["tch", "Tchebycheff"],
+ ["pbi", "PBI (θ = 5)"],
+ ["ws", "Weighted sum"],
+ ],
+ value: state.mode,
+ onChange: (v) => ((state.mode = v), render()),
+ });
+ select(ctl, {
+ label: "Mating pool",
+ options: [
+ ["neighbourhood", "Neighbourhood (probability δ = 0.9)"],
+ ["population", "Whole population (probability 1 − δ)"],
+ ],
+ value: state.pool,
+ onChange: (v) => ((state.pool = v), resetOrder(), render()),
+ });
+ button(ctl, "Shuffle order", () => {
+ const a = state.order.slice();
+ for (let k = a.length - 1; k > 0; k--) {
+ const r = Math.floor(Math.random() * (k + 1));
+ [a[k], a[r]] = [a[r], a[k]];
+ }
+ state.order = a;
+ render();
+ });
+ const body = h("div", { class: "vf-body" }, node);
+ const plot = createPlot(body, { x: [0, 1.2], y: [0, 1.2], xLabel: "f₁", yLabel: "f₂", label: "MOEA/D subproblems, the neighbourhood of the selected one and a draggable offspring" });
+ const readout = h("div", { class: "vf-readout" }, body);
+ legend(node, [
+ { label: "Selected subproblem", shape: "line", cls: "vf-line-2" },
+ { label: "Its neighbourhood (candidates)", shape: "line", cls: "vf-line-1" },
+ { label: "Offspring y (drag it)", shape: "triangle", cls: "vf-pt vf-pt-2" },
+ { label: "Replaced by y", shape: "circle", cls: "vf-ring" },
+ { label: "Better, but n_r reached", shape: "circle", cls: "vf-pt-hollow" },
+ ]);
+ function owner(k) {
+ return state.mode === "tch" ? k : N - 1 - k;
+ }
+ function resetOrder() {
+ const B = moeadNeighbours(W, state.T)[state.i];
+ state.order = state.pool === "population" ? W.map((_, k) => k) : B.slice();
+ }
+ const yHandle = handle(plot, {
+ cls: "vf-pt vf-pt-2",
+ shape: "triangle",
+ r: 7,
+ label: () => "Offspring y",
+ get: () => state.y,
+ set: (a, b) => ((state.y = [a, b]), render()),
+ });
+ function render() {
+ pick.value = String(state.i);
+ const current = W.map((_, k) => P[owner(k)]);
+ const res = moeadReplace(current, W, state.y, state.order, state.nr, state.mode, 5);
+ const candidates = new Set(state.order);
+ const z = res.z;
+ clear(plot.layers.mid);
+ clear(plot.layers.marks);
+ clear(plot.layers.top);
+ W.forEach((w, k) => {
+ const dir = state.mode === "tch" ? [1 / (w[0] || 1e-4), 1 / (w[1] || 1e-4)] : w;
+ const len = Math.hypot(dir[0], dir[1]);
+ const end = [z[0] + (3 * dir[0]) / len, z[1] + (3 * dir[1]) / len];
+ const cls = k === state.i ? "vf-line-2" : candidates.has(k) ? "vf-line-1" : "vf-line-thin";
+ const ray = plot.line(plot.layers.mid, [z, end], cls);
+ ray.style.cursor = "pointer";
+ ray.addEventListener("click", () => ((state.i = k), resetOrder(), render()));
+ });
+ marker(plot.layers.marks, "cross", plot.x(z[0]), plot.y(z[1]), 4, "vf-line-ink");
+ txt(plot.layers.top, plot.x(z[0]) + 6, plot.y(z[1]) + 16, "z*", { class: "vf-mark-label" });
+ const byJ = {};
+ res.rows.forEach((r) => (byJ[r.j] = r));
+ W.forEach((_, k) => {
+ const p = current[k];
+ const px = plot.x(p[0]);
+ const py = plot.y(p[1]);
+ const r = byJ[k];
+ const mark = marker(plot.layers.marks, "circle", px, py, 5.5, candidates.has(k) ? "vf-pt vf-pt-1" : "vf-pt vf-pt-muted");
+ mark.style.cursor = "pointer";
+ mark.addEventListener("click", () => ((state.i = k), resetOrder(), render()));
+ if (r && r.result === "replaced") {
+ marker(plot.layers.marks, "circle", px, py, 10, "vf-ring");
+ s("line", { x1: px, y1: py, x2: plot.x(state.y[0]), y2: plot.y(state.y[1]), class: "vf-line-2 vf-dashed" }, plot.layers.marks);
+ } else if (r && r.result !== "kept") marker(plot.layers.marks, "circle", px, py, 10, "vf-pt-hollow");
+ txt(plot.layers.top, px + 8, py - 7, String(k), { class: "vf-mark-label" });
+ });
+ yHandle.place();
+ clear(readout);
+ table(
+ readout,
+ ["Order", "Subproblem", "w", "g(current)", "g(offspring)", "Result"],
+ res.rows.map((r, n) => [String(n + 1), String(r.j), pair(W[r.j], 1), fmt(r.gx, 4), fmt(r.gy, 4), r.result]),
+ [true, true, false, true, true, false]
+ );
+ const better = res.rows.filter((r) => r.result !== "kept").length;
+ h("p", {}, readout, `Ideal point z* = ${pair(z, 3)}. The offspring replaced ${res.replaced} of the ${better} subproblems it improves (n_r = ${state.nr}).`);
+ if (state.pool === "population") h("p", {}, readout, "Mating pool: whole population (probability 1 − δ = 0.1): every subproblem is a candidate.");
+ if (state.mode !== "tch") h("p", {}, readout, "With PBI and the weighted sum the optimum of a subproblem lies along w itself; with Tchebycheff along (1/w₁, 1/w₂). VAMOS gives subproblem 0 the weight (0, 1), so the labels run in opposite directions.");
+ }
+ render();
+ };
+
+ function arrow(plot, layer, from, to, cls) {
+ const x1 = plot.x(from[0]);
+ const y1 = plot.y(from[1]);
+ const x2 = plot.x(to[0]);
+ const y2 = plot.y(to[1]);
+ const len = Math.hypot(x2 - x1, y2 - y1);
+ if (len < 1) return;
+ const ux = (x2 - x1) / len;
+ const uy = (y2 - y1) / len;
+ s("line", { x1, y1, x2: x2 - ux * 5, y2: y2 - uy * 5, class: cls }, layer);
+ s("path", { d: `M${x2},${y2}L${x2 - ux * 8 - uy * 4},${y2 - uy * 8 + ux * 4}L${x2 - ux * 8 + uy * 4},${y2 - uy * 8 - ux * 4}Z`, class: cls.replace("vf-line", "vf-pt").replace(" vf-dashed", "") }, layer);
+ }
+
+ /* I11: one SMPSO velocity update. */
+ widgets["pso-velocity"] = function (node) {
+ const state = { x: [0.25, 0.3], v: [0.1, 0.05], p: [0.4, 0.2], g: [0.75, 0.7], c1: 2.0, c2: 1.9, r1: 0.6, r2: 0.8, clamp: true };
+ const ctl = controls(node);
+ const c1s = slider(ctl, { label: "C1", min: 1.5, max: 2.5, step: 0.05, value: state.c1, format: (v) => v.toFixed(2), onInput: (v) => ((state.c1 = v), render()) });
+ const c2s = slider(ctl, { label: "C2", min: 1.5, max: 2.5, step: 0.05, value: state.c2, format: (v) => v.toFixed(2), onInput: (v) => ((state.c2 = v), render()) });
+ button(ctl, "Resample r1, r2", () => ((state.r1 = Math.random()), (state.r2 = Math.random()), render()));
+ button(ctl, "Draw as VAMOS", () => {
+ state.c1 = Math.round((1.5 + Math.random()) * 20) / 20;
+ state.c2 = Math.round((1.5 + Math.random()) * 20) / 20;
+ state.r1 = Math.random();
+ state.r2 = Math.random();
+ c1s.set(state.c1);
+ c2s.set(state.c2);
+ render();
+ });
+ checkbox(ctl, { label: "Speed constraint", checked: true, onChange: (v) => ((state.clamp = v), render()) });
+ const body = h("div", { class: "vf-body vf-body--side" }, node);
+ const plot = createPlot(body, { x: [-0.1, 1.1], y: [-0.1, 1.1], xLabel: "x₁", yLabel: "x₂", label: "One particle of SMPSO: inertia, cognitive and social terms, constriction, clamping and the new position" });
+ const readout = h("div", { class: "vf-readout" }, body);
+ legend(node, [
+ { label: "Inertia w·v", shape: "line", cls: "vf-line-ink" },
+ { label: "Cognitive, towards the personal best p", shape: "line", cls: "vf-line-1" },
+ { label: "Social, towards the leader g", shape: "line", cls: "vf-line-3" },
+ { label: "Unconstrained velocity", shape: "line", cls: "vf-line-thin vf-dashed" },
+ { label: "Velocity after χ and clamping", shape: "line", cls: "vf-line-2" },
+ { label: "Speed limit box", shape: "region", cls: "vf-region-1" },
+ ]);
+ const mk = (key, label, cls, shape) =>
+ handle(plot, { cls, shape, r: 6, label: () => label, get: () => state[key], set: (a, b) => ((state[key] = [Math.min(1, Math.max(0, a)), Math.min(1, Math.max(0, b))]), render()), boundsX: [0, 1], boundsY: [0, 1] });
+ const handles = [mk("x", "Particle x", "vf-pt vf-pt-ink"), mk("p", "Personal best p", "vf-pt vf-pt-1", "diamond"), mk("g", "Leader g", "vf-pt vf-pt-3", "square")];
+ function render() {
+ const r = smpsoStep({ ...state, w: 0.1, vmax: 0.5, lower: [0, 0], upper: [1, 1] });
+ const x = state.x;
+ clear(plot.layers.back);
+ clear(plot.layers.mid);
+ clear(plot.layers.top);
+ plot.rect(plot.layers.back, x[0] - r.delta[0], x[1] - r.delta[1], x[0] + r.delta[0], x[1] + r.delta[1], "vf-region-1");
+ plot.line(plot.layers.mid, [[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]], "vf-line-ink");
+ const add = (a, b) => [a[0] + b[0], a[1] + b[1]];
+ arrow(plot, plot.layers.mid, [x[0] - state.v[0], x[1] - state.v[1]], x, "vf-line-thin");
+ const a1 = add(x, r.inertia);
+ const a2 = add(a1, r.cognitive);
+ const a3 = add(a2, r.social);
+ arrow(plot, plot.layers.mid, x, a1, "vf-line-ink");
+ arrow(plot, plot.layers.mid, a1, a2, "vf-line-1");
+ arrow(plot, plot.layers.mid, a2, a3, "vf-line-3");
+ plot.line(plot.layers.mid, [x, a3], "vf-line-thin vf-dashed");
+ arrow(plot, plot.layers.mid, x, add(x, r.clamped), "vf-line-2");
+ marker(plot.layers.mid, "circle", plot.x(r.position[0]), plot.y(r.position[1]), 6, "vf-pt vf-pt-2");
+ handles.forEach((hd) => hd.place());
+ [
+ [x, "x"],
+ [state.p, "p"],
+ [state.g, "g"],
+ [r.position, "x′"],
+ ].forEach(([q, label]) => txt(plot.layers.top, plot.x(q[0]) + 9, plot.y(q[1]) + 15, label, { class: "vf-mark-label" }));
+ clear(readout);
+ const v3 = (v) => `(${fmt(v[0])}, ${fmt(v[1])})`;
+ h("p", {}, readout, `φ = C1 + C2 = ${fmt(r.phi, 2)} → χ = ${r.phi <= 4 ? "1 (φ ≤ 4)" : fmt(r.chi, 4)}; r1 = ${fmt(state.r1, 2)}, r2 = ${fmt(state.r2, 2)}.`);
+ h("p", {}, readout, `w·v = ${v3(r.inertia)} C1·r1·(p − x) = ${v3(r.cognitive)} C2·r2·(g − x) = ${v3(r.social)}`);
+ h("p", {}, readout, `unconstrained v = ${v3(r.raw)} χ·v = ${v3(r.constricted)} ${state.clamp ? "clamped" : "unclamped"} v′ = ${v3(r.clamped)}`);
+ h("p", {}, readout, `new position x′ = ${v3(r.position)}`);
+ if (r.phi > 4) h("p", {}, readout, `χ < 0: VAMOS evaluates 2 / (2 − φ − √(φ² − 4φ)) without an absolute value, so the step points away from the guides; Clerc and Kennedy's coefficient is |χ| = ${fmt(Math.abs(r.chi), 4)}.`);
+ r.hit.forEach(([j, side]) => h("p", {}, readout, `x${j === 0 ? "₁" : "₂"} hit the ${side} bound: x${j === 0 ? "₁" : "₂"} = ${side === "lower" ? 0 : 1} and its velocity reverses.`));
+ }
+ render();
+ };
+
+ /** SMS-EMOA survival of N + 1 solutions (VAMOS' smsemoa/helpers.py, relative or jMetal reference point). */
+ function smsemoaStep(Q, offset, jmetal) {
+ const sorted = nonDominatedSort(Q);
+ const last = sorted.fronts[sorted.fronts.length - 1];
+ const top = Q[0].map((_, j) => Math.max(...Q.map((q) => q[j])));
+ const low = Q[0].map((_, j) => Math.min(...Q.map((q) => q[j])));
+ const ref = top.map((t, j) => (jmetal ? (t >= 0 ? 1.1 * t : t / 1.1) : t + offset * (t - low[j] > 0 ? t - low[j] : 1)));
+ let contributions = null;
+ let boxes = null;
+ let removed = last[0];
+ if (last.length > 1) {
+ const res = hvContributions2d(
+ last.map((i) => Q[i]),
+ ref
+ );
+ contributions = res.contributions;
+ boxes = res.boxes;
+ let k = 0;
+ contributions.forEach((c, i) => {
+ if (c < contributions[k]) k = i;
+ });
+ removed = last[k];
+ }
+ return { fronts: sorted.fronts, last, ref, contributions, boxes, removed };
+ }
+
+ /* I9: one SMS-EMOA selection step. */
+ widgets["smsemoa-step"] = function (node) {
+ const parents = [
+ [0.08, 0.9],
+ [0.2, 0.62],
+ [0.35, 0.45],
+ [0.4, 0.4],
+ [0.62, 0.22],
+ [0.9, 0.06],
+ ];
+ const children = { A: [0.55, 0.5], B: [0.5, 0.3] };
+ const names = ["P1", "P2", "P3", "P4", "P5", "P6", "C"];
+ const state = { scenario: "A", Q: parents.concat([children.A]).map((p) => p.slice()), step: 0, offset: 1, jmetal: false };
+ const ctl = controls(node);
+ select(ctl, {
+ label: "Scenario",
+ options: [
+ ["A", "A. The child is dominated"],
+ ["B", "B. The child joins the front"],
+ ],
+ value: "A",
+ onChange: (v) => {
+ state.scenario = v;
+ state.Q = parents.concat([children[v]]).map((p) => p.slice());
+ state.step = 0;
+ render();
+ },
+ });
+ const back = button(ctl, "Back", () => ((state.step = Math.max(0, state.step - 1)), render()));
+ const next = button(ctl, "Next step", () => ((state.step = Math.min(4, state.step + 1)), render()), true);
+ button(ctl, "Reset step", () => ((state.step = 0), render()));
+ slider(ctl, { label: "Reference offset", min: 0, max: 1, step: 0.1, value: 1, format: (v) => v.toFixed(1), onInput: (v) => ((state.offset = v), render()) });
+ checkbox(ctl, { label: "jMetal rule (1.1 · max)", checked: false, onChange: (v) => ((state.jmetal = v), render()) });
+ const body = h("div", { class: "vf-body vf-body--side" }, node);
+ const plot = createPlot(body, { x: [0, 1.9], y: [0, 1.9], xLabel: "f₁", yLabel: "f₂", label: "Six parents and one child; SMS-EMOA removes one solution of the last front" });
+ const readout = h("div", { class: "vf-readout" }, body);
+ legend(node, [
+ { label: "Parent", shape: "circle", cls: "vf-pt vf-pt-muted" },
+ { label: "Child C", shape: "triangle", cls: "vf-pt vf-pt-muted" },
+ { label: "Front 1, 2 … (darker is better)", shape: "circle", cls: "vf-pt vf-r1" },
+ { label: "Exclusive contribution in the last front", shape: "region", cls: "vf-region-2" },
+ { label: "Reference point r (computed)", shape: "diamond", cls: "vf-pt vf-pt-3" },
+ ]);
+ const handles = state.Q.map((_, i) =>
+ handle(plot, {
+ cls: "vf-pt vf-pt-muted",
+ shape: i === 6 ? "triangle" : "circle",
+ label: () => names[i],
+ get: () => state.Q[i],
+ set: (a, b) => ((state.Q[i] = [Math.min(1, a), Math.min(1, b)]), (state.step = 0), render()),
+ boundsX: [0, 1],
+ boundsY: [0, 1],
+ })
+ );
+ const STEPS = ["", "Sort into fronts", "Identify the last front", "Compute contributions", "Remove the worst"];
+ function render() {
+ const r = smsemoaStep(state.Q, state.offset, state.jmetal);
+ back.disabled = state.step === 0;
+ next.disabled = state.step === 4;
+ next.textContent = state.step < 4 ? "Next: " + STEPS[state.step + 1] : "Done";
+ const rank = new Array(7).fill(0);
+ r.fronts.forEach((f, k) => f.forEach((i) => (rank[i] = k)));
+ clear(plot.layers.back);
+ clear(plot.layers.marks);
+ clear(plot.layers.top);
+ if (state.step >= 3 && r.boxes) {
+ const pts = r.last.map((i) => state.Q[i]).sort((a, b) => a[0] - b[0]);
+ const poly = [[pts[0][0], r.ref[1]]];
+ pts.forEach((p, k) => {
+ poly.push(p);
+ poly.push([k + 1 < pts.length ? pts[k + 1][0] : r.ref[0], p[1]]);
+ });
+ poly.push(r.ref);
+ plot.line(plot.layers.back, poly, "vf-region-1");
+ r.boxes.forEach((b) => b && plot.rect(plot.layers.back, b[0], b[1], b[2], b[3], "vf-region-2"));
+ }
+ marker(plot.layers.marks, "diamond", plot.x(r.ref[0]), plot.y(r.ref[1]), 5, "vf-pt vf-pt-3");
+ txt(plot.layers.top, plot.x(r.ref[0]) + 8, plot.y(r.ref[1]) - 6, "r", { class: "vf-mark-label" });
+ state.Q.forEach((p, i) => {
+ handles[i].place();
+ let cls = state.step >= 1 ? "vf-pt " + rankClass(rank[i]) : "vf-pt vf-pt-muted";
+ if (state.step >= 4 && i === r.removed) cls += " vf-faded";
+ handles[i].setClass(cls);
+ if (state.step === 2 && r.last.includes(i)) marker(plot.layers.marks, "circle", plot.x(p[0]), plot.y(p[1]), 10.5, "vf-ring");
+ txt(plot.layers.top, plot.x(p[0]) + 9, plot.y(p[1]) - 7, names[i] + (state.step >= 4 && i === r.removed ? " ✕" : ""), { class: "vf-mark-label" });
+ });
+ clear(readout);
+ const list = (rows) => rows.map((i) => names[i]).join(", ");
+ const lines = [`r = ${pair(r.ref, 3)}, computed from all seven points.`];
+ if (state.step >= 1) lines.push(r.fronts.map((f, k) => `Front ${k + 1}: ${list(f)}`).join(" · "));
+ if (state.step >= 2) lines.push(r.fronts.length === 1 ? "The last front is front 1: all seven points." : `The last front is front ${r.fronts.length}: ${list(r.last)}.`);
+ lines.forEach((t) => h("p", {}, readout, t));
+ if (state.step >= 3) {
+ if (!r.contributions) h("p", { class: "vf-step-text" }, readout, "One member: removed without computing any hypervolume.");
+ else table(readout, ["Point", "Objectives", "Contribution"], r.last.map((i, k) => [names[i], pair(state.Q[i]), fmt(r.contributions[k], 4)]), [false, true, true]);
+ }
+ if (state.step >= 4) {
+ const k = r.last.indexOf(r.removed);
+ const what = r.contributions ? `SMS-EMOA removes ${names[r.removed]} (contribution ${fmt(r.contributions[k], 4)}).` : `SMS-EMOA removes ${names[r.removed]}: it is alone in the last front.`;
+ h("p", { class: "vf-step-text" }, readout, what + (r.removed === 6 ? " The child loses: the population does not change." : ` C replaces ${names[r.removed]} in the population.`));
+ }
+ if (state.step === 0) h("p", {}, readout, "Six parents and one child compete for six places. Press Next step.");
+ }
+ render();
+ };
+
+ /* A6-A9: one candidate set, the selection rules of CCMO, C-TAEA, ToP and CMOEA-MS. */
+ widgets["constrained-selection"] = function (node) {
+ const algo = node.getAttribute("data-rule") || "ccmo";
+ const labels = CS_CANDIDATES.map((c) => c[0]);
+ const F = CS_CANDIDATES.map((c) => [c[1], c[2]]);
+ const cv = F.map((f) => ctpViolation(f));
+ const N = 8;
+ const rules = {
+ ccmo: [
+ ["pop1", "Population 1: constraint violation first"],
+ ["pop2", "Population 2: helper problem, constraints ignored"],
+ ],
+ ctaea: [
+ ["ca", "Convergence archive (CA)"],
+ ["da", "Diversity archive (DA)"],
+ ],
+ top: [
+ ["p1", "Phase 1: single-objective, pairwise"],
+ ["p2", "Phase 2: NSGA-II with constrained dominance"],
+ ],
+ cmoeams: [
+ ["A", "Stage A: density and violation as two objectives"],
+ ["B", "Stage B: violation first"],
+ ],
+ }[algo];
+ const state = { rule: rules[0][0] };
+ const ctl = controls(node);
+ select(ctl, { label: algo === "ctaea" ? "Archive update" : algo === "top" ? "Phase" : algo === "cmoeams" ? "Stage" : "Rule", options: rules, value: state.rule, onChange: (v) => ((state.rule = v), render()) });
+ const body = h("div", { class: "vf-body" }, node);
+ const plot = createPlot(body, { x: [0, 1], y: [0, 1.6], xLabel: "f₁", yLabel: "f₂", label: "Sixteen candidates on CTP2 and the eight that the selected rule keeps" });
+ const tip = tooltip(plot);
+ const readout = h("div", { class: "vf-readout" }, body);
+ legend(node, [
+ { label: "Infeasible region", shape: "region", cls: "vf-region-2" },
+ { label: "Constrained Pareto front", shape: "line", cls: "vf-line-1" },
+ { label: "Kept, feasible", shape: "circle", cls: "vf-pt vf-pt-1" },
+ { label: "Kept, infeasible", shape: "square", cls: "vf-pt vf-pt-1" },
+ { label: "Not kept", shape: "circle", cls: "vf-pt-hollow" },
+ ]);
+ drawCtp2(plot);
+ const ccmo1 = algo === "ccmo" ? ccmoSelect(F, cv, N) : null;
+ const ccmo2 = algo === "ccmo" ? ccmoSelect(F, new Array(F.length).fill(0), N) : null;
+ const ctaea = algo === "ctaea" ? ctaeaSelect(F, cv, N) : null;
+ const top = algo === "top" ? topSelect(F, cv, N) : null;
+ const cms = algo === "cmoeams" ? cmoeamsSelect(F, cv, N) : null;
+ const list = (rows) => rows.map((i) => labels[i]).join(", ");
+ function strengthTable(res, extra) {
+ const rows = F.map((_, i) => i).sort((a, b) => res.fitness[a] - res.fitness[b] || a - b);
+ table(
+ readout,
+ ["Label"].concat(extra.map((e) => e[0]), ["Dominated by", "R", "Fitness", "Kept"]),
+ rows.map((i) => [labels[i]].concat(extra.map((e) => e[1](i)), [res.by[i].length > 6 ? `${res.by[i].length} candidates` : list(res.by[i]) || "–", String(res.R[i]), fmt(res.fitness[i], 4), res.kept.includes(i) ? "✓" : ""])),
+ [false].concat(extra.map(() => true), [false, true, true, false])
+ );
+ }
+ function render() {
+ clear(plot.layers.mid);
+ clear(plot.layers.marks);
+ clear(plot.layers.top);
+ clear(readout);
+ let kept = [];
+ const feasibleKept = () => kept.filter((i) => cv[i] <= 0).length;
+ if (algo === "ccmo") {
+ const res = state.rule === "pop1" ? ccmo1 : ccmo2;
+ kept = res.kept;
+ h("p", {}, readout, state.rule === "pop1" ? `Population 1 keeps ${feasibleKept()} of the 9 feasible candidates and ${N - feasibleKept()} infeasible ones: a smaller violation always dominates.` : `Population 2 ignores the constraints and keeps ${N - feasibleKept()} infeasible candidates and ${feasibleKept()} feasible one${feasibleKept() === 1 ? "" : "s"} (${list(kept.filter((i) => cv[i] <= 0))}), the solutions closest to the unconstrained front.`);
+ h("p", {}, readout, `Fewer than ${N} candidates have fitness below 1, so the ${N} lowest fitness values are kept. Density uses the distance d₄ to the 4th nearest candidate.`);
+ strengthTable(res, [
+ ["CV", (i) => fmt(cv[i], 4)],
+ ["d₄", (i) => fmt(res.dk[i], 4)],
+ ]);
+ } else if (algo === "ctaea") {
+ if (state.rule === "ca") {
+ kept = ctaea.CA;
+ const step = ctaea.ca.removals[0];
+ h("p", {}, readout, `${ctaea.feasible.length} of 16 candidates are feasible, ${ctaea.feasible.length - N} more than the archive holds. Fronts of the feasible candidates: ${ctaea.ca.fronts.map((f, k) => `front ${k + 1} = ${list(f)}`).join("; ")}.`);
+ if (step) h("p", { class: "vf-step-text" }, readout, `Most crowded subregion (after normalizing the selected candidates): ${step.crowded}, with ${step.counts[step.crowded]} members. Its closest pair is ${list(step.closest)}; Tchebycheff values with ideal ${pair(step.ideal, 3)}: ${step.closest.map((i, a) => `${labels[i]} ${fmt(step.tch[a])}`).join(", ")} → ${labels[step.removed]} is removed.`);
+ table(
+ readout,
+ ["Label", "CV", "Front", "Normalized subregion", "Kept"],
+ F.map((_, i) => {
+ const fr = ctaea.ca.fronts.findIndex((f) => f.includes(i));
+ const nrm = ctaea.ca.normalized.find((x) => x.i === i);
+ return [labels[i], fmt(cv[i], 4), fr >= 0 ? String(fr + 1) : "infeasible", nrm ? String(nrm.region) : "–", kept.includes(i) ? "✓" : ""];
+ }),
+ [false, true, false, true, false]
+ );
+ } else {
+ kept = ctaea.DA;
+ h("p", {}, readout, `The CA has ${ctaea.caCounts.join(", ")} members in subregions 0–7. The DA fills, round by round, the subregions where the CA has fewest, ignoring the constraints: it keeps ${N - feasibleKept()} infeasible candidates.`);
+ table(
+ readout,
+ ["Step", "Round", "Subregion", "CA members", "Candidates", "Non-dominated", "Chosen"],
+ ctaea.trace.map((t, a) => [String(a + 1), String(t.iteration), String(t.region), String(t.ca), list(t.cands), t.nd.map((i, b) => `${labels[i]} ${fmt(t.tch[b])}`).join(", "), labels[t.chosen]]),
+ [true, true, true, true, false, false, false]
+ );
+ }
+ } else if (algo === "top") {
+ if (state.rule === "p1") {
+ kept = top.next;
+ top.pairs.forEach((p) => plot.line(plot.layers.mid, [F[p.p], F[p.o]], "vf-line-thin vf-dashed"));
+ table(
+ readout,
+ ["Pair", "Parent CV, mean", "Trial CV, mean", "Winner", "Why"],
+ top.pairs.map((p) => {
+ const why = cv[p.o] < cv[p.p] ? "smaller violation" : cv[p.o] === cv[p.p] && p.om < p.pm ? "same violation, smaller mean" : cv[p.p] < cv[p.o] ? "parent: smaller violation" : "parent: not worse";
+ return [`${labels[p.p]} / ${labels[p.o]}`, `${fmt(cv[p.p], 4)}, ${fmt(p.pm, 4)}`, `${fmt(cv[p.o], 4)}, ${fmt(p.om, 4)}`, labels[p.winner], why];
+ }),
+ [false, true, true, false, false]
+ );
+ h("p", {}, readout, `Pf = ${top.next.filter((i) => cv[i] <= 0).length}/${N} = ${fmt(top.Pf)}, δ = ${fmt(top.delta)}. Phase 1 continues while δ ≥ 0.2 or Pf ≤ 1/3 (and only until 90% of the budget): ${top.phaseOneContinues ? "phase 1 continues." : "the next generation is phase 2."}`);
+ } else {
+ kept = top.kept;
+ h("p", {}, readout, `Fronts: ${top.fronts.map((f, k) => `${k + 1} = ${list(f)}`).join("; ")}. Feasible fronts by Pareto dominance, then one front per violation value.`);
+ table(
+ readout,
+ ["Label", "Front", "Crowding", "Kept"],
+ F.map((_, i) => [labels[i], String(top.fronts.findIndex((f) => f.includes(i)) + 1), fmt(top.crowd[i]), kept.includes(i) ? "✓" : ""]),
+ [false, true, true, false]
+ );
+ }
+ } else {
+ const res = state.rule === "A" ? cms.A : cms.B;
+ kept = res.kept;
+ h("p", {}, readout, `${Math.round(cms.share * 16)} of 16 candidates are feasible: ${fmt(cms.share, 4)} > λ = 0.5. VAMOS uses stage B once 10% of the evaluations are done, stage A before. ${state.rule === "A" ? `Stage A keeps ${N - feasibleKept()} infeasible candidates.` : "Stage B keeps only feasible candidates."}`);
+ strengthTable(
+ res,
+ state.rule === "A"
+ ? [
+ ["SDE", (i) => fmt(cms.sde[i], 4)],
+ ["CVn", (i) => fmt(cms.cvn[i], 4)],
+ ]
+ : [["CVn", (i) => fmt(cms.cvn[i], 4)]]
+ );
+ }
+ if (algo === "ctaea") {
+ ctaea.W.forEach((w, k) => {
+ plot.line(plot.layers.mid, [[0, 0], [w[0] * 3, w[1] * 3]], "vf-line-thin");
+ const t = Math.min(0.97 / Math.max(w[0], 1e-6), 1.55 / Math.max(w[1], 1e-6));
+ txt(plot.layers.top, plot.x(w[0] * t) + (k === 0 ? 5 : -10), plot.y(w[1] * t) + 12, String(k), { class: "vf-mark-label" });
+ });
+ }
+ const strength = algo === "ccmo" ? (state.rule === "pop1" ? ccmo1 : ccmo2) : algo === "cmoeams" ? (state.rule === "A" ? cms.A : cms.B) : null;
+ const detail = (i) => {
+ if (strength) {
+ const dom = strength.by[i].length > 6 ? `${strength.by[i].length} candidates` : list(strength.by[i]) || "nobody";
+ const extra = algo === "cmoeams" ? ` · SDE ${fmt(cms.sde[i], 4)} · CVn ${fmt(cms.cvn[i], 4)}` : "";
+ return `${extra} · dominated by ${dom} · fitness ${fmt(strength.fitness[i], 4)}`;
+ }
+ if (algo === "top" && state.rule === "p2") return ` · front ${top.fronts.findIndex((fr) => fr.includes(i)) + 1} · crowding ${fmt(top.crowd[i])}`;
+ if (algo === "ctaea") return ` · subregion ${ctaea.regions[i]}`;
+ return "";
+ };
+ F.forEach((f, i) => {
+ const px = plot.x(f[0]);
+ const py = plot.y(f[1]);
+ const hit = s("circle", { cx: px, cy: py, r: 11, class: "vf-hit" }, plot.layers.marks);
+ marker(plot.layers.marks, cv[i] > 0 ? "square" : "circle", px, py, 5.5, kept.includes(i) ? "vf-pt vf-pt-1" : "vf-pt-hollow");
+ attachTip(hit, tip, () => `${labels[i]} · f = ${pair(f, 3)} · CV ${fmt(cv[i], 4)}${detail(i)}${kept.includes(i) ? " · kept" : ""}`, px, py);
+ txt(plot.layers.top, px + 8, py - 6, labels[i], { class: "vf-mark-label" });
+ });
+ }
+ render();
+ };
+
+ /* A4: AGE-MOEA curvature estimate and survival score. */
+ widgets["agemoea-geometry"] = function (node) {
+ const angles = [90, 82, 71, 62, 53, 41, 29, 17, 8, 0];
+ const state = { p: 2, N: 6, euclid: false };
+ const ctl = controls(node);
+ slider(ctl, { label: "True p", min: 0.5, max: 3, step: 0.1, value: state.p, format: (v) => v.toFixed(1), onInput: (v) => ((state.p = v), render()) });
+ slider(ctl, { label: "Survivors N", min: 2, max: 10, step: 1, value: state.N, format: (v) => String(v), onInput: (v) => ((state.N = v), render()) });
+ checkbox(ctl, { label: "What if: Euclidean distances (p = 2)", checked: false, onChange: (v) => ((state.euclid = v), render()) });
+ const body = h("div", { class: "vf-body" }, node);
+ const plot = createPlot(body, { x: [0, 1.1], y: [0, 1.1], xLabel: "f₁", yLabel: "f₂", label: "Ten points on a front of curvature p, AGE-MOEA's estimate and its survival scores" });
+ const readout = h("div", { class: "vf-readout" }, body);
+ legend(node, [
+ { label: "True front f₁ᵖ + f₂ᵖ = 1", shape: "line", cls: "vf-front" },
+ { label: "Fitted front with the estimate p̂", shape: "line", cls: "vf-line-1" },
+ { label: "Kept (selection order shown)", shape: "circle", cls: "vf-pt vf-pt-1" },
+ { label: "Dropped", shape: "circle", cls: "vf-pt-hollow" },
+ { label: "Central point used for p̂", shape: "circle", cls: "vf-ring" },
+ ]);
+ function points(p) {
+ return angles.map((deg) => {
+ const t = (deg * Math.PI) / 180;
+ const c = deg === 90 ? 0 : Math.cos(t);
+ const sn = deg === 0 ? 0 : Math.sin(t);
+ const r = Math.pow(Math.pow(c, p) + Math.pow(sn, p), -1 / p);
+ return [r * c, r * sn];
+ });
+ }
+ function curve(p) {
+ return frontPoints((t) => Math.pow(Math.max(0, 1 - Math.pow(t, p)), 1 / p), 0, 1, 201);
+ }
+ function render() {
+ const F = points(state.p);
+ const res = agemoeaSurvival(F, state.euclid ? 2 : undefined);
+ const kept = new Set(agemoeaCut(res.score, state.N));
+ clear(plot.layers.mid);
+ clear(plot.layers.marks);
+ clear(plot.layers.top);
+ plot.line(plot.layers.mid, [[0, 0], [1.1, 1.1]], "vf-line-thin vf-dashed");
+ plot.line(plot.layers.mid, curve(state.p), "vf-front");
+ plot.line(plot.layers.mid, curve(res.estimated), "vf-line-1");
+ F.forEach((f, i) => {
+ const px = plot.x(f[0]);
+ const py = plot.y(f[1]);
+ marker(plot.layers.marks, "circle", px, py, 5.5, kept.has(i) ? "vf-pt vf-pt-1" : "vf-pt-hollow");
+ if (i === res.central) marker(plot.layers.marks, "circle", px, py, 10, "vf-ring");
+ const ord = res.order.indexOf(i) + 1;
+ txt(plot.layers.top, px + 8, py - 6, `${i + 1}${kept.has(i) ? " ·" + ord : ""}`, { class: "vf-mark-label" });
+ });
+ clear(readout);
+ const c = F[res.central];
+ h("p", {}, readout, `Estimated p̂ = ${fmt(res.estimated)} (true p = ${state.p.toFixed(1)}) · central point ${res.central + 1} = ${pair(c, 3)}.`);
+ if (state.euclid) h("p", {}, readout, "What if: proximities and distances measured with p = 2 instead of p̂. This is not a VAMOS option; it shows why the estimate matters.");
+ table(
+ readout,
+ ["Point", "f₁", "f₂", "Proximity", "Score", "Order", "Status"],
+ F.map((f, i) => [String(i + 1), fmt(f[0], 3), fmt(f[1], 3), fmt(res.proximity[i]), fmt(res.score[i]), String(res.order.indexOf(i) + 1), kept.has(i) ? "kept" : "dropped"]),
+ [true, true, true, true, true, true, false]
+ );
+ }
+ render();
+ };
+
+ /* A2: NSGA-III association and niche preservation. */
+ widgets["nsga3-niching"] = function (node) {
+ const W = [0, 1, 2, 3, 4, 5].map((k) => [k / 5, 1 - k / 5]);
+ const data = [
+ ["A", 0, 1, 1],
+ ["B", 0.09, 0.99, 1],
+ ["C", 0.5, 0.87, 1],
+ ["D", 0.87, 0.5, 1],
+ ["E", 1, 0, 1],
+ ["F", 0.06, 1.18, 2],
+ ["G", 0.3, 1.1, 2],
+ ["H", 0.41, 1.02, 2],
+ ["I", 0.61, 0.975, 2],
+ ["J", 0.72, 0.9, 2],
+ ["K", 1.105, 0.317, 2],
+ ["L", 0.2, 1.3, 3],
+ ["M", 0.5, 1.2, 3],
+ ["N", 0.68, 1.12, 3],
+ ["O", 0.8, 1.05, 3],
+ ["P", 1, 0.95, 3],
+ ["Q", 1.2, 0.4, 3],
+ ["R", 1.3, 0.35, 3],
+ ].map(([id, f1, f2, front]) => ({ id, f: [f1, f2], front, ...nsga3Associate([f1, f2], W) }));
+ const state = { N: 9, seed: 7, step: 0, focus: null };
+ const ctl = controls(node);
+ slider(ctl, { label: "Population size N", min: 6, max: 10, step: 1, value: state.N, format: (v) => String(v), onInput: (v) => ((state.N = v), (state.step = 0), render()) });
+ button(ctl, "Step", () => ((state.step += 1), render()), true);
+ button(ctl, "Fill", () => ((state.step = 99), render()));
+ button(ctl, "Reset", () => ((state.step = 0), render()));
+ button(ctl, "Reshuffle", () => ((state.seed = Math.floor(Math.random() * 1e6)), (state.step = 0), render()));
+ const body = h("div", { class: "vf-body vf-body--side" }, node);
+ const plot = createPlot(body, { x: [0, 1.4], y: [0, 1.4], xLabel: "f₁ (normalized)", yLabel: "f₂ (normalized)", label: "NSGA-III reference directions, associations and niche preservation" });
+ const tip = tooltip(plot);
+ const readout = h("div", { class: "vf-readout" }, body);
+ legend(node, [
+ { label: "Front 1, already selected", shape: "circle", cls: "vf-pt vf-pt-1" },
+ { label: "Front 2 (last front), candidate", shape: "circle", cls: "vf-pt-hollow" },
+ { label: "Picked by niching (round shown)", shape: "circle", cls: "vf-pt vf-pt-2" },
+ { label: "Front 3, not examined", shape: "circle", cls: "vf-pt vf-pt-muted vf-faded" },
+ ]);
+ function render() {
+ const rho0 = W.map((_, j) => data.filter((d) => d.front === 1 && d.dir === j).length);
+ const cands = data.filter((d) => d.front === 2);
+ const K = state.N - 5;
+ const all = nsga3Niching(rho0, cands, K, mulberry32(state.seed));
+ const shown = all.picks.slice(0, Math.min(state.step, all.picks.length));
+ const picked = new Map(shown.map((p) => [p.id, p.round]));
+ const rho = rho0.slice();
+ shown.forEach((p) => (rho[p.dir] += 1));
+ clear(plot.layers.mid);
+ clear(plot.layers.marks);
+ clear(plot.layers.top);
+ plot.line(plot.layers.mid, [[0, 1], [1, 0]], "vf-front");
+ W.forEach((w, j) => {
+ const t = 1.38 / Math.max(w[0], w[1]);
+ plot.line(plot.layers.mid, [[0, 0], [w[0] * t, w[1] * t]], "vf-line-thin");
+ txt(plot.layers.top, plot.x(w[0] * t * 0.97) + (j === 0 ? 5 : j === 1 ? 5 : -18), plot.y(w[1] * t * 0.97) + (j === 5 ? -8 : j < 2 ? 10 : 4), `w${j + 1}`, { class: "vf-mark-label" });
+ });
+ data.forEach((d) => {
+ const px = plot.x(d.f[0]);
+ const py = plot.y(d.f[1]);
+ const w = W[d.dir];
+ const wn = Math.hypot(w[0], w[1]);
+ const dot = (d.f[0] * w[0] + d.f[1] * w[1]) / wn;
+ if (d.front === 2 || state.focus === d.id) plot.line(plot.layers.mid, [d.f, [(dot * w[0]) / wn, (dot * w[1]) / wn]], state.focus === d.id ? "vf-line-2" : "vf-line-thin vf-dashed");
+ const cls = d.front === 1 ? "vf-pt vf-pt-1" : d.front === 3 ? "vf-pt vf-pt-muted vf-faded" : picked.has(d.id) ? "vf-pt vf-pt-2" : "vf-pt-hollow";
+ const hit = s("circle", { cx: px, cy: py, r: 11, class: "vf-hit" }, plot.layers.marks);
+ const mark = marker(plot.layers.marks, "circle", px, py, 5.5, cls);
+ const show = () => {
+ tip.show(`${d.id} · front ${d.front} · w${d.dir + 1} · d⊥ ${fmt(d.dperp, 4)}`, px, py);
+ if (state.focus !== d.id) {
+ state.focus = d.id;
+ render();
+ }
+ };
+ hit.addEventListener("pointerenter", show);
+ mark.addEventListener("pointerenter", show);
+ hit.addEventListener("pointerleave", () => tip.hide());
+ txt(plot.layers.top, px + 8, py - 6, d.id + (picked.has(d.id) ? " ·" + picked.get(d.id) : ""), { class: "vf-mark-label" });
+ });
+ clear(readout);
+ h("p", {}, readout, picked.size >= K ? `Population full: ${data.filter((d) => d.front === 1 || picked.has(d.id)).map((d) => d.id).join(" ")}.` : `Selected ${5 + picked.size} of ${state.N} · places left ${K - picked.size}.`);
+ shown.forEach((p) => {
+ const d = data.find((x) => x.id === p.id);
+ h("p", { class: "vf-step-text" }, readout, `Round ${p.round} · smallest count ${p.low} → ${p.Jmin.map((j) => "w" + (j + 1)).join(", ")} · w${p.dir + 1} has count ${p.count}: ${p.closest ? `closest candidate ${p.id} (d⊥ ${fmt(d.dperp, 3)})` : `random candidate ${p.id}`}`);
+ });
+ table(
+ readout,
+ ["Direction", "ρ", "Last-front candidates"],
+ W.map((_, j) => ["w" + (j + 1), String(rho[j]), cands.filter((c) => c.dir === j).map((c) => c.id).join(", ") || "none"]),
+ [false, true, false]
+ );
+ }
+ render();
+ };
+
+ /* ------------------------------------------------------------------ */
+ /* Boot */
+ /* ------------------------------------------------------------------ */
+
+ function init() {
+ document.querySelectorAll("[data-vf-widget]").forEach((node) => {
+ if (node.getAttribute("data-vf-ready")) return;
+ const build = widgets[node.getAttribute("data-vf-widget")];
+ if (!build) return;
+ node.setAttribute("data-vf-ready", "true");
+ clear(node);
+ build(node);
+ });
+ }
+
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init);
+ else init();
+ if (typeof document$ !== "undefined") document$.subscribe(init);
+})(typeof window !== "undefined" ? window : globalThis);
diff --git a/docs/stylesheets/foundations.css b/docs/stylesheets/foundations.css
new file mode 100644
index 000000000..6a220427c
--- /dev/null
+++ b/docs/stylesheets/foundations.css
@@ -0,0 +1,437 @@
+/* Foundations learning path: interactive figures and lesson furniture.
+ Series colours are the first three validated categorical slots (blue, orange,
+ aqua) stepped separately for the light and dark schemes. Aqua sits below 3:1
+ on the light surface, so it is only used with a distinct marker shape, a
+ legend and a numeric readout. Fronts and ranks use one ordinal blue ramp. */
+
+.md-typeset .vf-widget {
+ --vf-surface: var(--md-default-bg-color);
+ --vf-panel: #FFFFFF;
+ --vf-ink: #1F2937;
+ --vf-ink-2: #475569;
+ --vf-muted: #94A3B8;
+ --vf-grid: #E2E8F0;
+ --vf-axis: #94A3B8;
+ --vf-s1: #2a78d6;
+ --vf-s2: #eb6834;
+ --vf-s3: #1baf7a;
+ --vf-r0: #104281;
+ --vf-r1: #256abf;
+ --vf-r2: #5598e7;
+ --vf-r3: #86b6ef;
+ --vf-r4: #b7d3f6;
+ --vf-infeasible: rgba(235, 104, 52, 0.20);
+ --vf-feasible: rgba(42, 120, 214, 0.10);
+ margin: 1.5em 0;
+ padding: 0.9rem;
+ border: 1px solid var(--vamos-border);
+ border-radius: 12px;
+ background: var(--vf-panel);
+ color: var(--vf-ink);
+}
+
+[data-md-color-scheme="slate"] .md-typeset .vf-widget {
+ --vf-panel: #111F2E;
+ --vf-ink: #E5ECF2;
+ --vf-ink-2: #C3CED8;
+ --vf-muted: #6B7C8F;
+ --vf-grid: rgba(216, 226, 234, 0.10);
+ --vf-axis: #6B7C8F;
+ --vf-s1: #3987e5;
+ --vf-s2: #d95926;
+ --vf-s3: #199e70;
+ --vf-r0: #9ec5f4;
+ --vf-r1: #6da7ec;
+ --vf-r2: #3987e5;
+ --vf-r3: #256abf;
+ --vf-r4: #184f95;
+ --vf-infeasible: rgba(217, 89, 38, 0.26);
+ --vf-feasible: rgba(57, 135, 229, 0.14);
+}
+
+.md-typeset .vf-fallback {
+ margin: 0;
+ color: var(--vamos-muted);
+ font-size: 0.75rem;
+}
+
+.md-typeset .vf-title {
+ margin: 0 0 0.6rem;
+ font-size: 0.8rem;
+ font-weight: 700;
+ color: var(--vf-ink);
+}
+
+.md-typeset .vf-body {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr);
+ gap: 0.9rem;
+ align-items: start;
+}
+
+@media screen and (min-width: 52em) {
+ .md-typeset .vf-body--side {
+ grid-template-columns: minmax(0, 27rem) minmax(0, 1fr);
+ }
+ .md-typeset .vf-body--two {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+}
+
+.md-typeset .vf-plot {
+ display: block;
+ width: 100%;
+ max-width: 27rem;
+ height: auto;
+ overflow: visible;
+ font-family: var(--md-text-font-family, "DM Sans"), sans-serif;
+ user-select: none;
+ -webkit-user-select: none;
+}
+
+.md-typeset .vf-plot text {
+ fill: var(--vf-ink-2);
+ font-size: 11px;
+}
+
+.md-typeset .vf-plot .vf-axis-label {
+ fill: var(--vf-ink);
+ font-size: 12px;
+ font-weight: 600;
+}
+
+.md-typeset .vf-plot .vf-mark-label {
+ fill: var(--vf-ink);
+ font-size: 11px;
+ font-weight: 600;
+ paint-order: stroke;
+ stroke: var(--vf-panel);
+ stroke-width: 3px;
+ stroke-linejoin: round;
+}
+
+.vf-grid-line { stroke: var(--vf-grid); stroke-width: 1; }
+.vf-axis-line { fill: none; stroke: var(--vf-axis); stroke-width: 1; }
+.vf-front { fill: none; stroke: var(--vf-ink-2); stroke-width: 1.5; stroke-dasharray: 5 4; }
+.vf-line-1 { fill: none; stroke: var(--vf-s1); stroke-width: 2; }
+.vf-line-2 { fill: none; stroke: var(--vf-s2); stroke-width: 2; }
+.vf-line-3 { fill: none; stroke: var(--vf-s3); stroke-width: 2; }
+.vf-line-ink { fill: none; stroke: var(--vf-ink-2); stroke-width: 1.5; }
+.vf-line-thin { fill: none; stroke: var(--vf-ink-2); stroke-width: 1; opacity: 0.7; }
+.vf-dashed { stroke-dasharray: 4 3; }
+.vf-region-1 { fill: var(--vf-s1); opacity: 0.14; }
+.vf-region-2 { fill: var(--vf-s2); opacity: 0.16; }
+.vf-region-3 { fill: var(--vf-s3); opacity: 0.16; }
+.vf-region-strong { fill: var(--vf-s2); opacity: 0.45; }
+[data-md-color-scheme="slate"] .vf-region-1 { opacity: 0.24; }
+[data-md-color-scheme="slate"] .vf-region-2,
+[data-md-color-scheme="slate"] .vf-region-3 { opacity: 0.32; }
+[data-md-color-scheme="slate"] .vf-region-strong { opacity: 0.6; }
+.vf-pt { stroke: var(--vf-panel); stroke-width: 2; }
+.vf-pt-1 { fill: var(--vf-s1); }
+.vf-pt-2 { fill: var(--vf-s2); }
+.vf-pt-3 { fill: var(--vf-s3); }
+.vf-pt-muted { fill: var(--vf-muted); }
+.vf-pt-hollow { fill: var(--vf-panel); stroke: var(--vf-ink-2); stroke-width: 1.5; }
+.vf-pt-ink { fill: var(--vf-ink); }
+.vf-pt-thin { fill: var(--vf-ink-2); opacity: 0.7; }
+.vf-cloud { fill: var(--vf-muted); opacity: 0.55; }
+.vf-r0 { fill: var(--vf-r0); }
+.vf-r1 { fill: var(--vf-r1); }
+.vf-r2 { fill: var(--vf-r2); }
+.vf-r3 { fill: var(--vf-r3); }
+.vf-r4 { fill: var(--vf-r4); }
+.vf-faded { opacity: 0.22; }
+.vf-ring { fill: none; stroke: var(--vf-s2); stroke-width: 2.5; }
+.vf-bar-1 { fill: var(--vf-s1); }
+.vf-bar-2 { fill: var(--vf-s2); }
+
+.vf-handle {
+ cursor: grab;
+ touch-action: none;
+}
+
+.vf-handle:active {
+ cursor: grabbing;
+}
+
+.vf-handle:focus,
+.vf-focusable:focus {
+ outline: none;
+}
+
+.vf-focus {
+ fill: none;
+ stroke: none;
+}
+
+.vf-focusable:focus-visible {
+ stroke: var(--vf-s2);
+ stroke-width: 3;
+}
+
+.vf-handle:focus-visible > .vf-focus,
+.vf-handle.vf-selected > .vf-focus {
+ stroke: var(--vf-s2);
+ stroke-width: 2.5;
+ fill: none;
+}
+
+.vf-hit {
+ fill: transparent;
+ stroke: none;
+}
+
+.md-typeset .vf-controls {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem 0.9rem;
+ align-items: center;
+ margin: 0 0 0.6rem;
+ font-size: 0.72rem;
+}
+
+.md-typeset .vf-controls label {
+ display: inline-flex;
+ flex-wrap: wrap;
+ gap: 0.35rem;
+ align-items: center;
+ max-width: 100%;
+ min-width: 0;
+ color: var(--vf-ink-2);
+}
+
+.md-typeset .vf-controls input[type="range"] {
+ width: 8.5rem;
+ max-width: 100%;
+ accent-color: var(--vf-s1);
+}
+
+.md-typeset .vf-controls output {
+ min-width: 2.6rem;
+ font-family: var(--md-code-font-family), monospace;
+ color: var(--vf-ink);
+}
+
+.md-typeset .vf-controls select {
+ max-width: 100%;
+ min-width: 0;
+ padding: 0.15rem 0.3rem;
+ border: 1px solid var(--vamos-border);
+ border-radius: 6px;
+ background: var(--vf-panel);
+ color: var(--vf-ink);
+ font: inherit;
+}
+
+.md-typeset .vf-button {
+ padding: 0.3rem 0.75rem;
+ border: 1px solid var(--vamos-border);
+ border-radius: 999px;
+ background: var(--vf-panel);
+ color: var(--vf-ink);
+ font: inherit;
+ font-weight: 600;
+ cursor: pointer;
+}
+
+.md-typeset .vf-button:hover {
+ border-color: var(--vf-s1);
+}
+
+.md-typeset .vf-button--primary {
+ border-color: var(--vf-s1);
+ background: var(--vf-s1);
+ color: #FFFFFF;
+}
+
+.md-typeset .vf-button:disabled {
+ cursor: default;
+ opacity: 0.45;
+}
+
+.md-typeset .vf-button:focus-visible,
+.md-typeset .vf-controls input:focus-visible,
+.md-typeset .vf-controls select:focus-visible {
+ outline: 3px solid var(--vamos-teal);
+ outline-offset: 2px;
+}
+
+.md-typeset .vf-readout {
+ font-size: 0.72rem;
+ line-height: 1.55;
+ color: var(--vf-ink);
+}
+
+.md-typeset .vf-readout p {
+ margin: 0 0 0.5em;
+}
+
+.md-typeset .vf-readout table:not([class]) {
+ display: table;
+ width: 100%;
+ margin: 0.2em 0 0.6em;
+ font-size: 0.7rem;
+ border: 1px solid var(--vamos-border);
+ border-radius: 8px;
+}
+
+.md-typeset .vf-readout table:not([class]) th,
+.md-typeset .vf-readout table:not([class]) td {
+ min-width: 0;
+ padding: 0.3em 0.5em;
+}
+
+.md-typeset .vf-table-wrap {
+ max-width: 100%;
+ overflow-x: auto;
+}
+
+.md-typeset .vf-readout td.vf-num,
+.md-typeset .vf-readout th.vf-num {
+ text-align: right;
+ font-family: var(--md-code-font-family), monospace;
+}
+
+.md-typeset .vf-legend {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.3rem 0.9rem;
+ margin: 0.4rem 0 0;
+ padding: 0;
+ list-style: none;
+ font-size: 0.68rem;
+ color: var(--vf-ink-2);
+}
+
+.md-typeset .vf-legend li {
+ display: inline-flex;
+ gap: 0.35rem;
+ align-items: center;
+ margin: 0;
+}
+
+.md-typeset .vf-legend svg {
+ width: 14px;
+ height: 14px;
+ flex: none;
+}
+
+.md-typeset .vf-step-text {
+ min-height: 3.2em;
+ padding: 0.5em 0.7em;
+ border-left: 3px solid var(--vf-s1);
+ border-radius: 0 6px 6px 0;
+ background: color-mix(in srgb, var(--vf-s1) 7%, transparent);
+}
+
+.md-typeset .vf-tooltip {
+ position: absolute;
+ z-index: 3;
+ padding: 0.25rem 0.5rem;
+ border: 1px solid var(--vamos-border);
+ border-radius: 6px;
+ background: var(--vf-panel);
+ color: var(--vf-ink);
+ font-size: 0.66rem;
+ line-height: 1.4;
+ white-space: nowrap;
+ pointer-events: none;
+ box-shadow: 0 4px 14px rgba(11, 37, 69, 0.14);
+}
+
+.md-typeset .vf-plot-wrap {
+ position: relative;
+ max-width: 27rem;
+}
+
+/* Lesson furniture */
+
+.md-typeset .vf-level-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(13rem, 1fr));
+ gap: 0.9rem;
+ margin: 1.2em 0 1.6em;
+}
+
+.md-typeset .vf-level {
+ padding: 1rem 1.1rem;
+ border: 1px solid var(--vamos-border);
+ border-radius: 12px;
+ background: var(--md-default-bg-color);
+}
+
+.md-typeset .vf-level h3 {
+ margin: 0 0 0.4em;
+ font-size: 0.95rem;
+}
+
+.md-typeset .vf-level p {
+ margin: 0 0 0.6em;
+ font-size: 0.75rem;
+}
+
+.md-typeset .vf-level ol {
+ margin: 0;
+ font-size: 0.74rem;
+}
+
+.md-typeset .vf-formula {
+ margin: 1em 0;
+ padding: 0.7em 1em;
+ overflow-x: auto;
+ border-left: 3px solid var(--vamos-teal);
+ border-radius: 0 8px 8px 0;
+ background: var(--md-code-bg-color);
+ font-family: var(--md-code-font-family), monospace;
+ font-size: 0.78rem;
+ line-height: 1.7;
+ white-space: pre-wrap;
+}
+
+.md-typeset .vf-diagram {
+ display: block;
+ width: 100%;
+ max-width: 40rem;
+ height: auto;
+ margin: 1em auto;
+ color: var(--md-default-fg-color);
+}
+
+.md-typeset .vf-diagram .vf-box {
+ fill: var(--md-code-bg-color);
+ stroke: var(--vamos-teal-dark);
+ stroke-width: 1.5;
+}
+
+[data-md-color-scheme="slate"] .md-typeset .vf-diagram .vf-box {
+ stroke: #5EEAD4;
+}
+
+.md-typeset .vf-diagram text {
+ fill: currentColor;
+ font-size: 13px;
+}
+
+.md-typeset .vf-diagram .vf-diagram-small {
+ font-size: 11px;
+ opacity: 0.8;
+}
+
+.md-typeset .vf-diagram .vf-arrow {
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.5;
+ opacity: 0.7;
+}
+
+.md-typeset .vf-diagram .vf-arrowhead {
+ fill: currentColor;
+ opacity: 0.7;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .md-typeset .vf-widget * {
+ transition: none !important;
+ }
+}
diff --git a/docs/tutorials/index.md b/docs/tutorials/index.md
index 84174de17..7488a2ab5 100644
--- a/docs/tutorials/index.md
+++ b/docs/tutorials/index.md
@@ -9,6 +9,8 @@ search:
Learn a workflow from its first run to an interpretable result. Start with the
route that matches your question; each link below leads to an existing worked
example. For a single operation, use the [How-to Guides](../guide/index.md).
+For the concepts behind the lessons, such as Pareto dominance, quality
+indicators and how NSGA-II works, follow the [Foundations](../foundations/index.md) path.
## Choose a learning path
diff --git a/docs/tutorials/t07-quality-and-budget.md b/docs/tutorials/t07-quality-and-budget.md
index 535d8ef56..0f8ba2853 100644
--- a/docs/tutorials/t07-quality-and-budget.md
+++ b/docs/tutorials/t07-quality-and-budget.md
@@ -34,7 +34,7 @@ of convergence.
| Interface status | **Stable** study/result loading and `verify_run`; MooCore is an optional third-party indicator API |
| Work | Load and measure; **no optimization executes** |
-## Fix the measurement rule
+## Fix the measurement rule: hypervolume and IGD+
All objectives are minimized and use their original units. Each run contributes
its returned population's non-dominated subset. These two benchmarks are
diff --git a/mkdocs.yml b/mkdocs.yml
index 06345ad8e..68c16a9e9 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -45,10 +45,12 @@ theme:
extra_css:
- stylesheets/vamos.css
- stylesheets/home-hero.css
+ - stylesheets/foundations.css
extra_javascript:
- javascripts/api-reference.js
- javascripts/site-navigation.js
+ - javascripts/foundations.js
markdown_extensions:
- admonition
@@ -218,3 +220,33 @@ nav:
- Architecture Health: dev/architecture_health.md
- Repository Hygiene: dev/repository_hygiene.md
- Release Verification: release_smoke.md
+ - Foundations:
+ - Overview: foundations/index.md
+ - Basic:
+ - B1. Multi-objective Problems: foundations/basic/multi-objective-problems.md
+ - B2. Pareto Dominance: foundations/basic/pareto-dominance.md
+ - B3. Quality Aspects: foundations/basic/quality-aspects.md
+ - B4. Quality Indicators: foundations/basic/quality-indicators.md
+ - Intermediate:
+ - I1. NSGA-II at a Glance: foundations/intermediate/nsga-ii.md
+ - I2. Non-dominated Sorting: foundations/intermediate/non-dominated-sorting.md
+ - I3. Crowding and Tournaments: foundations/intermediate/crowding-distance.md
+ - I4. SBX and Polynomial Mutation: foundations/intermediate/variation-operators.md
+ - I5. Elitist Survival: foundations/intermediate/elitist-survival.md
+ - I6. Beyond NSGA-II: foundations/intermediate/beyond-nsga-ii.md
+ - I7. SPEA2: foundations/intermediate/spea2.md
+ - I8. MOEA/D: foundations/intermediate/moead.md
+ - I9. SMS-EMOA: foundations/intermediate/smsemoa.md
+ - I10. IBEA: foundations/intermediate/ibea.md
+ - I11. SMPSO: foundations/intermediate/smpso.md
+ - Advanced:
+ - A1. Many Objectives: foundations/advanced/many-objective.md
+ - A2. NSGA-III: foundations/advanced/nsga-iii.md
+ - A3. RVEA: foundations/advanced/rvea.md
+ - A4. AGE-MOEA: foundations/advanced/agemoea.md
+ - A5. Constraints: foundations/advanced/constrained.md
+ - A6. CCMO: foundations/advanced/ccmo.md
+ - A7. C-TAEA: foundations/advanced/ctaea.md
+ - A8. ToP: foundations/advanced/top.md
+ - A9. CMOEA-MS: foundations/advanced/cmoeams.md
+ - A10. Rigorous Comparison: foundations/advanced/performance-assessment.md
diff --git a/tests/docs/smoke_manifest.py b/tests/docs/smoke_manifest.py
index 53d673e76..c97ea8978 100644
--- a/tests/docs/smoke_manifest.py
+++ b/tests/docs/smoke_manifest.py
@@ -425,4 +425,54 @@ def build_my_algorithm(cfg: dict[str, Any], kernel: KernelBackend | None = None)
subprocess.run([sys.executable, "-c", (chr(10) * 2).join(blocks)], cwd=tmp, check=True)
""",
),
+ # The Foundations learning path runs every example of a lesson from the page itself;
+ # tests/docs/test_foundations.py also compares their printed output with the documented one.
+ *[
+ DocSmokeCase(
+ name=f"foundations_{page.replace('/', '_').replace('-', '_')}",
+ source_path=f"docs/foundations/{page}.md",
+ code=f"""
+import re
+from pathlib import Path
+
+import pytest
+
+text = Path("docs/foundations/{page}.md").read_text(encoding="utf-8")
+blocks = re.findall(r"^```python\\n(.*?)^```", text, flags=re.MULTILINE | re.DOTALL)
+examples = [block for block in blocks if not block.startswith("# Excerpt from ")]
+assert examples, "docs/foundations/{page}.md has no runnable example"
+if any("moocore" in example for example in examples):
+ pytest.importorskip("moocore")
+for example in examples:
+ exec(compile(example, "docs/foundations/{page}.md", "exec"), {{"__name__": "__foundations_example__"}})
+""",
+ )
+ for page in (
+ "basic/multi-objective-problems",
+ "basic/pareto-dominance",
+ "basic/quality-aspects",
+ "basic/quality-indicators",
+ "intermediate/nsga-ii",
+ "intermediate/non-dominated-sorting",
+ "intermediate/crowding-distance",
+ "intermediate/variation-operators",
+ "intermediate/elitist-survival",
+ "intermediate/beyond-nsga-ii",
+ "intermediate/spea2",
+ "intermediate/moead",
+ "intermediate/smsemoa",
+ "intermediate/ibea",
+ "intermediate/smpso",
+ "advanced/many-objective",
+ "advanced/nsga-iii",
+ "advanced/rvea",
+ "advanced/agemoea",
+ "advanced/constrained",
+ "advanced/ccmo",
+ "advanced/ctaea",
+ "advanced/top",
+ "advanced/cmoeams",
+ "advanced/performance-assessment",
+ )
+ ],
]
diff --git a/tests/docs/test_documentation_architecture.py b/tests/docs/test_documentation_architecture.py
index d1b5773ac..dc159bd78 100644
--- a/tests/docs/test_documentation_architecture.py
+++ b/tests/docs/test_documentation_architecture.py
@@ -33,6 +33,7 @@ def test_public_navigation_is_task_first() -> None:
"How-to Guides",
"Reference",
"Developer",
+ "Foundations",
]
nav_text = yaml.safe_dump(nav, sort_keys=False)
diff --git a/tests/docs/test_foundations.py b/tests/docs/test_foundations.py
new file mode 100644
index 000000000..e7fe83603
--- /dev/null
+++ b/tests/docs/test_foundations.py
@@ -0,0 +1,232 @@
+"""The Foundations learning path: navigation, metadata, figures, examples and source excerpts."""
+
+from __future__ import annotations
+
+import contextlib
+import io
+import json
+import re
+import shutil
+import subprocess
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+import pytest
+import yaml
+
+from vamos.foundation.kernel.numpy_backend import _compute_crowding, _fast_non_dominated_sort
+from vamos.foundation.quality_indicators.hypervolume import hypervolume, hypervolume_contributions
+
+from .smoke_manifest import DOC_SMOKE_CASES
+
+ROOT = Path(__file__).resolve().parents[2]
+DOCS = ROOT / "docs"
+FOUNDATIONS = DOCS / "foundations"
+SCRIPT = DOCS / "javascripts" / "foundations.js"
+PAGES = sorted(FOUNDATIONS.rglob("*.md"))
+LESSONS = [page for page in PAGES if page.name != "index.md"]
+FENCE = re.compile(r"^```(?P[\w-]*)\n(?P.*?)^```[ \t]*$", re.MULTILINE | re.DOTALL)
+EXCERPT = re.compile(r"\A# Excerpt from (?P\S+)\n")
+NUMBER = re.compile(r"-?\d+(?:\.\d+)?(?:e[-+]?\d+)?")
+
+
+def _relative(page: Path) -> str:
+ return page.relative_to(DOCS).as_posix()
+
+
+def _nav_pages(node: object) -> list[str]:
+ if isinstance(node, str):
+ return [node]
+ if isinstance(node, list):
+ return [page for item in node for page in _nav_pages(item)]
+ if isinstance(node, dict):
+ return [page for value in node.values() for page in _nav_pages(value)]
+ return []
+
+
+def _config() -> dict[str, object]:
+ return yaml.safe_load((ROOT / "mkdocs.yml").read_text(encoding="utf-8"))
+
+
+def _foundations_nav() -> list[object]:
+ nav = _config()["nav"]
+ assert isinstance(nav, list)
+ return next(item["Foundations"] for item in nav if isinstance(item, dict) and "Foundations" in item)
+
+
+def _blocks(text: str) -> list[tuple[str, str, int, int]]:
+ return [(m["lang"], m["body"], m.start(), m.end()) for m in FENCE.finditer(text)]
+
+
+def _examples(page: Path) -> list[tuple[str, str]]:
+ """Each runnable Python block with the text block that documents its output."""
+ text = page.read_text(encoding="utf-8")
+ blocks = _blocks(text)
+ examples = []
+ for index, (lang, body, _, end) in enumerate(blocks):
+ if lang != "python" or EXCERPT.match(body):
+ continue
+ assert index + 1 < len(blocks), f"{_relative(page)}: an example has no documented output"
+ next_lang, next_body, next_start, _ = blocks[index + 1]
+ between = text[end:next_start].strip()
+ assert next_lang == "text" and between == "Output:", f"{_relative(page)}: an example must be followed by 'Output:' and a text block"
+ examples.append((body, next_body))
+ return examples
+
+
+def _excerpts() -> list[tuple[str, str, str]]:
+ found = []
+ for page in PAGES:
+ for lang, body, _, _ in _blocks(page.read_text(encoding="utf-8")):
+ match = EXCERPT.match(body)
+ if lang == "python" and match:
+ found.append((_relative(page), match["path"], body[match.end() :]))
+ return found
+
+
+def test_foundations_follows_developer_with_three_levels() -> None:
+ nav = _config()["nav"]
+ titles = [next(iter(item)) for item in nav if isinstance(item, dict)]
+ assert titles[-2:] == ["Developer", "Foundations"]
+
+ foundations = _foundations_nav()
+ assert foundations[0] == {"Overview": "foundations/index.md"}
+ assert [next(iter(item)) for item in foundations[1:]] == ["Basic", "Intermediate", "Advanced"]
+
+ listed = _nav_pages(foundations)
+ assert sorted(listed) == sorted(_relative(page) for page in PAGES)
+ all_pages = _nav_pages(nav)
+ assert [page for page in listed if all_pages.count(page) != 1] == []
+
+
+def test_assets_are_loaded_by_the_site() -> None:
+ config = _config()
+ assert "stylesheets/foundations.css" in config["extra_css"]
+ assert "javascripts/foundations.js" in config["extra_javascript"]
+
+
+@pytest.mark.parametrize("page", PAGES, ids=_relative)
+def test_pages_have_metadata_one_title_and_sources(page: Path) -> None:
+ text = page.read_text(encoding="utf-8")
+ metadata = yaml.safe_load(text.split("---", 2)[1])
+ assert isinstance(metadata.get("description"), str) and metadata["description"].strip()
+
+ prose = FENCE.sub("", text.split("---", 2)[2])
+ assert len(re.findall(r"^# ", prose, flags=re.MULTILINE)) == 1
+ if page in LESSONS:
+ assert "## Key points" in prose
+ assert "## References" in prose
+ groups = [[int(n) for n in group.split(", ")] for group in re.findall(r"\[(\d+(?:, \d+)*)\]", prose)]
+ cited = {n for group in groups if 0 not in group for n in group} # [0, 1] is an interval
+ listed = {int(n) for n in re.findall(r"^\[(\d+)\] ", prose, flags=re.MULTILINE)}
+ assert cited <= listed, f"cited but not listed: {sorted(cited - listed)}"
+
+
+def test_every_figure_is_implemented_and_has_a_fallback() -> None:
+ script = SCRIPT.read_text(encoding="utf-8")
+ implemented = set(re.findall(r'widgets\["([\w-]+)"\] = ', script)) | set(re.findall(r"widgets\.(\w+) = ", script))
+ used: set[str] = set()
+ for page in PAGES:
+ for name, inner in re.findall(
+ r']*>(.*?)
', page.read_text(encoding="utf-8")
+ ):
+ assert 'class="vf-fallback"' in inner, f"{_relative(page)}: {name} needs a fallback paragraph"
+ used.add(name)
+ assert used and used <= implemented, sorted(used - implemented)
+ assert implemented <= used, f"figures implemented but never used: {sorted(implemented - used)}"
+
+
+@pytest.mark.parametrize("excerpt", _excerpts(), ids=lambda item: f"{item[0]}:{item[1]}")
+def test_source_excerpts_are_verbatim_vamos_code(excerpt: tuple[str, str, str]) -> None:
+ page, source, body = excerpt
+ lines = (ROOT / source).read_text(encoding="utf-8").splitlines()
+ position = 0
+ for line in (line for line in body.splitlines() if line.strip()):
+ try:
+ position = lines.index(line, position) + 1
+ except ValueError:
+ pytest.fail(f"{page}: line not found in order in {source}: {line!r}")
+
+
+@pytest.mark.parametrize("page", [page for page in PAGES if _examples(page)], ids=_relative)
+def test_examples_run_and_print_the_documented_output(page: Path) -> None:
+ for code, documented in _examples(page):
+ if "moocore" in code:
+ pytest.importorskip("moocore")
+ stdout = io.StringIO()
+ with contextlib.redirect_stdout(stdout):
+ exec(compile(code, str(page), "exec"), {"__name__": "__foundations_example__"}) # noqa: S102
+ printed = stdout.getvalue()
+ if "optimize(" in code:
+ # An optimization run is repeatable in one environment, not bitwise identical
+ # everywhere: compare the printed structure and leave the digits free.
+ assert NUMBER.sub("#", printed) == NUMBER.sub("#", documented), printed
+ else:
+ assert printed == documented, printed
+
+
+def _run_figure_algorithms(cases: list[np.ndarray], ref: list[float]) -> list[dict[str, Any]]:
+ """Evaluate the figures' JavaScript algorithms on each set with Node.js."""
+ program = f"""
+require({json.dumps(str(SCRIPT))});
+const V = globalThis.VamosFoundations;
+const ref = {json.dumps(ref)};
+const results = {json.dumps([case.tolist() for case in cases])}.map((F) => {{
+ const sorted = V.nonDominatedSort(F);
+ return {{
+ rank: sorted.rank,
+ crowding: sorted.fronts.map((front) => V.crowdingDistance(F, front).map((d) => (Number.isFinite(d) ? d : null))),
+ fronts: sorted.fronts,
+ hv: V.hypervolume2d(F, ref),
+ contributions: V.hvContributions2d(F, ref).contributions,
+ }};
+}});
+process.stdout.write(JSON.stringify(results));
+"""
+ completed = subprocess.run(["node", "-e", program], capture_output=True, text=True, check=True, timeout=60)
+ return json.loads(completed.stdout)
+
+
+@pytest.mark.skipif(shutil.which("node") is None, reason="the figures' script runs under Node.js")
+def test_figure_algorithms_agree_with_vamos() -> None:
+ rng = np.random.default_rng(20261119)
+ ref = [1.1, 1.1]
+ cases = [rng.random((int(rng.integers(4, 15)), 2)) for _ in range(20)]
+ for case in cases[::4]:
+ case[1] = case[0] # duplicated points
+ cases.append(np.array([[0.1, 0.1], [0.5, 0.5]])) # a dominated point
+ cases.append(np.array([[0.2, 0.6], [0.2, 0.6], [0.6, 0.2]])) # a duplicate next to another point
+ cases.append(np.array([[0.2, 0.6], [0.6, 0.2], [1.2, 0.1], [0.3, 1.3]])) # points outside the reference box
+ for F, js in zip(cases, _run_figure_algorithms(cases, ref)):
+ fronts, ranks = _fast_non_dominated_sort(F)
+ assert js["rank"] == ranks.tolist()
+ crowding = _compute_crowding(F, fronts)
+ for front, values in zip(js["fronts"], js["crowding"]):
+ expected = crowding[np.asarray(front)]
+ np.testing.assert_allclose([np.inf if v is None else v for v in values], expected, rtol=1e-12)
+ assert js["hv"] == pytest.approx(hypervolume(F, ref), rel=1e-12)
+ np.testing.assert_allclose(js["contributions"], hypervolume_contributions(F, ref), rtol=1e-12, atol=1e-15)
+
+
+@pytest.mark.skipif(shutil.which("node") is None, reason="the figures' script runs under Node.js")
+def test_tchebycheff_contour_is_a_level_set() -> None:
+ weights = [0.2, 0.35, 0.5, 0.65, 0.8]
+ program = f"""
+require({json.dumps(str(SCRIPT))});
+const V = globalThis.VamosFoundations;
+process.stdout.write(JSON.stringify({json.dumps(weights)}.map((w) => V.tchebycheffContour(w, 0.3))));
+"""
+ completed = subprocess.run(["node", "-e", program], capture_output=True, text=True, check=True, timeout=60)
+ for w, contour in zip(weights, json.loads(completed.stdout)):
+ vertices = np.asarray(contour, dtype=float)
+ # Every vertex and every segment midpoint lies on max(w·f₁, (1 − w)·f₂) = c.
+ points = np.vstack([vertices, (vertices[:-1] + vertices[1:]) / 2])
+ values = np.maximum(w * points[:, 0], (1 - w) * points[:, 1])
+ np.testing.assert_allclose(values, 0.3, rtol=1e-12, err_msg=f"w = {w}: {contour}")
+
+
+def test_every_page_with_examples_is_a_docs_smoke_case() -> None:
+ smoked = {case.source_path for case in DOC_SMOKE_CASES}
+ pages = {f"docs/{_relative(page)}" for page in PAGES if _examples(page)}
+ assert pages <= smoked, f"Foundations pages with examples missing from tests/docs/smoke_manifest.py: {sorted(pages - smoked)}"
diff --git a/tests/docs/test_home_hero_layout.py b/tests/docs/test_home_hero_layout.py
index b2a1666d7..c80ce525b 100644
--- a/tests/docs/test_home_hero_layout.py
+++ b/tests/docs/test_home_hero_layout.py
@@ -32,6 +32,7 @@ def test_homepage_hero_styles_are_loaded_after_the_base_identity_styles() -> Non
assert config["extra_css"] == [
"stylesheets/vamos.css",
"stylesheets/home-hero.css",
+ "stylesheets/foundations.css",
]
diff --git a/tests/docs/test_visual_identity.py b/tests/docs/test_visual_identity.py
index 539e8cf22..0daa6df20 100644
--- a/tests/docs/test_visual_identity.py
+++ b/tests/docs/test_visual_identity.py
@@ -14,6 +14,7 @@ def test_vamos_visual_identity_is_wired_into_canonical_docs() -> None:
assert config["extra_css"] == [
"stylesheets/vamos.css",
"stylesheets/home-hero.css",
+ "stylesheets/foundations.css",
]
assert config["theme"]["font"] == {"text": "DM Sans", "code": "JetBrains Mono"}
assert config["theme"]["logo"] == "assets/vamos-mark.svg"
diff --git a/tools/check_docs_browser.py b/tools/check_docs_browser.py
index 290a21561..a56023d34 100644
--- a/tools/check_docs_browser.py
+++ b/tools/check_docs_browser.py
@@ -27,6 +27,8 @@
"reference/algorithms/",
"reference/api/optimization/",
"guide/installation/",
+ "foundations/basic/quality-indicators/",
+ "foundations/intermediate/nsga-ii/",
)