Source code for easyiec.strategies.evolutionary

"""Population-based interactive strategies: GA, ES (EASY-IEC), Blind Watchmaker, random search."""

from __future__ import annotations

import numpy as np

from ..core.feedback import Feedback, Query
from ..core.operators import CROSSOVERS, reflect, self_adaptive_mutation
from .base import Strategy

__all__ = ["InteractiveGA", "InteractiveES", "EasyIEC", "Watchmaker", "RandomSearch"]


[docs] class InteractiveGA(Strategy): """Interactive genetic algorithm (IGA; Takagi, 2001). The evaluator chooses (or ranks, rates) candidates; parents are drawn with probability proportional to their utility, recombined (BLX-α, SBX, arithmetic or uniform crossover) and mutated. Chosen and explicitly *kept* candidates survive unchanged (``elite``), as in Picbreeder, so that good designs are never lost between generations. Works on structured genomes through ``problem.representation`` as well. Parameters ---------- pop_size : int n_select : int, optional crossover : {"blx", "sbx", "arithmetic", "uniform"} crossover_rate : float sigma : float Gaussian mutation step in the unit cube. mutation_rate : float, optional Per-gene mutation probability (default: every gene). elite : int Number of top-ranked candidates carried over unchanged (in addition to the ones the evaluator asked to keep). immigrants : float Fraction of random newcomers per generation (diversity). sigma_decay : float Multiplicative annealing of ``sigma`` per generation. """ protocols = ("select", "rank", "rate", "best_worst", "pairs") real_only = False def __init__(self, pop_size: int = 9, protocol: str | None = None, n_select: int | None = None, crossover: str = "blx", crossover_rate: float = 0.7, sigma: float = 0.08, mutation_rate: float | None = None, elite: int = 1, immigrants: float = 0.0, sigma_decay: float = 0.97, sigma_min: float = 0.01, **kw): super().__init__(pop_size, protocol, n_select, **kw) self.crossover = crossover self.crossover_rate = crossover_rate self.sigma0 = sigma self.mutation_rate = mutation_rate self.elite = elite self.immigrants = immigrants self.sigma_decay = sigma_decay self.sigma_min = sigma_min def _setup(self): self.sigma = self.sigma0 self._population = self.random_individuals(self.pop_size) def ask(self) -> Query: items = self._population if self.protocol == "pairs": idx = list(range(len(items))) self.rng.shuffle(idx) pairs = [(idx[i], idx[i + 1]) for i in range(0, len(idx) - 1, 2)] return self.make_query(items, "pairs", pairs=pairs) return self.make_query(items) def _child(self, parents, weights): p = weights / weights.sum() i, j = self.rng.choice(len(parents), size=2, p=p, replace=len(parents) < 2) a, b = parents[i], parents[j] if self.real: za, zb = self.z(a), self.z(b) if a is not b and self.rng.random() < self.crossover_rate: zc = CROSSOVERS[self.crossover](za, zb, self.rng) origin, par = "crossover", (a.id, b.id) else: zc, origin, par = za.copy(), "mutation", (a.id,) step = self.sigma * self.rng.standard_normal(zc.size) if self.mutation_rate is not None: step *= self.rng.random(zc.size) < self.mutation_rate return self.new(z=self._biased(zc + step), parents=par, origin=origin) g = a.genome origin, par = "mutation", (a.id,) if a is not b and self.rng.random() < self.crossover_rate: g = self.rep.crossover(a.genome, b.genome, self.rng) origin, par = "crossover", (a.id, b.id) return self.new(genome=self.rep.mutate(g, self.rng), parents=par, origin=origin) def tell(self, feedback: Feedback, query: Query) -> None: inds = self.resolved(feedback, query) u = feedback.utilities(query) order = feedback.order(query) for old, new in feedback.meta.get("edited_individuals", {}).items(): u[new.id] = 1.0 order = [new.id if i == int(old) else i for i in order] inds[new.id] = new chosen = feedback.chosen(query) chosen = [feedback.meta["edited_individuals"][c].id if c in feedback.meta.get("edited_individuals", {}) else c for c in chosen] if order: self._best = inds[order[0]] if order[0] in inds else self._best if not chosen and not feedback.keep: if feedback.stop: return chosen = order[: max(1, len(order) // 3)] pool_ids = list(dict.fromkeys(chosen + [i for i in order if u.get(i, 0) > 0])) parents = [inds[i] for i in pool_ids if i in inds] w = np.array([max(u.get(p.id, 0.0), 0.0) + 0.05 for p in parents]) survivors = [] keep = [inds[i] for i in feedback.keep if i in inds] for k in keep + [inds[i] for i in order[: self.elite] if i in inds]: if k not in survivors: survivors.append(k) self.generation += 1 n_imm = int(round(self.immigrants * self.pop_size)) offspring = [self._child(parents, w) for _ in range(max(self.pop_size - len(survivors) - n_imm, 0))] newcomers = self.random_individuals(n_imm, origin="immigrant") if n_imm else [] self._population = (survivors + offspring + newcomers)[: self.pop_size] self.sigma = max(self.sigma * self.sigma_decay, self.sigma_min) self._decay_bias()
[docs] class InteractiveES(Strategy): """Interactive evolution strategy with self-adaptive step sizes. ``(μ/ρ, λ)`` (comma) or ``(μ/ρ + λ)`` (plus) selection where the evaluator determines the μ parents; every individual carries its own step-size vector adapted by log-normal self-adaptation (Beyer and Schwefel, 2002). Breukelaar, Emmerich and Bäck (2006) analysed this family of interactive ES with simulated users. Parameters ---------- pop_size : int λ, the number of candidates shown. plus : bool Plus selection (the chosen parents reappear unchanged). recombination : {"intermediate", "discrete", None} rho : int Parents per recombination. sigma0 : float Initial step size in the unit cube. """ protocols = ("select", "rank", "rate", "best_worst") def __init__(self, pop_size: int = 9, protocol: str | None = None, n_select: int | None = None, plus: bool = True, recombination: str | None = "intermediate", rho: int = 2, sigma0: float = 0.15, init: str = "uniform", **kw): super().__init__(pop_size, protocol, n_select, **kw) self.plus = plus self.recombination = recombination self.rho = rho self.sigma0 = sigma0 self.init = init def _setup(self): d = self.space.dim if self.init == "center": c = np.full(d, 0.5) self._population = [self.new(z=c + self.sigma0 * self.rng.standard_normal(d), params={"sigma": np.full(d, self.sigma0)}) for _ in range(self.pop_size)] seeds = self._initial for k, g in enumerate(seeds[: self.pop_size]): self._population[k] = self.new(genome=g, origin="seed", params={"sigma": np.full(d, self.sigma0)}) else: self._population = self.random_individuals(self.pop_size) for ind in self._population: ind.params["sigma"] = np.full(d, self.sigma0) def ask(self) -> Query: return self.make_query(self._population) def _offspring(self, parents, n): out = [] for _ in range(n): if len(parents) >= 2 and self.recombination: k = min(self.rho, len(parents)) sel = [parents[i] for i in self.rng.choice(len(parents), size=k, replace=False)] Z = np.array([self.z(p) for p in sel]) S = np.array([p.params["sigma"] for p in sel]) if self.recombination == "intermediate": z, s = Z.mean(0), np.exp(np.log(S).mean(0)) else: pick = self.rng.integers(0, k, size=Z.shape[1]) z, s = Z[pick, np.arange(Z.shape[1])], S[pick, np.arange(Z.shape[1])] par = tuple(p.id for p in sel) origin = "recombination" else: p = parents[self.rng.integers(len(parents))] z, s, par, origin = self.z(p), p.params["sigma"], (p.id,), "mutation" if self._bias is not None: z = z + self._bias zn, sn = self_adaptive_mutation(z, s, self.rng) out.append(self.new(z=zn, parents=par, origin=origin, params={"sigma": sn})) return out def _parents_from(self, feedback, query): inds = self.resolved(feedback, query) for ind in inds.values(): ind.params.setdefault("sigma", np.full(self.space.dim, self.sigma0)) chosen = feedback.chosen(query) edited = feedback.meta.get("edited_individuals", {}) chosen = [edited[c].id if c in edited else c for c in chosen] for new in edited.values(): inds[new.id] = new if not chosen: order = feedback.order(query) chosen = order[: max(1, len(order) // 3)] return [inds[i] for i in chosen if i in inds], inds def tell(self, feedback: Feedback, query: Query) -> None: if feedback.stop and not feedback.chosen(query): return parents, inds = self._parents_from(feedback, query) self._best = parents[0] if parents else self._best keep = [inds[i] for i in feedback.keep if i in inds] survivors = list(dict.fromkeys(keep + (parents if self.plus else []))) self.generation += 1 offspring = self._offspring(parents, max(self.pop_size - len(survivors), 0)) self._population = (survivors + offspring)[: self.pop_size] self._decay_bias()
[docs] class EasyIEC(InteractiveES): """The EASY-IEC algorithm of the MATLAB toolbox (Madár, Abonyi and Szeifert, 2005). Reconstructed from the toolbox documentation: real-coded chromosomes with one vector of strategy parameters (``devi``) per individual, initialized as ``(UB-LB)/sqrt(nvar)/2`` around an initial chromosome. The operator marks *parents* (selected once) and *offspring to keep* (selected twice; carried over unchanged); the rest of the next generation is produced from the parents by recombination and self-adaptive Gaussian mutation. Use ``feedback.selected`` for parents and ``feedback.keep`` for the kept ones. """ def __init__(self, pop_size: int = 9, protocol: str | None = None, n_select: int | None = None, init_chrom=None, **kw): kw.setdefault("plus", False) kw.setdefault("recombination", "intermediate") super().__init__(pop_size, protocol, n_select, init="center", **kw) self.init_chrom = init_chrom def _setup(self): d = self.space.dim self.sigma0 = 1.0 / np.sqrt(d) / 2.0 c = self.space.normalize(self.init_chrom) if self.init_chrom is not None else np.full(d, 0.5) self._population = [] for k in range(self.pop_size): if k < len(self._initial): ind = self.new(genome=self._initial[k], origin="seed") else: ind = self.new(z=c + self.sigma0 * self.rng.standard_normal(d)) ind.params["sigma"] = np.full(d, self.sigma0) self._population.append(ind) def tell(self, feedback: Feedback, query: Query) -> None: if feedback.stop and not feedback.selected and not feedback.keep: return inds = self.resolved(feedback, query) for ind in inds.values(): ind.params.setdefault("sigma", np.full(self.space.dim, self.sigma0)) edited = feedback.meta.get("edited_individuals", {}) par_ids = [edited[c].id if c in edited else c for c in feedback.selected] keep_ids = [edited[c].id if c in edited else c for c in feedback.keep] for new in edited.values(): inds[new.id] = new if not par_ids and not keep_ids: par_ids = feedback.order(query)[:2] parents = [inds[i] for i in par_ids if i in inds] or [inds[i] for i in keep_ids if i in inds] kept = [inds[i] for i in keep_ids if i in inds] self._best = (kept or parents)[0] self.generation += 1 self._population = (kept + self._offspring(parents, max(self.pop_size - len(kept), 0)))[: self.pop_size] self._decay_bias()
[docs] class Watchmaker(Strategy): """Dawkins's *Blind Watchmaker* scheme (Dawkins, 1986). One parent and ``pop_size-1`` mutated offspring are shown; the evaluator picks one, which becomes the next parent. The mutation step shrinks when the parent itself is chosen again (no better variant was offered) and grows when an offspring is chosen (a 1/5-success-rule analogue). """ protocols = ("select", "rank", "rate", "best_worst") real_only = False def __init__(self, pop_size: int = 9, protocol: str | None = None, sigma: float = 0.12, adapt: bool = True, **kw): super().__init__(pop_size, protocol, n_select=1, **kw) self.sigma0 = sigma self.adapt = adapt def _setup(self): self.sigma = self.sigma0 self.parent = self.random_individuals(1)[0] self._best = self.parent self._population = [self.parent] + self._children() def _children(self): out = [] for _ in range(self.pop_size - 1): if self.real: out.append(self.new(z=self.mutate_genome(self.parent, self.sigma), parents=(self.parent.id,), origin="mutation")) else: out.append(self.new(genome=self.rep.mutate(self.parent.genome, self.rng), parents=(self.parent.id,), origin="mutation")) return out def ask(self) -> Query: return self.make_query(self._population, n_select=1 if self.protocol == "select" else None) def tell(self, feedback: Feedback, query: Query) -> None: inds = self.resolved(feedback, query) order = feedback.order(query) if not order or (feedback.stop and not feedback.chosen(query)): return top = order[0] new_parent = inds.get(top, self.parent) if self.adapt and self.real: self.sigma = self.sigma * (0.7 if new_parent is self.parent else 1.15) self.sigma = float(np.clip(self.sigma, 0.01, 0.4)) self.parent = new_parent self._best = new_parent self.generation += 1 self._population = [self.parent] + self._children() self._decay_bias()
[docs] class RandomSearch(Strategy): """Baseline: a fresh random gallery every generation; remembers the best choice.""" protocols = ("select", "rank", "rate", "best_worst") real_only = False def _setup(self): self._population = self.random_individuals(self.pop_size) def ask(self) -> Query: return self.make_query(self._population) def tell(self, feedback: Feedback, query: Query) -> None: order = feedback.order(query) if order: cand = query.item(order[0]) if self._best is None or feedback.utilities(query)[order[0]] > 0: self._best = cand self.generation += 1 keep = [self._best] if self._best is not None else [] self._population = keep + self.random_individuals(self.pop_size - len(keep))
def _unused(): # pragma: no cover - keeps reflect imported for subclasses return reflect