Skip to main content

scouter_types/psi/
types.rs

1use crate::util::PyHelperFuncs;
2use chrono::{DateTime, Utc};
3use pyo3::prelude::*;
4use serde::{Deserialize, Serialize};
5use std::collections::BTreeMap;
6
7#[pyclass]
8#[derive(Serialize, Deserialize, Debug, Clone, Default)]
9pub struct BinnedPsiMetric {
10    #[pyo3(get)]
11    pub created_at: Vec<DateTime<Utc>>,
12
13    #[pyo3(get)]
14    pub psi: Vec<f64>,
15
16    #[pyo3(get)]
17    pub overall_psi: f64,
18
19    #[pyo3(get)]
20    pub bins: BTreeMap<i32, f64>,
21}
22
23#[pymethods]
24impl BinnedPsiMetric {
25    pub fn __str__(&self) -> String {
26        // serialize the struct to a string
27        PyHelperFuncs::__str__(self)
28    }
29}
30
31#[pyclass]
32#[derive(Serialize, Deserialize, Debug, Clone, Default)]
33pub struct BinnedPsiFeatureMetrics {
34    #[pyo3(get)]
35    pub features: BTreeMap<String, BinnedPsiMetric>,
36}
37
38#[pymethods]
39impl BinnedPsiFeatureMetrics {
40    pub fn __str__(&self) -> String {
41        // serialize the struct to a string
42        PyHelperFuncs::__str__(self)
43    }
44}
45
46#[derive(Debug, Clone, Serialize, Deserialize, Default)]
47pub struct FeatureBinProportionResult {
48    pub feature: String,
49    pub created_at: Vec<DateTime<Utc>>,
50    pub bin_proportions: Vec<BTreeMap<i32, f64>>,
51    pub overall_proportions: BTreeMap<i32, f64>,
52}
53
54#[cfg(feature = "server")]
55impl<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow> for FeatureBinProportionResult {
56    fn from_row(row: &'r sqlx::postgres::PgRow) -> Result<Self, sqlx::Error> {
57        use sqlx::Row;
58
59        let bin_proportions_json: Vec<serde_json::Value> = row.try_get("bin_proportions")?;
60        let bin_proportions: Vec<BTreeMap<i32, f64>> = bin_proportions_json
61            .into_iter()
62            .map(|json| serde_json::from_value(json).map_err(|e| sqlx::Error::Decode(Box::new(e))))
63            .collect::<Result<Vec<_>, sqlx::Error>>()?;
64
65        let overall_proportions_json: serde_json::Value = row.try_get("overall_proportions")?;
66        let overall_proportions: BTreeMap<i32, f64> =
67            serde_json::from_value(overall_proportions_json)
68                .map_err(|e| sqlx::Error::Decode(Box::new(e)))?;
69
70        Ok(FeatureBinProportionResult {
71            feature: row.try_get("feature")?,
72            created_at: row.try_get("created_at")?,
73            bin_proportions,
74            overall_proportions,
75        })
76    }
77}