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 observations: Option<Vec<OlsObservation>>,
26}
27
28#[derive(Debug, Clone, Copy)]
29pub(crate) struct OlsObservation {
30 pub(crate) fitted: f64,
31 pub(crate) residual: f64,
32 pub(crate) leverage: f64,
33}
34
35#[cfg(test)]
36thread_local! {
37 static OLS_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
38}
39
40impl OlsFit {
41 pub(crate) fn new(x: &[f64], y: &[f64]) -> Result<Self, Error> {
42 Self::with_observations(x, y, false)
43 }
44
45 #[expect(
46 clippy::cast_precision_loss,
47 reason = "an in-memory sample cannot approach the first usize not exactly representable as f64"
48 )]
49 pub(crate) fn with_observations(x: &[f64], y: &[f64], capture: bool) -> Result<Self, Error> {
50 #[cfg(test)]
51 OLS_CALLS.with(|count| count.set(count.get() + 1));
52 if x.len() != y.len() {
53 return Err(Error::Data(
54 format!("ols: x.len() ({}) != y.len() ({})", x.len(), y.len()).into(),
55 ));
56 }
57 if x.len() < 2 {
58 return Err(Error::Data(
59 format!("ols: need at least 2 points, got {}", x.len()).into(),
60 ));
61 }
62 if x.iter().chain(y).any(|value| !value.is_finite()) {
63 return Err(Error::Data(
64 "ols: x and y must contain only finite values".into(),
65 ));
66 }
67
68 let x_scale = nonzero_scale(x);
69 let y_scale = nonzero_scale(y);
70 let n = x.len();
71 let n_f = n as f64;
72 let x_mean_scaled = compensated_sum(x.iter().map(|value| value / x_scale))? / n_f;
73 let y_mean_scaled = compensated_sum(y.iter().map(|value| value / y_scale))? / n_f;
74 let mut predictor_variation = CompensatedSum::default();
75 let mut cross_product = CompensatedSum::default();
76 let mut response_variation = CompensatedSum::default();
77 for (index, (&x_value, &y_value)) in x.iter().zip(y).enumerate() {
78 if index.is_multiple_of(1024) {
79 crate::operation::checkpoint()?;
80 }
81 crate::operation::check()?;
82 let dx = x_value / x_scale - x_mean_scaled;
83 let dy = y_value / y_scale - y_mean_scaled;
84 predictor_variation.add(dx * dx)?;
85 cross_product.add(dx * dy)?;
86 response_variation.add(dy * dy)?;
87 }
88 let denominator = predictor_variation.finish()?;
89 if denominator == 0.0 {
90 return Err(Error::Data(
91 "ols: x has zero variance; slope is undefined".into(),
92 ));
93 }
94 let covariance_numerator = cross_product.finish()?;
95 let total_variation = response_variation.finish()?;
96 let slope_scaled = covariance_numerator / denominator;
97 let normalized_intercept = y_mean_scaled - slope_scaled * x_mean_scaled;
98 let intercept = normalized_intercept * y_scale;
99 let slope = (slope_scaled * y_scale) / x_scale;
100 if !intercept.is_finite() || !slope.is_finite() {
101 return Err(Error::Data(
102 "ols: fitted coefficients are not numerically representable".into(),
103 ));
104 }
105 let r_squared = if total_variation == 0.0 {
106 1.0
107 } else {
108 let correlation = (covariance_numerator / denominator.sqrt()) / total_variation.sqrt();
109 correlation.mul_add(correlation, 0.0).clamp(0.0, 1.0)
110 };
111
112 let mut residual_sum_squares_scaled = CompensatedSum::default();
113 let mut observations = capture.then(Vec::new);
114 if let Some(values) = &mut observations {
115 crate::data::source::reserve_source(values, n)?;
116 }
117 for (index, (&x_value, &y_value)) in x.iter().zip(y).enumerate() {
118 if index.is_multiple_of(1024) {
119 crate::operation::checkpoint()?;
120 }
121 crate::operation::check()?;
122 let estimate_scaled =
123 y_mean_scaled + slope_scaled * (x_value / x_scale - x_mean_scaled);
124 let residual_scaled = y_value / y_scale - estimate_scaled;
125 residual_sum_squares_scaled.add(residual_scaled * residual_scaled)?;
126 if let Some(values) = &mut observations {
127 values.push(OlsObservation {
128 fitted: estimate_scaled * y_scale,
129 residual: residual_scaled * y_scale,
130 leverage: 1.0 / n_f + (x_value / x_scale - x_mean_scaled).powi(2) / denominator,
131 });
132 }
133 }
134
135 Ok(Self {
136 n,
137 x_scale,
138 y_scale,
139 x_mean_scaled,
140 y_mean_scaled,
141 slope_scaled,
142 sxx_scaled: denominator,
143 residual_sum_squares_scaled: residual_sum_squares_scaled.finish()?,
144 intercept,
145 slope,
146 r_squared,
147 observations,
148 })
149 }
150
151 pub(crate) fn observations(&self) -> Option<&[OlsObservation]> {
152 self.observations.as_deref()
153 }
154
155 pub(crate) fn residual_sum_squares(&self) -> Option<f64> {
156 let value = (self.residual_sum_squares_scaled.sqrt() * self.y_scale).powi(2);
157 value.is_finite().then_some(value)
158 }
159
160 pub(crate) const fn coefficients(&self) -> (f64, f64, f64) {
161 (self.intercept, self.slope, self.r_squared)
162 }
163
164 pub(crate) fn predict(&self, x: f64) -> Result<f64, Error> {
165 if !x.is_finite() {
166 return Err(Error::Data(
167 "ols: prediction coordinate must be finite".into(),
168 ));
169 }
170 let estimate = self.prediction_scaled(x) * self.y_scale;
171 if estimate.is_finite() {
172 Ok(estimate)
173 } else {
174 Err(Error::Data(
175 "ols: fitted value is not numerically representable".into(),
176 ))
177 }
178 }
179
180 #[expect(
181 clippy::cast_precision_loss,
182 reason = "an in-memory sample cannot approach the first usize not exactly representable as f64"
183 )]
184 pub(crate) fn pointwise_mean_response_95(&self, x: f64) -> Result<MeanResponseInterval, Error> {
185 if self.n < 3 {
186 return Err(Error::Data(format!(
187 "regression: a pointwise mean-response Student-t band requires at least 3 points, got {}",
188 self.n
189 ).into()));
190 }
191 if !x.is_finite() {
192 return Err(Error::Data(
193 "regression: band coordinate must be finite".into(),
194 ));
195 }
196 let residual_df = self.n - 2;
197 let critical = super::student_t_critical_975(residual_df)
198 .map_err(|reason| Error::Data(format!("regression: {reason}").into()))?;
199 let x_scaled = x / self.x_scale;
200 let leverage =
201 1.0 / self.n as f64 + (x_scaled - self.x_mean_scaled).powi(2) / self.sxx_scaled;
202 let mse_scaled = self.residual_sum_squares_scaled / residual_df as f64;
203 let half_width_scaled = critical * (mse_scaled * leverage).sqrt();
204 let estimate_scaled = self.prediction_scaled(x);
205 let interval = MeanResponseInterval {
206 estimate: estimate_scaled * self.y_scale,
207 lower: (estimate_scaled - half_width_scaled) * self.y_scale,
208 upper: (estimate_scaled + half_width_scaled) * self.y_scale,
209 };
210 if [interval.estimate, interval.lower, interval.upper]
211 .into_iter()
212 .all(f64::is_finite)
213 && interval.lower <= interval.estimate
214 && interval.estimate <= interval.upper
215 {
216 Ok(interval)
217 } else {
218 Err(Error::Data(
219 "regression: confidence-band geometry is not numerically representable".into(),
220 ))
221 }
222 }
223
224 fn prediction_scaled(&self, x: f64) -> f64 {
225 self.y_mean_scaled + self.slope_scaled * (x / self.x_scale - self.x_mean_scaled)
226 }
227}
228
229pub fn ols(x: &[f64], y: &[f64]) -> Result<(f64, f64, f64), Error> {
236 ols_with_operation(x, y, &crate::operation::OperationOptions::default())
237}
238
239pub fn ols_with_operation(
241 x: &[f64],
242 y: &[f64],
243 options: &crate::operation::OperationOptions,
244) -> Result<(f64, f64, f64), Error> {
245 crate::operation::run(options, || {
246 crate::operation::phase(crate::errors::OperationPhase::Prepare)?;
247 let coefficients = OlsFit::new(x, y)?.coefficients();
248 crate::operation::checkpoint()?;
249 Ok(coefficients)
250 })
251}
252
253fn nonzero_scale(values: &[f64]) -> f64 {
254 let scale = values.iter().map(|value| value.abs()).fold(0.0, f64::max);
255 if scale == 0.0 {
256 1.0
257 } else {
258 scale
259 }
260}
261
262fn compensated_sum(values: impl IntoIterator<Item = f64>) -> Result<f64, Error> {
263 let mut sum = CompensatedSum::default();
264 for (index, value) in values.into_iter().enumerate() {
265 if index.is_multiple_of(1024) {
266 crate::operation::checkpoint()?;
267 }
268 crate::operation::check()?;
269 sum.add(value)?;
270 }
271 sum.finish()
272}
273
274#[derive(Debug, Default)]
275struct CompensatedSum {
276 sum: f64,
277 correction: f64,
278}
279
280impl CompensatedSum {
281 fn add(&mut self, value: f64) -> Result<(), Error> {
282 let next = self.sum + value;
283 if !next.is_finite() {
284 return Err(Error::Data(
285 "ols: centered/scaled accumulation is not numerically representable".into(),
286 ));
287 }
288 self.correction += if self.sum.abs() >= value.abs() {
289 (self.sum - next) + value
290 } else {
291 (value - next) + self.sum
292 };
293 if !self.correction.is_finite() {
294 return Err(Error::Data(
295 "ols: centered/scaled accumulation is not numerically representable".into(),
296 ));
297 }
298 self.sum = next;
299 Ok(())
300 }
301
302 fn finish(self) -> Result<f64, Error> {
303 let value = self.sum + self.correction;
304 if value.is_finite() {
305 Ok(value)
306 } else {
307 Err(Error::Data(
308 "ols: centered/scaled accumulation is not numerically representable".into(),
309 ))
310 }
311 }
312}
313
314#[cfg(test)]
315mod tests {
316 use super::OlsFit;
317
318 fn assert_close(actual: f64, expected: f64, tolerance: f64) {
319 assert!(
320 (actual - expected).abs() <= tolerance,
321 "{actual} != {expected} within {tolerance}"
322 );
323 }
324
325 #[test]
326 fn same_preparation_fit_does_not_train_twice() {
327 use super::OLS_CALLS;
328 let plot = crate::Plot::regression(
329 crate::NumericValues::new("x", [1., 2., 3.]),
330 crate::NumericValues::new("y", [1., 2., 4.]),
331 );
332 OLS_CALLS.with(|count| count.set(0));
333 plot.stat_result().unwrap();
334 assert_eq!(OLS_CALLS.with(std::cell::Cell::get), 1);
335 let run = plot.render_with_results().unwrap();
336 assert_eq!(OLS_CALLS.with(std::cell::Cell::get), 2);
337 assert!(run.output().width() > 0.0);
338 assert!(OlsFit::new(&[1., 2.], &[2., 3.])
339 .unwrap()
340 .observations()
341 .is_none());
342 }
343
344 #[test]
345 fn pointwise_band_matches_hard_coded_student_t_oracle() {
346 let fit = OlsFit::new(&[1.0, 2.0, 3.0], &[1.0, 2.0, 4.0]).unwrap();
347 let interval = fit.pointwise_mean_response_95(2.0).unwrap();
348
349 assert_close(interval.estimate, 2.333_333_333_333_333_5, 1e-14);
350 assert_close(interval.lower, -0.661_547_844_031_249_9, 1e-12);
351 assert_close(interval.upper, 5.328_214_510_697_917, 1e-12);
352 }
353
354 #[test]
355 fn fit_and_band_are_affine_and_scale_invariant() {
356 let x = [1.0, 2.0, 4.0, 7.0, 11.0];
357 let y = [2.0, 2.5, 5.0, 6.5, 10.0];
358 let transformed_x = x.map(|value| 1_073_741_824.0 + 1_024.0 * value);
359 let transformed_y = y.map(|value| -268_435_456.0 + 4_096.0 * value);
360 let original = OlsFit::new(&x, &y).unwrap();
361 let transformed = OlsFit::new(&transformed_x, &transformed_y).unwrap();
362 let original_interval = original.pointwise_mean_response_95(4.0).unwrap();
363 let transformed_interval = transformed
364 .pointwise_mean_response_95(1_073_741_824.0 + 4_096.0)
365 .unwrap();
366
367 assert_close(
368 transformed_interval.estimate,
369 -268_435_456.0 + 4_096.0 * original_interval.estimate,
370 1e-7,
371 );
372 assert_close(
373 transformed_interval.lower,
374 -268_435_456.0 + 4_096.0 * original_interval.lower,
375 1e-7,
376 );
377 assert_close(
378 transformed_interval.upper,
379 -268_435_456.0 + 4_096.0 * original_interval.upper,
380 1e-7,
381 );
382 }
383
384 #[test]
385 fn pointwise_band_rejects_two_points() {
386 let fit = OlsFit::new(&[2.0, 4.0], &[5.0, 9.0]).unwrap();
387
388 assert!(fit
389 .pointwise_mean_response_95(3.0)
390 .unwrap_err()
391 .to_string()
392 .contains("at least 3 points"));
393 }
394}