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
use crate::data::error_model::ErrorPoly;
use crate::prelude::simulator::Prediction;
use serde::{Deserialize, Serialize};
use std::fmt;

// ============================================================================
// Shared Analysis Types
// ============================================================================

/// Administration route for a dosing event
///
/// Determined by the type of dose events and their target compartment:
/// - [`Event::Infusion`] → [`Route::IVInfusion`]
/// - [`Event::Bolus`] with `input >= 1` (central compartment) → [`Route::IVBolus`]
/// - [`Event::Bolus`] with `input == 0` (depot compartment) → [`Route::Extravascular`]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum Route {
    /// Intravenous bolus
    IVBolus,
    /// Intravenous infusion
    IVInfusion,
    /// Extravascular (oral, SC, IM, etc.)
    #[default]
    Extravascular,
}

/// AUC calculation method
///
/// Controls how the area under the concentration-time curve is computed.
/// This is a general trapezoidal method applicable to any AUC calculation,
/// not specific to NCA analysis.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum AUCMethod {
    /// Linear trapezoidal rule
    Linear,
    /// Linear up / log down (industry standard)
    #[default]
    LinUpLogDown,
    /// Linear before Tmax, log-linear after Tmax (PKNCA "lin-log")
    ///
    /// Uses linear trapezoidal before and at Tmax, then log-linear for
    /// descending portions after Tmax. Falls back to linear if either
    /// concentration is zero or non-positive.
    LinLog,
}

/// BLQ (Below Limit of Quantification) handling rule
///
/// Controls how observations marked with [`Censor::BLOQ`] are handled
/// during analysis. Applicable to NCA, AUC calculations, and any
/// observation-processing pipeline.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub enum BLQRule {
    /// Replace BLQ with zero
    Zero,
    /// Replace BLQ with LOQ/2
    LoqOver2,
    /// Exclude BLQ values from analysis
    #[default]
    Exclude,
    /// Position-aware handling (PKNCA default): first=keep(0), middle=drop, last=keep(0)
    ///
    /// This is the FDA-recommended approach that:
    /// - Keeps first BLQ (before tfirst) as 0 to anchor the profile start
    /// - Drops middle BLQ (between tfirst and tlast) to avoid deflating AUC
    /// - Keeps last BLQ (at/after tlast) as 0 to define profile end
    Positional,
    /// Tmax-relative handling: different rules before vs after Tmax
    ///
    /// Contains (before_tmax_rule, after_tmax_rule) where each rule can be:
    /// - "keep" = keep as 0
    /// - "drop" = exclude from analysis
    /// Default PKNCA: before.tmax=drop, after.tmax=keep
    TmaxRelative {
        /// Rule for BLQ before Tmax: true=keep as 0, false=drop
        before_tmax_keep: bool,
        /// Rule for BLQ at or after Tmax: true=keep as 0, false=drop
        after_tmax_keep: bool,
    },
}

/// Represents a pharmacokinetic/pharmacodynamic event
///
/// Events represent key occurrences in a PK/PD profile, including:
/// - [Bolus] doses (instantaneous drug input)
/// - [Infusion]s (continuous drug input over a duration)
/// - [Observation]s (measured concentrations or other values)
#[derive(Serialize, Debug, Clone, Deserialize)]
pub enum Event {
    /// A bolus dose (instantaneous drug input)
    Bolus(Bolus),
    /// An infusion (continuous drug input over a duration)
    Infusion(Infusion),
    /// An observation of drug concentration or other measure
    Observation(Observation),
}
impl Event {
    /// Get the time of the event
    pub fn time(&self) -> f64 {
        match self {
            Event::Bolus(bolus) => bolus.time,
            Event::Infusion(infusion) => infusion.time,
            Event::Observation(observation) => observation.time,
        }
    }
    /// Increment the event time by a specified delta
    pub(crate) fn inc_time(&mut self, dt: f64) {
        match self {
            Event::Bolus(bolus) => bolus.time += dt,
            Event::Infusion(infusion) => infusion.time += dt,
            Event::Observation(observation) => observation.time += dt,
        }
    }

    /// Get the occasion index for this event
    pub fn occasion(&self) -> usize {
        match self {
            Event::Bolus(bolus) => bolus.occasion,
            Event::Infusion(infusion) => infusion.occasion,
            Event::Observation(observation) => observation.occasion,
        }
    }

    /// Get a mutable reference to the occasion index
    pub fn mut_occasion(&mut self) -> &mut usize {
        match self {
            Event::Bolus(bolus) => bolus.mut_occasion(),
            Event::Infusion(infusion) => infusion.mut_occasion(),
            Event::Observation(observation) => observation.mut_occasion(),
        }
    }

    /// Set the occasion index for this event
    pub fn set_occasion(&mut self, occasion: usize) {
        match self {
            Event::Bolus(_) => {
                *self.mut_occasion() = occasion;
            }
            Event::Infusion(_) => {
                *self.mut_occasion() = occasion;
            }
            Event::Observation(_) => {
                *self.mut_occasion() = occasion;
            }
        }
    }
}

/// Represents an instantaneous input of drug
///
/// A [Bolus] is a discrete amount of drug added to a specific compartment at a specific time.
#[derive(Serialize, Debug, Clone, Deserialize)]
pub struct Bolus {
    time: f64,
    amount: f64,
    input: usize,
    occasion: usize,
}
impl Bolus {
    /// Create a new bolus event
    ///
    /// # Arguments
    ///
    /// * `time` - Time of the bolus dose
    /// * `amount` - Amount of drug administered
    /// * `input` - The compartment number receiving the dose
    pub fn new(time: f64, amount: f64, input: usize, occasion: usize) -> Self {
        Bolus {
            time,
            amount,
            input,
            occasion,
        }
    }

    /// Get the amount of drug in the bolus
    pub fn amount(&self) -> f64 {
        self.amount
    }

    /// Get the compartment number that receives the bolus
    pub fn input(&self) -> usize {
        self.input
    }

    /// Get the time of the bolus administration
    pub fn time(&self) -> f64 {
        self.time
    }

    /// Set the amount of drug in the bolus
    pub fn set_amount(&mut self, amount: f64) {
        self.amount = amount;
    }

    /// Set the compartment number that receives the bolus
    pub fn set_input(&mut self, input: usize) {
        self.input = input;
    }

    /// Set the time of the bolus administration
    pub fn set_time(&mut self, time: f64) {
        self.time = time;
    }

    /// Get a mutable reference to the amount of drug in the bolus
    pub fn mut_amount(&mut self) -> &mut f64 {
        &mut self.amount
    }

    /// Get a mutable reference to the compartment number (1-indexed) that receives the bolus
    pub fn mut_input(&mut self) -> &mut usize {
        &mut self.input
    }

    /// Get a mutable reference to the time of the bolus administration
    pub fn mut_time(&mut self) -> &mut f64 {
        &mut self.time
    }

    /// Get the occasion index for this bolus
    pub fn occasion(&self) -> usize {
        self.occasion
    }

    /// Get a mutable reference to the occasion index
    pub fn mut_occasion(&mut self) -> &mut usize {
        &mut self.occasion
    }
}

/// Represents a continuous dose of drug over time
///
/// An [Infusion] administers drug at a constant rate over a specified duration.
#[derive(Serialize, Debug, Clone, Deserialize)]
pub struct Infusion {
    time: f64,
    amount: f64,
    input: usize,
    duration: f64,
    occasion: usize,
}
impl Infusion {
    /// Create a new infusion event
    ///
    /// # Arguments
    ///
    /// * `time` - Start time of the infusion
    /// * `amount` - Total amount of drug to be administered
    /// * `input` - The compartment number receiving the dose
    /// * `duration` - Duration of the infusion in time units
    pub fn new(time: f64, amount: f64, input: usize, duration: f64, occasion: usize) -> Self {
        Infusion {
            time,
            amount,
            input,
            duration,
            occasion,
        }
    }

    /// Get the total amount of drug provided over the infusion
    pub fn amount(&self) -> f64 {
        self.amount
    }

    /// Get the compartment number that receives the infusion
    pub fn input(&self) -> usize {
        self.input
    }

    /// Get the duration of the infusion
    pub fn duration(&self) -> f64 {
        self.duration
    }

    /// Get the start time of the infusion
    ///
    /// The infusion continues from this time until time + duration.
    pub fn time(&self) -> f64 {
        self.time
    }

    /// Set the amount of drug in the infusion
    pub fn set_amount(&mut self, amount: f64) {
        self.amount = amount;
    }

    /// Set the compartment number that receives the infusion
    pub fn set_input(&mut self, input: usize) {
        self.input = input;
    }

    /// Set the time of the infusion administration
    pub fn set_time(&mut self, time: f64) {
        self.time = time;
    }

    /// Set the duration of the infusion
    pub fn set_duration(&mut self, duration: f64) {
        self.duration = duration;
    }

    /// Set the amount of drug in the infusion
    pub fn mut_amount(&mut self) -> &mut f64 {
        &mut self.amount
    }

    /// Get a mutable reference to the compartment number (1-indexed) that receives the infusion
    pub fn mut_input(&mut self) -> &mut usize {
        &mut self.input
    }

    /// Set the time of the infusion administration
    pub fn mut_time(&mut self) -> &mut f64 {
        &mut self.time
    }

    /// Set the duration of the infusion
    pub fn mut_duration(&mut self) -> &mut f64 {
        &mut self.duration
    }

    /// Get the occasion index for this infusion
    pub fn occasion(&self) -> usize {
        self.occasion
    }

    /// Get a mutable reference to the occasion index
    pub fn mut_occasion(&mut self) -> &mut usize {
        &mut self.occasion
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Censor {
    /// No censoring
    #[default]
    None,
    /// Below the lower limit of quantification
    BLOQ,
    /// Above the limit of quantification
    ALOQ,
}

/// Represents an observation of drug concentration or other measured value
#[derive(Serialize, Debug, Clone, Deserialize)]
pub struct Observation {
    time: f64,
    value: Option<f64>,
    outeq: usize,
    errorpoly: Option<ErrorPoly>,
    occasion: usize,
    censoring: Censor,
}
impl Observation {
    /// Create a new observation
    ///
    /// # Arguments
    ///
    /// * `time` - Time of the observation
    /// * `value` - Observed value (e.g., drug concentration)
    /// * `outeq` - Output equation number corresponding to this observation
    /// * `errorpoly` - Optional error polynomial coefficients (c0, c1, c2, c3)
    /// * `occasion` - Occasion index
    /// * `censoring` - Censoring type for this observation
    pub(crate) fn new(
        time: f64,
        value: Option<f64>,
        outeq: usize,
        errorpoly: Option<ErrorPoly>,
        occasion: usize,
        censoring: Censor,
    ) -> Self {
        Observation {
            time,
            value,
            outeq,
            errorpoly,
            occasion,
            censoring,
        }
    }

    /// Get the time of the observation
    pub fn time(&self) -> f64 {
        self.time
    }

    /// Get the value of the observation (e.g., drug concentration)
    pub fn value(&self) -> Option<f64> {
        self.value
    }

    /// Get the output equation number corresponding to this observation
    pub fn outeq(&self) -> usize {
        self.outeq
    }

    /// Get the error polynomial coefficients (c0, c1, c2, c3) if available
    ///
    /// The error polynomial is used to model the observation error.
    pub fn errorpoly(&self) -> Option<ErrorPoly> {
        self.errorpoly
    }

    /// Set the time of the observation
    pub fn set_time(&mut self, time: f64) {
        self.time = time;
    }

    /// Set the value of the observation (e.g., drug concentration)
    pub fn set_value(&mut self, value: Option<f64>) {
        self.value = value;
    }

    /// Set the output equation number corresponding to this observation
    pub fn set_outeq(&mut self, outeq: usize) {
        self.outeq = outeq;
    }

    /// Set the [ErrorPoly] for this observation
    pub fn set_errorpoly(&mut self, errorpoly: Option<ErrorPoly>) {
        self.errorpoly = errorpoly;
    }

    /// Get a mutable reference to the time of the observation
    pub fn mut_time(&mut self) -> &mut f64 {
        &mut self.time
    }

    /// Get a mutable reference to the value of the observation
    pub fn mut_value(&mut self) -> &mut Option<f64> {
        &mut self.value
    }

    /// Get a mutable reference to the output equation number
    pub fn mut_outeq(&mut self) -> &mut usize {
        &mut self.outeq
    }

    /// Get a mutable reference to the error polynomial
    pub fn mut_errorpoly(&mut self) -> &mut Option<ErrorPoly> {
        &mut self.errorpoly
    }

    /// Get the occasion index for this observation
    pub fn occasion(&self) -> usize {
        self.occasion
    }

    /// Get a mutable reference to the occasion index
    pub fn mut_occasion(&mut self) -> &mut usize {
        &mut self.occasion
    }

    /// Create a [Prediction] from this observation
    pub fn to_prediction(&self, pred: f64, state: Vec<f64>) -> Prediction {
        Prediction {
            time: self.time(),
            observation: self.value(),
            prediction: pred,
            outeq: self.outeq(),
            errorpoly: self.errorpoly(),
            state,
            occasion: self.occasion(),
            censoring: self.censoring(),
        }
    }

    /// Check if the observation is censored
    pub fn censored(&self) -> bool {
        match self.censoring {
            Censor::None => false,
            Censor::ALOQ => true,
            Censor::BLOQ => true,
        }
    }

    /// Get the censoring type of the observation
    pub fn censoring(&self) -> Censor {
        self.censoring
    }

    /// Set whether the observation is censored
    pub fn censor(&mut self, censor: Censor) {
        self.censoring = censor;
    }

    /// Get a mutable reference to the censoring flag
    pub fn mut_censoring(&mut self) -> &mut Censor {
        &mut self.censoring
    }
}

impl fmt::Display for Event {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Event::Bolus(bolus) => write!(
                f,
                "Bolus at time {:.2} with amount {:.2} in compartment {}",
                bolus.time, bolus.amount, bolus.input
            ),
            Event::Infusion(infusion) => write!(
                f,
                "Infusion starting at {:.2} with amount {:.2} over {:.2} hours in compartment {}",
                infusion.time, infusion.amount, infusion.duration, infusion.input
            ),
            Event::Observation(observation) => {
                let errpoly_desc = match observation.errorpoly {
                    Some(errorpoly) => {
                        format!(
                            "with error poly {} {} {} {}",
                            errorpoly.coefficients().0,
                            errorpoly.coefficients().1,
                            errorpoly.coefficients().2,
                            errorpoly.coefficients().3
                        )
                    }
                    None => "".to_string(),
                };
                write!(
                    f,
                    "Observation at time {:.2}: {:#?} (outeq {}) {}",
                    observation.time, observation.value, observation.outeq, errpoly_desc
                )
            }
        }
    }
}

#[cfg(test)]

mod tests {
    use super::*;

    #[test]
    fn test_bolus_creation() {
        let bolus = Bolus::new(2.5, 100.0, 1, 0);
        assert_eq!(bolus.time(), 2.5);
        assert_eq!(bolus.amount(), 100.0);
        assert_eq!(bolus.input(), 1);
    }

    #[test]
    fn test_bolus_setters() {
        let mut bolus = Bolus::new(2.5, 100.0, 1, 0);

        bolus.set_time(3.0);
        assert_eq!(bolus.time(), 3.0);

        bolus.set_amount(150.0);
        assert_eq!(bolus.amount(), 150.0);

        bolus.set_input(2);
        assert_eq!(bolus.input(), 2);
    }

    #[test]
    fn test_infusion_creation() {
        let infusion = Infusion::new(1.0, 200.0, 1, 2.5, 0);
        assert_eq!(infusion.time(), 1.0);
        assert_eq!(infusion.amount(), 200.0);
        assert_eq!(infusion.input(), 1);
        assert_eq!(infusion.duration(), 2.5);
    }

    #[test]
    fn test_infusion_setters() {
        let mut infusion = Infusion::new(1.0, 200.0, 1, 2.5, 0);

        infusion.set_time(1.5);
        assert_eq!(infusion.time(), 1.5);

        infusion.set_amount(250.0);
        assert_eq!(infusion.amount(), 250.0);

        infusion.set_input(2);
        assert_eq!(infusion.input(), 2);

        infusion.set_duration(3.0);
        assert_eq!(infusion.duration(), 3.0);
    }

    #[test]
    fn test_observation_creation() {
        let error_poly = Some(ErrorPoly::new(0.1, 0.2, 0.3, 0.4));
        let observation = Observation::new(5.0, Some(75.5), 2, error_poly, 0, Censor::None);

        assert_eq!(observation.time(), 5.0);
        assert_eq!(observation.value(), Some(75.5));
        assert_eq!(observation.outeq(), 2);
        assert_eq!(observation.errorpoly(), error_poly);
    }

    #[test]
    fn test_observation_setters() {
        let mut observation = Observation::new(
            5.0,
            Some(75.5),
            2,
            Some(ErrorPoly::new(0.1, 0.2, 0.3, 0.4)),
            0,
            Censor::None,
        );

        observation.set_time(6.0);
        assert_eq!(observation.time(), 6.0);

        observation.set_value(Some(80.0));
        assert_eq!(observation.value(), Some(80.0));

        observation.set_outeq(3);
        assert_eq!(observation.outeq(), 3);

        let new_error_poly = Some(ErrorPoly::new(0.2, 0.3, 0.4, 0.5));
        observation.set_errorpoly(new_error_poly);
        assert_eq!(observation.errorpoly(), new_error_poly);
    }

    #[test]
    fn test_event_time_operations() {
        let mut bolus_event = Event::Bolus(Bolus::new(1.0, 100.0, 1, 0));
        let mut infusion_event = Event::Infusion(Infusion::new(2.0, 200.0, 1, 2.5, 0));
        let mut observation_event =
            Event::Observation(Observation::new(3.0, Some(75.5), 2, None, 0, Censor::None));

        assert_eq!(bolus_event.time(), 1.0);
        assert_eq!(infusion_event.time(), 2.0);
        assert_eq!(observation_event.time(), 3.0);

        bolus_event.inc_time(0.5);
        infusion_event.inc_time(0.5);
        observation_event.inc_time(0.5);

        assert_eq!(bolus_event.time(), 1.5);
        assert_eq!(infusion_event.time(), 2.5);
        assert_eq!(observation_event.time(), 3.5);
    }
}