1use serde::{Deserialize, Serialize};
23
24use super::factor::{Effect, Factor, FactorTarget};
25use super::system_key;
26use super::{accumulate::SystemBurden, accumulate::accumulate};
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
34pub struct Kinetics {
35 pub onset_minutes: u32,
36 pub half_life_minutes: u32,
37}
38
39impl Kinetics {
40 pub const CHRONIC: Kinetics = Kinetics {
42 onset_minutes: 0,
43 half_life_minutes: 0,
44 };
45
46 pub fn new(onset_minutes: u32, half_life_minutes: u32) -> Self {
48 Self {
49 onset_minutes,
50 half_life_minutes,
51 }
52 }
53
54 pub fn magnitude_at(self, base_milli: u32, dose_scale_pct: u32, elapsed_minutes: i64) -> u32 {
60 if elapsed_minutes < 0 {
61 return 0; }
63 let e = elapsed_minutes as u64;
64 let peak = (base_milli as u64 * dose_scale_pct as u64 / 100).min(1000);
65 if peak == 0 {
66 return 0;
67 }
68 let onset = self.onset_minutes as u64;
69 let shaped = if onset > 0 && e < onset {
70 peak * e / onset } else if self.half_life_minutes == 0 {
72 peak } else {
74 let since_peak = e - onset; let hl = self.half_life_minutes as u64;
76 let n = (since_peak / hl).min(63); let r = since_peak % hl;
78 let hi = peak >> n;
79 let lo = peak >> (n + 1).min(63);
80 hi - (hi - lo) * r / hl };
82 shaped.min(1000) as u32
83 }
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
92pub struct FactorEvent {
93 pub factor: Factor,
94 pub at_minute: i64,
96 pub dose_scale_pct: u32,
98 pub default_kinetics: Kinetics,
100 #[serde(default)]
102 pub system_kinetics: Vec<(String, Kinetics)>,
103}
104
105impl FactorEvent {
106 pub fn new(factor: Factor, at_minute: i64) -> Self {
108 Self {
109 factor,
110 at_minute,
111 dose_scale_pct: 100,
112 default_kinetics: Kinetics::CHRONIC,
113 system_kinetics: Vec::new(),
114 }
115 }
116
117 pub fn with_dose_pct(mut self, dose_scale_pct: u32) -> Self {
119 self.dose_scale_pct = dose_scale_pct;
120 self
121 }
122
123 pub fn with_default_kinetics(mut self, k: Kinetics) -> Self {
125 self.default_kinetics = k;
126 self
127 }
128
129 pub fn with_system_kinetics(mut self, system_id: impl Into<String>, k: Kinetics) -> Self {
131 self.system_kinetics.push((system_id.into(), k));
132 self
133 }
134
135 fn kinetics_for(&self, system_id: &str) -> Kinetics {
136 self.system_kinetics
137 .iter()
138 .find(|(id, _)| system_key(id) == system_key(system_id))
139 .map(|(_, k)| *k)
140 .unwrap_or(self.default_kinetics)
141 }
142}
143
144#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
151pub struct EnvironmentModulator {
152 pub label: String,
153 pub from_minute: i64,
154 pub to_minute: i64,
155 #[serde(default, skip_serializing_if = "Option::is_none")]
156 pub target_system: Option<String>,
157 #[serde(default, skip_serializing_if = "Option::is_none")]
158 pub target_effect: Option<Effect>,
159 pub scale_pct: u32,
160}
161
162impl EnvironmentModulator {
163 fn applies(&self, now: i64, system_id: &str, effect: Effect) -> bool {
164 if now < self.from_minute || now > self.to_minute {
165 return false;
166 }
167 if let Some(sys) = &self.target_system {
168 if system_key(sys) != system_key(system_id) {
169 return false;
170 }
171 }
172 match self.target_effect {
173 Some(e) if e != effect => false,
174 _ => true,
175 }
176 }
177}
178
179#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
183pub struct Timeline {
184 pub events: Vec<FactorEvent>,
185 #[serde(default)]
186 pub environment: Vec<EnvironmentModulator>,
187}
188
189#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
191pub struct TrajectoryPoint {
192 pub minute: i64,
193 pub net_milli: u32,
194 pub adverse_milli: u32,
195 pub supportive_milli: u32,
196}
197
198impl Timeline {
199 pub fn new() -> Self {
201 Self::default()
202 }
203
204 pub fn with_event(mut self, e: FactorEvent) -> Self {
206 self.events.push(e);
207 self
208 }
209
210 pub fn with_environment(mut self, m: EnvironmentModulator) -> Self {
212 self.environment.push(m);
213 self
214 }
215
216 pub fn snapshot_at(&self, minute: i64) -> Vec<Factor> {
221 let mut out = Vec::new();
222 for ev in &self.events {
223 let elapsed = minute - ev.at_minute;
224 let mut targets: Vec<FactorTarget> = Vec::new();
225 for t in &ev.factor.targets {
226 let base = ev.kinetics_for(&t.system_id).magnitude_at(
227 t.weight_milli,
228 ev.dose_scale_pct,
229 elapsed,
230 );
231 if base == 0 {
232 continue;
233 }
234 let scaled = self.apply_environment(minute, &t.system_id, t.effect, base);
235 if scaled == 0 {
236 continue;
237 }
238 targets.push(FactorTarget {
239 system_id: t.system_id.clone(),
240 effect: t.effect,
241 evidence: t.evidence,
242 weight_milli: scaled,
243 });
244 }
245 if targets.is_empty() {
246 continue;
247 }
248 out.push(Factor {
249 id: ev.factor.id.clone(),
250 kind: ev.factor.kind.clone(),
251 label: ev.factor.label.clone(),
252 targets,
253 source: ev.factor.source.clone(),
254 });
255 }
256 out
257 }
258
259 pub fn burden_at(&self, minute: i64) -> Vec<SystemBurden> {
261 accumulate(&self.snapshot_at(minute))
262 }
263
264 pub fn system_trajectory(&self, system_id: &str, samples: &[i64]) -> Vec<TrajectoryPoint> {
266 samples
267 .iter()
268 .map(|&minute| {
269 let burden = self
270 .burden_at(minute)
271 .into_iter()
272 .find(|b| system_key(&b.system_id) == system_key(system_id));
273 match burden {
274 Some(b) => TrajectoryPoint {
275 minute,
276 net_milli: b.net_milli,
277 adverse_milli: b.adverse_milli,
278 supportive_milli: b.supportive_milli,
279 },
280 None => TrajectoryPoint {
281 minute,
282 net_milli: 0,
283 adverse_milli: 0,
284 supportive_milli: 0,
285 },
286 }
287 })
288 .collect()
289 }
290
291 fn apply_environment(&self, minute: i64, system_id: &str, effect: Effect, base: u32) -> u32 {
292 let mut v = base as u64;
293 for m in &self.environment {
294 if m.applies(minute, system_id, effect) {
295 v = v * m.scale_pct as u64 / 100;
296 }
297 }
298 v.min(1000) as u32
299 }
300}
301
302#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
304#[serde(rename_all = "snake_case")]
305pub enum RecoveryBand {
306 Hours,
308 Days,
310 Weeks,
312 Extended,
314}
315
316pub fn recovery_band(points: &[TrajectoryPoint]) -> Option<RecoveryBand> {
324 let peak_idx = points
325 .iter()
326 .enumerate()
327 .max_by_key(|(_, p)| p.net_milli)
328 .map(|(i, _)| i)?;
329 let peak = points[peak_idx].net_milli;
330 if peak == 0 {
331 return None; }
333 let threshold = (peak / 10).max(20);
334 let peak_minute = points[peak_idx].minute;
335 let recovered_at = points[peak_idx..]
336 .iter()
337 .find(|p| p.net_milli <= threshold)
338 .map(|p| p.minute - peak_minute);
339 Some(match recovered_at {
340 Some(mins) if mins <= 12 * 60 => RecoveryBand::Hours,
341 Some(mins) if mins <= 3 * 24 * 60 => RecoveryBand::Days,
342 Some(mins) if mins <= 21 * 24 * 60 => RecoveryBand::Weeks,
343 _ => RecoveryBand::Extended,
344 })
345}
346
347#[cfg(test)]
348mod tests {
349 use super::*;
350 use crate::anatomy::{EvidenceTier, FactorKind};
351
352 fn minutes_over(hours_end: i64, step_min: i64) -> Vec<i64> {
353 (0..=(hours_end * 60 / step_min))
354 .map(|i| i * step_min)
355 .collect()
356 }
357
358 #[test]
359 fn kinetics_rise_peak_and_halve() {
360 let k = Kinetics::new(60, 120); assert_eq!(k.magnitude_at(400, 100, -10), 0); assert_eq!(k.magnitude_at(400, 100, 0), 0); assert_eq!(k.magnitude_at(400, 100, 30), 200); assert_eq!(k.magnitude_at(400, 100, 60), 400); assert_eq!(k.magnitude_at(400, 100, 180), 200); assert_eq!(k.magnitude_at(400, 100, 300), 100); assert!(k.magnitude_at(400, 100, 60 + 120 * 10) < 5);
369 }
370
371 #[test]
372 fn dose_scaling_amplifies_but_stays_bounded() {
373 let k = Kinetics::new(0, 0); assert_eq!(k.magnitude_at(300, 100, 0), 300);
375 assert_eq!(k.magnitude_at(300, 200, 0), 600); assert_eq!(k.magnitude_at(300, 1000, 0), 1000); }
378
379 #[test]
380 fn chronic_kinetics_never_clears() {
381 let k = Kinetics::CHRONIC;
382 assert_eq!(k.magnitude_at(500, 100, 0), 500);
383 assert_eq!(k.magnitude_at(500, 100, 100_000), 500);
384 }
385
386 #[test]
387 fn snapshot_reproduces_a_slice1_factor_set_that_accumulates() {
388 let beer = Factor::new("intake:beer", FactorKind::Food, "beer").targeting(
389 "digestive",
390 Effect::Adverse,
391 EvidenceTier::Mechanistic,
392 300,
393 );
394 let tl = Timeline::new()
395 .with_event(FactorEvent::new(beer, 0).with_default_kinetics(Kinetics::new(30, 240)));
396 let at_peak = tl.snapshot_at(30);
398 assert_eq!(at_peak.len(), 1);
399 assert!(at_peak[0].targets[0].weight_milli > 0);
400 assert!(
401 tl.snapshot_at(100_000).is_empty(),
402 "fully-cleared event drops out of the snapshot"
403 );
404 }
405
406 #[test]
407 fn environment_amplifies_matching_adverse_load() {
408 let sweat = Factor::new("intake:none", FactorKind::Environmental, "fluid loss").targeting(
409 "urinary",
410 Effect::Adverse,
411 EvidenceTier::Mechanistic,
412 300,
413 );
414 let base = Timeline::new().with_event(
415 FactorEvent::new(sweat.clone(), 0).with_default_kinetics(Kinetics::CHRONIC),
416 );
417 let hot = base.clone().with_environment(EnvironmentModulator {
418 label: "heatwave".into(),
419 from_minute: 0,
420 to_minute: 10_000,
421 target_system: Some("urinary".into()),
422 target_effect: Some(Effect::Adverse),
423 scale_pct: 150,
424 });
425 let cool_net = base
426 .burden_at(60)
427 .into_iter()
428 .find(|b| b.system_id == "urinary")
429 .unwrap()
430 .net_milli;
431 let hot_net = hot
432 .burden_at(60)
433 .into_iter()
434 .find(|b| b.system_id == "urinary")
435 .unwrap()
436 .net_milli;
437 assert_eq!(cool_net, 300);
438 assert_eq!(hot_net, 450, "heat amplifies the renal/fluid load by 50%");
439 }
440
441 #[test]
445 fn hot_week_beer_and_water_recover_on_different_clocks() {
446 let beer = Factor::new("intake:slab-of-beer", FactorKind::Food, "a slab of beer")
448 .targeting("digestive", Effect::Adverse, EvidenceTier::Mechanistic, 300) .targeting("urinary", Effect::Adverse, EvidenceTier::Mechanistic, 300); let beer_event = FactorEvent::new(beer, 0)
451 .with_dose_pct(300) .with_system_kinetics("digestive", Kinetics::new(30, 300)) .with_system_kinetics("urinary", Kinetics::new(60, 180)); let water = Factor::new(
457 "act:water-electrolytes",
458 FactorKind::Lifestyle,
459 "water + electrolytes",
460 )
461 .targeting(
462 "urinary",
463 Effect::Supportive,
464 EvidenceTier::Mechanistic,
465 600,
466 );
467 let water_event =
468 FactorEvent::new(water, 120).with_default_kinetics(Kinetics::new(20, 240));
469
470 let tl = Timeline::new()
472 .with_event(beer_event)
473 .with_event(water_event)
474 .with_environment(EnvironmentModulator {
475 label: "summer heatwave".into(),
476 from_minute: 0,
477 to_minute: 7 * 24 * 60,
478 target_system: Some("urinary".into()),
479 target_effect: Some(Effect::Adverse),
480 scale_pct: 140,
481 });
482
483 let samples = minutes_over(48, 15); let renal = tl.system_trajectory("urinary", &samples);
485 let hepatic = tl.system_trajectory("digestive", &samples);
486
487 let renal_band = recovery_band(&renal).unwrap();
488 let hepatic_band = recovery_band(&hepatic).unwrap();
489
490 assert_eq!(
492 renal_band,
493 RecoveryBand::Hours,
494 "rehydration bends the renal curve down fast"
495 );
496 assert_ne!(
497 hepatic_band,
498 RecoveryBand::Hours,
499 "alcohol clearance is not sped by water"
500 );
501
502 let at_12h =
504 |pts: &[TrajectoryPoint]| pts.iter().find(|p| p.minute == 12 * 60).unwrap().net_milli;
505 let renal_12h = at_12h(&renal);
506 let hepatic_12h = at_12h(&hepatic);
507 assert!(renal_12h < 60, "renal recovered by 12h: {renal_12h}");
508 assert!(
509 hepatic_12h > renal_12h,
510 "hepatic still more loaded than renal at 12h: {hepatic_12h} vs {renal_12h}"
511 );
512 }
513
514 #[test]
515 fn recovery_band_none_when_no_adverse_load() {
516 let pts = vec![
517 TrajectoryPoint {
518 minute: 0,
519 net_milli: 0,
520 adverse_milli: 0,
521 supportive_milli: 0,
522 },
523 TrajectoryPoint {
524 minute: 60,
525 net_milli: 0,
526 adverse_milli: 0,
527 supportive_milli: 0,
528 },
529 ];
530 assert!(recovery_band(&pts).is_none());
531 }
532
533 #[test]
534 fn timeline_serde_round_trips() {
535 let tl = Timeline::new().with_event(
536 FactorEvent::new(
537 Factor::new("f", FactorKind::Herb, "f").targeting(
538 "digestive",
539 Effect::Supportive,
540 EvidenceTier::TraditionalUse,
541 100,
542 ),
543 0,
544 )
545 .with_dose_pct(150)
546 .with_system_kinetics("digestive", Kinetics::new(10, 60)),
547 );
548 let json = serde_json::to_string(&tl).unwrap();
549 let back: Timeline = serde_json::from_str(&json).unwrap();
550 assert_eq!(tl, back);
551 }
552}