Class EvolutionListenerLogTopN<T extends Comparable<T>>

java.lang.Object
net.bmahe.genetics4j.core.evolutionlisteners.EvolutionListenerLogTopN<T>
Type Parameters:
T - the type of fitness values, must be Comparable
All Implemented Interfaces:
EvolutionListener<T>

public class EvolutionListenerLogTopN<T extends Comparable<T>> extends Object implements EvolutionListener<T>
Evolution listener that logs the top N individuals from each generation.

This listener provides detailed logging of the best-performing individuals during evolution, allowing for real-time monitoring of algorithm progress and population quality. It supports configurable logging frequency, custom fitness comparators, and pretty-printing of genotypes.

Key features:

  • Top-N logging: Configurable number of best individuals to log per generation
  • Skip functionality: Optional generation skipping to reduce log volume
  • Custom comparators: Override default fitness comparison logic
  • Pretty printing: Customizable genotype display formatting
  • Automatic sorting: Uses EA configuration's fitness comparator when none provided

The listener automatically adapts to the fitness comparison strategy defined in the EA configuration during the preEvaluation phase. If a custom comparator is provided during construction, it will be used instead of the configuration's comparator.

Usage examples:

// Basic usage - log top 5 individuals every generation
Logger logger = LogManager.getLogger();
EvolutionListener<Double> topLogger = new EvolutionListenerLogTopN<>(logger, 5, 0);

// Log top 3 individuals every 10 generations with custom formatting
EvolutionListener<Double> periodicLogger = new EvolutionListenerLogTopN<>(logger,
		3,
		10,
		null,
		genotype -> "Custom: " + genotype.toString());

// Use custom fitness comparator for minimization problems
Comparator<Double> minimizer = Double::compare; // Natural order for minimization
EvolutionListener<Double> minLogger = new EvolutionListenerLogTopN<>(logger, 5, 0, minimizer, null);

Thread safety: This listener is thread-safe and can be used in parallel evolution contexts. The logger instance should be thread-safe (Log4j loggers are thread-safe by default).

See Also:
  • Field Details

  • Constructor Details

    • EvolutionListenerLogTopN

      public EvolutionListenerLogTopN(org.apache.logging.log4j.Logger _logger, int _topN, int _skipN, Comparator<T> _userComparator, Function<Genotype,String> _prettyPrinter)
      Constructs a new EvolutionListenerLogTopN with full configuration options.
      Parameters:
      _logger - the Log4j logger instance to use for output
      _topN - the number of top individuals to log each generation (must be > 0)
      _skipN - the number of generations to skip between logging (0 = log every generation, must be >= 0)
      _userComparator - custom fitness comparator for sorting individuals, or null to use EA configuration's comparator
      _prettyPrinter - function to format genotype display, or null to use default toString()
      Throws:
      NullPointerException - if _logger is null
      IllegalArgumentException - if _topN invalid input: '<'= 0 or _skipN invalid input: '<' 0
    • EvolutionListenerLogTopN

      public EvolutionListenerLogTopN(org.apache.logging.log4j.Logger _logger, int _topN, int _skipN)
      Constructs a new EvolutionListenerLogTopN with default formatting and comparison.

      This convenience constructor uses the EA configuration's fitness comparator and default toString() formatting for genotypes.

      Parameters:
      _logger - the Log4j logger instance to use for output
      _topN - the number of top individuals to log each generation (must be > 0)
      _skipN - the number of generations to skip between logging (0 = log every generation, must be >= 0)
      Throws:
      NullPointerException - if _logger is null
      IllegalArgumentException - if _topN invalid input: '<'= 0 or _skipN invalid input: '<' 0
  • Method Details

    • preEvaluation

      public void preEvaluation(AbstractEAConfiguration<T> eaConfiguration)
      Initializes the listener with EA configuration and sets up the fitness comparator.

      This method is called before evolution begins to provide access to the EA configuration. The listener uses this information to determine the appropriate fitness comparison strategy. If a custom comparator was provided during construction, it takes precedence over the configuration's comparator.

      The resulting comparator is reversed to ensure that the "best" individuals (highest fitness according to the comparator) are sorted first in the top-N listing.

      Specified by:
      preEvaluation in interface EvolutionListener<T extends Comparable<T>>
      Parameters:
      eaConfiguration - the EA configuration containing fitness comparison logic
      Throws:
      NullPointerException - if eaConfiguration is null
    • onEvolution

      public void onEvolution(long generation, List<Genotype> population, List<T> fitness, boolean isDone)
      Logs the top N individuals for the current generation.

      This method is called after each generation to log the best-performing individuals. The behavior is controlled by the skipN parameter - if skipN > 0, logging only occurs when the generation number is divisible by skipN.

      The method sorts all individuals by fitness using the configured comparator and logs the top N results with their fitness values and formatted genotype representations.

      Output format:

      Top {N} individuals at generation {generation}
        Fitness: {fitness_value} -> {formatted_genotype}
        Fitness: {fitness_value} -> {formatted_genotype}
        ...
      
      Specified by:
      onEvolution in interface EvolutionListener<T extends Comparable<T>>
      Parameters:
      generation - the current generation number (0-based)
      population - the list of genotypes in the current generation
      fitness - the list of fitness values corresponding to each genotype
      isDone - whether the evolution has completed (not used by this implementation)
      Throws:
      IllegalStateException - if preEvaluation has not been called