File size: 14,903 Bytes
5e0b58b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
"""Homeostatic self-regulation for Brain-5D v0.5.

This module provides firing-rate and energy homeostasis through a post-step
observer that continuously adjusts neuron thresholds and energy levels
to maintain stable network activity.
"""

from __future__ import annotations

import math
from collections.abc import Mapping
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, cast

from .signals import HomeostasisSignal

if TYPE_CHECKING:
    from src.core.network import NeuralNetwork, StepResult


# ============================================================================
# Parameters
# ============================================================================


@dataclass(frozen=True, slots=True)
class HomeostasisParameters:
    """Validated parameters for firing-rate and energy homeostasis."""

    enabled: bool = False
    target_rate_hz: float = 5.0
    rate_tau_ticks: float = 200.0
    threshold_learning_rate: float = 0.001
    threshold_min: float = -15.0
    threshold_max: float = 30.0
    energy_enabled: bool = True
    target_energy: float = 1.0
    energy_recovery_rate: float = 0.001
    energy_min: float = 0.0
    energy_max: float = 1.0

    @classmethod
    def from_config(cls, config: Mapping[str, object]) -> HomeostasisParameters:
        """Load the optional ``homeostasis`` section from configuration."""
        section = _string_mapping(config.get("homeostasis", {}), "homeostasis")
        params = cls(
            enabled=_bool_value(section.get("enabled", False), "enabled"),
            target_rate_hz=_float_value(
                section.get("target_rate_hz", 5.0), "target_rate_hz"
            ),
            rate_tau_ticks=_float_value(
                section.get("rate_tau_ticks", 200.0), "rate_tau_ticks"
            ),
            threshold_learning_rate=_float_value(
                section.get("threshold_learning_rate", 0.001),
                "threshold_learning_rate",
            ),
            threshold_min=_float_value(
                section.get("threshold_min", -15.0), "threshold_min"
            ),
            threshold_max=_float_value(
                section.get("threshold_max", 30.0), "threshold_max"
            ),
            energy_enabled=_bool_value(
                section.get("energy_enabled", True), "energy_enabled"
            ),
            target_energy=_float_value(
                section.get("target_energy", 1.0), "target_energy"
            ),
            energy_recovery_rate=_float_value(
                section.get("energy_recovery_rate", 0.001),
                "energy_recovery_rate",
            ),
            energy_min=_float_value(section.get("energy_min", 0.0), "energy_min"),
            energy_max=_float_value(section.get("energy_max", 1.0), "energy_max"),
        )
        params.validate()
        return params

    def validate(self) -> None:
        """Reject unstable or nonsensical regulator parameters."""
        if self.target_rate_hz < 0.0 or not math.isfinite(self.target_rate_hz):
            raise ValueError("homeostasis.target_rate_hz must be finite and >= 0")
        if self.rate_tau_ticks <= 0.0 or not math.isfinite(self.rate_tau_ticks):
            raise ValueError("homeostasis.rate_tau_ticks must be finite and > 0")
        if self.threshold_learning_rate < 0.0 or not math.isfinite(
            self.threshold_learning_rate
        ):
            raise ValueError("threshold_learning_rate must be finite and >= 0")
        if self.threshold_min > self.threshold_max:
            raise ValueError("threshold_min must be <= threshold_max")
        if not 0.0 <= self.energy_recovery_rate <= 1.0:
            raise ValueError("energy_recovery_rate must be between 0 and 1")
        if self.energy_min > self.energy_max:
            raise ValueError("energy_min must be <= energy_max")
        if not self.energy_min <= self.target_energy <= self.energy_max:
            raise ValueError("target_energy must be inside energy bounds")


# ============================================================================
# Statistics
# ============================================================================


@dataclass(frozen=True, slots=True)
class HomeostasisStats:
    """Immutable observable state of the regulator."""

    enabled: bool
    updates: int
    target_rate_hz: float
    mean_rate_hz: float
    mean_rate_error_hz: float
    mean_threshold_adaptation: float
    target_energy: float
    mean_energy: float
    mean_energy_error: float
    active_neurons: int

    def to_dict(self) -> dict[str, Any]:
        """Convert to dictionary for serialization."""
        return {
            "enabled": self.enabled,
            "updates": self.updates,
            "target_rate_hz": self.target_rate_hz,
            "mean_rate_hz": self.mean_rate_hz,
            "mean_rate_error_hz": self.mean_rate_error_hz,
            "mean_threshold_adaptation": self.mean_threshold_adaptation,
            "target_energy": self.target_energy,
            "mean_energy": self.mean_energy,
            "mean_energy_error": self.mean_energy_error,
            "active_neurons": self.active_neurons,
        }


# ============================================================================
# Engine
# ============================================================================


class HomeostasisEngine:
    """Regulate firing rate and energy through a post-step observer.

    This engine attaches to the network as a post-step hook and continuously
    adjusts neuron thresholds and energy levels to maintain homeostasis.

    Example:
        >>> engine = HomeostasisEngine(network, config)
        >>> engine.attach()
        >>> # ... run simulation ...
        >>> stats = engine.stats
        >>> signal = engine.build_signal()
    """

    def __init__(self, network: NeuralNetwork, config: Mapping[str, object]) -> None:
        """Initialize the homeostasis engine.

        Args:
            network: The neural network to regulate.
            config: Configuration dictionary containing the 'homeostasis' section.
        """
        self.network: NeuralNetwork = network
        self.params: HomeostasisParameters = HomeostasisParameters.from_config(config)
        self._rates_hz: dict[int, float] = {}
        self._attached: bool = False
        self._updates: int = 0
        self._last_stats: HomeostasisStats = HomeostasisStats(
            enabled=self.params.enabled,
            updates=0,
            target_rate_hz=self.params.target_rate_hz,
            mean_rate_hz=0.0,
            mean_rate_error_hz=-self.params.target_rate_hz,
            mean_threshold_adaptation=0.0,
            target_energy=self.params.target_energy,
            mean_energy=0.0,
            mean_energy_error=self.params.target_energy,
            active_neurons=0,
        )

    @property
    def enabled(self) -> bool:
        """Return whether self-regulation is active."""
        return self.params.enabled

    @property
    def stats(self) -> HomeostasisStats:
        """Return the latest immutable regulator metrics."""
        return self._last_stats

    def attach(self) -> None:
        """Attach the regulator to the network post-step hook."""
        if not self._attached:
            self.network.add_post_step_hook(self.update)
            self._attached = True

    def detach(self) -> None:
        """Detach the regulator from the network."""
        if self._attached:
            self.network.remove_post_step_hook(self.update)
            self._attached = False

    def update(self, step_result: StepResult) -> None:
        """Observe one completed tick and apply slow homeostatic feedback.

        Args:
            step_result: The result of the completed network step.
        """
        if not self.params.enabled:
            return

        spike_ids = set(step_result.spike_ids)
        alpha = 1.0 - math.exp(-1.0 / self.params.rate_tau_ticks)
        # The reference core always uses dt_ms = 1.0
        instantaneous_hz: float = 1000.0

        rate_sum: float = 0.0
        threshold_sum: float = 0.0
        energy_sum: float = 0.0
        active_neurons: int = 0
        live_ids = set(self.network.neurons)

        # Remove rates for deleted neurons
        self._rates_hz = {
            neuron_id: rate
            for neuron_id, rate in self._rates_hz.items()
            if neuron_id in live_ids
        }

        # Explicit deterministic iteration: sort by neuron_id
        for neuron_id, neuron in sorted(self.network.neurons.items()):
            previous_rate = self._rates_hz.get(neuron_id, 0.0)
            sample = instantaneous_hz if neuron_id in spike_ids else 0.0
            rate = previous_rate + alpha * (sample - previous_rate)
            self._rates_hz[neuron_id] = rate

            if neuron_id in spike_ids:
                active_neurons += 1

            # Rate homeostasis
            rate_error = rate - self.params.target_rate_hz
            adjustment = self.params.threshold_learning_rate * rate_error
            neuron.threshold_adaptation = _clamp(
                neuron.threshold_adaptation + adjustment,
                self.params.threshold_min,
                self.params.threshold_max,
            )
            neuron.mark_dirty()

            # Energy homeostasis
            if self.params.energy_enabled:
                recovery = self.params.energy_recovery_rate * (
                    self.params.target_energy - neuron.energy
                )
                neuron.energy = _clamp(
                    neuron.energy + recovery,
                    self.params.energy_min,
                    self.params.energy_max,
                )
                neuron.mark_dirty()

            rate_sum += rate
            threshold_sum += neuron.threshold_adaptation
            energy_sum += neuron.energy

        self._updates += 1
        count = len(self.network.neurons)

        mean_rate = rate_sum / count if count else 0.0
        mean_threshold = threshold_sum / count if count else 0.0
        mean_energy = energy_sum / count if count else 0.0

        self._last_stats = HomeostasisStats(
            enabled=True,
            updates=self._updates,
            target_rate_hz=self.params.target_rate_hz,
            mean_rate_hz=mean_rate,
            mean_rate_error_hz=mean_rate - self.params.target_rate_hz,
            mean_threshold_adaptation=mean_threshold,
            target_energy=self.params.target_energy,
            mean_energy=mean_energy,
            mean_energy_error=self.params.target_energy - mean_energy,
            active_neurons=active_neurons,
        )

    def rate_hz(self, neuron_id: int) -> float:
        """Return the exponentially smoothed firing rate of one neuron.

        Args:
            neuron_id: ID of the neuron.

        Returns:
            Smoothed firing rate in Hz.

        Raises:
            KeyError: If the neuron does not exist.
        """
        if neuron_id not in self.network.neurons:
            raise KeyError(f"Neuron {neuron_id} not found")
        return self._rates_hz.get(neuron_id, 0.0)

    def build_signal(self, tick: int | None = None) -> HomeostasisSignal:
        """Build an immutable aggregate for higher-level policies.

        Args:
            tick: Optional tick number. If not provided, uses current network tick.

        Returns:
            A HomeostasisSignal with aggregate statistics.
        """
        neurons = tuple(self.network.neurons.items())
        rates = tuple(self._rates_hz.get(neuron_id, 0.0) for neuron_id, _ in neurons)
        energies = tuple(float(neuron.energy) for _, neuron in neurons)
        adaptations = tuple(float(neuron.threshold_adaptation) for _, neuron in neurons)

        count = len(neurons)
        mean_rate = sum(rates) / count if count else 0.0
        variance = (
            sum((rate - mean_rate) ** 2 for rate in rates) / count if count else 0.0
        )
        mean_energy = sum(energies) / count if count else 0.0
        mean_adaptation = sum(adaptations) / count if count else 0.0

        low_rate_boundary = self.params.target_rate_hz * 0.5
        high_rate_boundary = self.params.target_rate_hz * 1.5
        low_energy_boundary = (self.params.energy_min + self.params.target_energy) / 2.0
        high_energy_boundary = (
            self.params.target_energy + self.params.energy_max
        ) / 2.0

        return HomeostasisSignal(
            tick=int(self.network.current_tick if tick is None else tick),
            neuron_count=count,
            target_rate_hz=self.params.target_rate_hz,
            mean_rate_hz=mean_rate,
            rate_variance_hz2=variance,
            rate_error_hz=mean_rate - self.params.target_rate_hz,
            mean_threshold_adaptation=mean_adaptation,
            mean_energy=mean_energy,
            mean_energy_error=self.params.target_energy - mean_energy,
            low_rate_neurons=sum(rate < low_rate_boundary for rate in rates),
            high_rate_neurons=sum(rate > high_rate_boundary for rate in rates),
            low_energy_neurons=sum(energy < low_energy_boundary for energy in energies),
            high_energy_neurons=sum(
                energy > high_energy_boundary for energy in energies
            ),
        )


# ============================================================================
# Helper Functions
# ============================================================================


def _string_mapping(value: object, name: str) -> dict[str, object]:
    """Convert a Mapping to a dict with string keys."""
    if not isinstance(value, Mapping):
        raise TypeError(f"{name} config must be a mapping")

    mapping = cast(Mapping[object, object], value)
    result: dict[str, object] = {}
    for key, item in mapping.items():
        if not isinstance(key, str):
            raise TypeError(f"{name} config keys must be strings")
        result[key] = item
    return result


def _clamp(value: float, minimum: float, maximum: float) -> float:
    """Clamp a value between minimum and maximum."""
    return max(minimum, min(maximum, value))


def _float_value(value: object, name: str) -> float:
    """Extract a float value from a configuration field."""
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise TypeError(f"homeostasis.{name} must be numeric")
    return float(value)


def _bool_value(value: object, name: str) -> bool:
    """Extract a boolean value from a configuration field."""
    if not isinstance(value, bool):
        raise TypeError(f"homeostasis.{name} must be boolean")
    return value


# ============================================================================
# Module Exports
# ============================================================================

__all__ = [
    "HomeostasisEngine",
    "HomeostasisParameters",
    "HomeostasisStats",
]