feagi_structures/genomic/
modulator.rs1use serde::{Deserialize, Serialize};
11use std::fmt;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
15pub enum ModulatorKind {
16 FiringThreshold,
18 Leak,
20 FiringProbability,
22 TransmissionGain,
24 Reward,
26 LearningRate,
28 Gate,
31 MemoryFormation,
34 MemoryFreeze,
39 MemoryCapture,
42}
43
44impl ModulatorKind {
45 pub fn as_str(self) -> &'static str {
47 match self {
48 Self::FiringThreshold => "neuro.firing_threshold",
49 Self::Leak => "neuro.leak",
50 Self::FiringProbability => "neuro.firing_probability",
51 Self::TransmissionGain => "synaptic.transmission_gain",
52 Self::Reward => "synaptic.reward",
53 Self::LearningRate => "synaptic.learning_rate",
54 Self::Gate => "synaptic.gate",
55 Self::MemoryFormation => "memory.formation",
56 Self::MemoryFreeze => "memory.freeze",
57 Self::MemoryCapture => "memory.capture",
58 }
59 }
60
61 pub fn parse(value: &str) -> Result<Self, String> {
63 match value {
64 "neuro.firing_threshold" => Ok(Self::FiringThreshold),
65 "neuro.leak" => Ok(Self::Leak),
66 "neuro.firing_probability" => Ok(Self::FiringProbability),
67 "synaptic.transmission_gain" => Ok(Self::TransmissionGain),
68 "synaptic.reward" => Ok(Self::Reward),
69 "synaptic.learning_rate" => Ok(Self::LearningRate),
70 "synaptic.gate" => Ok(Self::Gate),
71 "memory.formation" => Ok(Self::MemoryFormation),
72 "memory.freeze" => Ok(Self::MemoryFreeze),
73 "memory.capture" => Ok(Self::MemoryCapture),
74 other => Err(format!("unknown modulator type '{other}'")),
75 }
76 }
77
78 pub fn all() -> &'static [Self] {
80 &[
81 Self::FiringThreshold,
82 Self::Leak,
83 Self::FiringProbability,
84 Self::TransmissionGain,
85 Self::Reward,
86 Self::LearningRate,
87 Self::Gate,
88 Self::MemoryFormation,
89 Self::MemoryFreeze,
90 Self::MemoryCapture,
91 ]
92 }
93
94 pub fn is_neuromodulator(self) -> bool {
96 matches!(
97 self,
98 Self::FiringThreshold | Self::Leak | Self::FiringProbability
99 )
100 }
101
102 pub fn is_area_level(self) -> bool {
105 self.is_neuromodulator()
106 || matches!(
107 self,
108 Self::MemoryFormation | Self::MemoryFreeze | Self::MemoryCapture
109 )
110 }
111
112 pub fn is_synaptic(self) -> bool {
114 !self.is_area_level()
115 }
116
117 pub fn combines_by_addition(self) -> bool {
119 matches!(self, Self::Reward)
120 }
121}
122
123impl fmt::Display for ModulatorKind {
124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125 f.write_str(self.as_str())
126 }
127}
128
129#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct ModulatorValidationError(pub String);
132
133impl fmt::Display for ModulatorValidationError {
134 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135 f.write_str(&self.0)
136 }
137}
138
139pub fn validate_instance_fields(
145 magnitude_percent: f32,
146 effect_duration_bursts: u16,
147 graded: bool,
148 full_scale_potential: Option<f32>,
149) -> Result<(), ModulatorValidationError> {
150 if !magnitude_percent.is_finite() || magnitude_percent < -100.0 {
151 return Err(ModulatorValidationError(
152 "magnitude_percent must be finite and >= -100".to_string(),
153 ));
154 }
155 if effect_duration_bursts < 1 {
156 return Err(ModulatorValidationError(
157 "effect_duration_bursts must be >= 1".to_string(),
158 ));
159 }
160 if graded {
161 match full_scale_potential {
162 Some(scale) if scale.is_finite() && scale > 0.0 => {}
163 _ => {
164 return Err(ModulatorValidationError(
165 "graded modulators require full_scale_potential > 0".to_string(),
166 ));
167 }
168 }
169 }
170 Ok(())
171}
172
173pub fn validate_spike_train(
175 enabled: bool,
176 consecutive_fire_limit: u16,
177) -> Result<(), ModulatorValidationError> {
178 if enabled && consecutive_fire_limit < 1 {
179 return Err(ModulatorValidationError(
180 "spike_train requires consecutive_fire_limit >= 1".to_string(),
181 ));
182 }
183 Ok(())
184}
185
186pub fn modulator_signal(
192 magnitude_percent: f32,
193 fired: bool,
194 graded: bool,
195 membrane_potential: f32,
196 full_scale_potential: f32,
197) -> f32 {
198 if !fired {
199 return 0.0;
200 }
201 let strength = if graded {
202 (membrane_potential / full_scale_potential).min(1.0)
203 } else {
204 1.0
205 };
206 (magnitude_percent / 100.0) * strength
207}
208
209pub fn multiplicative_factor(signals: &[f32]) -> f32 {
211 signals
212 .iter()
213 .fold(1.0_f32, |acc, signal| acc * (1.0 + signal))
214}
215
216pub fn gate_factor(signals: &[f32]) -> f32 {
219 signals.iter().copied().fold(0.0_f32, f32::max)
220}
221
222pub fn memory_formation_factor(signals: &[f32]) -> f32 {
225 multiplicative_factor(signals).clamp(0.0, 1.0)
226}
227
228pub fn memory_freeze_active(signals: &[f32]) -> bool {
230 signals.iter().sum::<f32>() > 0.0
231}
232
233pub fn memory_capture_active(signals: &[f32]) -> bool {
235 signals.iter().sum::<f32>() > 0.0
236}
237
238pub fn summed_reward(signals: &[f32]) -> f32 {
240 signals.iter().sum()
241}
242
243pub fn scale_baseline(kind: ModulatorKind, baseline: f32, factor: f32) -> f32 {
248 let value = baseline * factor;
249 match kind {
250 ModulatorKind::Leak | ModulatorKind::FiringProbability => value.clamp(0.0, 1.0),
251 ModulatorKind::FiringThreshold
252 | ModulatorKind::TransmissionGain
253 | ModulatorKind::LearningRate
254 | ModulatorKind::Gate
255 | ModulatorKind::MemoryFormation
256 | ModulatorKind::MemoryFreeze
257 | ModulatorKind::MemoryCapture => value.max(0.0),
258 ModulatorKind::Reward => value,
259 }
260}
261
262#[cfg(test)]
263mod tests {
264 use super::*;
265
266 #[test]
267 fn silent_driver_contributes_nothing() {
268 assert_eq!(modulator_signal(30.0, false, false, 10.0, 10.0), 0.0);
269 }
270
271 #[test]
272 fn ungraded_firing_uses_full_magnitude() {
273 assert!((modulator_signal(30.0, true, false, 1.0, 10.0) - 0.3).abs() < 1e-6);
274 assert!((modulator_signal(-80.0, true, false, 1.0, 10.0) + 0.8).abs() < 1e-6);
275 }
276
277 #[test]
278 fn graded_firing_scales_with_membrane_potential_and_caps_at_one() {
279 let half = modulator_signal(30.0, true, true, 5.0, 10.0);
280 assert!((half - 0.15).abs() < 1e-6);
281 let capped = modulator_signal(30.0, true, true, 40.0, 10.0);
282 assert!((capped - 0.3).abs() < 1e-6);
283 }
284
285 #[test]
286 fn factors_multiply_and_reward_adds() {
287 let factor = multiplicative_factor(&[0.3, -0.5]);
288 assert!((factor - (1.3 * 0.5)).abs() < 1e-6);
289 assert!((summed_reward(&[0.3, -0.5]) + 0.2).abs() < 1e-6);
290 }
291
292 #[test]
293 fn leak_and_excitability_clamp_to_unit_interval() {
294 assert!((scale_baseline(ModulatorKind::Leak, 0.8, 2.0) - 1.0).abs() < 1e-6);
295 assert!((scale_baseline(ModulatorKind::FiringProbability, 0.2, 0.0) - 0.0).abs() < 1e-6);
296 assert!(scale_baseline(ModulatorKind::FiringThreshold, 2.0, 3.0) > 0.0);
297 }
298
299 #[test]
300 fn magnitude_below_minus_100_is_rejected() {
301 assert!(validate_instance_fields(-100.1, 1, false, None).is_err());
302 assert!(validate_instance_fields(-100.0, 1, false, None).is_ok());
303 }
304
305 #[test]
306 fn graded_requires_positive_full_scale() {
307 assert!(validate_instance_fields(10.0, 1, true, None).is_err());
308 assert!(validate_instance_fields(10.0, 1, true, Some(0.0)).is_err());
309 assert!(validate_instance_fields(10.0, 1, true, Some(4.0)).is_ok());
310 }
311
312 #[test]
313 fn spike_train_rejects_unlimited_consecutive_fire() {
314 assert!(validate_spike_train(true, 0).is_err());
315 assert!(validate_spike_train(true, 1).is_ok());
316 assert!(validate_spike_train(false, 0).is_ok());
317 }
318
319 #[test]
320 fn memory_freeze_is_area_level_and_active_above_zero() {
321 assert_eq!(
322 ModulatorKind::parse("memory.freeze").unwrap(),
323 ModulatorKind::MemoryFreeze
324 );
325 assert!(ModulatorKind::MemoryFreeze.is_area_level());
326 assert!(!ModulatorKind::MemoryFreeze.is_synaptic());
327 assert!(!memory_freeze_active(&[]));
328 assert!(!memory_freeze_active(&[0.0]));
329 assert!(memory_freeze_active(&[0.5]));
330 }
331
332 #[test]
333 fn memory_capture_is_area_level_and_active_above_zero() {
334 assert_eq!(
335 ModulatorKind::parse("memory.capture").unwrap(),
336 ModulatorKind::MemoryCapture
337 );
338 assert_eq!(ModulatorKind::MemoryCapture.as_str(), "memory.capture");
339 assert!(ModulatorKind::all().contains(&ModulatorKind::MemoryCapture));
340 assert!(ModulatorKind::MemoryCapture.is_area_level());
341 assert!(!ModulatorKind::MemoryCapture.is_synaptic());
342 assert!(!memory_capture_active(&[]));
343 assert!(!memory_capture_active(&[0.0]));
344 assert!(memory_capture_active(&[0.5]));
345 }
346
347 #[test]
348 fn type_strings_round_trip() {
349 for kind in ModulatorKind::all() {
350 assert_eq!(ModulatorKind::parse(kind.as_str()).unwrap(), *kind);
351 }
352 }
353
354 #[test]
355 fn gate_kind_is_synaptic_and_parses() {
356 assert_eq!(
357 ModulatorKind::parse("synaptic.gate").unwrap(),
358 ModulatorKind::Gate
359 );
360 assert_eq!(ModulatorKind::Gate.as_str(), "synaptic.gate");
361 assert!(ModulatorKind::Gate.is_synaptic());
362 assert!(!ModulatorKind::Gate.combines_by_addition());
363 }
364
365 #[test]
366 fn gate_factor_is_closed_when_silent_and_open_if_any_open() {
367 assert_eq!(gate_factor(&[0.0]), 0.0);
368 assert_eq!(gate_factor(&[0.0, 1.0]), 1.0);
369 assert!((gate_factor(&[0.5, 0.25]) - 0.5).abs() < 1e-6);
370 }
371
372 #[test]
373 fn memory_formation_is_area_level_and_clamped() {
374 assert_eq!(
375 ModulatorKind::parse("memory.formation").unwrap(),
376 ModulatorKind::MemoryFormation
377 );
378 assert!(ModulatorKind::MemoryFormation.is_area_level());
379 assert!(!ModulatorKind::MemoryFormation.is_synaptic());
380 assert!(!ModulatorKind::MemoryFormation.is_neuromodulator());
381 assert_eq!(memory_formation_factor(&[-1.0]), 0.0);
382 assert_eq!(memory_formation_factor(&[0.0]), 1.0);
383 assert_eq!(memory_formation_factor(&[0.5]), 1.0);
384 assert!((memory_formation_factor(&[-0.25]) - 0.75).abs() < 1e-6);
385 assert_eq!(memory_formation_factor(&[]), 1.0);
386 }
387}