Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
lfit_test.cc
Go to the documentation of this file.
1#include <gtest/gtest.h>
2#include <lfit.H>
3#include <ah-random.H> // for ALEPH_WITH_GSL
4#include <algorithm>
5#include <cmath>
6#include <cstring>
7#include <iomanip>
8#include <limits>
9#include <random>
10
11#if ALEPH_WITH_GSL
12# include <gsl/gsl_fit.h>
13# include <gsl/gsl_statistics_double.h>
14#endif
15
16class LFitTest : public ::testing::Test
17{
18protected:
19 void SetUp() override {}
20 void TearDown() override {}
21
22 bool approx_equal(double a, double b, double eps = 1e-6) {
23 return std::abs(a - b) < eps;
24 }
25};
26
27// =============================================================================
28// Basic Fitting Tests
29// =============================================================================
30
31TEST_F(LFitTest, PerfectLineFit)
32{
33 // y = 2x + 1
34 Array<double> x = {1, 2, 3, 4, 5};
35 Array<double> y = {3, 5, 7, 9, 11};
36
37 LFit fit(x, y);
38
39 EXPECT_TRUE(approx_equal(fit.m, 2.0, 1e-10));
40 EXPECT_TRUE(approx_equal(fit.c, 1.0, 1e-10));
41 EXPECT_TRUE(approx_equal(fit.r2, 1.0, 1e-10));
42 EXPECT_TRUE(approx_equal(fit.sumsq, 0.0, 1e-10));
43}
44
45TEST_F(LFitTest, HorizontalLine)
46{
47 Array<double> x = {1, 2, 3, 4, 5};
48 Array<double> y = {5, 5, 5, 5, 5};
49
50 LFit fit(x, y);
51
52 EXPECT_TRUE(approx_equal(fit.m, 0.0, 1e-10));
53 EXPECT_TRUE(approx_equal(fit.c, 5.0, 1e-10));
54}
55
56TEST_F(LFitTest, VerticalIncrement)
57{
58 // y = x (45 degree line)
59 Array<double> x = {0, 1, 2, 3, 4};
60 Array<double> y = {0, 1, 2, 3, 4};
61
62 LFit fit(x, y);
63
64 EXPECT_TRUE(approx_equal(fit.m, 1.0, 1e-10));
65 EXPECT_TRUE(approx_equal(fit.c, 0.0, 1e-10));
66 EXPECT_TRUE(approx_equal(fit.r2, 1.0, 1e-10));
67}
68
69TEST_F(LFitTest, NegativeSlope)
70{
71 // y = -2x + 10
72 Array<double> x = {1, 2, 3, 4, 5};
73 Array<double> y = {8, 6, 4, 2, 0};
74
75 LFit fit(x, y);
76
77 EXPECT_TRUE(approx_equal(fit.m, -2.0, 1e-10));
78 EXPECT_TRUE(approx_equal(fit.c, 10.0, 1e-10));
79 EXPECT_TRUE(approx_equal(fit.r2, 1.0, 1e-10));
80}
81
82// =============================================================================
83// Noisy Data Tests
84// =============================================================================
85
86TEST_F(LFitTest, SlightNoise)
87{
88 // y = 2x + 1 with small noise
89 Array<double> x = {1, 2, 3, 4, 5};
90 Array<double> y = {3.1, 4.9, 7.1, 8.9, 11.0};
91
92 LFit fit(x, y);
93
94 EXPECT_TRUE(approx_equal(fit.m, 2.0, 0.2));
95 EXPECT_TRUE(approx_equal(fit.c, 1.0, 0.2));
96 EXPECT_GT(fit.r2, 0.95);
97}
98
99TEST_F(LFitTest, ModerateNoise)
100{
101 Array<double> x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
102 Array<double> y = {2.5, 4.2, 6.1, 7.8, 10.3, 12.1, 13.9, 16.2, 17.8, 20.1};
103
104 LFit fit(x, y);
105
106 EXPECT_GT(fit.m, 1.5);
107 EXPECT_LT(fit.m, 2.5);
108 EXPECT_GT(fit.r2, 0.9);
109}
110
111// =============================================================================
112// Prediction Tests
113// =============================================================================
114
115TEST_F(LFitTest, PredictWithinRange)
116{
117 Array<double> x = {1, 2, 3, 4, 5};
118 Array<double> y = {3, 5, 7, 9, 11};
119
120 LFit fit(x, y);
121
122 auto [pred, err] = fit.predict(3.0);
123 EXPECT_TRUE(approx_equal(pred, 7.0, 1e-10));
124}
125
126TEST_F(LFitTest, PredictExtrapolation)
127{
128 Array<double> x = {1, 2, 3, 4, 5};
129 Array<double> y = {3, 5, 7, 9, 11};
130
131 LFit fit(x, y);
132
133 auto [pred, err] = fit.predict(10.0);
134 EXPECT_TRUE(approx_equal(pred, 21.0, 1e-10));
135}
136
137TEST_F(LFitTest, PredictMultipleValues)
138{
139 Array<double> x = {0, 1, 2, 3, 4};
140 Array<double> y = {1, 3, 5, 7, 9};
141
142 LFit fit(x, y);
143
144 for (double xval = 0; xval <= 4; xval += 0.5)
145 {
146 auto [pred, err] = fit.predict(xval);
147 double expected = 2.0 * xval + 1.0;
148 EXPECT_TRUE(approx_equal(pred, expected, 1e-10));
149 }
150}
151
152// =============================================================================
153// Edge Cases Tests
154// =============================================================================
155
156TEST_F(LFitTest, TwoPoints)
157{
158 Array<double> x = {1, 5};
159 Array<double> y = {2, 10};
160
161 LFit fit(x, y);
162
163 EXPECT_TRUE(approx_equal(fit.m, 2.0, 1e-10));
164 EXPECT_TRUE(approx_equal(fit.r2, 1.0, 1e-10));
165}
166
167TEST_F(LFitTest, LargeNumbers)
168{
169 Array<double> x = {1000, 2000, 3000, 4000, 5000};
170 Array<double> y = {2000, 4000, 6000, 8000, 10000};
171
172 LFit fit(x, y);
173
174 EXPECT_TRUE(approx_equal(fit.m, 2.0, 1e-6));
175}
176
177TEST_F(LFitTest, SmallNumbers)
178{
179 Array<double> x = {0.001, 0.002, 0.003, 0.004, 0.005};
180 Array<double> y = {0.002, 0.004, 0.006, 0.008, 0.010};
181
182 LFit fit(x, y);
183
184 EXPECT_TRUE(approx_equal(fit.m, 2.0, 1e-6));
185}
186
187TEST_F(LFitTest, NegativeValues)
188{
189 Array<double> x = {-5, -4, -3, -2, -1};
190 Array<double> y = {-10, -8, -6, -4, -2};
191
192 LFit fit(x, y);
193
194 EXPECT_TRUE(approx_equal(fit.m, 2.0, 1e-10));
195}
196
197// =============================================================================
198// Statistical Properties Tests
199// =============================================================================
200
201TEST_F(LFitTest, RSquaredRange)
202{
203 Array<double> x = {1, 2, 3, 4, 5};
204 Array<double> y = {2.1, 3.9, 6.1, 8.0, 10.2};
205
206 LFit fit(x, y);
207
208 EXPECT_GE(fit.r2, 0.0);
209 EXPECT_LE(fit.r2, 1.0);
210}
211
212TEST_F(LFitTest, ResidualSum)
213{
214 Array<double> x = {1, 2, 3, 4, 5};
215 Array<double> y = {3, 5, 7, 9, 11};
216
217 LFit fit(x, y);
218
219 EXPECT_GE(fit.sumsq, 0.0);
220 EXPECT_TRUE(approx_equal(fit.sumsq, 0.0, 1e-10));
221}
222
223TEST_F(LFitTest, MSECalculation)
224{
225 Array<double> x = {1, 2, 3, 4, 5};
226 Array<double> y = {3.1, 5.2, 6.9, 9.1, 10.8};
227
228 LFit fit(x, y);
229
230 EXPECT_GE(fit.mse, 0.0);
231 EXPECT_GT(fit.sigma, 0.0);
232}
233
234// =============================================================================
235// Different Data Patterns Tests
236// =============================================================================
237
238TEST_F(LFitTest, UniformSpacing)
239{
240 Array<double> x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
242
243 for (size_t i = 0; i < x.size(); ++i)
244 y.append(3.0 * x[i] + 2.0);
245
246 LFit fit(x, y);
247
248 EXPECT_TRUE(approx_equal(fit.m, 3.0, 1e-10));
249 EXPECT_TRUE(approx_equal(fit.c, 2.0, 1e-10));
250}
251
252TEST_F(LFitTest, NonUniformSpacing)
253{
254 Array<double> x = {1, 3, 5, 10, 15};
255 Array<double> y = {2, 6, 10, 20, 30};
256
257 LFit fit(x, y);
258
259 EXPECT_TRUE(approx_equal(fit.m, 2.0, 1e-10));
260}
261
262TEST_F(LFitTest, ReversedOrder)
263{
264 Array<double> x = {5, 4, 3, 2, 1};
265 Array<double> y = {11, 9, 7, 5, 3};
266
267 LFit fit(x, y);
268
269 EXPECT_TRUE(approx_equal(fit.m, 2.0, 1e-10));
270 EXPECT_TRUE(approx_equal(fit.c, 1.0, 1e-10));
271}
272
273// =============================================================================
274// Stress Tests
275// =============================================================================
276
277TEST_F(LFitTest, LargeDataset)
278{
279 Array<double> x, y;
280
281 for (int i = 0; i < 1000; ++i)
282 {
283 x.append(i);
284 y.append(2.5 * i + 10.0);
285 }
286
287 LFit fit(x, y);
288
289 EXPECT_TRUE(approx_equal(fit.m, 2.5, 1e-10));
290 EXPECT_TRUE(approx_equal(fit.c, 10.0, 1e-8));
291 EXPECT_TRUE(approx_equal(fit.r2, 1.0, 1e-10));
292}
293
294TEST_F(LFitTest, ManyPredictions)
295{
296 Array<double> x = {1, 2, 3, 4, 5};
297 Array<double> y = {2, 4, 6, 8, 10};
298
299 LFit fit(x, y);
300
301 for (int i = -10; i <= 20; ++i)
302 {
303 auto [pred, err] = fit.predict(i);
304 EXPECT_TRUE(approx_equal(pred, 2.0 * i, 1e-10));
305 }
306}
307
308TEST_F(LFitTest, RepeatConstruction)
309{
310 Array<double> x = {1, 2, 3, 4, 5};
311 Array<double> y = {3, 5, 7, 9, 11};
312
313 for (int i = 0; i < 100; ++i)
314 {
315 LFit fit(x, y);
316 EXPECT_TRUE(approx_equal(fit.m, 2.0, 1e-10));
317 EXPECT_TRUE(approx_equal(fit.c, 1.0, 1e-10));
318 }
319}
320
321// =============================================================================
322// Comparison Tests
323// =============================================================================
324
325TEST_F(LFitTest, DifferentSlopes)
326{
327 Array<double> x = {1, 2, 3, 4, 5};
328
329 Array<double> y1 = {2, 4, 6, 8, 10};
330 LFit fit1(x, y1);
331
332 Array<double> y2 = {3, 6, 9, 12, 15};
333 LFit fit2(x, y2);
334
335 EXPECT_TRUE(approx_equal(fit1.m, 2.0, 1e-10));
336 EXPECT_TRUE(approx_equal(fit2.m, 3.0, 1e-10));
337 EXPECT_GT(fit2.m, fit1.m);
338}
339
340TEST_F(LFitTest, DifferentIntercepts)
341{
342 Array<double> x = {1, 2, 3, 4, 5};
343
344 Array<double> y1 = {3, 5, 7, 9, 11};
345 LFit fit1(x, y1);
346
347 Array<double> y2 = {5, 7, 9, 11, 13};
348 LFit fit2(x, y2);
349
350 EXPECT_TRUE(approx_equal(fit1.c, 1.0, 1e-10));
351 EXPECT_TRUE(approx_equal(fit2.c, 3.0, 1e-10));
352 EXPECT_GT(fit2.c, fit1.c);
353}
354
355// =============================================================================
356// The errors of the fit (they were taken from x - y, not from the residuals)
357// =============================================================================
358
359TEST_F(LFitTest, AnExactLineHasNoErrors)
360{
361 // y = 2x + 1: the residuals are 0, and so are the errors; before, mse was
362 // 4.243, the root of the mean of the squares of x - y
363 Array<double> x = {1, 2, 3, 4, 5};
364 Array<double> y = {3, 5, 7, 9, 11};
365
366 LFit fit(x, y);
367
368 EXPECT_EQ(fit.sumsq, 0.0);
369 EXPECT_EQ(fit.mse, 0.0);
370 EXPECT_EQ(fit.sigma, 0.0);
371}
372
373TEST_F(LFitTest, TheErrorsComeFromTheResiduals)
374{
375 Array<double> x = {1, 2, 3, 4, 5, 6, 7, 8};
376 Array<double> y = {3.1, 5.2, 6.9, 9.1, 10.8, 13.3, 14.9, 17.2};
377
378 LFit fit(x, y);
379
380 const size_t n = x.size();
381 double sum = 0;
382 for (size_t i = 0; i < n; ++i)
383 {
384 const double e = y[i] - (fit.c + fit.m * x[i]);
385 sum += e * e;
386 }
387
388 // the sum of the squares of the residuals, y - (c + m x), and from it the
389 // mean squared error and the standard deviation of the errors
390 EXPECT_NEAR(fit.sumsq, sum, 1e-12 * sum);
391 EXPECT_EQ(fit.mse, fit.sumsq / n);
392 EXPECT_EQ(fit.sigma, std::sqrt(fit.sumsq / (n - 2.0)));
393 EXPECT_GT(fit.sigma, 0.0);
394 EXPECT_NEAR(fit.mse, sum / n, 1e-12 * sum);
395
396 // the variance of the errors, sigma^2, is the one of the covariances
397 EXPECT_NEAR(fit.cov11, fit.sigma * fit.sigma / (n * 5.25), 1e-12 * fit.cov11);
398}
399
400TEST_F(LFitTest, TwoPointsGiveNoStandardDeviationOfTheErrors)
401{
402 // With two points, the line passes through them and the errors have no
403 // degree of freedom: sigma is undefined, as the covariances of GSL are
404 Array<double> x = {1, 5};
405 Array<double> y = {2, 10};
406
407 LFit fit(x, y);
408
409 EXPECT_EQ(fit.sumsq, 0.0);
410 EXPECT_EQ(fit.mse, 0.0);
411 EXPECT_TRUE(std::isnan(fit.sigma));
412}
413
414// LFit throws SizeMismatch until 8.0.0, of aleph-exceptions.H, deprecated
415#if defined(_MSC_VER) && !defined(__clang__)
416# pragma warning(push)
417# pragma warning(disable : 4996)
418#else
419# pragma GCC diagnostic push
420# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
421#endif
422
423TEST_F(LFitTest, EmptyArraysThrow)
424{
425 // Before, the correlation read the first element of the empty arrays
426 Array<double> x, y;
427 EXPECT_THROW((void) LFit(x, y), SizeMismatch);
428
429 Array<double> one = {1};
430 EXPECT_THROW((void) LFit(one, one), SizeMismatch);
431}
432
433TEST_F(LFitTest, ArraysOfDifferentSizesThrow)
434{
435 Array<double> x = {1, 2, 3};
436 Array<double> y = {1, 2};
437 EXPECT_THROW((void) LFit(x, y), SizeMismatch);
438 EXPECT_THROW((void) LFit(y, x), SizeMismatch);
439}
440
441#if defined(_MSC_VER) && !defined(__clang__)
442# pragma warning(pop)
443#else
444# pragma GCC diagnostic pop
445#endif
446
447// SizeMismatch is a std::runtime_error: a program that catches that, or
448// std::exception, which LFit throws also from 8.0.0, does not name it
449TEST_F(LFitTest, ItsErrorsAreRuntimeErrors)
450{
451 Array<double> x = {1, 2, 3};
452 Array<double> y = {1, 2};
454 EXPECT_THROW((void) LFit(x, y), std::runtime_error);
455 EXPECT_THROW((void) LFit(e, e), std::exception);
456}
457
458#if ALEPH_WITH_GSL
459namespace
460{
461 // Bit by bit where this test and GSL round each operation alike: x86-64,
462 // whose GSL is built without fused multiply-adds, when the test is built
463 // without them too. Elsewhere, relative to the greater of gsl and scale:
464 // a fused multiply-add rounds the residuals, which cancel the deviations
465 // of y, otherwise. With -mfma, the fit differs at most by 1.4e-12, and the
466 // sums of squares and the covariances by 1.1e-9, in these data
467 constexpr bool exact =
468# if (defined(__x86_64__) || defined(_M_X64)) && !defined(__FMA__) && !defined(__FP_FAST_FMA)
469 true;
470# else
471 false;
472# endif
473
474 ::testing::AssertionResult same_as_gsl(const double ours, const double gsl,
475 const double tolerance, const double scale = 0)
476 {
477 if (std::memcmp(&ours, &gsl, sizeof ours) == 0 or (std::isnan(ours) and std::isnan(gsl)))
478 return ::testing::AssertionSuccess();
479 if (not exact and std::abs(ours - gsl) <= tolerance * std::max(std::abs(gsl), scale))
480 return ::testing::AssertionSuccess();
481 return ::testing::AssertionFailure() << std::setprecision(17) << ours << " instead of "
482 << gsl << " of GSL";
483 }
484}
485
486TEST_F(LFitTest, TheFitIsThatOfGsl)
487{
488 // For each scale of x, from 2^-12 to 2^12, and each size, lines with
489 // noise, an exact one, a horizontal one, a vertical one and ones far from
490 // 0, against gsl_fit_linear(), gsl_stats_correlation() and
491 // gsl_fit_linear_est(); the degenerate ones, and the two points, which
492 // the line fits exactly, only bit by bit
493 std::mt19937_64 g(2026);
494 std::uniform_real_distribution<double> u(-1, 1);
495 size_t compared = 0;
496 for (int scale = -12; scale <= 12; scale += 3)
497 for (const size_t n : {2, 3, 4, 5, 7, 10, 31, 100, 1000})
498 for (int rep = 0; rep < 10; ++rep)
499 {
500 const double sx = std::ldexp(1.0, scale), sy = std::ldexp(1.0, -scale / 2);
501 const double slope = u(g) * 10, intercept = u(g) * 1000;
502 const bool degenerate = rep < 3 or n == 2; // exact fits
503 Array<double> x, y;
504 for (size_t i = 0; i < n; ++i)
505 {
506 const double xi = (rep % 4 == 3 ? static_cast<double>(i) : u(g)) * sx
507 + (rep >= 8 ? 1e6 : 0);
508 x.append(rep == 2 ? -1.5 : xi);
509 y.append(rep == 1 ? 3.25 : slope * x[i] + intercept + (rep == 0 ? 0 : u(g) * sy));
510 }
511 if (degenerate and not exact)
512 continue;
513
514 LFit fit(x, y);
515
516 double c, m, cov00, cov01, cov11, sumsq;
517 gsl_fit_linear(&x.base(), 1, &y.base(), 1, n, &c, &m, &cov00, &cov01, &cov11, &sumsq);
518 double r2 = pow2(gsl_stats_correlation(&x.base(), 1, &y.base(), 1, n));
519 if (not is_normal_number(r2))
520 r2 = 1;
521
522 double ymax = 0;
523 for (size_t i = 0; i < n; ++i)
524 ymax = std::max(ymax, std::abs(y[i]));
525
526 const auto where = [&] { return "scale " + std::to_string(scale) + ", n "
527 + std::to_string(n) + ", case " + std::to_string(rep); };
528 EXPECT_TRUE(same_as_gsl(fit.c, c, 1e-10, ymax)) << where();
529 EXPECT_TRUE(same_as_gsl(fit.m, m, 1e-10)) << where();
530 EXPECT_TRUE(same_as_gsl(fit.cov00, cov00, 1e-6)) << where();
531 EXPECT_TRUE(same_as_gsl(fit.cov01, cov01, 1e-6)) << where();
532 EXPECT_TRUE(same_as_gsl(fit.cov11, cov11, 1e-6)) << where();
533 EXPECT_TRUE(same_as_gsl(fit.sumsq, sumsq, 1e-6)) << where();
534 EXPECT_TRUE(same_as_gsl(fit.r2, r2, 1e-10)) << where();
535
536 for (const double xp : {0.0, u(g) * sx, 3 * sx})
537 {
538 double yp, yp_err;
539 gsl_fit_linear_est(xp, c, m, cov00, cov01, cov11, &yp, &yp_err);
540 const auto [ours, ours_err] = fit.predict(xp);
541 EXPECT_TRUE(same_as_gsl(ours, yp, 1e-10, ymax)) << where() << ", x " << xp;
542 EXPECT_TRUE(same_as_gsl(ours_err, yp_err, 1e-6)) << where() << ", x " << xp;
543 }
544 ++compared;
545 }
546 EXPECT_GT(compared, exact ? 800u : 500u);
547}
548#else
549// Without GSL (ALEPH_WITH_GSL is 0), the cases that compare with it
550// report SKIPPED instead of disappearing from the run, as
551// docs/ci_sanitizer_policy.md asks of a case that a configuration
552// cannot run; the other cases check the fit by themselves
553TEST_F(LFitTest, TheFitIsThatOfGsl)
554{
555 GTEST_SKIP() << "without GSL (ALEPH_WITH_GSL is 0)";
556}
557#endif // ALEPH_WITH_GSL
The random number generators of Aleph: the one that gives the numbers of the gsl_rng_mt19937 of GSL,...
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
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
Minimal std::expected-style result type for C++20.
void TearDown() override
Definition lfit_test.cc:20
void SetUp() override
Definition lfit_test.cc:19
bool approx_equal(double a, double b, double eps=1e-6)
Definition lfit_test.cc:22
bool approx_equal(double a, double b, double tol=EPSILON)
__gmp_expr< T, __gmp_unary_expr< __gmp_expr< T, U >, __gmp_y1_function > > y1(const __gmp_expr< T, U > &expr)
Definition gmpfrxx.h:4181
Freq_Node * pred
Predecessor node in level-order traversal.
Linear regression (least squares fitting).
TEST_F(LFitTest, PerfectLineFit)
Definition lfit_test.cc:31
static mpfr_t y
Definition mpfr_mul_d.c:3
DynList< T > intercept(const Container< T > &c1, const Container< T > &c2)
Return intersection of two containers as a DynList.
DynList< T > rep(const size_t n, const T &item)
Create a sequence of repeated items.
and
Check uniqueness with explicit hash + equality functors.
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
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
Linear regression calculator using least squares method.
Definition lfit.H:117
double sumsq
Sum of the squares of the residuals, y - (c + m x)
Definition lfit.H:123
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
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
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)