rasayan 1.0.0

Rasayan — biochemistry engine: enzyme kinetics, metabolic pathways, signal transduction, protein structure, membrane transport
Documentation
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
//! Integration tests for rasayan — cross-module behavior and serde roundtrips.

use rasayan::amino_catabolism::{AminoCatabConfig, AminoCatabState};
use rasayan::beta_oxidation::{BetaOxConfig, BetaOxState};
use rasayan::energy::BioenergyState;
use rasayan::enzyme::{self, EnzymeParams};
use rasayan::etc::{EtcConfig, EtcState};
use rasayan::glycolysis::{GlycolysisConfig, GlycolysisState};
use rasayan::membrane::{self, IonicState, MembranePermeability};
use rasayan::metabolism::MetabolicState;
use rasayan::signal::{self, SecondMessenger};
use rasayan::tca::{TcaConfig, TcaState};

// --- Serde roundtrip tests ---

#[test]
fn test_metabolic_state_serde_roundtrip() {
    let m = MetabolicState::default();
    let json = serde_json::to_string(&m).unwrap();
    let m2: MetabolicState = serde_json::from_str(&json).unwrap();
    assert!((m2.atp - m.atp).abs() < f64::EPSILON);
    assert!((m2.adp - m.adp).abs() < f64::EPSILON);
    assert!((m2.glucose - m.glucose).abs() < f64::EPSILON);
    assert!((m2.oxygen - m.oxygen).abs() < f64::EPSILON);
    assert!((m2.lactate - m.lactate).abs() < f64::EPSILON);
    assert!((m2.nad_ratio - m.nad_ratio).abs() < f64::EPSILON);
}

#[test]
fn test_enzyme_params_serde_roundtrip() {
    let e = EnzymeParams {
        vmax: 12.5,
        km: 0.003,
        hill_n: 2.8,
        kcat: 450.0,
    };
    let json = serde_json::to_string(&e).unwrap();
    let e2: EnzymeParams = serde_json::from_str(&json).unwrap();
    assert!((e2.vmax - e.vmax).abs() < f64::EPSILON);
    assert!((e2.km - e.km).abs() < f64::EPSILON);
    assert!((e2.hill_n - e.hill_n).abs() < f64::EPSILON);
    assert!((e2.kcat - e.kcat).abs() < f64::EPSILON);
}

#[test]
fn test_second_messenger_serde_roundtrip() {
    let mut sm = SecondMessenger::default();
    sm.activate_gs(0.7);
    let json = serde_json::to_string(&sm).unwrap();
    let sm2: SecondMessenger = serde_json::from_str(&json).unwrap();
    assert!((sm2.camp - sm.camp).abs() < f64::EPSILON);
    assert!((sm2.calcium - sm.calcium).abs() < f64::EPSILON);
    assert!((sm2.ip3 - sm.ip3).abs() < f64::EPSILON);
}

#[test]
fn test_ionic_state_serde_roundtrip() {
    let ions = IonicState::default();
    let json = serde_json::to_string(&ions).unwrap();
    let ions2: IonicState = serde_json::from_str(&json).unwrap();
    assert!((ions2.na_in - ions.na_in).abs() < f64::EPSILON);
    assert!((ions2.na_out - ions.na_out).abs() < f64::EPSILON);
    assert!((ions2.k_in - ions.k_in).abs() < f64::EPSILON);
    assert!((ions2.k_out - ions.k_out).abs() < f64::EPSILON);
    assert!((ions2.cl_in - ions.cl_in).abs() < f64::EPSILON);
    assert!((ions2.cl_out - ions.cl_out).abs() < f64::EPSILON);
}

#[test]
fn test_membrane_permeability_serde_roundtrip() {
    let perm = MembranePermeability::default();
    let json = serde_json::to_string(&perm).unwrap();
    let perm2: MembranePermeability = serde_json::from_str(&json).unwrap();
    assert!((perm2.p_na - perm.p_na).abs() < f64::EPSILON);
    assert!((perm2.p_k - perm.p_k).abs() < f64::EPSILON);
    assert!((perm2.p_cl - perm.p_cl).abs() < f64::EPSILON);
}

#[test]
fn test_bioenergy_state_serde_roundtrip() {
    let b = BioenergyState::default();
    let json = serde_json::to_string(&b).unwrap();
    let b2: BioenergyState = serde_json::from_str(&json).unwrap();
    assert!((b2.phosphocreatine - b.phosphocreatine).abs() < f64::EPSILON);
    assert!((b2.glycogen - b.glycogen).abs() < f64::EPSILON);
    assert!((b2.met - b.met).abs() < f64::EPSILON);
    assert!((b2.anaerobic_threshold - b.anaerobic_threshold).abs() < f64::EPSILON);
}

// --- Serde roundtrip tests for ALL remaining Serialize+Deserialize types ---

/// Helper: roundtrip via JSON Value and check structural equality.
/// Uses Value comparison which handles f64 representation faithfully.
fn assert_serde_roundtrip<T>(val: &T)
where
    T: serde::Serialize + serde::de::DeserializeOwned + std::fmt::Debug,
{
    let v1 = serde_json::to_value(val).unwrap();
    let val2: T = serde_json::from_value(v1.clone()).unwrap();
    let v2 = serde_json::to_value(&val2).unwrap();
    assert_eq!(v1, v2, "serde roundtrip mismatch for {val:?}");
}

// -- Signaling module --
#[test]
fn test_signaling_config_serde_roundtrip() {
    assert_serde_roundtrip(&rasayan::signaling::SignalingConfig::default());
}

#[test]
fn test_signaling_input_serde_roundtrip() {
    assert_serde_roundtrip(&rasayan::signaling::SignalingInput {
        growth_factor: 0.5,
        cytokine: 0.3,
        ip3: 0.2,
    });
}

#[test]
fn test_signaling_flux_serde_roundtrip() {
    let config = rasayan::signaling::SignalingConfig::default();
    let input = rasayan::signaling::SignalingInput {
        growth_factor: 0.5,
        cytokine: 0.3,
        ip3: 0.2,
    };
    let mut net = rasayan::signaling::SignalingNetwork::default();
    let flux = net.tick(&config, &input, 0.01);
    assert_serde_roundtrip(&flux);
}

// -- Nuclear receptor --
#[test]
fn test_nuclear_receptor_config_serde_roundtrip() {
    assert_serde_roundtrip(&rasayan::nuclear_receptor::NuclearReceptorConfig::default());
}

#[test]
fn test_nuclear_receptor_flux_serde_roundtrip() {
    let config = rasayan::nuclear_receptor::NuclearReceptorConfig::default();
    let mut state = rasayan::nuclear_receptor::NuclearReceptorState::default();
    let flux = state.tick(&config, 0.5, 0.01);
    assert_serde_roundtrip(&flux);
}

// -- Receptor --
#[test]
fn test_receptor_config_serde_roundtrip() {
    assert_serde_roundtrip(&rasayan::receptor::ReceptorConfig::default());
}

#[test]
fn test_receptor_flux_serde_roundtrip() {
    let config = rasayan::receptor::ReceptorConfig::default();
    let mut state = rasayan::receptor::ReceptorState::default();
    let flux = state.tick(&config, 0.5, 0.01);
    assert_serde_roundtrip(&flux);
}

// -- Calcium --
#[test]
fn test_calcium_config_serde_roundtrip() {
    assert_serde_roundtrip(&rasayan::calcium::CalciumConfig::default());
}

#[test]
fn test_calcium_flux_serde_roundtrip() {
    let config = rasayan::calcium::CalciumConfig::default();
    let mut state = rasayan::calcium::CalciumState::default();
    let flux = state.tick(&config, 0.5, 0.01);
    assert_serde_roundtrip(&flux);
}

// -- MAPK --
#[test]
fn test_mapk_config_serde_roundtrip() {
    assert_serde_roundtrip(&rasayan::mapk::MapkConfig::default());
}

#[test]
fn test_mapk_flux_serde_roundtrip() {
    let config = rasayan::mapk::MapkConfig::default();
    let mut state = rasayan::mapk::MapkState::default();
    let flux = state.tick(&config, 0.5, 0.01);
    assert_serde_roundtrip(&flux);
}

// -- JAK-STAT --
#[test]
fn test_jak_stat_config_serde_roundtrip() {
    assert_serde_roundtrip(&rasayan::jak_stat::JakStatConfig::default());
}

#[test]
fn test_jak_stat_flux_serde_roundtrip() {
    let config = rasayan::jak_stat::JakStatConfig::default();
    let mut state = rasayan::jak_stat::JakStatState::default();
    let flux = state.tick(&config, 0.5, 0.01);
    assert_serde_roundtrip(&flux);
}

// -- PI3K --
#[test]
fn test_pi3k_config_serde_roundtrip() {
    assert_serde_roundtrip(&rasayan::pi3k::Pi3kConfig::default());
}

#[test]
fn test_pi3k_flux_serde_roundtrip() {
    let config = rasayan::pi3k::Pi3kConfig::default();
    let mut state = rasayan::pi3k::Pi3kState::default();
    let flux = state.tick(&config, 0.5, 0.01);
    assert_serde_roundtrip(&flux);
}

// -- ETC --
#[test]
fn test_etc_flux_serde_roundtrip() {
    let config = rasayan::etc::EtcConfig::default();
    let mut state = rasayan::etc::EtcState::default();
    let flux = state.tick(&config, 0.5, 0.1, 1.0, 0.5, 0.01);
    assert_serde_roundtrip(&flux);
}

// -- TCA --
#[test]
fn test_tca_flux_serde_roundtrip() {
    let config = rasayan::tca::TcaConfig::default();
    let mut state = rasayan::tca::TcaState::default();
    let flux = state.tick(&config, 0.1, 6.0, 0.5, 700.0, 0.01);
    assert_serde_roundtrip(&flux);
}

// -- Glycolysis (flux already tested above) --

// -- Beta-oxidation --
#[test]
fn test_beta_ox_flux_serde_roundtrip() {
    let config = rasayan::beta_oxidation::BetaOxConfig::default();
    let mut state = rasayan::beta_oxidation::BetaOxState::default();
    let flux = state.tick(&config, 0.0, 700.0, 0.01);
    assert_serde_roundtrip(&flux);
}

// -- Amino catabolism --
#[test]
fn test_amino_catab_flux_serde_roundtrip() {
    let config = rasayan::amino_catabolism::AminoCatabConfig::default();
    let mut state = rasayan::amino_catabolism::AminoCatabState::default();
    let flux = state.tick(&config, 0.3, 700.0, 0.01);
    assert_serde_roundtrip(&flux);
}

#[test]
fn test_carbon_skeleton_output_serde_roundtrip() {
    assert_serde_roundtrip(&rasayan::amino_catabolism::CarbonSkeletonOutput {
        pyruvate: 0.1,
        acetyl_coa: 0.2,
        alpha_kg: 0.1,
        succinyl_coa: 0.05,
        fumarate: 0.03,
        oxaloacetate: 0.02,
    });
}

// -- Pathway --
#[test]
fn test_network_flux_serde_roundtrip() {
    let config = rasayan::pathway::NetworkConfig::default();
    let mut net = rasayan::pathway::MetabolicNetwork::default();
    let flux = net.tick(&config, 0.01);
    assert_serde_roundtrip(&flux);
}

// -- Hormonal --
#[test]
fn test_hormonal_input_serde_roundtrip() {
    assert_serde_roundtrip(&rasayan::hormonal::HormonalInput {
        stress: 0.5,
        serotonin: 0.4,
        light: 0.8,
        social_stimulus: 0.3,
        neural_activity: 0.6,
    });
}

#[test]
fn test_hormonal_flux_serde_roundtrip() {
    let config = rasayan::hormonal::HormonalConfig::default();
    let mut state = rasayan::hormonal::HormonalState::default();
    let input = rasayan::hormonal::HormonalInput {
        stress: 0.5,
        serotonin: 0.4,
        light: 0.8,
        social_stimulus: 0.3,
        neural_activity: 0.6,
    };
    let flux = state.tick(&config, &input, 0.01);
    assert_serde_roundtrip(&flux);
}

// -- Neurotransmitter --
#[test]
fn test_neurotransmitter_flux_serde_roundtrip() {
    let config = rasayan::neurotransmitter::NeurotransmitterConfig::default();
    let mut state = rasayan::neurotransmitter::NeurotransmitterState::default();
    let flux = state.tick(&config, 0.5, 0.5, 0.01);
    assert_serde_roundtrip(&flux);
}

// -- Serialize-only types (test that serialization succeeds) --

#[test]
fn test_alignment_score_serialize() {
    let score =
        rasayan::alignment::score_alignment("ACDEF", "ACDEF", rasayan::alignment::Matrix::Blosum62)
            .unwrap();
    let json = serde_json::to_string(&score).unwrap();
    assert!(json.contains("identity"));
}

#[test]
fn test_extinction_coefficient_serialize() {
    let ec = rasayan::protein::extinction_coefficient("WYCC").unwrap();
    let json = serde_json::to_string(&ec).unwrap();
    assert!(json.contains("oxidized"));
}

#[test]
fn test_amino_acid_serialize() {
    let aa = rasayan::protein::lookup('A').unwrap();
    let json = serde_json::to_string(&aa).unwrap();
    assert!(json.contains("Alanine"));
}

#[test]
fn test_known_enzyme_serialize() {
    let enz = rasayan::enzyme::lookup_enzyme("Catalase").unwrap();
    let json = serde_json::to_string(&enz).unwrap();
    assert!(json.contains("Catalase"));
}

// --- Error display tests ---

#[test]
fn test_error_display_negative_concentration() {
    let err = rasayan::RasayanError::NegativeConcentration {
        name: "ATP".into(),
        value: -1.5,
    };
    let msg = err.to_string();
    assert!(msg.contains("ATP"));
    assert!(msg.contains("-1.5"));
    assert!(msg.contains("concentration"));
}

#[test]
fn test_error_display_invalid_parameter() {
    let err = rasayan::RasayanError::InvalidParameter {
        name: "Km".into(),
        value: -0.01,
        reason: "must be positive".into(),
    };
    let msg = err.to_string();
    assert!(msg.contains("Km"));
    assert!(msg.contains("-0.01"));
    assert!(msg.contains("must be positive"));
}

#[test]
fn test_error_display_unknown_amino_acid() {
    let err = rasayan::RasayanError::UnknownAminoAcid('X');
    assert!(err.to_string().contains('X'));
}

#[test]
fn test_error_display_unknown_pathway() {
    let err = rasayan::RasayanError::UnknownPathway("pentose phosphate".into());
    assert!(err.to_string().contains("pentose phosphate"));
}

// --- Function tests ---

#[test]
fn test_michaelis_menten_half_vmax_at_km() {
    let rate = enzyme::michaelis_menten(1.0, 10.0, 1.0);
    assert!((rate - 5.0).abs() < 0.01);
}

#[test]
fn test_michaelis_menten_saturation() {
    let rate = enzyme::michaelis_menten(10000.0, 10.0, 1.0);
    assert!((rate - 10.0).abs() < 0.01);
}

#[test]
fn test_michaelis_menten_zero_substrate() {
    let rate = enzyme::michaelis_menten(0.0, 10.0, 1.0);
    assert!((rate - 0.0).abs() < f64::EPSILON);
}

#[test]
fn test_nernst_potassium() {
    let e = membrane::nernst(310.0, 1, 4.0, 155.0);
    assert!(e < -80.0 && e > -110.0, "Nernst K+ = {e} mV");
}

#[test]
fn test_nernst_sodium() {
    let e = membrane::nernst(310.0, 1, 145.0, 12.0);
    assert!(e > 50.0 && e < 80.0, "Nernst Na+ = {e} mV");
}

#[test]
fn test_dose_response_at_ec50() {
    let r = signal::dose_response(1.0, 1.0, 1.0, 1.0);
    assert!((r - 0.5).abs() < 0.01);
}

#[test]
fn test_dose_response_steep_hill() {
    let r_low = signal::dose_response(0.5, 1.0, 1.0, 1.0);
    let r_high = signal::dose_response(0.5, 1.0, 1.0, 4.0);
    assert!(r_high < r_low);
}

// --- Cross-module integration ---

#[test]
fn test_metabolic_energy_charge_consistency() {
    let m = MetabolicState::default();
    let ec = m.energy_charge();
    assert!((0.0..=1.0).contains(&ec));
    assert!(ec > 0.9);
}

#[test]
fn test_bioenergy_and_metabolism_alignment() {
    let met = MetabolicState::default();
    let bio = BioenergyState::default();
    assert!(!met.is_anaerobic());
    assert!(!bio.is_anaerobic());
}

#[test]
fn test_membrane_potential_physiological_range() {
    let ions = IonicState::default();
    let vm = ions.resting_potential();
    assert!(
        vm < -50.0 && vm > -100.0,
        "Resting potential {vm} mV out of physiological range"
    );
}

// --- Validation integration ---

#[test]
fn test_all_defaults_validate() {
    assert!(MetabolicState::default().validate().is_ok());
    assert!(BioenergyState::default().validate().is_ok());
    assert!(
        EnzymeParams {
            vmax: 10.0,
            km: 1.0,
            hill_n: 1.0,
            kcat: 100.0,
        }
        .validate()
        .is_ok()
    );
}

#[test]
fn test_goldman_with_custom_permeability() {
    let ions = IonicState::default();
    // All-K+ permeability should give Nernst K+ potential
    let k_only = MembranePermeability {
        p_na: 0.0,
        p_k: 1.0,
        p_cl: 0.0,
    };
    let vm = membrane::goldman(310.0, &ions, &k_only);
    let e_k = membrane::nernst(310.0, 1, ions.k_out, ions.k_in);
    // Goldman with only K+ permeability should approximate Nernst K+
    assert!(
        (vm - e_k).abs() < 1.0,
        "Goldman K+-only ({vm:.1}) should ~ Nernst K+ ({e_k:.1})"
    );
}

#[test]
fn test_nernst_zero_concentrations() {
    assert!(membrane::nernst(310.0, 1, 0.0, 155.0).abs() < f64::EPSILON);
    assert!(membrane::nernst(310.0, 1, 4.0, 0.0).abs() < f64::EPSILON);
    assert!(membrane::nernst(310.0, 0, 4.0, 155.0).abs() < f64::EPSILON);
}

// --- 0.2.0 Expanded kinetics integration ---

#[test]
fn test_inhibition_hierarchy() {
    // All inhibition types should reduce rate below uninhibited
    let base = enzyme::michaelis_menten(1.0, 10.0, 1.0);
    let comp = enzyme::competitive_inhibition(1.0, 1.0, 10.0, 1.0, 1.0);
    let uncomp = enzyme::uncompetitive_inhibition(1.0, 1.0, 10.0, 1.0, 1.0);
    let mixed = enzyme::mixed_inhibition(1.0, 1.0, 10.0, 1.0, 1.0, 1.0);
    assert!(comp < base);
    assert!(uncomp < base);
    assert!(mixed < base);
}

#[test]
fn test_reversible_haldane_consistency() {
    // At equilibrium, the rate should be ~zero
    let vf = 10.0;
    let kmf = 1.0;
    let vr = 5.0;
    let kmr = 2.0;
    let keq = enzyme::haldane_keq(vf, kmf, vr, kmr);
    // At equilibrium: [P]/[S] = Keq, so [P] = Keq * [S]
    let s = 1.0;
    let p = keq * s;
    let rate = enzyme::reversible_michaelis_menten(s, p, vf, kmf, vr, kmr);
    assert!(
        rate.abs() < 0.01,
        "Rate at equilibrium should be ~0, got {rate}"
    );
}

#[test]
fn test_enzyme_db_params_produce_valid_rates() {
    // Every enzyme in the database should produce a valid rate
    for enz in enzyme::KNOWN_ENZYMES {
        let params = enz.params(1e-6);
        assert!(params.validate().is_ok(), "Invalid params for {}", enz.name);
        let rate = params.rate(enz.km); // rate at Km
        assert!(rate > 0.0, "Zero rate for {} at Km", enz.name);
        assert!(rate.is_finite(), "Non-finite rate for {}", enz.name);
    }
}

#[test]
fn test_lineweaver_burk_and_eadie_hofstee_agree() {
    let data: Vec<(f64, f64)> = [0.2, 0.5, 1.0, 2.0, 5.0, 10.0]
        .iter()
        .map(|&s| (s, enzyme::michaelis_menten(s, 8.0, 0.5)))
        .collect();
    let lb = enzyme::lineweaver_burk_fit(&data).unwrap();
    let eh = enzyme::eadie_hofstee_fit(&data).unwrap();
    // Both should recover the same Km and Vmax from ideal data
    assert!(
        (lb.km - eh.km).abs() < 0.05,
        "Km mismatch: LB={} EH={}",
        lb.km,
        eh.km
    );
    assert!(
        (lb.vmax - eh.vmax).abs() < 0.05,
        "Vmax mismatch: LB={} EH={}",
        lb.vmax,
        eh.vmax
    );
}

#[test]
fn test_kinetic_fit_serde_roundtrip() {
    let fit = enzyme::lineweaver_burk_fit(&[
        (0.5, enzyme::michaelis_menten(0.5, 10.0, 1.0)),
        (1.0, enzyme::michaelis_menten(1.0, 10.0, 1.0)),
        (5.0, enzyme::michaelis_menten(5.0, 10.0, 1.0)),
    ])
    .unwrap();
    let json = serde_json::to_string(&fit).unwrap();
    let fit2: enzyme::KineticFit = serde_json::from_str(&json).unwrap();
    assert!((fit2.km - fit.km).abs() < f64::EPSILON);
    assert!((fit2.vmax - fit.vmax).abs() < f64::EPSILON);
}

#[test]
fn test_arrhenius_temperature_sensitivity() {
    // Enzyme rate should roughly double for every 10K increase (typical biological range)
    let k1 = enzyme::arrhenius(1e10, 50_000.0, 300.0);
    let k2 = enzyme::arrhenius(1e10, 50_000.0, 310.0);
    let ratio = k2 / k1;
    // For Ea=50kJ/mol, ratio should be ~1.9 over 10K
    assert!(ratio > 1.5 && ratio < 3.0, "Ratio={ratio}");
}

// --- Glycolysis → TCA integration ---

#[test]
fn test_glycolysis_feeds_tca() {
    let glyco_config = GlycolysisConfig::default();
    let tca_config = TcaConfig::default();
    let mut glyco = GlycolysisState::default();
    let mut tca = TcaState::default();

    let mut total_nadh = 0.0;
    let mut total_atp = 0.0;

    // Run 50 seconds: glycolysis produces pyruvate, TCA consumes it
    for _ in 0..500 {
        let gflux = glyco.tick(&glyco_config, 6.0, 0.5, 700.0, 0.1);
        let tflux = tca.tick(&tca_config, glyco.pyruvate, 6.0, 0.5, 700.0, 0.1);

        // TCA consumed some pyruvate — deduct it
        glyco.pyruvate = (glyco.pyruvate - tflux.pyruvate_consumed).max(0.0);

        total_nadh += gflux.nadh_produced + tflux.nadh_produced;
        total_atp += gflux.net_atp + tflux.gtp_produced;
    }

    // Both pathways should have produced meaningful output
    assert!(total_nadh > 0.0, "Combined NADH should be positive");
    assert!(total_atp > 0.0, "Combined ATP+GTP should be positive");
    // TCA should have consumed some pyruvate
    assert!(
        glyco.pyruvate < 5.0,
        "Pyruvate should not accumulate unbounded when TCA is consuming it"
    );
}

#[test]
fn test_glycolysis_tca_pathway_validation() {
    assert!(GlycolysisState::default().validate().is_ok());
    assert!(GlycolysisConfig::default().validate().is_ok());
    assert!(TcaState::default().validate().is_ok());
    assert!(TcaConfig::default().validate().is_ok());
    assert!(EtcState::default().validate().is_ok());
    assert!(EtcConfig::default().validate().is_ok());
}

// --- Full respiration: Glycolysis → TCA → ETC ---

#[test]
fn test_full_respiration_pipeline() {
    let glyco_config = GlycolysisConfig::default();
    let tca_config = TcaConfig::default();
    let etc_config = EtcConfig::default();
    let mut glyco = GlycolysisState::default();
    let mut tca = TcaState::default();
    let mut etc = EtcState::default();

    let mut total_atp = 0.0;
    let mut total_o2 = 0.0;

    // Run 20 seconds of full respiration
    for _ in 0..200 {
        let gflux = glyco.tick(&glyco_config, 6.0, 0.5, 700.0, 0.1);
        let tflux = tca.tick(&tca_config, glyco.pyruvate, 6.0, 0.5, 700.0, 0.1);
        glyco.pyruvate = (glyco.pyruvate - tflux.pyruvate_consumed).max(0.0);

        let nadh_pool = gflux.nadh_produced + tflux.nadh_produced;
        let eflux = etc.tick(&etc_config, nadh_pool, tflux.fadh2_produced, 1.0, 0.5, 0.1);

        total_atp += gflux.net_atp + tflux.gtp_produced + eflux.atp_produced;
        total_o2 += eflux.o2_consumed;
    }

    assert!(total_atp > 0.0, "Full respiration should produce ATP");
    assert!(total_o2 > 0.0, "Full respiration should consume O2");
    // ETC should produce the majority of ATP
    assert!(
        total_atp > 0.1,
        "Total ATP from full pipeline should be meaningful: {total_atp}"
    );
}

#[test]
fn test_beta_ox_feeds_tca() {
    let box_config = BetaOxConfig::default();
    let tca_config = TcaConfig::default();
    let mut beta_ox = BetaOxState::default();
    let mut tca = TcaState::default();

    let mut total_accoa = 0.0;
    let mut total_nadh = 0.0;

    for _ in 0..200 {
        let bflux = beta_ox.tick(&box_config, 0.0, 700.0, 0.1);
        // Feed beta-ox acetyl-CoA into TCA
        tca.acetyl_coa += bflux.acetyl_coa_produced;
        let tflux = tca.tick(&tca_config, 0.0, 6.0, 0.5, 700.0, 0.1);
        total_accoa += bflux.acetyl_coa_produced;
        total_nadh += bflux.nadh_produced + tflux.nadh_produced;
    }

    assert!(total_accoa > 0.0, "Beta-ox should produce acetyl-CoA");
    assert!(total_nadh > 0.0, "Combined NADH from beta-ox + TCA");
}

#[test]
fn test_beta_ox_validation() {
    assert!(BetaOxState::default().validate().is_ok());
    assert!(BetaOxConfig::default().validate().is_ok());
}

// --- Amino acid catabolism integration ---

#[test]
fn test_amino_catab_feeds_tca() {
    let aa_config = AminoCatabConfig::default();
    let tca_config = TcaConfig::default();
    let mut aa = AminoCatabState::default();
    let mut tca = TcaState::default();

    for _ in 0..200 {
        let aflux = aa.tick(&aa_config, tca.alpha_kg, 700.0, 0.1);
        // Route carbon skeletons to TCA intermediates
        tca.acetyl_coa += aflux.to_acetyl_coa;
        tca.oxaloacetate += aflux.to_oxaloacetate;
        tca.alpha_kg += aflux.to_alpha_kg;
        tca.succinyl_coa += aflux.to_succinyl_coa;
        tca.fumarate += aflux.to_fumarate;
        let _ = tca.tick(&tca_config, aflux.to_pyruvate, 6.0, 0.5, 700.0, 0.1);
    }

    assert!(
        aa.amino_acid_pool < AminoCatabState::default().amino_acid_pool,
        "AA pool should deplete as catabolism feeds TCA"
    );
}

#[test]
fn test_amino_catab_validation() {
    assert!(AminoCatabState::default().validate().is_ok());
    assert!(AminoCatabConfig::default().validate().is_ok());
}

// --- Long-run stability tests ---

#[test]
fn test_network_long_run_stability() {
    use rasayan::pathway::{MetabolicNetwork, NetworkConfig};
    let mut net = MetabolicNetwork::default();
    let config = NetworkConfig::default();
    // Run for 100 simulated seconds
    for _ in 0..1000 {
        let _ = net.tick(&config, 0.1);
    }
    assert!(net.atp >= 0.0, "ATP went negative: {}", net.atp);
    assert!(net.adp >= 0.0, "ADP went negative: {}", net.adp);
    assert!(
        net.nad_ratio >= 1.0,
        "NAD ratio collapsed: {}",
        net.nad_ratio
    );
    assert!(net.glycolysis.validate().is_ok());
    assert!(net.tca.validate().is_ok());
    assert!(net.etc.validate().is_ok());
}

#[test]
fn test_neurotransmitter_long_run_stability() {
    use rasayan::neurotransmitter::{NeurotransmitterConfig, NeurotransmitterState};
    let mut state = NeurotransmitterState::default();
    let config = NeurotransmitterConfig::default();
    for _ in 0..1000 {
        let _ = state.tick(&config, 0.05, 1.0, 0.1);
    }
    assert!(state.validate().is_ok());
    // All NTs should still be positive after 100s
    assert!(state.serotonin > 0.0);
    assert!(state.dopamine > 0.0);
    assert!(state.gaba > 0.0);
    assert!(state.glutamate > 0.0);
}

#[test]
fn test_hormonal_long_run_stability() {
    use rasayan::hormonal::{HormonalConfig, HormonalInput, HormonalState};
    let mut state = HormonalState::default();
    let config = HormonalConfig::default();
    let input = HormonalInput::default();
    for _ in 0..1000 {
        let _ = state.tick(&config, &input, 0.1);
    }
    assert!(state.validate().is_ok());
    assert!(state.cortisol > 0.0);
}

#[test]
fn test_network_zero_glucose_graceful() {
    use rasayan::pathway::{MetabolicNetwork, NetworkConfig};
    let mut net = MetabolicNetwork::default();
    net.glycolysis.glucose = 0.0;
    let config = NetworkConfig::default();
    for _ in 0..500 {
        let _ = net.tick(&config, 0.1);
    }
    // Should not panic or produce NaN
    assert!(net.atp.is_finite());
    assert!(net.adp.is_finite());
}

#[test]
fn test_network_zero_oxygen_graceful() {
    use rasayan::pathway::{MetabolicNetwork, NetworkConfig};
    let mut net = MetabolicNetwork {
        oxygen: 0.0,
        ..MetabolicNetwork::default()
    };
    let config = NetworkConfig::default();
    for _ in 0..500 {
        let _ = net.tick(&config, 0.1);
    }
    assert!(net.atp.is_finite());
    // Without O2 for 50s, pmf should be very low
    assert!(
        net.etc.pmf < 0.5,
        "PMF should drop without O2: {}",
        net.etc.pmf
    );
}

#[test]
fn test_nt_stress_response_chain() {
    use rasayan::hormonal::{HormonalConfig, HormonalInput, HormonalState};
    use rasayan::neurotransmitter::{NeurotransmitterConfig, NeurotransmitterState};

    let mut nt = NeurotransmitterState::default();
    let nt_config = NeurotransmitterConfig::default();
    let mut horm = HormonalState::default();
    let horm_config = HormonalConfig::default();

    // Simulate stress response: high stimulus
    for _ in 0..100 {
        let nt_flux = nt.tick(&nt_config, 0.05, 2.0, 0.1);
        let input = HormonalInput {
            stress: 2.0,
            serotonin: nt.serotonin,
            ..HormonalInput::default()
        };
        let _ = horm.tick(&horm_config, &input, 0.1);
        let _ = nt_flux; // used for accounting
    }

    // Cortisol should be elevated from stress
    assert!(
        horm.cortisol > HormonalState::default().cortisol,
        "Cortisol should rise under stress"
    );
    // NE should be elevated from high stimulus
    assert!(
        nt.norepinephrine > 0.0,
        "NE should be present during stress"
    );
}