Skip to content

Metrics and plotting

metrics

Population diversity measures, for GeneticAlgorithm(diversity=...).

A measure receives the genomes of the current population and returns a number, or None when it cannot be computed for those genomes. Write your own with the same signature for other genome types.

positional_diversity

positional_diversity(genomes: Sequence[Any]) -> float | None

Diversity in [0, 1] for sequence genomes of equal length (str, list, tuple, bytes, numpy array).

For each gene position, the share of individuals that do not carry the most common gene, averaged over positions. 0 = every individual is identical (premature convergence). Genes are compared by equality: for real-valued genes use :func:gene_spread. Returns None for other genomes, unequal lengths or unhashable genes.

Source code in src/carmelolg/galib/metrics.py
def positional_diversity(genomes: Sequence[Any]) -> float | None:
    """Diversity in [0, 1] for sequence genomes of equal length (str, list, tuple, bytes, numpy array).

    For each gene position, the share of individuals that do not carry the most common gene, averaged over
    positions. 0 = every individual is identical (premature convergence).
    Genes are compared by equality: for real-valued genes use :func:`gene_spread`.
    Returns ``None`` for other genomes, unequal lengths or unhashable genes.
    """
    if not genomes:
        return None
    count = len(genomes)
    if all(is_array(g) for g in genomes):
        matrix = _matrix(genomes)
        if matrix is None:
            return None
        if matrix.shape[1] == 0:
            return 0.0
        return float(1 - _most_common_counts(matrix).mean() / count)
    if not all(isinstance(g, Sequence) for g in genomes):
        return None
    length = len(genomes[0])
    if any(len(g) != length for g in genomes):
        return None
    if length == 0:
        return 0.0
    try:
        tops = [Counter(column).most_common(1)[0][1] for column in zip(*genomes, strict=True)]
    except TypeError:  # unhashable genes
        return None
    return sum(1 - top / count for top in tops) / length

gene_spread

gene_spread(genomes: Sequence[Any]) -> float | None

Mean, over gene positions, of the population standard deviation of each gene.

Meant for real-valued genomes (list, tuple or numpy array of numbers). It is in the same unit as the genes, so compare it with the size of the search space. Returns None for non-numeric genomes or unequal lengths.

Source code in src/carmelolg/galib/metrics.py
def gene_spread(genomes: Sequence[Any]) -> float | None:
    """Mean, over gene positions, of the population standard deviation of each gene.

    Meant for real-valued genomes (list, tuple or numpy array of numbers). It is in the same unit as the
    genes, so compare it with the size of the search space. Returns ``None`` for non-numeric genomes or
    unequal lengths.
    """
    if not genomes:
        return None
    if all(is_array(g) for g in genomes):
        matrix = _matrix(genomes)
        if matrix is None or matrix.shape[1] == 0 or not np.issubdtype(matrix.dtype, np.number):
            return None
        return float(matrix.astype(float).std(axis=0).mean())
    if not all(isinstance(g, (list, tuple)) for g in genomes):
        return None
    length = len(genomes[0])
    if length == 0 or any(len(g) != length for g in genomes):
        return None
    try:
        spreads = [statistics.pstdev(column) for column in zip(*genomes, strict=True)]
    except TypeError:  # non-numeric genes
        return None
    return float(sum(spreads) / length)

plot

Optional plotting. Requires matplotlib: pip install "carmelolg-galib[plot]".

plot_history

plot_history(result: Result[Any], show: bool = True) -> Any

Plot best/mean fitness and diversity of a finished run. Returns the matplotlib figure.

Source code in src/carmelolg/galib/plot.py
def plot_history(result: Result[Any], show: bool = True) -> Any:
    """Plot best/mean fitness and diversity of a finished run. Returns the matplotlib figure."""
    try:
        import matplotlib.pyplot as plt
    except ImportError as error:
        raise ImportError("plot_history needs matplotlib: pip install matplotlib") from error

    history = result.history
    fig, (top, bottom) = plt.subplots(2, 1, sharex=True)
    generations = [s.generation for s in history]
    top.plot(generations, [s.best_fitness for s in history], label="best")
    top.plot(generations, [s.mean_fitness for s in history], label="mean")
    top.set_ylabel("fitness")
    top.legend()
    measured = [s for s in history if s.diversity is not None]  # skip unmeasurable points, don't fake 0
    bottom.plot([s.generation for s in measured], [s.diversity for s in measured])
    bottom.set_ylabel("diversity")
    bottom.set_xlabel("generation")
    if show:
        plt.show()
    return fig