NK fitness landscapes
Agents that climb Kauffman's NK fitness landscape until they reach local peaks.
- Class:
NKLandscapeSystem - Import:
from skcomplex.systems.biology.evolution import NKLandscapeSystem - Field:
biology/evolution - Topics:
fitness landscape,agents,NK system,hill climbing,ruggedness - References:
- Kauffman and Levin 1987
- Downey 2018
- Thurner et al. 2018
Use this system
The block imports the class and simulates the system with its default parameters and its tuned run settings.
from skcomplex.systems.biology.evolution import NKLandscapeSystem
trajectory = NKLandscapeSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
climbers |
50 |
n |
10 |
k |
2 |
seed |
0 |
random_state |
0 |
solver |
'auto' |
backend |
'auto' |
Tags
The system with its default parameters has these capability tags, which solvers and analyses check.
| Tag | Values |
|---|---|
| Time | discrete |
| Space | none |
| Laws | update |
| Randomness | stochastic |
| Domains | integer, real |
| Structure | variable membership |
Class
The source of the class shows how it builds its components from its model parameters.
class NKLandscapeSystem(BaseSystem):
"""Agents that climb Kauffman's NK fitness landscape until they reach local peaks.
The agents start from random genomes.
The landscape grows more rugged with `k`, from a single peak at `k = 0` to a random landscape at `k = n - 1`, so the
climbers end on more peaks of lower fitness. The system has the group `climbers`.
Args:
climbers:
The number of agents.
n:
The number of bits of a genome.
k:
The number of other bits each bit interacts with.
seed:
The seed of the landscape.
random_state:
The seed or generator of the initial genomes.
label:
The label of the system, which names it when it is nested in another one.
solver:
The solver of the problem, or `'auto'` for the one the system chooses.
backend:
The backend that evaluates the compiled functions, or `'auto'` for the one the system chooses.
Examples:
>>> from skcomplex.systems.biology.evolution import NKLandscapeSystem
>>> NKLandscapeSystem(5).prepare().system_.elements[0].size
5
"""
field = 'biology/evolution'
topics = ('fitness landscape', 'agents', 'NK system', 'hill climbing', 'ruggedness')
references = ('Kauffman and Levin 1987', 'Downey 2018', 'Thurner et al. 2018')
until = 50
def __init__(
self,
climbers: int = 50,
*,
n: int = 10,
k: int = 2,
seed: int = 0,
random_state: int | np.random.Generator | None = 0,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.climbers = climbers
self.n = n
self.k = k
self.seed = seed
self.random_state = random_state
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the system of agents on an NK landscape.
Args:
context:
The observables to compile with the problem, or `None` for none.
"""
super()._prepare(context)
genomes = np.random.default_rng(self.random_state).integers(0, 2**self.n, size=self.climbers)
fitness = [ClimberElement._get_nk_fitness(int(genome), self.n, self.k, self.seed) for genome in genomes]
climbers = ClimberElement(
'climbers',
genome=genomes.astype(float),
fitness=np.asarray(fitness),
n=float(self.n),
k=float(self.k),
seed=float(self.seed),
size=self.climbers,
)
self.system_ = System(
self.label,
elements=[climbers],
interactions=[ClimbingInteraction('climbing', target='climbers')],
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
ClimberElement, fromElement
Interactions:
ClimbingInteraction, fromInteraction
class ClimberElement(Element):
"""Agent that walks an NK fitness landscape.
It flips one random bit of its genome when that raises its fitness, by `ClimbingInteraction`.
The fitness of a genome of `n` bits is the mean of the contributions of its bits, each a random function of the bit
and the next `k` bits, fixed by `seed`.
Args:
label:
The label of the agent or group.
genome:
The bits of the genome.
fitness:
The fitness of the genome.
n:
The number of bits.
k:
The number of other bits each bit interacts with.
seed:
The seed of the landscape.
values:
Further values by name, or `None` for none.
size:
The number of climbers, or `None` for one.
space:
The space of the climbers, or `None` for none.
Examples:
>>> from skcomplex.systems.biology.evolution import ClimberElement
>>> ClimberElement('climbers', size=10).size
10
"""
visual = VisualSpec('agents', {'color_by': 'fitness', 'color_range': (0.0, 1.0)})
def __init__(
self,
label: str,
*,
genome: Annotated[float | npt.ArrayLike, NN] = 0.0,
fitness: Annotated[float | npt.ArrayLike, RealSet.closed_open(0, oo)] = 0.0,
n: Annotated[float, RealSet.open(0, oo)] = 10.0,
k: Annotated[float, NN] = 2.0,
seed: Annotated[float, NN] = 0.0,
values: Mapping[str, object] | None = None,
size: int | None = None,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, values=values, size=size, space=space)
self.genome = genome
self.fitness = fitness
self.n = n
self.k = k
self.seed = seed
@staticmethod
@lru_cache(maxsize=16)
def _get_nk_tables(seed: int, n: int, k: int) -> Array:
"""Return the fitness contributions of every locus.
There is one contribution for every configuration of the locus and its `k` neighbours.
"""
return np.random.default_rng(seed).random((n, 2 ** (k + 1)))
@staticmethod
def _get_nk_fitness(genome: int, n: int, k: int, seed: int) -> float:
"""Return the NK fitness of a genome.
It is the mean contribution of its loci, each read with the next `k` loci.
"""
tables = ClimberElement._get_nk_tables(seed, n, k)
bits = [(genome >> locus) & 1 for locus in range(n)]
total = 0.0
for locus in range(n):
index = sum(bits[(locus + offset) % n] << offset for offset in range(k + 1))
total += tables[locus, index]
return total / n
class ClimbingInteraction(Interaction):
"""Hill climbing of agents on an NK fitness landscape.
At every step each climber flips one random bit of its genome and keeps the flip when it raises its fitness.
Args:
label:
The label of the interaction.
target:
The path of the group of climbers.
Examples:
>>> from skcomplex.systems.biology.evolution import ClimbingInteraction
>>> ClimbingInteraction('climbing', target='climbers').target
'climbers'
"""
draws = True
law_classes = (UpdateLaw,)
def __init__(self, label: str, *, target: Role) -> None:
super().__init__(label)
self.target = target
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the climbing rule of every climber.
Args:
context:
The namespace of the climbers.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = [UpdateLaw(context.target, self.climb)]
def climb(self, agent: ClimberView, system: SystemView) -> None:
"""Flip a random bit, and keep the flip when it raises the fitness.
Args:
agent:
The climber.
system:
The system.
"""
n, k, seed = int(agent.n), int(agent.k), int(agent.seed)
mutant = int(agent.genome) ^ (1 << int(system.rng.integers(n)))
fitness = ClimberElement._get_nk_fitness(mutant, n, k, seed)
if fitness > agent.fitness:
agent.genome = float(mutant)
agent.fitness = fitness
Equations
The equations are those that symbolic returns for the system with its default parameters.