pharmsol 0.26.1

Rust library for solving analytic and ode-defined pharmacometric models.
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
//! Extension traits for NCA analysis and observation-level pharmacokinetic metrics
//!
//! ```rust,ignore
//! use pharmsol::prelude::*;
//!
//! // Full NCA
//! let result = subject.nca(&NCAOptions::default())?;
//!
//! // Quick metrics
//! let auc = subject.auc(0, &AUCMethod::Linear);
//! let cmax = subject.cmax(0);
//! ```

use super::observation::ObservationProfile;
use crate::data::event::{AUCMethod, BLQRule};
use crate::data::observation_error::ObservationError;
use crate::nca::analyze::{analyze, AnalysisContext};
use crate::nca::calc::tlag_from_raw;
use crate::nca::error::NCAError;
use crate::nca::types::{NCAOptions, NCAResult, Warning};
use crate::{Data, Occasion, Subject};
use rayon::prelude::*;

/// Structured NCA result for a single subject
///
/// Groups occasion-level results under a subject identifier,
/// making it easy to associate results back to subjects.
#[derive(Debug, Clone)]
pub struct SubjectNCAResult {
    /// Subject identifier
    pub subject_id: String,
    /// NCA results for each occasion
    pub occasions: Vec<Result<NCAResult, NCAError>>,
}

impl SubjectNCAResult {
    /// Collect all successful NCA results across occasions
    pub fn successes(&self) -> Vec<&NCAResult> {
        self.occasions
            .iter()
            .filter_map(|r| r.as_ref().ok())
            .collect()
    }

    /// Collect all errors across occasions
    pub fn errors(&self) -> Vec<&NCAError> {
        self.occasions
            .iter()
            .filter_map(|r| r.as_ref().err())
            .collect()
    }
}

// ============================================================================
// Trait: Full NCA analysis
// ============================================================================

/// Extension trait for Non-Compartmental Analysis
///
/// Provides `.nca()` (first occasion) and `.nca_all()` (all occasions)
/// on [`Data`], [`Subject`], and [`Occasion`].
///
/// The output equation is controlled by [`NCAOptions::outeq`] (default 0).
///
/// # Example
///
/// ```rust,ignore
/// use pharmsol::prelude::*;
/// use pharmsol::nca::NCAOptions;
///
/// let subject = Subject::builder("patient_001")
///     .bolus(0.0, 100.0, 0)
///     .observation(1.0, 10.0, 0)
///     .observation(2.0, 8.0, 0)
///     .observation(4.0, 4.0, 0)
///     .build();
///
/// // Single-occasion (the common case)
/// let result = subject.nca(&NCAOptions::default())?;
/// println!("Cmax: {:.2}", result.exposure.cmax);
///
/// // All occasions
/// let all = subject.nca_all(&NCAOptions::default());
/// ```
pub trait NCA {
    /// NCA on the first occasion (the common case). Returns a single result.
    fn nca(&self, options: &NCAOptions) -> Result<NCAResult, NCAError>;

    /// NCA on all occasions. Returns a Vec of results.
    fn nca_all(&self, options: &NCAOptions) -> Vec<Result<NCAResult, NCAError>>;
}

/// Extension trait for structured population-level NCA
///
/// Returns results grouped by subject, making it easy to associate
/// NCA results back to their source subjects.
pub trait NCAPopulation {
    /// Perform NCA and return results grouped by subject
    ///
    /// Unlike [`NCA::nca_all`] which returns a flat `Vec`, this returns
    /// a `Vec<SubjectNCAResult>` where each entry groups all occasion
    /// results for a single subject.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use pharmsol::prelude::*;
    /// use pharmsol::nca::{NCAOptions, NCAPopulation};
    ///
    /// let population_results = data.nca_grouped(&NCAOptions::default());
    /// for subject_result in &population_results {
    ///     println!("Subject {}: {} occasions", subject_result.subject_id, subject_result.occasions.len());
    /// }
    /// ```
    fn nca_grouped(&self, options: &NCAOptions) -> Vec<SubjectNCAResult>;
}

// ============================================================================
// NCA on ObservationProfile (simulated / raw data)
// ============================================================================

use crate::data::Route;

impl Occasion {
    /// Run NCA with an explicit dose, overriding what is embedded in the occasion.
    ///
    /// Use this when you want to supply or override dose amount, route, or infusion
    /// duration without modifying the underlying data.
    pub fn nca_with_dose(
        &self,
        dose_amount: f64,
        route: Route,
        infusion_duration: Option<f64>,
        options: &NCAOptions,
    ) -> Result<NCAResult, NCAError> {
        let profile = ObservationProfile::from_occasion(self, options.outeq, &options.blq_rule)?;
        let (times, concs, censoring) = self.get_observations(options.outeq);
        let raw_tlag = tlag_from_raw(&times, &concs, &censoring);
        analyze(&AnalysisContext {
            profile: &profile,
            dose_amount: Some(dose_amount),
            route,
            infusion_duration,
            options,
            raw_tlag,
            subject_id: None,
            occasion: Some(self.index()),
        })
    }
}

impl NCA for Occasion {
    fn nca(&self, options: &NCAOptions) -> Result<NCAResult, NCAError> {
        nca_occasion(self, options, None)
    }

    fn nca_all(&self, options: &NCAOptions) -> Vec<Result<NCAResult, NCAError>> {
        vec![self.nca(options)]
    }
}

impl Subject {
    /// Run NCA with an explicit dose on the first occasion, overriding what is
    /// embedded in the subject's events.
    ///
    /// Use this when you want to supply or override dose amount, route, or infusion
    /// duration without modifying the underlying data.
    pub fn nca_with_dose(
        &self,
        dose_amount: f64,
        route: Route,
        infusion_duration: Option<f64>,
        options: &NCAOptions,
    ) -> Result<NCAResult, NCAError> {
        let occasion = self
            .occasions()
            .iter()
            .next()
            .ok_or(NCAError::InvalidParameter {
                param: "occasion".to_string(),
                value: "none found".to_string(),
            })?;
        occasion.nca_with_dose(dose_amount, route, infusion_duration, options)
    }
}

impl NCA for Subject {
    fn nca(&self, options: &NCAOptions) -> Result<NCAResult, NCAError> {
        self.occasions()
            .first()
            .map(|occ| nca_occasion(occ, options, Some(self.id())))
            .unwrap_or(Err(NCAError::InvalidParameter {
                param: "occasion".to_string(),
                value: "none found".to_string(),
            }))
    }

    fn nca_all(&self, options: &NCAOptions) -> Vec<Result<NCAResult, NCAError>> {
        self.occasions()
            .par_iter()
            .map(|occasion| nca_occasion(occasion, options, Some(self.id())))
            .collect()
    }
}

impl NCA for Data {
    fn nca(&self, options: &NCAOptions) -> Result<NCAResult, NCAError> {
        self.subjects()
            .first()
            .map(|s| s.nca(options))
            .unwrap_or(Err(NCAError::InvalidParameter {
                param: "subject".to_string(),
                value: "none found".to_string(),
            }))
    }

    fn nca_all(&self, options: &NCAOptions) -> Vec<Result<NCAResult, NCAError>> {
        self.subjects()
            .par_iter()
            .flat_map(|subject| subject.nca_all(options))
            .collect()
    }
}

impl NCAPopulation for Data {
    fn nca_grouped(&self, options: &NCAOptions) -> Vec<SubjectNCAResult> {
        self.subjects()
            .par_iter()
            .map(|subject| {
                let occasions = subject
                    .occasions()
                    .par_iter()
                    .map(|occasion| nca_occasion(occasion, options, Some(subject.id())))
                    .collect();
                SubjectNCAResult {
                    subject_id: subject.id().to_string(),
                    occasions,
                }
            })
            .collect()
    }
}

/// Core NCA implementation for a single occasion
fn nca_occasion(
    occasion: &Occasion,
    options: &NCAOptions,
    subject_id: Option<&str>,
) -> Result<NCAResult, NCAError> {
    let outeq = options.outeq;

    // Build profile directly from the occasion
    let profile = ObservationProfile::from_occasion(occasion, outeq, &options.blq_rule)?;

    // Compute tlag from raw (unfiltered) data to match PKNCA
    let (times, concs, censoring) = occasion.get_observations(outeq);
    let raw_tlag = tlag_from_raw(&times, &concs, &censoring);

    // Extract dose info from Occasion directly (no DoseContext)
    let dose_amount = {
        let d = occasion.total_dose();
        if d > 0.0 {
            Some(d)
        } else {
            None
        }
    };
    let route = options.route_override.unwrap_or_else(|| occasion.route());
    let infusion_duration = occasion.infusion_duration();

    // Calculate NCA directly on the profile
    let mut result = analyze(&AnalysisContext {
        profile: &profile,
        dose_amount,
        route,
        infusion_duration,
        options,
        raw_tlag,
        subject_id,
        occasion: Some(occasion.index()),
    })?;

    // Warn about mixed routes if no explicit override was given
    let routes = occasion.routes();
    if routes.len() > 1 && options.route_override.is_none() {
        result
            .quality
            .warnings
            .push(Warning::MixedRoutes { routes });
    }

    Ok(result)
}

// ============================================================================
// Observation-level metrics (AUC, Cmax, Tmax, etc.)
// ============================================================================

/// Error type for observation metric computations
///
/// Wraps [`ObservationError`] with context about which subject or output equation failed.
#[derive(Debug, Clone, thiserror::Error)]
pub enum MetricsError {
    #[error(transparent)]
    Observation(#[from] ObservationError),

    #[error("Output equation {outeq} not found in subject{}", subject_id.as_ref().map(|id| format!(" '{}'", id)).unwrap_or_default())]
    OutputEquationNotFound {
        outeq: usize,
        subject_id: Option<String>,
    },
}

/// Observation-level pharmacokinetic metrics (AUC, Cmax, Tmax, etc.)
///
/// Methods without `_blq` default to [`BLQRule::Exclude`].
/// The `_first` variants return a single result for the first occasion.
///
/// ```rust,ignore
/// use pharmsol::prelude::*;
///
/// let auc = subject.auc(0, &AUCMethod::Linear);
/// let cmax_val = subject.cmax_first(0).unwrap();
/// ```
pub trait ObservationMetrics {
    // Required methods — with explicit BLQ rule

    /// Calculate AUC from time 0 to Tlast with explicit BLQ handling
    fn auc_blq(
        &self,
        outeq: usize,
        method: &AUCMethod,
        blq_rule: &BLQRule,
    ) -> Vec<Result<f64, MetricsError>>;

    /// Calculate partial AUC over a time interval with explicit BLQ handling
    fn auc_interval_blq(
        &self,
        outeq: usize,
        start: f64,
        end: f64,
        method: &AUCMethod,
        blq_rule: &BLQRule,
    ) -> Vec<Result<f64, MetricsError>>;

    /// Get Cmax with explicit BLQ handling
    fn cmax_blq(&self, outeq: usize, blq_rule: &BLQRule) -> Vec<Result<f64, MetricsError>>;

    /// Get Tmax with explicit BLQ handling
    fn tmax_blq(&self, outeq: usize, blq_rule: &BLQRule) -> Vec<Result<f64, MetricsError>>;

    /// Get Clast with explicit BLQ handling
    fn clast_blq(&self, outeq: usize, blq_rule: &BLQRule) -> Vec<Result<f64, MetricsError>>;

    /// Get Tlast with explicit BLQ handling
    fn tlast_blq(&self, outeq: usize, blq_rule: &BLQRule) -> Vec<Result<f64, MetricsError>>;

    /// Calculate AUMC with explicit BLQ handling
    fn aumc_blq(
        &self,
        outeq: usize,
        method: &AUCMethod,
        blq_rule: &BLQRule,
    ) -> Vec<Result<f64, MetricsError>>;

    // Ergonomic defaults — BLQ observations excluded

    /// Calculate AUC from time 0 to Tlast
    fn auc(&self, outeq: usize, method: &AUCMethod) -> Vec<Result<f64, MetricsError>> {
        self.auc_blq(outeq, method, &BLQRule::Exclude)
    }

    /// Calculate partial AUC over a time interval
    fn auc_interval(
        &self,
        outeq: usize,
        start: f64,
        end: f64,
        method: &AUCMethod,
    ) -> Vec<Result<f64, MetricsError>> {
        self.auc_interval_blq(outeq, start, end, method, &BLQRule::Exclude)
    }

    /// Get Cmax
    fn cmax(&self, outeq: usize) -> Vec<Result<f64, MetricsError>> {
        self.cmax_blq(outeq, &BLQRule::Exclude)
    }

    /// Get Tmax
    fn tmax(&self, outeq: usize) -> Vec<Result<f64, MetricsError>> {
        self.tmax_blq(outeq, &BLQRule::Exclude)
    }

    /// Get Clast
    fn clast(&self, outeq: usize) -> Vec<Result<f64, MetricsError>> {
        self.clast_blq(outeq, &BLQRule::Exclude)
    }

    /// Get Tlast
    fn tlast(&self, outeq: usize) -> Vec<Result<f64, MetricsError>> {
        self.tlast_blq(outeq, &BLQRule::Exclude)
    }

    /// Calculate AUMC
    fn aumc(&self, outeq: usize, method: &AUCMethod) -> Vec<Result<f64, MetricsError>> {
        self.aumc_blq(outeq, method, &BLQRule::Exclude)
    }

    // Single-occasion convenience — no BLQ

    /// Calculate AUC for the first occasion
    fn auc_first(&self, outeq: usize, method: &AUCMethod) -> Result<f64, MetricsError> {
        self.auc(outeq, method)
            .into_iter()
            .next()
            .unwrap_or(Err(MetricsError::Observation(
                ObservationError::InsufficientData { n: 0, required: 2 },
            )))
    }

    /// Get Cmax for the first occasion
    fn cmax_first(&self, outeq: usize) -> Result<f64, MetricsError> {
        self.cmax(outeq)
            .into_iter()
            .next()
            .unwrap_or(Err(MetricsError::Observation(
                ObservationError::InsufficientData { n: 0, required: 2 },
            )))
    }

    /// Get Tmax for the first occasion
    fn tmax_first(&self, outeq: usize) -> Result<f64, MetricsError> {
        self.tmax(outeq)
            .into_iter()
            .next()
            .unwrap_or(Err(MetricsError::Observation(
                ObservationError::InsufficientData { n: 0, required: 2 },
            )))
    }

    /// Get Clast for the first occasion
    fn clast_first(&self, outeq: usize) -> Result<f64, MetricsError> {
        self.clast(outeq)
            .into_iter()
            .next()
            .unwrap_or(Err(MetricsError::Observation(
                ObservationError::InsufficientData { n: 0, required: 2 },
            )))
    }

    /// Get Tlast for the first occasion
    fn tlast_first(&self, outeq: usize) -> Result<f64, MetricsError> {
        self.tlast(outeq)
            .into_iter()
            .next()
            .unwrap_or(Err(MetricsError::Observation(
                ObservationError::InsufficientData { n: 0, required: 2 },
            )))
    }

    /// Calculate AUMC for the first occasion
    fn aumc_first(&self, outeq: usize, method: &AUCMethod) -> Result<f64, MetricsError> {
        self.aumc(outeq, method)
            .into_iter()
            .next()
            .unwrap_or(Err(MetricsError::Observation(
                ObservationError::InsufficientData { n: 0, required: 2 },
            )))
    }

    /// Calculate partial AUC for the first occasion
    fn auc_interval_first(
        &self,
        outeq: usize,
        start: f64,
        end: f64,
        method: &AUCMethod,
    ) -> Result<f64, MetricsError> {
        self.auc_interval(outeq, start, end, method)
            .into_iter()
            .next()
            .unwrap_or(Err(MetricsError::Observation(
                ObservationError::InsufficientData { n: 0, required: 2 },
            )))
    }

    // Single-occasion convenience — with BLQ

    /// Calculate AUC for the first occasion with explicit BLQ handling
    fn auc_blq_first(
        &self,
        outeq: usize,
        method: &AUCMethod,
        blq_rule: &BLQRule,
    ) -> Result<f64, MetricsError> {
        self.auc_blq(outeq, method, blq_rule)
            .into_iter()
            .next()
            .unwrap_or(Err(MetricsError::Observation(
                ObservationError::InsufficientData { n: 0, required: 2 },
            )))
    }

    /// Get Cmax for the first occasion with explicit BLQ handling
    fn cmax_blq_first(&self, outeq: usize, blq_rule: &BLQRule) -> Result<f64, MetricsError> {
        self.cmax_blq(outeq, blq_rule)
            .into_iter()
            .next()
            .unwrap_or(Err(MetricsError::Observation(
                ObservationError::InsufficientData { n: 0, required: 2 },
            )))
    }

    /// Calculate partial AUC for the first occasion with explicit BLQ handling
    fn auc_interval_blq_first(
        &self,
        outeq: usize,
        start: f64,
        end: f64,
        method: &AUCMethod,
        blq_rule: &BLQRule,
    ) -> Result<f64, MetricsError> {
        self.auc_interval_blq(outeq, start, end, method, blq_rule)
            .into_iter()
            .next()
            .unwrap_or(Err(MetricsError::Observation(
                ObservationError::InsufficientData { n: 0, required: 2 },
            )))
    }
}

// ============================================================================
// Occasion implementations (core metrics logic)
// ============================================================================

impl ObservationMetrics for Occasion {
    fn auc_blq(
        &self,
        outeq: usize,
        method: &AUCMethod,
        blq_rule: &BLQRule,
    ) -> Vec<Result<f64, MetricsError>> {
        vec![auc_occasion(self, outeq, method, blq_rule)]
    }

    fn auc_interval_blq(
        &self,
        outeq: usize,
        start: f64,
        end: f64,
        method: &AUCMethod,
        blq_rule: &BLQRule,
    ) -> Vec<Result<f64, MetricsError>> {
        vec![auc_interval_occasion(
            self, outeq, start, end, method, blq_rule,
        )]
    }

    fn cmax_blq(&self, outeq: usize, blq_rule: &BLQRule) -> Vec<Result<f64, MetricsError>> {
        vec![cmax_occasion(self, outeq, blq_rule)]
    }

    fn tmax_blq(&self, outeq: usize, blq_rule: &BLQRule) -> Vec<Result<f64, MetricsError>> {
        vec![tmax_occasion(self, outeq, blq_rule)]
    }

    fn clast_blq(&self, outeq: usize, blq_rule: &BLQRule) -> Vec<Result<f64, MetricsError>> {
        vec![clast_occasion(self, outeq, blq_rule)]
    }

    fn tlast_blq(&self, outeq: usize, blq_rule: &BLQRule) -> Vec<Result<f64, MetricsError>> {
        vec![tlast_occasion(self, outeq, blq_rule)]
    }

    fn aumc_blq(
        &self,
        outeq: usize,
        method: &AUCMethod,
        blq_rule: &BLQRule,
    ) -> Vec<Result<f64, MetricsError>> {
        vec![aumc_occasion(self, outeq, method, blq_rule)]
    }
}

// ============================================================================
// Subject implementations (iterate occasions)
// ============================================================================

impl ObservationMetrics for Subject {
    fn auc_blq(
        &self,
        outeq: usize,
        method: &AUCMethod,
        blq_rule: &BLQRule,
    ) -> Vec<Result<f64, MetricsError>> {
        self.occasions()
            .par_iter()
            .map(|o| auc_occasion(o, outeq, method, blq_rule))
            .collect()
    }

    fn auc_interval_blq(
        &self,
        outeq: usize,
        start: f64,
        end: f64,
        method: &AUCMethod,
        blq_rule: &BLQRule,
    ) -> Vec<Result<f64, MetricsError>> {
        self.occasions()
            .par_iter()
            .map(|o| auc_interval_occasion(o, outeq, start, end, method, blq_rule))
            .collect()
    }

    fn cmax_blq(&self, outeq: usize, blq_rule: &BLQRule) -> Vec<Result<f64, MetricsError>> {
        self.occasions()
            .par_iter()
            .map(|o| cmax_occasion(o, outeq, blq_rule))
            .collect()
    }

    fn tmax_blq(&self, outeq: usize, blq_rule: &BLQRule) -> Vec<Result<f64, MetricsError>> {
        self.occasions()
            .par_iter()
            .map(|o| tmax_occasion(o, outeq, blq_rule))
            .collect()
    }

    fn clast_blq(&self, outeq: usize, blq_rule: &BLQRule) -> Vec<Result<f64, MetricsError>> {
        self.occasions()
            .par_iter()
            .map(|o| clast_occasion(o, outeq, blq_rule))
            .collect()
    }

    fn tlast_blq(&self, outeq: usize, blq_rule: &BLQRule) -> Vec<Result<f64, MetricsError>> {
        self.occasions()
            .par_iter()
            .map(|o| tlast_occasion(o, outeq, blq_rule))
            .collect()
    }

    fn aumc_blq(
        &self,
        outeq: usize,
        method: &AUCMethod,
        blq_rule: &BLQRule,
    ) -> Vec<Result<f64, MetricsError>> {
        self.occasions()
            .par_iter()
            .map(|o| aumc_occasion(o, outeq, method, blq_rule))
            .collect()
    }
}

// ============================================================================
// Data implementations (iterate subjects, flatten)
// ============================================================================

impl ObservationMetrics for Data {
    fn auc_blq(
        &self,
        outeq: usize,
        method: &AUCMethod,
        blq_rule: &BLQRule,
    ) -> Vec<Result<f64, MetricsError>> {
        self.subjects()
            .par_iter()
            .flat_map(|s| s.auc_blq(outeq, method, blq_rule))
            .collect()
    }

    fn auc_interval_blq(
        &self,
        outeq: usize,
        start: f64,
        end: f64,
        method: &AUCMethod,
        blq_rule: &BLQRule,
    ) -> Vec<Result<f64, MetricsError>> {
        self.subjects()
            .par_iter()
            .flat_map(|s| s.auc_interval_blq(outeq, start, end, method, blq_rule))
            .collect()
    }

    fn cmax_blq(&self, outeq: usize, blq_rule: &BLQRule) -> Vec<Result<f64, MetricsError>> {
        self.subjects()
            .par_iter()
            .flat_map(|s| s.cmax_blq(outeq, blq_rule))
            .collect()
    }

    fn tmax_blq(&self, outeq: usize, blq_rule: &BLQRule) -> Vec<Result<f64, MetricsError>> {
        self.subjects()
            .par_iter()
            .flat_map(|s| s.tmax_blq(outeq, blq_rule))
            .collect()
    }

    fn clast_blq(&self, outeq: usize, blq_rule: &BLQRule) -> Vec<Result<f64, MetricsError>> {
        self.subjects()
            .par_iter()
            .flat_map(|s| s.clast_blq(outeq, blq_rule))
            .collect()
    }

    fn tlast_blq(&self, outeq: usize, blq_rule: &BLQRule) -> Vec<Result<f64, MetricsError>> {
        self.subjects()
            .par_iter()
            .flat_map(|s| s.tlast_blq(outeq, blq_rule))
            .collect()
    }

    fn aumc_blq(
        &self,
        outeq: usize,
        method: &AUCMethod,
        blq_rule: &BLQRule,
    ) -> Vec<Result<f64, MetricsError>> {
        self.subjects()
            .par_iter()
            .flat_map(|s| s.aumc_blq(outeq, method, blq_rule))
            .collect()
    }
}

// ============================================================================
// Private helpers for Occasion-level metric implementations
// ============================================================================

fn auc_occasion(
    occasion: &Occasion,
    outeq: usize,
    method: &AUCMethod,
    blq_rule: &BLQRule,
) -> Result<f64, MetricsError> {
    let profile = ObservationProfile::from_occasion(occasion, outeq, blq_rule)?;
    Ok(profile.auc_last(method)?)
}

fn auc_interval_occasion(
    occasion: &Occasion,
    outeq: usize,
    start: f64,
    end: f64,
    method: &AUCMethod,
    blq_rule: &BLQRule,
) -> Result<f64, MetricsError> {
    let profile = ObservationProfile::from_occasion(occasion, outeq, blq_rule)?;
    Ok(profile.auc_interval(start, end, method)?)
}

fn cmax_occasion(
    occasion: &Occasion,
    outeq: usize,
    blq_rule: &BLQRule,
) -> Result<f64, MetricsError> {
    let profile = ObservationProfile::from_occasion(occasion, outeq, blq_rule)?;
    Ok(profile.cmax())
}

fn tmax_occasion(
    occasion: &Occasion,
    outeq: usize,
    blq_rule: &BLQRule,
) -> Result<f64, MetricsError> {
    let profile = ObservationProfile::from_occasion(occasion, outeq, blq_rule)?;
    Ok(profile.tmax())
}

fn clast_occasion(
    occasion: &Occasion,
    outeq: usize,
    blq_rule: &BLQRule,
) -> Result<f64, MetricsError> {
    let profile = ObservationProfile::from_occasion(occasion, outeq, blq_rule)?;
    Ok(profile.clast())
}

fn tlast_occasion(
    occasion: &Occasion,
    outeq: usize,
    blq_rule: &BLQRule,
) -> Result<f64, MetricsError> {
    let profile = ObservationProfile::from_occasion(occasion, outeq, blq_rule)?;
    Ok(profile.tlast())
}

fn aumc_occasion(
    occasion: &Occasion,
    outeq: usize,
    method: &AUCMethod,
    blq_rule: &BLQRule,
) -> Result<f64, MetricsError> {
    let profile = ObservationProfile::from_occasion(occasion, outeq, blq_rule)?;
    Ok(profile.aumc_last(method)?)
}