/src/ocudu/lib/ntn/ntn_math_helpers.cpp
Line | Count | Source |
1 | | // SPDX-FileCopyrightText: Copyright (C) 2021-2026 Software Radio Systems Limited |
2 | | // SPDX-FileCopyrightText: Copyright (C) 2026 OCUDU contributors |
3 | | // SPDX-License-Identifier: BSD-3-Clause-Open-MPI |
4 | | // Portions of this file may implement 3GPP specifications, which may be subject to additional licensing requirements. |
5 | | |
6 | | #include "ntn_math_helpers.h" |
7 | | #include "ocudu/support/error_handling.h" |
8 | | #include <cmath> |
9 | | #include <vector> |
10 | | |
11 | | using namespace ocudu; |
12 | | using namespace ocudu_ntn; |
13 | | |
14 | | std::array<double, 3> ocudu::ocudu_ntn::fit_quadratic(span<const double> x, span<const double> y, double c0) |
15 | 0 | { |
16 | 0 | if (x.size() != y.size() || x.size() < 2) { |
17 | 0 | report_error("Input vectors must have same size and at least two points."); |
18 | 0 | } |
19 | |
|
20 | 0 | double Sx2 = 0.0, Sx3 = 0.0, Sx4 = 0.0; |
21 | 0 | double Sy1 = 0.0, Sy2 = 0.0; |
22 | |
|
23 | 0 | for (unsigned i = 0, e = x.size(); i != e; ++i) { |
24 | 0 | double xi = x[i]; |
25 | 0 | double yi = y[i] - c0; |
26 | |
|
27 | 0 | double xi2 = xi * xi; |
28 | 0 | double xi3 = xi2 * xi; |
29 | 0 | double xi4 = xi2 * xi2; |
30 | |
|
31 | 0 | Sx2 += xi2; |
32 | 0 | Sx3 += xi3; |
33 | 0 | Sx4 += xi4; |
34 | |
|
35 | 0 | Sy1 += yi * xi; |
36 | 0 | Sy2 += yi * xi2; |
37 | 0 | } |
38 | | |
39 | | // Solve linear system: |
40 | | // [Sx2 Sx3] [c1] = [Sy1] |
41 | | // [Sx3 Sx4] [c2] [Sy2] |
42 | |
|
43 | 0 | double det = Sx2 * Sx4 - Sx3 * Sx3; |
44 | 0 | if (std::abs(det) < 1e-12) { |
45 | 0 | report_error("Singular matrix - x values may be degenerate."); |
46 | 0 | } |
47 | |
|
48 | 0 | double c1 = (Sy1 * Sx4 - Sx3 * Sy2) / det; |
49 | 0 | double c2 = (Sx2 * Sy2 - Sy1 * Sx3) / det; |
50 | |
|
51 | 0 | return {c0, c1, c2}; |
52 | 0 | } |