Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
lfit.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
71# ifndef LFIT_H
72# define LFIT_H
73
74# include <cmath>
75# include <cstddef>
76# include <limits>
77# include <string>
78# include <utility>
79
80# include <ah-zip.H>
81# include <tpl_array.H>
82# include <ah-string-utils.H>
83
84# include <aleph-exceptions.H>
85
86// LFit throws SizeMismatch, deprecated, until 8.0.0: it warns only where
87// the programs name it
88# if defined(_MSC_VER) && !defined(__clang__)
89# pragma warning(push)
90# pragma warning(disable : 4996)
91# else
92# pragma GCC diagnostic push
93# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
94# endif
95
116struct LFit
117{
118 mutable double c = 0;
119 mutable double m = 1;
120 mutable double cov00 = 0;
121 mutable double cov01 = 0;
122 mutable double cov11 = 0;
123 mutable double sumsq = 0;
124 mutable double r2 = 0;
127 mutable double sigma = 0;
128 mutable double mse = 0;
129
137 friend std::ostream &operator <<(std::ostream & out, const LFit & f)
138 {
139 return out << "r2 = " << f.r2 << std::endl
140 << "sumsq = " << f.sumsq << std::endl
141 << "sigma = " << f.sigma << std::endl
142 << "mse = " << f.mse << std::endl
143 << "c = " << f.c << std::endl
144 << "m = " << f.m << std::endl;
145 }
146
148 LFit() noexcept {}
149
175 LFit(const Array<double> & x, const Array<double> & y)
176 {
177 const size_t n = y.size();
178 if (x.size() != n)
179 ALEPHTHROW(SizeMismatch, "x and y have different sizes");
180
181 if (n == 0)
182 ALEPHTHROW(SizeMismatch, "arrays are empty");
183
184 if (n == 1)
185 ALEPHTHROW(SizeMismatch, "arrays have length = 1");
186
187 fit(&x.base(), &y.base(), n);
188
189 r2 = pow2(correlation(&x.base(), &y.base(), n));
190 if (not is_normal_number(r2))
191 r2 = 1;
192
193 mse = sumsq / n;
194 sigma = n > 2 ? std::sqrt(sumsq / (n - 2.0)) : std::numeric_limits<double>::quiet_NaN();
195 }
196
213 std::pair<double, double> predict(const double x) const noexcept
214 {
215 // as gsl_fit_linear_est()
216 const double y = c + m * x;
217 const double y_err = std::sqrt(cov00 + x * (2 * cov01 + cov11 * x));
218 return std::make_pair(y, y_err);
219 }
220
221private:
222 // gsl_fit_linear(), in its order of operations: the means of x and y,
223 // and those of the squares and of the products of their deviations, by
224 // Welford's recurrences; the sum of the squares of the residuals, from
225 // the deviations; and the covariances, from that sum over n - 2. The
226 // divisor i + 1 of the recurrences is counted in a double, which is
227 // exact below 2^53, instead of converting i for each element
228 void fit(const double * x, const double * y, const size_t n) noexcept
229 {
230 double m_x = 0, m_y = 0, m_dx2 = 0, m_dxdy = 0;
231 double ip1 = 1;
232 for (size_t i = 0; i < n; ++i, ip1 += 1)
233 {
234 m_x += (x[i] - m_x) / ip1;
235 m_y += (y[i] - m_y) / ip1;
236 }
237
238 ip1 = 1;
239 for (size_t i = 0; i < n; ++i, ip1 += 1)
240 {
241 const double dx = x[i] - m_x;
242 const double dy = y[i] - m_y;
243 m_dx2 += (dx * dx - m_dx2) / ip1;
244 m_dxdy += (dx * dy - m_dxdy) / ip1;
245 }
246
247 const double b = m_dxdy / m_dx2;
248 const double a = m_y - m_x * b;
249
250 double d2 = 0;
251 for (size_t i = 0; i < n; ++i)
252 {
253 const double dx = x[i] - m_x;
254 const double dy = y[i] - m_y;
255 const double d = dy - b * dx;
256 d2 += d * d;
257 }
258
259 const double s2 = d2 / (n - 2.0);
260 c = a;
261 m = b;
262 cov00 = s2 * (1.0 / n) * (1 + m_x * m_x / m_dx2);
263 cov11 = s2 * 1.0 / (n * m_dx2);
264 cov01 = s2 * (-m_x) / (n * m_dx2);
265 sumsq = d2;
266 }
267
268 // gsl_stats_correlation(), with its sums in long double, by Welford's
269 // recurrences, and the roots of double, which C takes for a long double
270 // in GSL. i and i + 1 are counted in doubles, exactly below 2^53, and
271 // each mean is updated after its deviation, which changes no value and
272 // leaves Clang the registers of x87 for more of the sums
273 static double correlation(const double * x, const double * y, const size_t n) noexcept
274 {
275 long double sum_xsq = 0, sum_ysq = 0, sum_cross = 0;
276 long double mean_x = x[0], mean_y = y[0];
277 double di = 1;
278 for (size_t i = 1; i < n; ++i, di += 1)
279 {
280 const double ip1 = di + 1;
281 const long double delta_x = x[i] - mean_x;
282 mean_x += delta_x / ip1;
283 const long double delta_y = y[i] - mean_y;
284 mean_y += delta_y / ip1;
285 const long double ratio = di / ip1;
286 sum_xsq += delta_x * delta_x * ratio;
287 sum_ysq += delta_y * delta_y * ratio;
288 sum_cross += delta_x * delta_y * ratio;
289 }
290
291 const long double r = sum_cross / (std::sqrt(static_cast<double>(sum_xsq))
292 * std::sqrt(static_cast<double>(sum_ysq)));
293 return static_cast<double>(r);
294 }
295};
296
297
298# if defined(_MSC_VER) && !defined(__clang__)
299# pragma warning(pop)
300# else
301# pragma GCC diagnostic pop
302# endif
303
304# endif
String manipulation utilities.
Zip iterators and functional operations for multiple containers.
Custom exception classes with source location tracking.
#define ALEPHTHROW(type, msg)
Macro for throwing an aleph exception.
size_t size_t int32_t * out
Definition ca-c-api.h:120
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
T & base()
Return a reference to the first element of array.
Definition tpl_array.H:408
static mpfr_t y
Definition mpfr_mul_d.c:3
double pow2(const double x)
Return x^2.
Definition ahUtils.H:404
bool is_normal_number(const double n)
Return true if a floating-point number is normal or zero.
Definition ahUtils.H:509
Linear regression calculator using least squares method.
Definition lfit.H:117
LFit(const Array< double > &x, const Array< double > &y)
Construct and compute linear regression.
Definition lfit.H:175
LFit() noexcept
Default constructor creates an identity fit (y = x)
Definition lfit.H:148
double cov00
Covariance matrix element (0,0)
Definition lfit.H:120
double sumsq
Sum of the squares of the residuals, y - (c + m x)
Definition lfit.H:123
double cov01
Covariance matrix element (0,1)
Definition lfit.H:121
std::pair< double, double > predict(const double x) const noexcept
Predict y-value and error for given x.
Definition lfit.H:213
double r2
Coefficient of determination.
Definition lfit.H:124
double m
Slope of fitted line.
Definition lfit.H:119
friend std::ostream & operator<<(std::ostream &out, const LFit &f)
Output stream operator for fit results.
Definition lfit.H:137
void fit(const double *x, const double *y, const size_t n) noexcept
Definition lfit.H:228
double cov11
Covariance matrix element (1,1)
Definition lfit.H:122
double c
Y-intercept of fitted line.
Definition lfit.H:118
double mse
Mean squared error: sumsq / n.
Definition lfit.H:128
double sigma
Standard deviation of the errors: the root of sumsq / (n - 2), the estimate from which the covariance...
Definition lfit.H:127
static double correlation(const double *x, const double *y, const size_t n) noexcept
Definition lfit.H:273
Gsl_Compatible_Rng r
Dynamic array container with automatic resizing.