Skip to main content

pmcore/estimation/nonparametric/
theta.rs

1use std::{fmt::Debug, fs::File, path::Path};
2
3use anyhow::{bail, Context, Result};
4use faer::Mat;
5use serde::{Deserialize, Serialize};
6
7use super::sampling::{self, latin, sobol};
8use super::weights::Weights;
9use crate::model::{BoundedParameter, ParameterSpace};
10
11/// [Theta] is a structure that holds the support points
12/// These represent the joint population parameter distribution
13///
14/// Each row represents a support points, and each column a parameter
15#[derive(Clone, PartialEq)]
16pub struct Theta {
17    matrix: Mat<f64>,
18    parameters: ParameterSpace<BoundedParameter>,
19}
20
21impl Default for Theta {
22    fn default() -> Self {
23        Theta {
24            matrix: Mat::new(),
25            parameters: ParameterSpace::<BoundedParameter>::new(),
26        }
27    }
28}
29
30impl Theta {
31    pub fn new() -> Self {
32        Theta::default()
33    }
34
35    /// Create a new [Theta] from a matrix and [ParameterSpace]
36    ///
37    /// It is important that the number of columns in the matrix matches the number of parameters
38    /// in the [ParameterSpace]
39    ///
40    /// The order of parameters in the [ParameterSpace] should match the order of columns in the matrix
41    pub fn from_parts(
42        matrix: Mat<f64>,
43        parameters: ParameterSpace<BoundedParameter>,
44    ) -> Result<Self> {
45        if matrix.ncols() != parameters.len() {
46            bail!(
47                "Number of columns in matrix ({}) does not match number of parameters ({})",
48                matrix.ncols(),
49                parameters.len()
50            );
51        }
52
53        Ok(Theta { matrix, parameters })
54    }
55
56    /// Get the matrix containing parameter values
57    ///
58    /// The matrix is a 2D array where each row represents a support point, and each column a parameter
59    pub fn matrix(&self) -> &Mat<f64> {
60        &self.matrix
61    }
62
63    /// Get a mutable reference to the matrix
64    pub fn matrix_mut(&mut self) -> &mut Mat<f64> {
65        &mut self.matrix
66    }
67
68    /// Get the [ParameterSpace] associated with this [Theta]
69    pub fn parameters(&self) -> &ParameterSpace<BoundedParameter> {
70        &self.parameters
71    }
72
73    /// Get a mutable reference to the [ParameterSpace]
74    pub fn parameters_mut(&mut self) -> &mut ParameterSpace<BoundedParameter> {
75        &mut self.parameters
76    }
77
78    /// Get the number of support points, equal to the number of rows in the matrix
79    pub fn nspp(&self) -> usize {
80        self.matrix.nrows()
81    }
82
83    /// Get the parameter names
84    pub fn param_names(&self) -> Vec<String> {
85        self.parameters.names()
86    }
87
88    /// Modify the [Theta::matrix] to only include the rows specified by `indices`
89    pub(crate) fn filter_indices(&mut self, indices: &[usize]) {
90        let matrix = self.matrix.to_owned();
91
92        let new = Mat::from_fn(indices.len(), matrix.ncols(), |r, c| {
93            *matrix.get(indices[r], c)
94        });
95
96        self.matrix = new;
97    }
98
99    /// Forcibly add a support point to the matrix
100    pub fn add_point(&mut self, spp: &[f64]) -> Result<()> {
101        if spp.len() != self.matrix.ncols() {
102            bail!(
103                "Support point length ({}) does not match number of parameters ({})",
104                spp.len(),
105                self.matrix.ncols()
106            );
107        }
108
109        self.matrix
110            .resize_with(self.matrix.nrows() + 1, self.matrix.ncols(), |_, i| spp[i]);
111        Ok(())
112    }
113
114    /// Suggest a new support point to add to the matrix
115    /// The point is first clamped to the parameter bounds, and is only added if it is
116    /// at least `min_dist` away from all existing support points
117    pub(crate) fn suggest_point(&mut self, spp: &[f64], min_dist: f64) -> Result<()> {
118        let spp: Vec<f64> = spp
119            .iter()
120            .zip(self.parameters.finite_ranges())
121            .map(|(val, (lower, upper))| val.clamp(lower, upper))
122            .collect();
123        if self.check_point(&spp, min_dist) {
124            self.add_point(&spp)?;
125        }
126        Ok(())
127    }
128
129    /// Check if a point is at least `min_dist` away from all existing support points
130    pub(crate) fn check_point(&self, spp: &[f64], min_dist: f64) -> bool {
131        if self.matrix.nrows() == 0 {
132            return true;
133        }
134
135        let limits = self.parameters.finite_ranges();
136
137        for row_idx in 0..self.matrix.nrows() {
138            let mut squared_dist = 0.0;
139            for (i, val) in spp.iter().enumerate() {
140                let normalized_diff =
141                    (val - self.matrix.get(row_idx, i)) / (limits[i].1 - limits[i].0);
142                squared_dist += normalized_diff * normalized_diff;
143            }
144            let dist = squared_dist.sqrt();
145            if dist <= min_dist {
146                return false;
147            }
148        }
149        true
150    }
151
152    /// Create a new Theta with an additional parameter column.
153    ///
154    /// All existing rows keep their values. The new column is filled with
155    /// `initial_value` for every row. Returns a new `Theta` — does not
156    /// mutate in place.
157    ///
158    /// # Errors
159    ///
160    /// - `name` already exists in the parameter space
161    /// - `lower` or `upper` are non-finite
162    /// - `lower >= upper`
163    pub fn with_added_parameter(
164        &self,
165        name: &str,
166        lower: f64,
167        upper: f64,
168        initial_value: f64,
169    ) -> Result<Theta> {
170        // Validate uniqueness
171        if self.parameters().iter().any(|p| p.name.as_str() == name) {
172            bail!("parameter '{}' already exists in theta", name);
173        }
174
175        // Validate bounds
176        if !lower.is_finite() || !upper.is_finite() {
177            bail!(
178                "bounds must be finite for parameter '{}': [{}, {}]",
179                name,
180                lower,
181                upper
182            );
183        }
184        if lower >= upper {
185            bail!(
186                "lower bound ({}) must be strictly less than upper bound ({}) for parameter '{}'",
187                lower,
188                upper,
189                name
190            );
191        }
192
193        let (nrows, ncols) = (self.matrix().nrows(), self.matrix().ncols());
194        let new_matrix = faer::Mat::from_fn(nrows, ncols + 1, |r, c| {
195            if c < ncols {
196                self.matrix()[(r, c)]
197            } else {
198                initial_value
199            }
200        });
201
202        let new_params = self.parameters().clone().add(name, lower, upper);
203
204        Theta::from_parts(new_matrix, new_params)
205    }
206
207    /// Write the matrix to a CSV file
208    pub fn write(&self, path: &str) {
209        let mut writer = csv::Writer::from_path(path).unwrap();
210        for row in self.matrix.row_iter() {
211            writer
212                .write_record(row.iter().map(|x| x.to_string()))
213                .unwrap();
214        }
215    }
216
217    /// Write the matrix to a CSV file with weights
218    pub fn write_with_weights(&self, path: &str, weights: &Weights) -> Result<()> {
219        if self.nspp() != weights.len() {
220            bail!(
221                "Number of support points ({}) does not match number of weights ({})",
222                self.nspp(),
223                weights.len()
224            );
225        }
226
227        let mut writer = csv::Writer::from_path(path)?;
228
229        let header: Vec<String> = self
230            .parameters
231            .names()
232            .iter()
233            .cloned()
234            .chain(std::iter::once("prob".to_string()))
235            .collect();
236
237        writer.write_record(header)?;
238
239        for (row_idx, row) in self.matrix.row_iter().enumerate() {
240            let mut record: Vec<String> = row.iter().map(|x| x.to_string()).collect();
241            record.push(weights[row_idx].to_string());
242            writer.write_record(record)?;
243        }
244        Ok(())
245    }
246
247    /// Write the theta matrix to a CSV writer
248    /// Each row represents a support point, each column represents a parameter
249    pub fn to_csv<W: std::io::Write>(&self, writer: W) -> Result<()> {
250        let mut csv_writer = csv::Writer::from_writer(writer);
251
252        for i in 0..self.matrix.nrows() {
253            let row: Vec<f64> = (0..self.matrix.ncols())
254                .map(|j| *self.matrix.get(i, j))
255                .collect();
256            csv_writer.serialize(row)?;
257        }
258
259        csv_writer.flush()?;
260        Ok(())
261    }
262
263    /// Read theta matrix from a CSV reader
264    /// Each row represents a support point, each column represents a parameter
265    /// Note: This only reads the matrix values, not the parameter metadata
266    pub fn from_csv<R: std::io::Read>(reader: R) -> Result<Self> {
267        let mut csv_reader = csv::Reader::from_reader(reader);
268        let mut rows: Vec<Vec<f64>> = Vec::new();
269
270        for result in csv_reader.deserialize() {
271            let row: Vec<f64> = result?;
272            rows.push(row);
273        }
274
275        if rows.is_empty() {
276            bail!("CSV file is empty");
277        }
278
279        let nrows = rows.len();
280        let ncols = rows[0].len();
281
282        for (i, row) in rows.iter().enumerate() {
283            if row.len() != ncols {
284                bail!("Row {} has {} columns, expected {}", i, row.len(), ncols);
285            }
286        }
287
288        let mat = Mat::from_fn(nrows, ncols, |i, j| rows[i][j]);
289        let parameters = ParameterSpace::<BoundedParameter>::new();
290
291        Theta::from_parts(mat, parameters)
292    }
293
294    /// Generate a starting grid of `points` support points over `parameters`
295    /// using a Sobol sequence and the default seed ([`sampling::DEFAULT_SEED`]).
296    ///
297    /// The returned [Theta] carries `parameters`, so the chosen grid is explicit
298    /// and self-describing.
299    pub fn sobol(parameters: &ParameterSpace<BoundedParameter>, points: usize) -> Result<Self> {
300        Self::sobol_with_seed(parameters, points, sampling::DEFAULT_SEED)
301    }
302
303    /// Generate a starting grid over `parameters` using a Sobol sequence with the
304    /// default number of support points ([`sampling::DEFAULT_POINTS`]) and the
305    /// default seed ([`sampling::DEFAULT_SEED`]).
306    pub fn sobol_default(parameters: &ParameterSpace<BoundedParameter>) -> Result<Self> {
307        Self::sobol(parameters, sampling::DEFAULT_POINTS)
308    }
309
310    /// Like [`Theta::sobol`], with an explicit seed for the quasi-random sequence.
311    pub fn sobol_with_seed(
312        parameters: &ParameterSpace<BoundedParameter>,
313        points: usize,
314        seed: usize,
315    ) -> Result<Self> {
316        validate_bounds(parameters)?;
317        sobol::generate(parameters, points, seed)
318    }
319
320    /// Generate a starting grid of `points` support points over `parameters`
321    /// using Latin Hypercube Sampling and the default seed ([`sampling::DEFAULT_SEED`]).
322    ///
323    /// The returned [Theta] carries `parameters`, so the chosen grid is explicit
324    /// and self-describing.
325    pub fn latin(parameters: &ParameterSpace<BoundedParameter>, points: usize) -> Result<Self> {
326        Self::latin_with_seed(parameters, points, sampling::DEFAULT_SEED)
327    }
328
329    /// Like [`Theta::latin`], with an explicit seed for the quasi-random sequence.
330    pub fn latin_with_seed(
331        parameters: &ParameterSpace<BoundedParameter>,
332        points: usize,
333        seed: usize,
334    ) -> Result<Self> {
335        validate_bounds(parameters)?;
336        latin::generate(parameters, points, seed)
337    }
338
339    pub fn from_file(
340        path: impl AsRef<Path>,
341        parameters: &ParameterSpace<BoundedParameter>,
342    ) -> Result<(Theta, Option<Weights>)> {
343        let path = path.as_ref();
344        tracing::info!("Reading prior from {}", path.display());
345        let file = File::open(path).context(format!(
346            "Unable to open the prior file '{}'",
347            path.display()
348        ))?;
349        let mut reader = csv::ReaderBuilder::new()
350            .has_headers(true)
351            .from_reader(file);
352
353        let mut parameter_names: Vec<String> = reader
354            .headers()?
355            .clone()
356            .into_iter()
357            .map(|s| s.trim().to_owned())
358            .collect();
359
360        let prob_index = parameter_names.iter().position(|name| name == "prob");
361        if let Some(index) = prob_index {
362            parameter_names.remove(index);
363        }
364
365        let random_names: Vec<String> = parameters.names();
366
367        let mut reordered_indices: Vec<usize> = Vec::new();
368        for random_name in &random_names {
369            match parameter_names.iter().position(|name| name == random_name) {
370                Some(index) => {
371                    let adjusted_index = if let Some(prob_idx) = prob_index {
372                        if index >= prob_idx {
373                            index + 1
374                        } else {
375                            index
376                        }
377                    } else {
378                        index
379                    };
380                    reordered_indices.push(adjusted_index);
381                }
382                None => bail!("Parameter {} is not present in the CSV file.", random_name),
383            }
384        }
385
386        if parameter_names.len() > random_names.len() {
387            let extra_parameters: Vec<&String> = parameter_names.iter().collect();
388            bail!(
389                "Found parameters in the prior not present in configuration: {:?}",
390                extra_parameters
391            );
392        }
393
394        let mut theta_values = Vec::new();
395        let mut prob_values = Vec::new();
396
397        for result in reader.records() {
398            let record = result.unwrap();
399            let values: Vec<f64> = reordered_indices
400                .iter()
401                .map(|&i| record[i].parse::<f64>().unwrap())
402                .collect();
403            theta_values.push(values);
404
405            if let Some(prob_idx) = prob_index {
406                let prob_value: f64 = record[prob_idx].parse::<f64>().unwrap();
407                prob_values.push(prob_value);
408            }
409        }
410
411        let n_points = theta_values.len();
412        let n_params = random_names.len();
413        let theta_values: Vec<f64> = theta_values.into_iter().flatten().collect();
414        let theta_matrix: Mat<f64> =
415            Mat::from_fn(n_points, n_params, |i, j| theta_values[i * n_params + j]);
416
417        let theta = Theta::from_parts(theta_matrix, parameters.clone())?;
418        let weights = if !prob_values.is_empty() {
419            Some(Weights::from_vec(prob_values))
420        } else {
421            None
422        };
423
424        Ok((theta, weights))
425    }
426}
427
428impl Debug for Theta {
429    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
430        writeln!(f, "\nTheta contains {} support points\n", self.nspp())?;
431
432        for name in self.parameters.names().iter() {
433            write!(f, "\t{}", name)?;
434        }
435        writeln!(f)?;
436        self.matrix.row_iter().enumerate().for_each(|(index, row)| {
437            write!(f, "{}", index).unwrap();
438            for val in row.iter() {
439                write!(f, "\t{:.2}", val).unwrap();
440            }
441            writeln!(f).unwrap();
442        });
443        Ok(())
444    }
445}
446
447impl Serialize for Theta {
448    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
449    where
450        S: serde::Serializer,
451    {
452        use serde::ser::SerializeStruct;
453
454        let rows: Vec<Vec<f64>> = (0..self.matrix.nrows())
455            .map(|i| {
456                (0..self.matrix.ncols())
457                    .map(|j| *self.matrix.get(i, j))
458                    .collect()
459            })
460            .collect();
461
462        let mut state = serializer.serialize_struct("Theta", 2)?;
463        state.serialize_field("matrix", &rows)?;
464        state.serialize_field("parameters", &self.parameters)?;
465        state.end()
466    }
467}
468
469impl<'de> Deserialize<'de> for Theta {
470    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
471    where
472        D: serde::Deserializer<'de>,
473    {
474        #[derive(Deserialize)]
475        struct ThetaSerde {
476            matrix: Vec<Vec<f64>>,
477            parameters: ParameterSpace<BoundedParameter>,
478        }
479
480        let decoded = ThetaSerde::deserialize(deserializer)?;
481
482        if decoded.matrix.is_empty() {
483            return Ok(Self {
484                matrix: Mat::new(),
485                parameters: decoded.parameters,
486            });
487        }
488
489        let nrows = decoded.matrix.len();
490        let ncols = decoded.matrix[0].len();
491        for (index, row) in decoded.matrix.iter().enumerate() {
492            if row.len() != ncols {
493                return Err(serde::de::Error::custom(format!(
494                    "Row {} has {} columns, expected {}",
495                    index,
496                    row.len(),
497                    ncols
498                )));
499            }
500        }
501
502        let matrix = Mat::from_fn(nrows, ncols, |i, j| decoded.matrix[i][j]);
503        Self::from_parts(matrix, decoded.parameters).map_err(serde::de::Error::custom)
504    }
505}
506
507/// Validates that every parameter has a strictly-ordered, finite bound interval.
508fn validate_bounds(parameters: &ParameterSpace<BoundedParameter>) -> Result<()> {
509    for parameter in parameters.iter() {
510        if parameter.lower >= parameter.upper {
511            bail!(
512                "Parameter '{}' has invalid bounds: [{}, {}]. Lower bound must be less than upper bound.",
513                parameter.name,
514                parameter.lower,
515                parameter.upper
516            );
517        }
518    }
519    Ok(())
520}
521
522#[cfg(test)]
523mod tests {
524    use super::*;
525    use std::fs;
526
527    fn parameters() -> ParameterSpace<BoundedParameter> {
528        ParameterSpace::<BoundedParameter>::new()
529            .add("ke", 0.1, 1.0)
530            .add("v", 5.0, 50.0)
531    }
532
533    #[test]
534    fn suggest_point_clamps_to_bounds() {
535        let params = parameters();
536        let mut theta =
537            Theta::from_parts(Mat::from_fn(1, 2, |_, j| [0.5, 20.0][j]), params).unwrap();
538
539        theta.suggest_point(&[6.8, 1.0], 1e-4).unwrap();
540
541        assert_eq!(theta.nspp(), 2);
542        assert_eq!(*theta.matrix().get(1, 0), 1.0);
543        assert_eq!(*theta.matrix().get(1, 1), 5.0);
544    }
545
546    fn temp_csv_path() -> String {
547        format!("test_temp_theta_{}.csv", rand::random::<u32>())
548    }
549
550    #[test]
551    fn sobol_generates_expected_shape() {
552        let theta = Theta::sobol_with_seed(&parameters(), 10, 42).unwrap();
553        assert_eq!(theta.nspp(), 10);
554        assert_eq!(theta.matrix().ncols(), 2);
555    }
556
557    #[test]
558    fn latin_generates_expected_shape() {
559        let theta = Theta::latin(&parameters(), 10).unwrap();
560        assert_eq!(theta.nspp(), 10);
561        assert_eq!(theta.matrix().ncols(), 2);
562    }
563
564    #[test]
565    fn sampling_rejects_invalid_bounds() {
566        let bad = ParameterSpace::<BoundedParameter>::new().add("ke", 1.0, 1.0);
567        let err = Theta::sobol(&bad, 10).unwrap_err();
568        assert!(err.to_string().contains("invalid bounds"));
569    }
570
571    #[test]
572    fn from_file_parses_weights_and_reorders_columns() {
573        let path = temp_csv_path();
574        fs::write(&path, "v,ke,prob\n10.0,0.5,0.3\n15.0,0.7,0.7\n").unwrap();
575
576        let (theta, weights) = Theta::from_file(&path, &parameters()).unwrap();
577        let _ = fs::remove_file(&path);
578
579        assert_eq!(theta.nspp(), 2);
580        assert_eq!(theta.matrix()[(0, 0)], 0.5);
581        assert_eq!(theta.matrix()[(0, 1)], 10.0);
582
583        let weights = weights.expect("weights should be parsed from prob column");
584        assert_eq!(weights.len(), 2);
585        assert_eq!(weights[0], 0.3);
586        assert_eq!(weights[1], 0.7);
587    }
588
589    #[test]
590    fn from_file_rejects_extra_parameters() {
591        let path = temp_csv_path();
592        fs::write(&path, "ke,v,extra\n0.5,10.0,1.0\n").unwrap();
593
594        let err = Theta::from_file(&path, &parameters()).unwrap_err();
595        let _ = fs::remove_file(&path);
596
597        assert!(err
598            .to_string()
599            .contains("Found parameters in the prior not present in configuration"));
600    }
601}