Skip to main content

solow_summary/
regression.rs

1//! A labeled regression-results summary table.
2//!
3//! [`RegressionSummary`] collects the values any model's results can supply --
4//! parameter names and their estimates, standard errors, test statistics,
5//! p-values, and confidence intervals, plus a handful of header statistics --
6//! and renders them as a two-block fixed-width text table:
7//!
8//! * a *header block* of key statistics (model name, observations, degrees of
9//!   freedom, R-squared, F-statistic, log-likelihood, AIC, BIC), and
10//! * a *coefficient table* with columns `coef`, `std err`, the test statistic
11//!   (`t` or `z`), `P>|t|` (or `P>|z|`), and the two confidence-interval
12//!   bounds.
13//!
14//! The layout is Solow's own; only the numbers are ever cross-checked against
15//! a reference implementation.
16
17use crate::format::{format_fixed, format_g, format_pvalue};
18use crate::table::{Align, SummaryTable};
19use std::fmt;
20
21/// Whether the coefficient table reports a `t` statistic or a `z` statistic.
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum StatKind {
24    /// Student's t (column header `t`, p-value header `P>|t|`).
25    T,
26    /// Standard normal z (column header `z`, p-value header `P>|z|`).
27    Z,
28}
29
30impl StatKind {
31    fn stat_label(self) -> &'static str {
32        match self {
33            StatKind::T => "t",
34            StatKind::Z => "z",
35        }
36    }
37
38    fn pvalue_label(self) -> &'static str {
39        match self {
40            StatKind::T => "P>|t|",
41            StatKind::Z => "P>|z|",
42        }
43    }
44}
45
46/// Header statistics shown in the top block of the summary.
47///
48/// All fields are optional: a field set to `None` is simply omitted from the
49/// rendered header, so models that do not produce (say) an F-statistic can
50/// still build a summary.
51#[derive(Clone, Debug, Default)]
52pub struct HeaderStats {
53    pub model: Option<String>,
54    pub dep_variable: Option<String>,
55    pub method: Option<String>,
56    pub nobs: Option<f64>,
57    pub df_model: Option<f64>,
58    pub df_resid: Option<f64>,
59    pub rsquared: Option<f64>,
60    pub rsquared_adj: Option<f64>,
61    pub fvalue: Option<f64>,
62    pub f_pvalue: Option<f64>,
63    pub llf: Option<f64>,
64    pub aic: Option<f64>,
65    pub bic: Option<f64>,
66}
67
68impl HeaderStats {
69    /// Start from an all-`None` header.
70    pub fn new() -> Self {
71        Self::default()
72    }
73}
74
75/// Builder for a labeled regression-results summary.
76#[derive(Clone, Debug)]
77pub struct RegressionSummary {
78    title: String,
79    stat_kind: StatKind,
80    alpha: f64,
81    names: Vec<String>,
82    params: Vec<f64>,
83    bse: Vec<f64>,
84    tvalues: Vec<f64>,
85    pvalues: Vec<f64>,
86    conf_int: Vec<(f64, f64)>,
87    header: HeaderStats,
88}
89
90impl RegressionSummary {
91    /// Create a summary from the per-parameter vectors and a confidence
92    /// interval given as a `k x 2` set of `(lower, upper)` rows.
93    ///
94    /// All slices must share the parameter count `k`. The default confidence
95    /// level is 95% (`alpha = 0.05`); use [`with_alpha`](Self::with_alpha) to
96    /// change the displayed CI bounds.
97    ///
98    /// # Panics
99    ///
100    /// Panics if the input lengths do not all match.
101    #[allow(clippy::too_many_arguments)]
102    pub fn new(
103        names: &[impl AsRef<str>],
104        params: &[f64],
105        bse: &[f64],
106        tvalues: &[f64],
107        pvalues: &[f64],
108        conf_int: &[(f64, f64)],
109        header: HeaderStats,
110    ) -> Self {
111        let k = names.len();
112        assert_eq!(params.len(), k, "params length must match name count");
113        assert_eq!(bse.len(), k, "bse length must match name count");
114        assert_eq!(tvalues.len(), k, "tvalues length must match name count");
115        assert_eq!(pvalues.len(), k, "pvalues length must match name count");
116        assert_eq!(
117            conf_int.len(),
118            k,
119            "conf_int row count must match name count"
120        );
121        RegressionSummary {
122            title: "Regression Results".to_string(),
123            stat_kind: StatKind::T,
124            alpha: 0.05,
125            names: names.iter().map(|s| s.as_ref().to_string()).collect(),
126            params: params.to_vec(),
127            bse: bse.to_vec(),
128            tvalues: tvalues.to_vec(),
129            pvalues: pvalues.to_vec(),
130            conf_int: conf_int.to_vec(),
131            header,
132        }
133    }
134
135    /// Override the table title.
136    pub fn with_title(mut self, title: impl Into<String>) -> Self {
137        self.title = title.into();
138        self
139    }
140
141    /// Report a `z` statistic (and `P>|z|`) instead of a `t` statistic.
142    pub fn with_stat_kind(mut self, kind: StatKind) -> Self {
143        self.stat_kind = kind;
144        self
145    }
146
147    /// Set the confidence level used for the CI column headers (e.g. `0.05`
148    /// for a 95% interval renders `[0.025  0.975]`). This does not recompute
149    /// the bounds -- those are supplied to [`new`](Self::new) -- it only sets
150    /// the displayed quantile labels.
151    pub fn with_alpha(mut self, alpha: f64) -> Self {
152        self.alpha = alpha;
153        self
154    }
155
156    /// Build the header block as a two-column key/value table.
157    fn header_table(&self) -> SummaryTable {
158        let mut t = SummaryTable::new()
159            .title(self.title.clone())
160            .header(["Statistic", "Value"])
161            .aligns([Align::Left, Align::Right]);
162
163        let h = &self.header;
164        if let Some(m) = &h.model {
165            t.push_row(["Model:".to_string(), m.clone()]);
166        }
167        if let Some(d) = &h.dep_variable {
168            t.push_row(["Dep. Variable:".to_string(), d.clone()]);
169        }
170        if let Some(m) = &h.method {
171            t.push_row(["Method:".to_string(), m.clone()]);
172        }
173        if let Some(n) = h.nobs {
174            t.push_row(["No. Observations:".to_string(), format_fixed(n, 0)]);
175        }
176        if let Some(d) = h.df_model {
177            t.push_row(["Df Model:".to_string(), format_fixed(d, 0)]);
178        }
179        if let Some(d) = h.df_resid {
180            t.push_row(["Df Residuals:".to_string(), format_fixed(d, 0)]);
181        }
182        if let Some(r) = h.rsquared {
183            t.push_row(["R-squared:".to_string(), format_fixed(r, 3)]);
184        }
185        if let Some(r) = h.rsquared_adj {
186            t.push_row(["Adj. R-squared:".to_string(), format_fixed(r, 3)]);
187        }
188        if let Some(fv) = h.fvalue {
189            t.push_row(["F-statistic:".to_string(), format_g(fv, 4)]);
190        }
191        if let Some(fp) = h.f_pvalue {
192            t.push_row(["Prob (F-statistic):".to_string(), format_g(fp, 4)]);
193        }
194        if let Some(l) = h.llf {
195            t.push_row(["Log-Likelihood:".to_string(), format_g(l, 5)]);
196        }
197        if let Some(a) = h.aic {
198            t.push_row(["AIC:".to_string(), format_g(a, 5)]);
199        }
200        if let Some(b) = h.bic {
201            t.push_row(["BIC:".to_string(), format_g(b, 5)]);
202        }
203        t
204    }
205
206    /// CI column labels, e.g. `[0.025` and `0.975]` for `alpha = 0.05`.
207    fn ci_labels(&self) -> (String, String) {
208        let lo = self.alpha / 2.0;
209        let hi = 1.0 - self.alpha / 2.0;
210        (
211            format!("[{}", format_fixed(lo, 3)),
212            format!("{}]", format_fixed(hi, 3)),
213        )
214    }
215
216    /// Build the coefficient table.
217    fn coef_table(&self) -> SummaryTable {
218        let (ci_lo, ci_hi) = self.ci_labels();
219        let mut t = SummaryTable::new()
220            .header([
221                "".to_string(),
222                "coef".to_string(),
223                "std err".to_string(),
224                self.stat_kind.stat_label().to_string(),
225                self.stat_kind.pvalue_label().to_string(),
226                ci_lo,
227                ci_hi,
228            ])
229            .aligns([
230                Align::Left,
231                Align::Right,
232                Align::Right,
233                Align::Right,
234                Align::Right,
235                Align::Right,
236                Align::Right,
237            ]);
238
239        for i in 0..self.names.len() {
240            let (lo, hi) = self.conf_int[i];
241            t.push_row([
242                self.names[i].clone(),
243                format_g(self.params[i], 4),
244                format_g(self.bse[i], 4),
245                format_fixed(self.tvalues[i], 3),
246                format_pvalue(self.pvalues[i]),
247                format_fixed(lo, 3),
248                format_fixed(hi, 3),
249            ]);
250        }
251        t
252    }
253}
254
255impl fmt::Display for RegressionSummary {
256    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257        write!(f, "{}\n\n{}", self.header_table(), self.coef_table())
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264
265    fn sample() -> RegressionSummary {
266        let names = ["const", "x1", "x2"];
267        let params = [1.49339521, -1.90617444, 0.71064927];
268        let bse = [0.0728888, 0.08152201, 0.07324544];
269        let tvalues = [20.48867957, -23.38232831, 9.70229997];
270        let pvalues = [8.69594441e-22, 9.22865862e-24, 1.03889592e-11];
271        let conf_int = [
272            (1.345708481321229, 1.6410819449282237),
273            (-2.0713537205255537, -1.7409951503714414),
274            (0.562239906015244, 0.859058641160409),
275        ];
276        let header = HeaderStats {
277            model: Some("OLS".to_string()),
278            nobs: Some(40.0),
279            df_model: Some(2.0),
280            df_resid: Some(37.0),
281            rsquared: Some(0.9505900603362948),
282            rsquared_adj: Some(0.9479192527869054),
283            fvalue: Some(355.9185911967316),
284            f_pvalue: Some(6.848019459935387e-25),
285            llf: Some(-19.95229542493003),
286            aic: Some(45.90459084986006),
287            bic: Some(50.97122921220186),
288            ..HeaderStats::new()
289        };
290        RegressionSummary::new(&names, &params, &bse, &tvalues, &pvalues, &conf_int, header)
291    }
292
293    #[test]
294    fn renders_all_parameter_names() {
295        let s = sample().to_string();
296        assert!(s.contains("const"));
297        assert!(s.contains("x1"));
298        assert!(s.contains("x2"));
299    }
300
301    #[test]
302    fn header_contains_key_stats() {
303        let s = sample().to_string();
304        assert!(s.contains("R-squared:"));
305        assert!(s.contains("0.951"));
306        assert!(s.contains("Adj. R-squared:"));
307        assert!(s.contains("AIC:"));
308        assert!(s.contains("BIC:"));
309        assert!(s.contains("Model:"));
310        assert!(s.contains("OLS"));
311    }
312
313    #[test]
314    fn coef_columns_present() {
315        let s = sample().to_string();
316        assert!(s.contains("coef"));
317        assert!(s.contains("std err"));
318        // default is t statistic
319        assert!(s.contains("P>|t|"));
320        assert!(s.contains("[0.025"));
321        assert!(s.contains("0.975]"));
322    }
323
324    #[test]
325    fn z_kind_changes_labels() {
326        let s = sample().with_stat_kind(StatKind::Z).to_string();
327        assert!(s.contains("P>|z|"));
328        assert!(!s.contains("P>|t|"));
329    }
330
331    #[test]
332    fn coef_values_formatted() {
333        let s = sample().to_string();
334        // coef ~4 sig figs
335        assert!(s.contains("1.493"), "expected const coef; got:\n{s}");
336        assert!(s.contains("-1.906"));
337        // std err
338        assert!(s.contains("0.07289"));
339        // t to 3 decimals
340        assert!(s.contains("20.489"));
341        assert!(s.contains("-23.382"));
342        // tiny p-value collapses
343        assert!(s.contains("0.000"));
344    }
345
346    #[test]
347    #[should_panic(expected = "params length")]
348    fn mismatched_lengths_panic() {
349        let names = ["a", "b"];
350        let params = [1.0];
351        let bse = [1.0, 1.0];
352        let tv = [1.0, 1.0];
353        let pv = [0.1, 0.1];
354        let ci = [(0.0, 1.0), (0.0, 1.0)];
355        let _ = RegressionSummary::new(&names, &params, &bse, &tv, &pv, &ci, HeaderStats::new());
356    }
357}