QDpy
Loading...
Searching...
No Matches
geometric_encoding.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Decode neuron coordinates to dense feedforward weights with pL2."""
7
8from dataclasses import dataclass
9
10import numpy as np
11
12from .modern import _positive_int
13
14__all__ = ["GENEEncoding"]
15
16
17
18@dataclass(frozen=True)
20 """Decode a flat genome to alternating row-major weights and biases.
21
22 A genome stores all neuron coordinates in layer order followed by
23 the biases of all non-input layers. A weight is the L2 distance
24 between connected neurons multiplied by the coordinate difference
25 product clipped to [-1, 1]. Biases use direct encoding.
26
27 :param layer_sizes: Width of each layer, including input and output.
28 :param coordinate_size: Number of geometric coordinates per neuron.
29 """
30
31 layer_sizes: tuple[int, ...]
32 coordinate_size: int = 3
33
34 def __post_init__(self):
35 sizes = tuple(_positive_int(size, "layer width") for size in self.layer_sizes)
36 if len(sizes) < 2:
37 raise ValueError("Supply input and output layer sizes.")
38 object.__setattr__(self, "layer_sizes", sizes)
39 object.__setattr__(self, "coordinate_size", _positive_int(self.coordinate_size, "coordinate_size"))
40
41 @property
42 def genome_size(self):
43 """Return the number of evolved coordinates and bias values."""
44 return self.coordinate_size * sum(self.layer_sizes) + sum(self.layer_sizes[1:])
45
46 @property
47 def parameter_count(self):
48 """Return the number of parameters in the decoded dense actor."""
49 return sum((a + 1) * b for a, b in zip(self.layer_sizes, self.layer_sizes[1:]))
50
51
54 def decode(self, genome):
55 """Return a flat NumPy vector of weights and biases as float64."""
56 values = np.asarray(genome, dtype=float)
57 if values.shape != (self.genome_size,) or not np.isfinite(values).all():
58 raise ValueError(f"Supply {self.genome_size} finite coordinates and biases.")
59 count = self.coordinate_size * sum(self.layer_sizes)
60 points = np.split(values[:count].reshape(-1, self.coordinate_size), np.cumsum(self.layer_sizes[:-1]))
61 biases = np.split(values[count:], np.cumsum(self.layer_sizes[1:-1]))
62 blocks = []
63 with np.errstate(over="ignore", invalid="ignore", under="ignore"):
64 for source, target, bias in zip(points[:-1], points[1:], biases, strict=True):
65 difference = source[None, :, :] - target[:, None, :]
66 sign_and_scale = np.clip(np.prod(difference, axis=-1), -1., 1.)
67 weights = sign_and_scale * np.hypot.reduce(difference, axis=-1)
68 blocks.extend((weights.ravel(), bias))
69 dense = np.concatenate(blocks)
70 if not np.isfinite(dense).all():
71 raise ValueError("The geometric coordinates produced nonfinite weights.")
72 return dense
Encode layer weights with neuron coordinates and store biases directly.
decode(self, genome)
Decode into the dense parameter order used by QDpy feedforward policies.