evonet 0.1.0.dev27__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
evonet/__init__.py ADDED
File without changes
evonet/activation.py ADDED
@@ -0,0 +1,207 @@
1
+ # SPDX-License-Identifier: MIT
2
+ """
3
+ Activation functions for evolvable neural networks.
4
+
5
+ Includes standard nonlinearities (ReLU, Tanh, Sigmoid), linear and threshold functions,
6
+ modern smooth activations (Swish, Mish), and a softmax utility.
7
+
8
+ All functions are scalar-based and stateless, unless noted otherwise.
9
+ """
10
+
11
+ import random
12
+ from typing import Callable, List, Tuple, Union
13
+
14
+ import numpy as np
15
+
16
+ Scalar = Union[int, float]
17
+
18
+
19
+ # Common Activation Functions
20
+
21
+
22
+ def tanh(x: Scalar) -> float:
23
+ """Hyperbolic tangent activation: [-inf, inf] --> [-1, 1]."""
24
+ return float(np.tanh(x))
25
+
26
+
27
+ def ntanh(x: Scalar) -> float:
28
+ """Normalized tanh: (tanh(x) + 1) / 2 --> [0, 1]."""
29
+ return (np.tanh(x) + 1) / 2
30
+
31
+
32
+ def sigmoid(x: Scalar) -> float:
33
+ """Sigmoid/logistic function: [-inf, inf] --> [0, 1]."""
34
+ x = np.clip(float(x), -500, 500)
35
+ return 1 / (1 + np.exp(-x))
36
+
37
+
38
+ def relu(x: Scalar) -> float:
39
+ """ReLU: max(0, x)."""
40
+ return max(0.0, float(x))
41
+
42
+
43
+ def relu_max1(x: Scalar) -> float:
44
+ """ReLU clipped to [0, 1]."""
45
+ return min(max(0.0, float(x)), 1.0)
46
+
47
+
48
+ def leaky_relu(x: Scalar, alpha: float = 0.01) -> float:
49
+ """Leaky ReLU: x if x ≥ 0 else alpha * x."""
50
+ x = float(x)
51
+ return x if x >= 0 else alpha * x
52
+
53
+
54
+ def elu(x: Scalar, alpha: float = 1.0) -> float:
55
+ """Exponential Linear Unit."""
56
+ x = float(x)
57
+ return x if x >= 0 else alpha * (np.exp(x) - 1)
58
+
59
+
60
+ def selu(x: Scalar, alpha: float = 1.67326324, scale: float = 1.05070098) -> float:
61
+ """Scaled Exponential Linear Unit (SELU)."""
62
+ x = float(x)
63
+ return scale * x if x >= 0 else scale * alpha * (np.exp(x) - 1)
64
+
65
+
66
+ def gaussian(x: Scalar) -> float:
67
+ """Gaussian bell function: exp(-x^2)."""
68
+ x = float(x)
69
+ if np.abs(x) > 38:
70
+ return 0.0
71
+ return np.exp(-(x**2))
72
+
73
+
74
+ # Threshold Functions
75
+
76
+
77
+ def binary(x: Scalar) -> float:
78
+ """Step function: 1 if x > 0 else 0."""
79
+ return 1.0 if x > 0 else 0.0
80
+
81
+
82
+ def signum(x: Scalar) -> float:
83
+ """Sign function: 1, -1 or 0 depending on sign of x."""
84
+ return 1.0 if x > 0 else -1.0 if x < 0 else 0.0
85
+
86
+
87
+ # Linear Variants
88
+
89
+
90
+ def linear(x: Scalar) -> float:
91
+ """Linear identity: returns x."""
92
+ return float(x)
93
+
94
+
95
+ def linear_max1(x: Scalar) -> float:
96
+ """Linear function clipped to [-1, 1]."""
97
+ return min(max(-1.0, float(x)), 1.0)
98
+
99
+
100
+ def invert(x: Scalar) -> float:
101
+ """Returns -x."""
102
+ return -float(x)
103
+
104
+
105
+ def null(_: Scalar = 0) -> float:
106
+ """Always returns 0.0."""
107
+ return 0.0
108
+
109
+
110
+ # Modern Functions
111
+
112
+
113
+ def swish(x: Scalar) -> float:
114
+ """Swish activation: x * sigmoid(x). Smooth and non-monotonic."""
115
+ return float(x) * sigmoid(x)
116
+
117
+
118
+ def mish(x: Scalar) -> float:
119
+ """Mish activation: x * tanh(softplus(x))."""
120
+ return float(x) * np.tanh(np.log1p(np.exp(x)))
121
+
122
+
123
+ def softplus(x: Scalar) -> float:
124
+ """Smooth ReLU approximation: log(1 + exp(x))."""
125
+ return np.log1p(np.exp(float(x)))
126
+
127
+
128
+ def softsign(x: Scalar) -> float:
129
+ """Smooth alternative to tanh: x / (1 + |x|)."""
130
+ return float(x) / (1 + abs(float(x)))
131
+
132
+
133
+ def hard_sigmoid(x: Scalar) -> float:
134
+ """Piecewise linear approximation of sigmoid."""
135
+ return min(max(0.0, 0.2 * float(x) + 0.5), 1.0)
136
+
137
+
138
+ # Special Functions
139
+
140
+
141
+ def softmax(values: Union[List[float], Tuple[float], np.ndarray]) -> np.ndarray:
142
+ """
143
+ Applies softmax over a list of values.
144
+
145
+ Args:
146
+ values: Array-like input with ≥2 values.
147
+
148
+ Returns:
149
+ np.ndarray: Normalized softmax output summing to 1.
150
+ """
151
+ arr = np.array(values, dtype=float)
152
+ if arr.size < 2:
153
+ raise ValueError("Softmax input must have at least two values")
154
+ exp_x = np.exp(arr - np.max(arr)) # For numerical stability
155
+ return exp_x / np.sum(exp_x)
156
+
157
+
158
+ def random_function_name(activations: list[str] | None = None) -> str:
159
+ """
160
+ Return a random activation function name from the registry.
161
+
162
+ Args:
163
+ activations (list[str] | None): Optional subset of allowed function names.
164
+ If None, all registered activation names are considered.
165
+
166
+ Raises:
167
+ ValueError: If any name is not in the activation registry.
168
+
169
+ Returns:
170
+ str: Randomly selected activation function name.
171
+ """
172
+
173
+ if activations is None:
174
+ activations = list(ACTIVATIONS.keys())
175
+
176
+ invalid = set(activations) - set(ACTIVATIONS.keys())
177
+ if invalid:
178
+ raise ValueError(f"Invalid activation functions: {invalid}")
179
+
180
+ return random.choice(activations)
181
+
182
+
183
+ # Registry
184
+
185
+ ACTIVATIONS: dict[str, Callable] = {
186
+ "tanh": tanh,
187
+ "ntanh": ntanh,
188
+ "sigmoid": sigmoid,
189
+ "relu": relu,
190
+ "relu_max1": relu_max1,
191
+ "leaky_relu": leaky_relu,
192
+ "elu": elu,
193
+ "selu": selu,
194
+ "gaussian": gaussian,
195
+ "binary": binary,
196
+ "signum": signum,
197
+ "linear": linear,
198
+ "linear_max1": linear_max1,
199
+ "invert": invert,
200
+ "null": null,
201
+ "swish": swish,
202
+ "mish": mish,
203
+ "softplus": softplus,
204
+ "softsign": softsign,
205
+ "hard_sigmoid": hard_sigmoid,
206
+ "softmax": softmax,
207
+ }
evonet/connection.py ADDED
@@ -0,0 +1,124 @@
1
+ # SPDX-License-Identifier: MIT
2
+ """
3
+ Connection between neurons in an evolvable neural network.
4
+
5
+ A connection links a source neuron to a target neuron and transmits a weighted signal.
6
+ Supports optional connection types for specialized behaviors (e.g. inhibitory,
7
+ recurrent).
8
+ """
9
+
10
+
11
+ from collections import deque
12
+ from typing import TYPE_CHECKING, Deque, Optional
13
+
14
+ from evonet.enums import ConnectionType
15
+
16
+ if TYPE_CHECKING:
17
+ from evonet.neuron import Neuron
18
+
19
+
20
+ class Connection:
21
+ """
22
+ Represents a directed, weighted connection between two neurons.
23
+
24
+ Attributes:
25
+ source (Neuron): The source neuron (presynaptic).
26
+ target (Neuron): The target neuron (postsynaptic).
27
+ weight (float): Multiplicative weight of the transmitted signal.
28
+ delay (int): Delay in discrete time steps (used for recurrent edges).
29
+ type (ConnectionType): Type of connection (e.g. standard, recurrent).
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ source: "Neuron",
35
+ target: "Neuron",
36
+ weight: float = 1.0,
37
+ delay: int = 0,
38
+ conn_type: ConnectionType = ConnectionType.STANDARD,
39
+ ) -> None:
40
+
41
+ if delay < 0:
42
+ raise ValueError("delay must be >= 0")
43
+
44
+ # Normalize: recurrent implies delay >= 1
45
+ if conn_type is ConnectionType.RECURRENT and delay == 0:
46
+ delay = 1
47
+
48
+ self.source = source
49
+ self.target = target
50
+ self.weight = weight
51
+ self.delay = delay
52
+ self.type = conn_type
53
+
54
+ self._history: Optional[Deque[float]] = None
55
+ if self.type is ConnectionType.RECURRENT:
56
+ self._history = deque(maxlen=self.delay)
57
+
58
+ def set_delay(self, delay: int) -> None:
59
+ if self.type is not ConnectionType.RECURRENT:
60
+ raise ValueError("set_delay is only valid for recurrent connections")
61
+ if delay <= 0:
62
+ delay = 1
63
+ self.delay = int(delay)
64
+ self._history = deque(maxlen=self.delay)
65
+
66
+ def push_source_output(self, value: float) -> None:
67
+ """
68
+ Push the current source output into the delay buffer.
69
+
70
+ This should be called once per time step after the network computed outputs.
71
+ """
72
+ if self._history is None:
73
+ return
74
+ self._history.append(float(value))
75
+
76
+ def delayed_source_output(self) -> float:
77
+ """
78
+ Return the delayed source output.
79
+
80
+ Semantics:
81
+ - delay == 0 -> no delay buffer used (caller decides what to do)
82
+ - delay > 0 -> returns output[t-delay] if available else 0.0
83
+ """
84
+ if self.delay == 0:
85
+ return 0.0
86
+
87
+ if self._history is None:
88
+ return 0.0
89
+
90
+ if len(self._history) < self.delay:
91
+ return 0.0
92
+
93
+ return float(self._history[0])
94
+
95
+ def reset_buffer(self) -> None:
96
+ """Clear the internal delay history buffer."""
97
+ if self._history is not None:
98
+ self._history.clear()
99
+
100
+ def get_signal(self) -> float:
101
+ """
102
+ Return the weighted signal from the source neuron.
103
+
104
+ Returns:
105
+ float: source.output × weight
106
+ """
107
+
108
+ return self.source.output * self.weight
109
+
110
+ def __repr__(self) -> str:
111
+ """
112
+ Return a concise string representation of the connection.
113
+
114
+ Example:
115
+ <Conn abc123 -> def456 w=0.85 d=3 type=standard>
116
+ """
117
+
118
+ type_str = self.type.name.lower()
119
+ return (
120
+ f"<Conn {self.source.id[:6]} "
121
+ f"-> {self.target.id[:6]} "
122
+ f"d={self.delay} "
123
+ f"w={self.weight:.2f} type={type_str}>"
124
+ )