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.
TargetFitness
¶
Bases: StopCondition
Stop when the best fitness reaches target (>= when maximising, <= when minimising).
Source code in src/carmelolg/galib/termination.py
TimeLimit
¶
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
Stagnation
¶
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
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
on_generation
¶
on_generation(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
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 |
1
|
stream
|
TextIO | None
|
where to write; |
None
|
width
|
int
|
maximum number of characters of the best genome to show. |
60
|
flush
|
bool
|
passed to |
False
|
end
|
str
|
passed to |
'\n'
|
in_place
|
bool
|
keep a single line that is rewritten at every generation. The carriage return is
written before the text ( To change the line format, subclass and override |
False
|
Source code in src/carmelolg/galib/callbacks.py
format_line
¶
format_line(stats: GenerationStats[Any]) -> str
Return the text printed for one generation.