Source code for qdpy.algorithms.geometric_encoding
# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Compact geometric genomes for fully connected neural networks.
# @see https://doi.org/10.1145/3449639.3459361
"""Decode neuron coordinates to dense feedforward weights with pL2."""
from dataclasses import dataclass
import numpy as np
from .modern import _positive_int
__all__ = ["GENEEncoding"]
## @brief Encode layer weights with neuron coordinates and store biases directly.
[docs]
@dataclass(frozen=True)
class GENEEncoding:
"""Decode a flat genome to alternating row-major weights and biases.
A genome stores all neuron coordinates in layer order followed by
the biases of all non-input layers. A weight is the L2 distance
between connected neurons multiplied by the coordinate difference
product clipped to [-1, 1]. Biases use direct encoding.
:param layer_sizes: Width of each layer, including input and output.
:param coordinate_size: Number of geometric coordinates per neuron.
"""
layer_sizes: tuple[int, ...]
coordinate_size: int = 3
def __post_init__(self):
sizes = tuple(_positive_int(size, "layer width") for size in self.layer_sizes)
if len(sizes) < 2:
raise ValueError("Supply input and output layer sizes.")
object.__setattr__(self, "layer_sizes", sizes)
object.__setattr__(self, "coordinate_size", _positive_int(self.coordinate_size, "coordinate_size"))
@property
def genome_size(self):
"""Return the number of evolved coordinates and bias values."""
return self.coordinate_size * sum(self.layer_sizes) + sum(self.layer_sizes[1:])
@property
def parameter_count(self):
"""Return the number of parameters in the decoded dense actor."""
return sum((a + 1) * b for a, b in zip(self.layer_sizes, self.layer_sizes[1:]))
## @brief Decode into the dense parameter order used by QDpy feedforward policies.
# @param genome Flat coordinates in layer order followed by flat non-input biases.
# @return Float64 weights in target-by-source order, alternating with biases.
[docs]
def decode(self, genome):
"""Return a flat NumPy vector of weights and biases as float64."""
values = np.asarray(genome, dtype=float)
if values.shape != (self.genome_size,) or not np.isfinite(values).all():
raise ValueError(f"Supply {self.genome_size} finite coordinates and biases.")
count = self.coordinate_size * sum(self.layer_sizes)
points = np.split(values[:count].reshape(-1, self.coordinate_size), np.cumsum(self.layer_sizes[:-1]))
biases = np.split(values[count:], np.cumsum(self.layer_sizes[1:-1]))
blocks = []
with np.errstate(over="ignore", invalid="ignore", under="ignore"):
for source, target, bias in zip(points[:-1], points[1:], biases, strict=True):
difference = source[None, :, :] - target[:, None, :]
sign_and_scale = np.clip(np.prod(difference, axis=-1), -1., 1.)
weights = sign_and_scale * np.hypot.reduce(difference, axis=-1)
blocks.extend((weights.ravel(), bias))
dense = np.concatenate(blocks)
if not np.isfinite(dense).all():
raise ValueError("The geometric coordinates produced nonfinite weights.")
return dense