Skip to main content

feagi_evolutionary/circuit/
mod.rs

1// Copyright 2025 Neuraville Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `CircuitObjectiveSpec` v1 — a measurable, circuit-level objective for one brain region.
5//!
6//! A circuit is a brain region including its descendant regions. The spec pins the region's
7//! membership and boundary at definition time, the stimulus protocol, the fitness metric, the
8//! resource constraints, and the parameters an optimizer may change. It is the portable contract
9//! shared by local and cloud evaluation (`docs/CIRCUIT_OPTIMIZER_ARCHITECTURE_AND_DESIGN.md`,
10//! Section 5). Every metric carries a fixed improvement direction, so a metric cannot be paired
11//! with the wrong objective.
12//!
13//! The spec performs no I/O; hosts build it from live session data and store it.
14//!
15//! @cursor:ffi-safe — plain data, serde-only, no runtime reflection.
16
17mod boundary;
18
19pub use boundary::{resolve_boundary, AreaRole, MappingEdge};
20
21use std::collections::{BTreeMap, BTreeSet};
22
23use serde::{Deserialize, Serialize};
24use thiserror::Error;
25
26use crate::evaluation::FitnessObjective;
27
28#[cfg(test)]
29mod tests;
30
31/// Wire/format version of the `CircuitObjectiveSpec` contract.
32pub const SCHEMA_VERSION: u32 = 1;
33
34/// Voxel coordinate `[x, y, z]` inside a cortical area.
35pub type Voxel = [u32; 3];
36
37/// Areas through which the circuit exchanges activity with the rest of the brain.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct CircuitBoundary {
40    /// Member areas that receive activity from outside the circuit (or from sensors).
41    pub input_area_ids: BTreeSet<String>,
42    /// Member areas that send activity outside the circuit (or to actuators).
43    pub output_area_ids: BTreeSet<String>,
44}
45
46/// Which voxels of an area a stimulus drives.
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(tag = "kind", rename_all = "snake_case")]
49pub enum VoxelSelection {
50    /// Every voxel of the area.
51    All,
52    /// An explicit, non-empty set of voxels.
53    Listed {
54        /// Voxels to drive.
55        voxels: Vec<Voxel>,
56    },
57}
58
59/// One stimulus applied to a boundary input area.
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61pub struct Stimulus {
62    /// Stimulus class. Several stimuli may share a label to drive multiple areas at once.
63    pub label: String,
64    /// Boundary input area receiving the stimulus.
65    pub area_id: String,
66    /// Voxels driven in that area.
67    pub voxels: VoxelSelection,
68}
69
70/// How the circuit is driven during one evaluation.
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
72pub struct StimulusProtocol {
73    /// Stimuli; may be empty only for metrics that observe spontaneous activity.
74    pub stimuli: Vec<Stimulus>,
75    /// Bursts observed per trial.
76    pub bursts_per_trial: u32,
77    /// Trials per stimulus label.
78    pub trials_per_stimulus: u32,
79    /// Reset the circuit's neural state before each trial.
80    pub reset_between_trials: bool,
81}
82
83/// Fitness metric for the circuit. Each variant has a fixed improvement direction.
84#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
85#[serde(tag = "kind", rename_all = "snake_case")]
86pub enum CircuitMetric {
87    /// Bursts from stimulus onset to first firing in a boundary output area (minimize).
88    ResponseLatency {
89        /// Boundary output area observed.
90        output_area_id: String,
91    },
92    /// How distinctly a boundary output area responds to different stimulus labels (maximize).
93    Selectivity {
94        /// Boundary output area observed.
95        output_area_id: String,
96    },
97    /// Distance of a member area's firing rate from a target band (minimize).
98    FiringRateBand {
99        /// Member area observed.
100        area_id: String,
101        /// Lower edge of the band, in hertz.
102        min_hz: f64,
103        /// Upper edge of the band, in hertz.
104        max_hz: f64,
105    },
106    /// Distance of a boundary output area's active-neuron fraction from a target (minimize).
107    ActiveFraction {
108        /// Boundary output area observed.
109        output_area_id: String,
110        /// Target fraction of neurons that fire, in `[0, 1]`.
111        target: f64,
112    },
113    /// Match between a boundary output area's firing and a target pattern per label (maximize).
114    OutputPatternMatch {
115        /// Boundary output area observed.
116        output_area_id: String,
117        /// Target voxels per stimulus label; every stimulus label needs a non-empty target.
118        targets: BTreeMap<String, Vec<Voxel>>,
119    },
120}
121
122impl CircuitMetric {
123    /// Direction in which this metric improves.
124    pub fn objective(&self) -> FitnessObjective {
125        match self {
126            Self::Selectivity { .. } | Self::OutputPatternMatch { .. } => {
127                FitnessObjective::Maximize
128            }
129            Self::ResponseLatency { .. }
130            | Self::FiringRateBand { .. }
131            | Self::ActiveFraction { .. } => FitnessObjective::Minimize,
132        }
133    }
134
135    /// Minimum number of distinct stimulus labels the metric needs.
136    fn required_labels(&self) -> usize {
137        match self {
138            Self::Selectivity { .. } => 2,
139            Self::ResponseLatency { .. } | Self::OutputPatternMatch { .. } => 1,
140            Self::FiringRateBand { .. } | Self::ActiveFraction { .. } => 0,
141        }
142    }
143}
144
145/// Resource limits a candidate circuit must respect.
146#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
147pub struct CircuitConstraints {
148    /// Maximum neurons in the circuit; `None` means unconstrained.
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    pub max_neuron_count: Option<u64>,
151    /// Maximum synapses in the circuit; `None` means unconstrained.
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub max_synapse_count: Option<u64>,
154}
155
156/// Neural parameter an optimizer may change in a member area.
157#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
158#[serde(rename_all = "snake_case")]
159pub enum CircuitParameter {
160    /// Membrane potential at which a neuron fires.
161    FiringThreshold,
162    /// Fraction of membrane potential lost per burst.
163    LeakCoefficient,
164    /// Bursts a neuron stays silent after firing (integer).
165    RefractoryPeriod,
166    /// Bursts a neuron is silenced after reaching its consecutive fire limit (integer).
167    SnoozePeriod,
168    /// Consecutive bursts a neuron may fire before snoozing (integer).
169    ConsecutiveFireCount,
170    /// Postsynaptic potential delivered per synapse.
171    PostsynapticPotential,
172    /// Upper limit of the postsynaptic potential.
173    PostsynapticPotentialMax,
174    /// Probability-like excitability scaling of firing.
175    NeuronExcitability,
176}
177
178impl CircuitParameter {
179    /// Whether the parameter takes whole, non-negative values.
180    pub fn is_integer(self) -> bool {
181        matches!(
182            self,
183            Self::RefractoryPeriod | Self::SnoozePeriod | Self::ConsecutiveFireCount
184        )
185    }
186}
187
188/// Allowed range of one parameter in one member area.
189#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
190pub struct ParameterRange {
191    /// Member area the parameter belongs to.
192    pub area_id: String,
193    /// Parameter that may change.
194    pub parameter: CircuitParameter,
195    /// Inclusive lower bound.
196    pub min: f64,
197    /// Inclusive upper bound.
198    pub max: f64,
199}
200
201/// A measurable objective for one circuit (brain region).
202#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
203pub struct CircuitObjectiveSpec {
204    /// Wire/format version; must equal [`SCHEMA_VERSION`].
205    pub schema_version: u32,
206    /// Brain region the circuit is rooted at.
207    pub region_id: String,
208    /// Cortical areas in the region and its descendants when the spec was defined.
209    pub member_area_ids: BTreeSet<String>,
210    /// Boundary of the circuit.
211    pub boundary: CircuitBoundary,
212    /// How the circuit is driven.
213    pub stimulus: StimulusProtocol,
214    /// Fitness metric.
215    pub metric: CircuitMetric,
216    /// Resource limits.
217    pub constraints: CircuitConstraints,
218    /// Parameters an optimizer may change; empty for analysis-only objectives.
219    pub search_space: Vec<ParameterRange>,
220    /// Keep mappings that cross the circuit boundary unchanged.
221    pub interface_frozen: bool,
222}
223
224/// Contract violation found by [`CircuitObjectiveSpec::validate`].
225#[derive(Debug, Clone, PartialEq, Eq, Error)]
226pub enum CircuitSpecError {
227    /// `schema_version` is not [`SCHEMA_VERSION`].
228    #[error("unsupported schema_version {found}; expected {expected}")]
229    SchemaVersion {
230        /// Version on the spec.
231        found: u32,
232        /// Version this crate reads.
233        expected: u32,
234    },
235    /// A required string field is empty or whitespace.
236    #[error("field `{0}` must not be empty")]
237    EmptyField(&'static str),
238    /// The circuit has no member areas.
239    #[error("the circuit has no member areas")]
240    NoMembers,
241    /// The boundary breaks an invariant.
242    #[error("invalid boundary: {0}")]
243    InvalidBoundary(String),
244    /// An area is referenced where it is not allowed.
245    #[error("area `{area_id}` is not {expected}")]
246    AreaNotAllowed {
247        /// Offending area.
248        area_id: String,
249        /// Set the area had to belong to.
250        expected: &'static str,
251    },
252    /// The stimulus protocol breaks an invariant.
253    #[error("invalid stimulus protocol: {0}")]
254    InvalidStimulus(String),
255    /// The metric breaks an invariant.
256    #[error("invalid metric: {0}")]
257    InvalidMetric(String),
258    /// A constraint breaks an invariant.
259    #[error("invalid constraint: {0}")]
260    InvalidConstraint(String),
261    /// The search space breaks an invariant.
262    #[error("invalid search space: {0}")]
263    InvalidSearchSpace(String),
264}
265
266impl CircuitObjectiveSpec {
267    /// Direction in which the spec's fitness improves.
268    pub fn objective(&self) -> FitnessObjective {
269        self.metric.objective()
270    }
271
272    /// Checks every contract invariant; hosts call this before storing or running a spec.
273    ///
274    /// # Errors
275    /// Returns the first [`CircuitSpecError`] found.
276    pub fn validate(&self) -> Result<(), CircuitSpecError> {
277        if self.schema_version != SCHEMA_VERSION {
278            return Err(CircuitSpecError::SchemaVersion {
279                found: self.schema_version,
280                expected: SCHEMA_VERSION,
281            });
282        }
283        require_text("region_id", &self.region_id)?;
284        validate_members(&self.member_area_ids)?;
285        validate_boundary(&self.boundary, &self.member_area_ids)?;
286        validate_stimulus(&self.stimulus, &self.boundary)?;
287        validate_metric(self)?;
288        validate_constraints(&self.constraints)?;
289        validate_search_space(&self.search_space, &self.member_area_ids)?;
290        Ok(())
291    }
292}
293
294fn require_text(field: &'static str, value: &str) -> Result<(), CircuitSpecError> {
295    if value.trim().is_empty() {
296        return Err(CircuitSpecError::EmptyField(field));
297    }
298    Ok(())
299}
300
301fn require_in(
302    area_id: &str,
303    set: &BTreeSet<String>,
304    expected: &'static str,
305) -> Result<(), CircuitSpecError> {
306    if !set.contains(area_id) {
307        return Err(CircuitSpecError::AreaNotAllowed {
308            area_id: area_id.to_string(),
309            expected,
310        });
311    }
312    Ok(())
313}
314
315fn validate_members(members: &BTreeSet<String>) -> Result<(), CircuitSpecError> {
316    if members.is_empty() {
317        return Err(CircuitSpecError::NoMembers);
318    }
319    for area_id in members {
320        require_text("member_area_ids[]", area_id)?;
321    }
322    Ok(())
323}
324
325fn validate_boundary(
326    boundary: &CircuitBoundary,
327    members: &BTreeSet<String>,
328) -> Result<(), CircuitSpecError> {
329    if boundary.input_area_ids.is_empty() {
330        return Err(CircuitSpecError::InvalidBoundary(
331            "at least one input area is required".to_string(),
332        ));
333    }
334    if boundary.output_area_ids.is_empty() {
335        return Err(CircuitSpecError::InvalidBoundary(
336            "at least one output area is required".to_string(),
337        ));
338    }
339    for area_id in &boundary.input_area_ids {
340        require_in(area_id, members, "a member area")?;
341    }
342    for area_id in &boundary.output_area_ids {
343        require_in(area_id, members, "a member area")?;
344    }
345    Ok(())
346}
347
348fn validate_voxels(voxels: &VoxelSelection, context: &str) -> Result<(), CircuitSpecError> {
349    if let VoxelSelection::Listed { voxels } = voxels {
350        if voxels.is_empty() {
351            return Err(CircuitSpecError::InvalidStimulus(format!(
352                "{context}: a listed voxel selection must not be empty"
353            )));
354        }
355        let unique: BTreeSet<&Voxel> = voxels.iter().collect();
356        if unique.len() != voxels.len() {
357            return Err(CircuitSpecError::InvalidStimulus(format!(
358                "{context}: voxels must be distinct"
359            )));
360        }
361    }
362    Ok(())
363}
364
365fn validate_stimulus(
366    protocol: &StimulusProtocol,
367    boundary: &CircuitBoundary,
368) -> Result<(), CircuitSpecError> {
369    if protocol.bursts_per_trial == 0 {
370        return Err(CircuitSpecError::InvalidStimulus(
371            "bursts_per_trial must be at least 1".to_string(),
372        ));
373    }
374    if protocol.trials_per_stimulus == 0 {
375        return Err(CircuitSpecError::InvalidStimulus(
376            "trials_per_stimulus must be at least 1".to_string(),
377        ));
378    }
379    let mut seen: BTreeSet<(&str, &str)> = BTreeSet::new();
380    for stimulus in &protocol.stimuli {
381        require_text("stimulus.stimuli[].label", &stimulus.label)?;
382        require_in(
383            &stimulus.area_id,
384            &boundary.input_area_ids,
385            "a boundary input area",
386        )?;
387        validate_voxels(&stimulus.voxels, &stimulus.label)?;
388        if !seen.insert((stimulus.label.as_str(), stimulus.area_id.as_str())) {
389            return Err(CircuitSpecError::InvalidStimulus(format!(
390                "label `{}` drives area `{}` more than once",
391                stimulus.label, stimulus.area_id
392            )));
393        }
394    }
395    Ok(())
396}
397
398fn stimulus_labels(protocol: &StimulusProtocol) -> BTreeSet<&str> {
399    protocol.stimuli.iter().map(|s| s.label.as_str()).collect()
400}
401
402fn validate_metric(spec: &CircuitObjectiveSpec) -> Result<(), CircuitSpecError> {
403    let metric = &spec.metric;
404    let labels = stimulus_labels(&spec.stimulus);
405    let required = metric.required_labels();
406    if labels.len() < required {
407        return Err(CircuitSpecError::InvalidMetric(format!(
408            "this metric needs at least {required} distinct stimulus label(s); found {}",
409            labels.len()
410        )));
411    }
412    let outputs = &spec.boundary.output_area_ids;
413    match metric {
414        CircuitMetric::ResponseLatency { output_area_id }
415        | CircuitMetric::Selectivity { output_area_id } => {
416            require_in(output_area_id, outputs, "a boundary output area")
417        }
418        CircuitMetric::FiringRateBand {
419            area_id,
420            min_hz,
421            max_hz,
422        } => {
423            require_in(area_id, &spec.member_area_ids, "a member area")?;
424            let valid = min_hz.is_finite() && max_hz.is_finite() && *min_hz >= 0.0;
425            if !valid || min_hz > max_hz {
426                return Err(CircuitSpecError::InvalidMetric(
427                    "firing rate band must be finite with 0 <= min_hz <= max_hz".to_string(),
428                ));
429            }
430            Ok(())
431        }
432        CircuitMetric::ActiveFraction {
433            output_area_id,
434            target,
435        } => {
436            require_in(output_area_id, outputs, "a boundary output area")?;
437            if !(0.0..=1.0).contains(target) {
438                return Err(CircuitSpecError::InvalidMetric(
439                    "active fraction target must be in [0, 1]".to_string(),
440                ));
441            }
442            Ok(())
443        }
444        CircuitMetric::OutputPatternMatch {
445            output_area_id,
446            targets,
447        } => {
448            require_in(output_area_id, outputs, "a boundary output area")?;
449            validate_pattern_targets(targets, &labels)
450        }
451    }
452}
453
454fn validate_pattern_targets(
455    targets: &BTreeMap<String, Vec<Voxel>>,
456    labels: &BTreeSet<&str>,
457) -> Result<(), CircuitSpecError> {
458    let target_labels: BTreeSet<&str> = targets.keys().map(String::as_str).collect();
459    if &target_labels != labels {
460        return Err(CircuitSpecError::InvalidMetric(
461            "output pattern targets must cover exactly the stimulus labels".to_string(),
462        ));
463    }
464    for (label, voxels) in targets {
465        if voxels.is_empty() {
466            return Err(CircuitSpecError::InvalidMetric(format!(
467                "target pattern for `{label}` must not be empty"
468            )));
469        }
470        let unique: BTreeSet<&Voxel> = voxels.iter().collect();
471        if unique.len() != voxels.len() {
472            return Err(CircuitSpecError::InvalidMetric(format!(
473                "target pattern for `{label}` has duplicate voxels"
474            )));
475        }
476    }
477    Ok(())
478}
479
480fn validate_constraints(constraints: &CircuitConstraints) -> Result<(), CircuitSpecError> {
481    if constraints.max_neuron_count == Some(0) {
482        return Err(CircuitSpecError::InvalidConstraint(
483            "max_neuron_count must be at least 1 when set".to_string(),
484        ));
485    }
486    if constraints.max_synapse_count == Some(0) {
487        return Err(CircuitSpecError::InvalidConstraint(
488            "max_synapse_count must be at least 1 when set".to_string(),
489        ));
490    }
491    Ok(())
492}
493
494fn validate_search_space(
495    ranges: &[ParameterRange],
496    members: &BTreeSet<String>,
497) -> Result<(), CircuitSpecError> {
498    let mut seen: BTreeSet<(&str, CircuitParameter)> = BTreeSet::new();
499    for range in ranges {
500        require_in(&range.area_id, members, "a member area")?;
501        if !seen.insert((range.area_id.as_str(), range.parameter)) {
502            return Err(CircuitSpecError::InvalidSearchSpace(format!(
503                "{:?} in `{}` appears more than once",
504                range.parameter, range.area_id
505            )));
506        }
507        if !range.min.is_finite() || !range.max.is_finite() || range.min > range.max {
508            return Err(CircuitSpecError::InvalidSearchSpace(format!(
509                "{:?} in `{}` needs finite bounds with min <= max",
510                range.parameter, range.area_id
511            )));
512        }
513        let whole = range.min.fract() == 0.0 && range.max.fract() == 0.0;
514        if range.parameter.is_integer() && (!whole || range.min < 0.0) {
515            return Err(CircuitSpecError::InvalidSearchSpace(format!(
516                "{:?} in `{}` takes whole, non-negative bounds",
517                range.parameter, range.area_id
518            )));
519        }
520    }
521    Ok(())
522}