Skip to content

Stop conditions and callbacks

termination

Stop conditions. A run stops as soon as any of them returns True (or after max_generations).

StopCondition

Base class. Override should_stop; override reset too if the condition keeps state.

should_stop is called once per generation, generation 0 (the initial population) included.

reset

reset() -> None

Called at the start of every run.

Source code in src/carmelolg/galib/termination.py
def reset(self) -> None:
    """Called at the start of every run."""

TargetFitness

TargetFitness(target: float)

Bases: StopCondition

Stop when the best fitness reaches target (>= when maximising, <= when minimising).

Source code in src/carmelolg/galib/termination.py
def __init__(self, target: float) -> None:
    self.target = target

TimeLimit

TimeLimit(seconds: float)

Bases: StopCondition

Stop once seconds have passed since the run started (initial population included).

Checked between generations, so a run can exceed the limit by up to one generation.

Source code in src/carmelolg/galib/termination.py
def __init__(self, seconds: float) -> None:
    if seconds <= 0:
        raise ValueError("seconds must be > 0")
    self.seconds = seconds
    self._started = time.monotonic()

Stagnation

Stagnation(generations: int, min_delta: float = 0.0)

Bases: StopCondition

Stop after generations consecutive generations in which the best individual did not improve by more than min_delta.

Source code in src/carmelolg/galib/termination.py
def __init__(self, generations: int, min_delta: float = 0.0) -> None:
    if generations < 1:
        raise ValueError("generations must be >= 1")
    if min_delta < 0:
        raise ValueError("min_delta must be >= 0")
    self.generations = generations
    self.min_delta = min_delta
    self._best_score: float | None = None
    self._stale = 0

callbacks

Hooks into a run.

Callback

Override only the methods you need; all of them do nothing by default.

on_start

on_start(engine: GeneticAlgorithm[Any]) -> None

Called once, after the initial population is built.

Source code in src/carmelolg/galib/callbacks.py
def on_start(self, engine: GeneticAlgorithm[Any]) -> None:
    """Called once, after the initial population is built."""

on_generation

on_generation(stats: GenerationStats[Any], engine: GeneticAlgorithm[Any]) -> None

Called for every generation, generation 0 (the initial population) included.

Source code in src/carmelolg/galib/callbacks.py
def on_generation(self, stats: GenerationStats[Any], engine: GeneticAlgorithm[Any]) -> None:
    """Called for every generation, generation 0 (the initial population) included."""

on_end

on_end(result: Result[Any], engine: GeneticAlgorithm[Any]) -> None

Called once, when the run is over.

Source code in src/carmelolg/galib/callbacks.py
def on_end(self, result: Result[Any], engine: GeneticAlgorithm[Any]) -> None:
    """Called once, when the run is over."""

PrintProgress

PrintProgress(every: int = 1, stream: TextIO | None = None, width: int = 60, *, flush: bool = False, end: str = '\n', in_place: bool = False)

Bases: Callback

Print one line every every generations.

Parameters:

Name Type Description Default
every int

print only generations that are multiples of every (generation 0 included).

1
stream TextIO | None

where to write; None means sys.stdout at print time.

None
width int

maximum number of characters of the best genome to show.

60
flush bool

passed to print; True forces the line out immediately (useful when output is buffered, e.g. piped to a file or shown in an IDE console).

False
end str

passed to print (ignored when in_place is True).

'\n'
in_place bool

keep a single line that is rewritten at every generation. The carriage return is written before the text ("\r" + line), as tqdm does: consoles such as PyCharm's erase a line that ends with "\r", so end="\r" may show nothing. Always flushes. A newline is printed when the run ends.

To change the line format, subclass and override format_line.

False
Source code in src/carmelolg/galib/callbacks.py
def __init__(
    self,
    every: int = 1,
    stream: TextIO | None = None,
    width: int = 60,
    *,
    flush: bool = False,
    end: str = "\n",
    in_place: bool = False,
) -> None:
    if every < 1:
        raise ValueError("every must be >= 1")
    if width < 0:
        raise ValueError("width must be >= 0")
    self.every = every
    self.stream = stream
    self.width = width
    self.flush = flush
    self.end = end
    self.in_place = in_place
    self._last_length = 0

format_line

format_line(stats: GenerationStats[Any]) -> str

Return the text printed for one generation.

Source code in src/carmelolg/galib/callbacks.py
def format_line(self, stats: GenerationStats[Any]) -> str:
    """Return the text printed for one generation."""
    diversity = "  -  " if stats.diversity is None else f"{stats.diversity:.3f}"
    return (
        f"gen {stats.generation:5d} | best {stats.best_fitness:10.4g} | "
        f"mean {stats.mean_fitness:10.4g} | div {diversity} | {str(stats.best_genome)[: self.width]}"
    )