# knotkit/evolution

> Runs deterministic population evolution with index-based parent selection and immutable permutation operators

## Use

```ts
import { evolution, inversionMutation } from 'knotkit/evolution'
import { splitmix32 } from 'knotkit/prng'

const engine = evolution<readonly number[]>({
  initialPopulation: [
    [0, 1, 2, 3],
    [0, 2, 1, 3],
    [3, 1, 2, 0],
  ],
  evaluate: (candidate) => candidate.reduce((total, value, index) => total + Math.abs(value - index), 0),
  objective: 'minimize',
  random: splitmix32(42),
  nextPopulation: ({ snapshot }) => snapshot.population.map(({ value }) => inversionMutation(value, 1, 2)),
})

engine.run(20)
engine.snapshot().best // { value, score }
```

```ts
import { type EvolutionContext, inversionMutation, rankSelection } from 'knotkit/evolution'

const nextPopulation = ({ snapshot, random }: EvolutionContext<readonly number[]>) => {
  const scores = snapshot.population.map(({ score }) => score)
  const selected = rankSelection(random, scores, scores.length, 'minimize')

  return selected.map((index) => inversionMutation(snapshot.population[index].value, 1, 2))
}
```

## What it solves

* find a good route or schedule where improving one position at a time gets stuck
* keep the best candidate seen across generations while a whole population changes
* select parents in proportion to rank, then recombine two orderings into one child ordering
* run an optimizer deterministically from a seed so a recorded run replays exactly
* decide when to stop from a stagnation count instead of a fixed generation budget
* mutate or cross a permutation without touching the array the caller handed in

## Worked example

* Evolve 12 permutations of 8 items for 30 generations, using seeds 17 and 42.
* Best displacement went from 10 to 0. Best order: \[0, 1, 2, 3, 4, 5, 6, 7].
* The population score can rise while the engine retains the best candidate it has seen.

Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/evolution/demo.ts) against `knotkit/evolution`.

## API

| Export                                                                                           | Returns             | Does                                                                                                                                                                                                                               |
| ------------------------------------------------------------------------------------------------ | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`evolution`](/reference/knotkit/evolution/functions/evolution/)                                 | `Evolution<T>`      | Generation-at-a-time engine: construction evaluates the initial population once, each \`step\` calls the caller's policy and evaluates its output once, and no intermediate generation is retained.                                |
| [`tournamentSelection`](/reference/knotkit/evolution/functions/tournamentselection/)             | `readonly number[]` | \`selectionSize\` winners, each from a tournament of distinct indices sampled by Floyd's algorithm; the same winner may repeat across tournaments and ties keep the first sampled index. O(k(n + t log t)) with tournament size t. |
| [`exponentialRankWeights`](/reference/knotkit/evolution/functions/exponentialrankweights/)       | `readonly number[]` | \`Math.exp(-rank)\` per score after one ranking pass from best to worst, equal scores sharing a competition rank; O(n log n).                                                                                                      |
| [`exponentialRankLogWeights`](/reference/knotkit/evolution/functions/exponentialranklogweights/) | `readonly number[]` | \`-rank\` from that same ranking pass, finite for every entry so it feeds \`weightedSampleFromLogWeights\` without an exponentiation that underflows; O(n log n).                                                                  |
| [`rankSelection`](/reference/knotkit/evolution/functions/rankselection/)                         | `readonly number[]` | \`exponentialRankWeights\` consumed once per output through \`weightedChoice\`, selecting with replacement; O(n log n + k n).                                                                                                      |
| [`orderCrossover`](/reference/knotkit/evolution/functions/ordercrossover/)                       | `readonly T[]`      | One child that keeps the inclusive cut segment of the first parent and fills the remaining positions in the second parent's cyclic order; O(n) expected, allocating a \`Set\` and a donor cycle.                                   |
| [`swapMutation`](/reference/knotkit/evolution/functions/swapmutation/)                           | `readonly T[]`      | Swap two positions in a copy; either index order is accepted and equal indices are a valid no-op. O(n).                                                                                                                            |
| [`inversionMutation`](/reference/knotkit/evolution/functions/inversionmutation/)                 | `readonly T[]`      | Reverse the inclusive segment between two positions in a copy; either index order is accepted. O(n).                                                                                                                               |
| [`rotateLeftMutation`](/reference/knotkit/evolution/functions/rotateleftmutation/)               | `readonly T[]`      | Rotate the inclusive segment one position left in a copy; requires \`first <= second\`. O(n).                                                                                                                                      |
| [`rotateRightMutation`](/reference/knotkit/evolution/functions/rotaterightmutation/)             | `readonly T[]`      | Rotate the inclusive segment one position right in a copy; requires \`first <= second\`. O(n).                                                                                                                                     |

Cost per member. Open a row for every operation.

`evolution` 3 members

| Member     | Cost                                |
| ---------- | ----------------------------------- |
| `snapshot` | O(1)                                |
| `step`     | O(n) plus evaluator and policy work |
| `run`      | O(generations) steps                |

## What you pass in

| Input                                                                                               | Type                                             | Get one from                               |
| --------------------------------------------------------------------------------------------------- | ------------------------------------------------ | ------------------------------------------ |
| randomness, drawn only by the caller's policy through the context and never allocated by the engine | `RandomSource`                                   | [`knotkit/prng`](/modules/prng/)           |
| fitness, which decides every score and therefore every selection outcome                            | `(candidate: T) => number`                       | `the caller`                               |
| the next-generation policy, which owns selection, crossover, and mutation                           | `(context: EvolutionContext<T>) => readonly T[]` | `the caller`                               |
| objective direction, which decides what a score better than another means                           | `Objective`                                      | [`knotkit/evolution`](/modules/evolution/) |

## Errors

Every error this module throws is `EvolutionInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.

* `EvolutionInvalidInputError`

  `EMPTY_POPULATION` `INVALID_SCORE` `INVALID_SELECTION_SIZE` `INVALID_TOURNAMENT_SIZE` `INVALID_OBJECTIVE` `INVALID_PERMUTATION` `INVALID_INDEX` `INVALID_CUT` `DUPLICATE_ELEMENT` `UNEQUAL_PARENT_DOMAIN`

* `Other`

  `INVALID_GENERATION_COUNT`

## When not to use it

| If you need to…                                                     | Use instead                                                                              |
| ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| a seeded random source, or control over the draw sequence           | [`knotkit/prng`](/modules/prng/)                                                         |
| draw a sample, a pair, or a weighted selection outside a population | [`knotkit/sampling`](/modules/sampling/)                                                 |
| a stopping rule, a checkpoint schedule, or a per-generation trace   | caller code around bounded \`run\` calls; the engine retains only the current generation |
| optimize real-valued parameters where a gradient exists             | a derivative-based optimizer, since the shipped operators act on permutations            |
| order the population by score                                       | Array.prototype.sort over \`snapshot().population\`                                      |

## Performance

Measured by the suite in [`packages/evolution/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/evolution/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.

## Prompt an agent

Prompt · knotkit/evolutionCopy prompt

```
Use knotkit/evolution for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/evolution'.

Exports:
- `evolution` → `Evolution<T>`: Generation-at-a-time engine: construction evaluates the initial population once, each `step` calls the caller's policy and evaluates its output once, and no intermediate generation is retained.
- `tournamentSelection` → `readonly number[]`: `selectionSize` winners, each from a tournament of distinct indices sampled by Floyd's algorithm; the same winner may repeat across tournaments and ties keep the first sampled index. O(k(n + t log t)) with tournament size t.
- `exponentialRankWeights` → `readonly number[]`: `Math.exp(-rank)` per score after one ranking pass from best to worst, equal scores sharing a competition rank; O(n log n).
- `exponentialRankLogWeights` → `readonly number[]`: `-rank` from that same ranking pass, finite for every entry so it feeds `weightedSampleFromLogWeights` without an exponentiation that underflows; O(n log n).
- `rankSelection` → `readonly number[]`: `exponentialRankWeights` consumed once per output through `weightedChoice`, selecting with replacement; O(n log n + k n).
- `orderCrossover` → `readonly T[]`: One child that keeps the inclusive cut segment of the first parent and fills the remaining positions in the second parent's cyclic order; O(n) expected, allocating a `Set` and a donor cycle.
- `swapMutation` → `readonly T[]`: Swap two positions in a copy; either index order is accepted and equal indices are a valid no-op. O(n).
- `inversionMutation` → `readonly T[]`: Reverse the inclusive segment between two positions in a copy; either index order is accepted. O(n).
- `rotateLeftMutation` → `readonly T[]`: Rotate the inclusive segment one position left in a copy; requires `first <= second`. O(n).
- `rotateRightMutation` → `readonly T[]`: Rotate the inclusive segment one position right in a copy; requires `first <= second`. O(n).

Inputs and their sources:
- randomness, drawn only by the caller's policy through the context and never allocated by the engine: `RandomSource` from `knotkit/prng`
- fitness, which decides every score and therefore every selection outcome: `(candidate: T) => number` from `the caller`
- the next-generation policy, which owns selection, crossover, and mutation: `(context: EvolutionContext<T>) => readonly T[]` from `the caller`
- objective direction, which decides what a score better than another means: `Objective` from `knotkit/evolution`

Use something else when:
- a seeded random source, or control over the draw sequence → knotkit/prng
- draw a sample, a pair, or a weighted selection outside a population → knotkit/sampling
- a stopping rule, a checkpoint schedule, or a per-generation trace → caller code around bounded `run` calls; the engine retains only the current generation
- optimize real-valued parameters where a gradient exists → a derivative-based optimizer, since the shipped operators act on permutations
- order the population by score → Array.prototype.sort over `snapshot().population`

Errors are EvolutionInvalidInputError with a `code` property. Branch on `error.code`, never on the message.

Full page: https://knotkit.jkomyno.dev/modules/evolution.md
Types: node_modules/knotkit/evolution/ and https://knotkit.jkomyno.dev/reference/knotkit/evolution/
```

## See also

* [API reference](/reference/knotkit/evolution/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/evolution/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/packages/evolution/knotkit.capability.json)suggest a change to the source record
