pmcore/structs/
psi.rs

1use anyhow::Result;
2use faer::Mat;
3use faer_ext::IntoFaer;
4use faer_ext::IntoNdarray;
5use ndarray::{Array2, ArrayView2};
6use pharmsol::prelude::simulator::psi;
7use pharmsol::Data;
8use pharmsol::Equation;
9use pharmsol::ErrorModel;
10
11use super::theta::Theta;
12
13/// [Psi] is a structure that holds the likelihood for each subject (row), for each support point (column)
14#[derive(Debug, Clone, PartialEq)]
15pub struct Psi {
16    matrix: Mat<f64>,
17}
18
19impl Psi {
20    pub fn new() -> Self {
21        Psi { matrix: Mat::new() }
22    }
23
24    pub fn matrix(&self) -> &Mat<f64> {
25        &self.matrix
26    }
27
28    pub fn nspp(&self) -> usize {
29        self.matrix.nrows()
30    }
31
32    pub fn nsub(&self) -> usize {
33        self.matrix.ncols()
34    }
35
36    /// Modify the [Psi::matrix] to only include the columns specified by `indices`
37    pub(crate) fn filter_column_indices(&mut self, indices: &[usize]) {
38        let matrix = self.matrix.to_owned();
39
40        let new = Mat::from_fn(matrix.nrows(), indices.len(), |r, c| {
41            *matrix.get(r, indices[c])
42        });
43
44        self.matrix = new;
45    }
46
47    /// Write the matrix to a CSV file
48    pub fn write(&self, path: &str) {
49        let mut writer = csv::Writer::from_path(path).unwrap();
50        for row in self.matrix.row_iter() {
51            writer
52                .write_record(row.iter().map(|x| x.to_string()))
53                .unwrap();
54        }
55    }
56}
57
58impl Default for Psi {
59    fn default() -> Self {
60        Psi::new()
61    }
62}
63
64impl From<Array2<f64>> for Psi {
65    fn from(array: Array2<f64>) -> Self {
66        let matrix = array.view().into_faer().to_owned();
67        Psi { matrix }
68    }
69}
70
71impl From<Mat<f64>> for Psi {
72    fn from(matrix: Mat<f64>) -> Self {
73        Psi { matrix }
74    }
75}
76
77impl From<ArrayView2<'_, f64>> for Psi {
78    fn from(array_view: ArrayView2<'_, f64>) -> Self {
79        let matrix = array_view.into_faer().to_owned();
80        Psi { matrix }
81    }
82}
83
84impl From<&Array2<f64>> for Psi {
85    fn from(array: &Array2<f64>) -> Self {
86        let matrix = array.view().into_faer().to_owned();
87        Psi { matrix }
88    }
89}
90
91pub(crate) fn calculate_psi(
92    equation: &impl Equation,
93    subjects: &Data,
94    theta: &Theta,
95    error_model: &ErrorModel,
96    progress: bool,
97    cache: bool,
98) -> Result<Psi> {
99    let psi_ndarray = psi(
100        equation,
101        subjects,
102        &theta.matrix().clone().as_ref().into_ndarray().to_owned(),
103        error_model,
104        progress,
105        cache,
106    )?;
107
108    Ok(psi_ndarray.view().into())
109}