1use crate::Error;
4
5#[derive(Debug, Clone, Copy)]
6pub(crate) struct MeanResponseInterval {
7 pub(crate) estimate: f64,
8 pub(crate) lower: f64,
9 pub(crate) upper: f64,
10}
11
12#[derive(Debug, Clone)]
13pub(crate) struct OlsFit {
14 n: usize,
15 x_scale: f64,
16 y_scale: f64,
17 x_mean_scaled: f64,
18 y_mean_scaled: f64,
19 slope_scaled: f64,
20 sxx_scaled: f64,
21 residual_sum_squares_scaled: f64,
22 intercept: f64,
23 slope: f64,
24 r_squared: f64,
25}
26
27impl OlsFit {
28 #[expect(
29 clippy::cast_precision_loss,
30 reason = "an in-memory sample cannot approach the first usize not exactly representable as f64"
31 )]
32 pub(crate) fn new(x: &[f64], y: &[f64]) -> Result<Self, Error> {
33 if x.len() != y.len() {
34 return Err(Error::Data(format!(
35 "ols: x.len() ({}) != y.len() ({})",
36 x.len(),
37 y.len()
38 )));
39 }
40 if x.len() < 2 {
41 return Err(Error::Data(format!(
42 "ols: need at least 2 points, got {}",
43 x.len()
44 )));
45 }
46 if x.iter().chain(y).any(|value| !value.is_finite()) {
47 return Err(Error::Data(
48 "ols: x and y must contain only finite values".into(),
49 ));
50 }
51
52 let x_scale = nonzero_scale(x);
53 let y_scale = nonzero_scale(y);
54 let n = x.len();
55 let n_f = n as f64;
56 let x_mean_scaled = compensated_sum(x.iter().map(|value| value / x_scale))? / n_f;
57 let y_mean_scaled = compensated_sum(y.iter().map(|value| value / y_scale))? / n_f;
58 let mut predictor_variation = CompensatedSum::default();
59 let mut cross_product = CompensatedSum::default();
60 let mut response_variation = CompensatedSum::default();
61 for (&x_value, &y_value) in x.iter().zip(y) {
62 let dx = x_value / x_scale - x_mean_scaled;
63 let dy = y_value / y_scale - y_mean_scaled;
64 predictor_variation.add(dx * dx)?;
65 cross_product.add(dx * dy)?;
66 response_variation.add(dy * dy)?;
67 }
68 let denominator = predictor_variation.finish()?;
69 if denominator == 0.0 {
70 return Err(Error::Data(
71 "ols: x has zero variance; slope is undefined".into(),
72 ));
73 }
74 let covariance_numerator = cross_product.finish()?;
75 let total_variation = response_variation.finish()?;
76 let slope_scaled = covariance_numerator / denominator;
77 let normalized_intercept = y_mean_scaled - slope_scaled * x_mean_scaled;
78 let intercept = normalized_intercept * y_scale;
79 let slope = (slope_scaled * y_scale) / x_scale;
80 if !intercept.is_finite() || !slope.is_finite() {
81 return Err(Error::Data(
82 "ols: fitted coefficients are not numerically representable".into(),
83 ));
84 }
85 let r_squared = if total_variation == 0.0 {
86 1.0
87 } else {
88 let correlation = (covariance_numerator / denominator.sqrt()) / total_variation.sqrt();
89 correlation.mul_add(correlation, 0.0).clamp(0.0, 1.0)
90 };
91
92 let mut residual_sum_squares_scaled = CompensatedSum::default();
93 for (&x_value, &y_value) in x.iter().zip(y) {
94 let estimate_scaled =
95 y_mean_scaled + slope_scaled * (x_value / x_scale - x_mean_scaled);
96 let residual_scaled = y_value / y_scale - estimate_scaled;
97 residual_sum_squares_scaled.add(residual_scaled * residual_scaled)?;
98 }
99
100 Ok(Self {
101 n,
102 x_scale,
103 y_scale,
104 x_mean_scaled,
105 y_mean_scaled,
106 slope_scaled,
107 sxx_scaled: denominator,
108 residual_sum_squares_scaled: residual_sum_squares_scaled.finish()?,
109 intercept,
110 slope,
111 r_squared,
112 })
113 }
114
115 pub(crate) const fn coefficients(&self) -> (f64, f64, f64) {
116 (self.intercept, self.slope, self.r_squared)
117 }
118
119 pub(crate) fn predict(&self, x: f64) -> Result<f64, Error> {
120 if !x.is_finite() {
121 return Err(Error::Data(
122 "ols: prediction coordinate must be finite".into(),
123 ));
124 }
125 let estimate = self.prediction_scaled(x) * self.y_scale;
126 if estimate.is_finite() {
127 Ok(estimate)
128 } else {
129 Err(Error::Data(
130 "ols: fitted value is not numerically representable".into(),
131 ))
132 }
133 }
134
135 #[expect(
136 clippy::cast_precision_loss,
137 reason = "an in-memory sample cannot approach the first usize not exactly representable as f64"
138 )]
139 pub(crate) fn pointwise_mean_response_95(&self, x: f64) -> Result<MeanResponseInterval, Error> {
140 if self.n < 3 {
141 return Err(Error::Data(format!(
142 "regression: a pointwise mean-response Student-t band requires at least 3 points, got {}",
143 self.n
144 )));
145 }
146 if !x.is_finite() {
147 return Err(Error::Data(
148 "regression: band coordinate must be finite".into(),
149 ));
150 }
151 let residual_df = self.n - 2;
152 let critical = super::student_t_critical_975(residual_df)
153 .map_err(|reason| Error::Data(format!("regression: {reason}")))?;
154 let x_scaled = x / self.x_scale;
155 let leverage =
156 1.0 / self.n as f64 + (x_scaled - self.x_mean_scaled).powi(2) / self.sxx_scaled;
157 let mse_scaled = self.residual_sum_squares_scaled / residual_df as f64;
158 let half_width_scaled = critical * (mse_scaled * leverage).sqrt();
159 let estimate_scaled = self.prediction_scaled(x);
160 let interval = MeanResponseInterval {
161 estimate: estimate_scaled * self.y_scale,
162 lower: (estimate_scaled - half_width_scaled) * self.y_scale,
163 upper: (estimate_scaled + half_width_scaled) * self.y_scale,
164 };
165 if [interval.estimate, interval.lower, interval.upper]
166 .into_iter()
167 .all(f64::is_finite)
168 && interval.lower <= interval.estimate
169 && interval.estimate <= interval.upper
170 {
171 Ok(interval)
172 } else {
173 Err(Error::Data(
174 "regression: confidence-band geometry is not numerically representable".into(),
175 ))
176 }
177 }
178
179 fn prediction_scaled(&self, x: f64) -> f64 {
180 self.y_mean_scaled + self.slope_scaled * (x / self.x_scale - self.x_mean_scaled)
181 }
182}
183
184pub fn ols(x: &[f64], y: &[f64]) -> Result<(f64, f64, f64), Error> {
191 Ok(OlsFit::new(x, y)?.coefficients())
192}
193
194fn nonzero_scale(values: &[f64]) -> f64 {
195 let scale = values.iter().map(|value| value.abs()).fold(0.0, f64::max);
196 if scale == 0.0 {
197 1.0
198 } else {
199 scale
200 }
201}
202
203fn compensated_sum(values: impl IntoIterator<Item = f64>) -> Result<f64, Error> {
204 let mut sum = CompensatedSum::default();
205 for value in values {
206 sum.add(value)?;
207 }
208 sum.finish()
209}
210
211#[derive(Debug, Default)]
212struct CompensatedSum {
213 sum: f64,
214 correction: f64,
215}
216
217impl CompensatedSum {
218 fn add(&mut self, value: f64) -> Result<(), Error> {
219 let next = self.sum + value;
220 if !next.is_finite() {
221 return Err(Error::Data(
222 "ols: centered/scaled accumulation is not numerically representable".into(),
223 ));
224 }
225 self.correction += if self.sum.abs() >= value.abs() {
226 (self.sum - next) + value
227 } else {
228 (value - next) + self.sum
229 };
230 if !self.correction.is_finite() {
231 return Err(Error::Data(
232 "ols: centered/scaled accumulation is not numerically representable".into(),
233 ));
234 }
235 self.sum = next;
236 Ok(())
237 }
238
239 fn finish(self) -> Result<f64, Error> {
240 let value = self.sum + self.correction;
241 if value.is_finite() {
242 Ok(value)
243 } else {
244 Err(Error::Data(
245 "ols: centered/scaled accumulation is not numerically representable".into(),
246 ))
247 }
248 }
249}
250
251#[cfg(test)]
252mod tests {
253 use super::OlsFit;
254
255 fn assert_close(actual: f64, expected: f64, tolerance: f64) {
256 assert!(
257 (actual - expected).abs() <= tolerance,
258 "{actual} != {expected} within {tolerance}"
259 );
260 }
261
262 #[test]
263 fn pointwise_band_matches_hard_coded_student_t_oracle() {
264 let fit = OlsFit::new(&[1.0, 2.0, 3.0], &[1.0, 2.0, 4.0]).unwrap();
265 let interval = fit.pointwise_mean_response_95(2.0).unwrap();
266
267 assert_close(interval.estimate, 2.333_333_333_333_333_5, 1e-14);
268 assert_close(interval.lower, -0.661_547_844_031_249_9, 1e-12);
269 assert_close(interval.upper, 5.328_214_510_697_917, 1e-12);
270 }
271
272 #[test]
273 fn fit_and_band_are_affine_and_scale_invariant() {
274 let x = [1.0, 2.0, 4.0, 7.0, 11.0];
275 let y = [2.0, 2.5, 5.0, 6.5, 10.0];
276 let transformed_x = x.map(|value| 1_073_741_824.0 + 1_024.0 * value);
277 let transformed_y = y.map(|value| -268_435_456.0 + 4_096.0 * value);
278 let original = OlsFit::new(&x, &y).unwrap();
279 let transformed = OlsFit::new(&transformed_x, &transformed_y).unwrap();
280 let original_interval = original.pointwise_mean_response_95(4.0).unwrap();
281 let transformed_interval = transformed
282 .pointwise_mean_response_95(1_073_741_824.0 + 4_096.0)
283 .unwrap();
284
285 assert_close(
286 transformed_interval.estimate,
287 -268_435_456.0 + 4_096.0 * original_interval.estimate,
288 1e-7,
289 );
290 assert_close(
291 transformed_interval.lower,
292 -268_435_456.0 + 4_096.0 * original_interval.lower,
293 1e-7,
294 );
295 assert_close(
296 transformed_interval.upper,
297 -268_435_456.0 + 4_096.0 * original_interval.upper,
298 1e-7,
299 );
300 }
301
302 #[test]
303 fn pointwise_band_rejects_two_points() {
304 let fit = OlsFit::new(&[2.0, 4.0], &[5.0, 9.0]).unwrap();
305
306 assert!(fit
307 .pointwise_mean_response_95(3.0)
308 .unwrap_err()
309 .to_string()
310 .contains("at least 3 points"));
311 }
312}