1mod 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
31pub const SCHEMA_VERSION: u32 = 1;
33
34pub type Voxel = [u32; 3];
36
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct CircuitBoundary {
40 pub input_area_ids: BTreeSet<String>,
42 pub output_area_ids: BTreeSet<String>,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(tag = "kind", rename_all = "snake_case")]
49pub enum VoxelSelection {
50 All,
52 Listed {
54 voxels: Vec<Voxel>,
56 },
57}
58
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61pub struct Stimulus {
62 pub label: String,
64 pub area_id: String,
66 pub voxels: VoxelSelection,
68}
69
70#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
72pub struct StimulusProtocol {
73 pub stimuli: Vec<Stimulus>,
75 pub bursts_per_trial: u32,
77 pub trials_per_stimulus: u32,
79 pub reset_between_trials: bool,
81}
82
83#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
85#[serde(tag = "kind", rename_all = "snake_case")]
86pub enum CircuitMetric {
87 ResponseLatency {
89 output_area_id: String,
91 },
92 Selectivity {
94 output_area_id: String,
96 },
97 FiringRateBand {
99 area_id: String,
101 min_hz: f64,
103 max_hz: f64,
105 },
106 ActiveFraction {
108 output_area_id: String,
110 target: f64,
112 },
113 OutputPatternMatch {
115 output_area_id: String,
117 targets: BTreeMap<String, Vec<Voxel>>,
119 },
120}
121
122impl CircuitMetric {
123 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 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#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
147pub struct CircuitConstraints {
148 #[serde(default, skip_serializing_if = "Option::is_none")]
150 pub max_neuron_count: Option<u64>,
151 #[serde(default, skip_serializing_if = "Option::is_none")]
153 pub max_synapse_count: Option<u64>,
154}
155
156#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
158#[serde(rename_all = "snake_case")]
159pub enum CircuitParameter {
160 FiringThreshold,
162 LeakCoefficient,
164 RefractoryPeriod,
166 SnoozePeriod,
168 ConsecutiveFireCount,
170 PostsynapticPotential,
172 PostsynapticPotentialMax,
174 NeuronExcitability,
176}
177
178impl CircuitParameter {
179 pub fn is_integer(self) -> bool {
181 matches!(
182 self,
183 Self::RefractoryPeriod | Self::SnoozePeriod | Self::ConsecutiveFireCount
184 )
185 }
186}
187
188#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
190pub struct ParameterRange {
191 pub area_id: String,
193 pub parameter: CircuitParameter,
195 pub min: f64,
197 pub max: f64,
199}
200
201#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
203pub struct CircuitObjectiveSpec {
204 pub schema_version: u32,
206 pub region_id: String,
208 pub member_area_ids: BTreeSet<String>,
210 pub boundary: CircuitBoundary,
212 pub stimulus: StimulusProtocol,
214 pub metric: CircuitMetric,
216 pub constraints: CircuitConstraints,
218 pub search_space: Vec<ParameterRange>,
220 pub interface_frozen: bool,
222}
223
224#[derive(Debug, Clone, PartialEq, Eq, Error)]
226pub enum CircuitSpecError {
227 #[error("unsupported schema_version {found}; expected {expected}")]
229 SchemaVersion {
230 found: u32,
232 expected: u32,
234 },
235 #[error("field `{0}` must not be empty")]
237 EmptyField(&'static str),
238 #[error("the circuit has no member areas")]
240 NoMembers,
241 #[error("invalid boundary: {0}")]
243 InvalidBoundary(String),
244 #[error("area `{area_id}` is not {expected}")]
246 AreaNotAllowed {
247 area_id: String,
249 expected: &'static str,
251 },
252 #[error("invalid stimulus protocol: {0}")]
254 InvalidStimulus(String),
255 #[error("invalid metric: {0}")]
257 InvalidMetric(String),
258 #[error("invalid constraint: {0}")]
260 InvalidConstraint(String),
261 #[error("invalid search space: {0}")]
263 InvalidSearchSpace(String),
264}
265
266impl CircuitObjectiveSpec {
267 pub fn objective(&self) -> FitnessObjective {
269 self.metric.objective()
270 }
271
272 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}