NumCpp  2.18.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
Loading...
Searching...
No Matches
Poly1d.hpp
Go to the documentation of this file.
1
28#pragma once
29
30#include <iostream>
31#include <numeric>
32#include <string>
33#include <utility>
34#include <vector>
35
37#include "NumCpp/Core/Enums.hpp"
41#include "NumCpp/Core/Types.hpp"
42#include "NumCpp/Linalg/inv.hpp"
43#include "NumCpp/NdArray.hpp"
47
48namespace nc::polynomial
49{
50 //================================================================================
54 template<typename dtype>
55 class Poly1d
56 {
57 private:
59
60 public:
61 //============================================================================
62 // Method Description:
66 Poly1d() = default;
67
68 //============================================================================
69 // Method Description:
76 Poly1d(const NdArray<dtype>& inValues, IsRoots isRoots = IsRoots::NO)
77 {
78 if (inValues.size() > DtypeInfo<uint8>::max())
79 {
80 THROW_INVALID_ARGUMENT_ERROR("can only make a polynomial of order " +
82 }
83
84 if (isRoots == IsRoots::YES)
85 {
86 coefficients_.push_back(1);
87 for (auto value : inValues)
88 {
89 NdArray<dtype> coeffs = { -(value), static_cast<dtype>(1) };
90 *this *= Poly1d<dtype>(coeffs, IsRoots::NO);
91 }
92 }
93 else
94 {
95 coefficients_.resize(inValues.size());
96 stl_algorithms::copy(inValues.begin(), inValues.end(), coefficients_.begin());
97 }
98 }
99
100 //============================================================================
101 // Method Description:
108 [[nodiscard]] double area(double a, double b) const
109 {
110 if (a > b)
111 {
112 std::swap(a, b);
113 }
114
115 auto polyIntegral = integ();
116 return polyIntegral(b) - polyIntegral(a);
117 }
118
119 //============================================================================
120 // Method Description:
125 template<typename dtypeOut>
127 {
128 auto newCoefficients = NdArray<dtypeOut>(1, static_cast<uint32>(coefficients_.size()));
129
130 const auto function = [](dtype value) -> dtypeOut { return static_cast<dtypeOut>(value); };
131
132 stl_algorithms::transform(coefficients_.begin(), coefficients_.end(), newCoefficients.begin(), function);
133
134 return Poly1d<dtypeOut>(newCoefficients);
135 }
136
137 //============================================================================
138 // Method Description:
143 [[nodiscard]] NdArray<dtype> coefficients() const
144 {
145 auto coefficientsCopy = coefficients_;
146 return NdArray<dtype>(coefficientsCopy);
147 }
148
149 //============================================================================
150 // Method Description:
154 [[nodiscard]] Poly1d<dtype> deriv() const
155 {
156 const auto numCoefficients = static_cast<uint32>(coefficients_.size());
157 if (numCoefficients == 0)
158 {
159 return {};
160 }
161 if (numCoefficients == 1)
162 {
163 return Poly1d<dtype>({ 0 });
164 }
165
166 NdArray<dtype> derivativeCofficients(1, numCoefficients - 1);
167
168 uint32 counter = 0;
169 for (uint32 i = 1; i < numCoefficients; ++i)
170 {
171 derivativeCofficients[counter++] = coefficients_[i] * i;
172 }
173
174 return Poly1d<dtype>(derivativeCofficients);
175 }
176
177 //============================================================================
178 // Method Description:
184 dtype eval(dtype xValue) const noexcept
185 {
186 return operator()(xValue);
187 }
188
189 //============================================================================
190 // Method Description:
196 NdArray<dtype> eval(const NdArray<dtype>& xValues) const noexcept
197 {
198 return operator()(xValues);
199 }
200
201 //============================================================================
202 // Method Description:
209 static Poly1d<double> fit(const NdArray<dtype>& xValues, const NdArray<dtype>& yValues, uint8 polyOrder)
210 {
211 const auto numMeasurements = xValues.size();
212
213 if (yValues.size() != numMeasurements)
214 {
215 THROW_INVALID_ARGUMENT_ERROR("Input x and y arrays must be of equal size.");
216 }
217
218 if (!xValues.isflat())
219 {
220 THROW_INVALID_ARGUMENT_ERROR("Input x must be a flattened [1, n] or [n, 1] array.");
221 }
222
223 if (!yValues.isflat())
224 {
225 THROW_INVALID_ARGUMENT_ERROR("Input y must be a flattened [n, 1] array.");
226 }
227
228 NdArray<double> a(numMeasurements, polyOrder + 1);
229 for (uint32 measIdx = 0; measIdx < numMeasurements; ++measIdx)
230 {
231 const auto xDouble = static_cast<double>(xValues[measIdx]);
232 for (uint8 order = 0; order < a.numCols(); ++order)
233 {
234 a(measIdx, order) = utils::power(xDouble, order);
235 }
236 }
237
238 NdArray<double> aInv;
239 if (a.issquare())
240 {
241 aInv = linalg::inv(a);
242 }
243 else
244 {
245 // psuedo-inverse
246 auto aT = a.transpose();
247 auto aTaInv = linalg::inv(aT.dot(a));
248 aInv = aTaInv.dot(aT);
249 }
250
251 auto x = aInv.dot(yValues.template astype<double>());
252 return Poly1d<double>(x);
253 }
254
255 //============================================================================
256 // Method Description:
264 static Poly1d<double> fit(const NdArray<dtype>& xValues,
265 const NdArray<dtype>& yValues,
266 const NdArray<dtype>& weights,
267 uint8 polyOrder)
268 {
269 const auto numMeasurements = xValues.size();
270
271 if (yValues.size() != numMeasurements)
272 {
273 THROW_INVALID_ARGUMENT_ERROR("Input x and y arrays must be of equal size.");
274 }
275
276 if (weights.size() != numMeasurements)
277 {
278 THROW_INVALID_ARGUMENT_ERROR("Input x and weights arrays must be of equal size.");
279 }
280
281 if (!xValues.isflat())
282 {
283 THROW_INVALID_ARGUMENT_ERROR("Input x must be a flattened [1, n] or [n, 1] array.");
284 }
285
286 if (!yValues.isflat())
287 {
288 THROW_INVALID_ARGUMENT_ERROR("Input y must be a flattened [n, 1] array.");
289 }
290
291 if (!weights.isflat())
292 {
293 THROW_INVALID_ARGUMENT_ERROR("Input weights must be a flattened [1, n] or [n, 1] array.");
294 }
295
296 NdArray<double> a(numMeasurements, polyOrder + 1);
297 for (uint32 measIdx = 0; measIdx < numMeasurements; ++measIdx)
298 {
299 const auto xDouble = static_cast<double>(xValues[measIdx]);
300 for (uint8 order = 0; order < a.numCols(); ++order)
301 {
302 a(measIdx, order) = utils::power(xDouble, order);
303 }
304 }
305
306 NdArray<double> aWeighted(a.shape());
307 NdArray<double> yWeighted(yValues.shape());
308
309 for (uint32 measIdx = 0; measIdx < numMeasurements; ++measIdx)
310 {
311 const auto weight = static_cast<double>(weights[measIdx]);
312
313 yWeighted[measIdx] = yValues[measIdx] * weight;
314 for (uint8 order = 0; order < a.numCols(); ++order)
315 {
316 aWeighted(measIdx, order) = a(measIdx, order) * weight;
317 }
318 }
319
320 NdArray<double> aInv;
321 if (aWeighted.issquare())
322 {
323 aInv = linalg::inv(aWeighted);
324 }
325 else
326 {
327 // psuedo-inverse
328 auto aT = a.transpose();
329 auto aTaInv = linalg::inv(aT.dot(aWeighted));
330 aInv = aTaInv.dot(aT);
331 }
332
333 auto x = aInv.dot(yWeighted);
334 return Poly1d<double>(x); // NOLINT(modernize-return-braced-init-list)
335 }
336
337 //============================================================================
338 // Method Description:
342 [[nodiscard]] Poly1d<double> integ() const
343 {
344 const auto numCoefficients = static_cast<uint32>(coefficients_.size());
345 if (numCoefficients == 0)
346 {
347 return {};
348 }
349
350 NdArray<double> integralCofficients(1, numCoefficients + 1);
351 integralCofficients[0] = 0.;
352
353 for (uint32 i = 0; i < numCoefficients; ++i)
354 {
355 integralCofficients[i + 1] = static_cast<double>(coefficients_[i]) / static_cast<double>(i + 1);
356 }
357
358 return Poly1d<double>(integralCofficients); // NOLINT(modernize-return-braced-init-list)
359 }
360
361 //============================================================================
362 // Method Description:
367 [[nodiscard]] uint32 order() const noexcept
368 {
369 return static_cast<uint32>(coefficients_.size() - 1);
370 }
371
372 //============================================================================
373 // Method Description:
377 void print() const
378 {
379 std::cout << *this << std::endl;
380 }
381
382 //============================================================================
383 // Method Description:
388 [[nodiscard]] std::string str() const
389 {
390 const auto numCoeffients = static_cast<uint32>(coefficients_.size());
391
392 std::string repr = "Poly1d<";
393 uint32 power = 0;
394 for (auto& coefficient : coefficients_)
395 {
396 if (utils::essentiallyEqual(coefficient, static_cast<dtype>(0)))
397 {
398 ++power;
399 continue;
400 }
401
402 repr += utils::num2str(coefficient);
403
404 if (power > 1)
405 {
406 repr += "x^" + utils::num2str(power);
407 }
408 else if (power == 1)
409 {
410 repr += "x";
411 }
412
413 ++power;
414
415 if (power < numCoeffients)
416 {
417 repr += " + ";
418 }
419 }
420
421 return repr + ">";
422 }
423
424 //============================================================================
425 // Method Description:
431 dtype operator()(dtype inValue) const noexcept
432 {
433 uint8 power = 0;
434 return std::accumulate(coefficients_.begin(),
435 coefficients_.end(),
436 dtype{ 0 },
437 [&power, inValue](dtype polyValue, const auto& coefficient) noexcept -> dtype
438 { return polyValue + coefficient * utils::power(inValue, power++); });
439 }
440
441 //============================================================================
442 // Method Description:
448 NdArray<dtype> operator()(const NdArray<dtype>& xValues) const noexcept
449 {
450 NdArray<dtype> returnArray(xValues.shape());
451
452 stl_algorithms::transform(xValues.begin(),
453 xValues.end(),
454 returnArray.begin(),
455 [this](const auto xValue) { return this->operator()(xValue); });
456 return returnArray;
457 }
458
459 //============================================================================
460 // Method Description:
466 Poly1d<dtype> operator+(const Poly1d<dtype>& inOtherPoly) const
467 {
468 return Poly1d<dtype>(*this) += inOtherPoly;
469 }
470
471 //============================================================================
472 // Method Description:
479 {
480 if (this->coefficients_.size() < inOtherPoly.coefficients_.size())
481 {
482 for (size_t i = 0; i < coefficients_.size(); ++i)
483 {
484 coefficients_[i] += inOtherPoly.coefficients_[i];
485 }
486 for (size_t i = coefficients_.size(); i < inOtherPoly.coefficients_.size(); ++i)
487 {
488 coefficients_.push_back(inOtherPoly.coefficients_[i]);
489 }
490 }
491 else
492 {
493 for (size_t i = 0; i < inOtherPoly.coefficients_.size(); ++i)
494 {
495 coefficients_[i] += inOtherPoly.coefficients_[i];
496 }
497 }
498
499 return *this;
500 }
501
502 //============================================================================
503 // Method Description:
509 Poly1d<dtype> operator-(const Poly1d<dtype>& inOtherPoly) const
510 {
511 return Poly1d<dtype>(*this) -= inOtherPoly;
512 }
513
514 //============================================================================
515 // Method Description:
522 {
523 if (this->coefficients_.size() < inOtherPoly.coefficients_.size())
524 {
525 for (size_t i = 0; i < coefficients_.size(); ++i)
526 {
527 coefficients_[i] -= inOtherPoly.coefficients_[i];
528 }
529 for (size_t i = coefficients_.size(); i < inOtherPoly.coefficients_.size(); ++i)
530 {
531 coefficients_.push_back(-inOtherPoly.coefficients_[i]);
532 }
533 }
534 else
535 {
536 for (size_t i = 0; i < inOtherPoly.coefficients_.size(); ++i)
537 {
538 coefficients_[i] -= inOtherPoly.coefficients_[i];
539 }
540 }
541
542 return *this;
543 }
544
545 //============================================================================
546 // Method Description:
552 Poly1d<dtype> operator*(const Poly1d<dtype>& inOtherPoly) const
553 {
554 return Poly1d<dtype>(*this) *= inOtherPoly;
555 }
556
557 //============================================================================
558 // Method Description:
565 {
566 const uint32 finalCoefficientsSize = order() + inOtherPoly.order() + 1;
567 std::vector<dtype> coeffsA(finalCoefficientsSize, 0);
568 std::vector<dtype> coeffsB(finalCoefficientsSize, 0);
569 stl_algorithms::copy(coefficients_.begin(), coefficients_.end(), coeffsA.begin());
570 stl_algorithms::copy(inOtherPoly.coefficients_.cbegin(), inOtherPoly.coefficients_.cend(), coeffsB.begin());
571
572 // now multiply out the coefficients
573 std::vector<dtype> finalCoefficients(finalCoefficientsSize, 0);
574 for (uint32 i = 0; i < finalCoefficientsSize; ++i)
575 {
576 for (uint32 k = 0; k <= i; ++k)
577 {
578 finalCoefficients[i] += coeffsA[k] * coeffsB[i - k];
579 }
580 }
581
582 this->coefficients_ = finalCoefficients;
583 return *this;
584 }
585
586 //============================================================================
587 // Method Description:
594 {
595 return Poly1d(*this) ^= inPower;
596 }
597
598 //============================================================================
599 // Method Description:
606 {
607 if (inPower == 0)
608 {
609 coefficients_.clear();
610 coefficients_.push_back(1);
611 return *this;
612 }
613 if (inPower == 1)
614 {
615 return *this;
616 }
617
618 auto thisPoly(*this);
619 for (uint32 power = 1; power < inPower; ++power)
620 {
621 *this *= thisPoly;
622 }
623
624 return *this;
625 }
626
627 //============================================================================
628 // Method Description:
635 friend std::ostream& operator<<(std::ostream& inOStream, const Poly1d<dtype>& inPoly)
636 {
637 inOStream << inPoly.str() << std::endl;
638 return inOStream;
639 }
640
641 private:
642 std::vector<dtype> coefficients_{};
643 };
644} // namespace nc::polynomial
#define THROW_INVALID_ARGUMENT_ERROR(msg)
Definition Error.hpp:37
#define STATIC_ASSERT_ARITHMETIC(dtype)
Definition StaticAsserts.hpp:39
static constexpr dtype max() noexcept
Definition DtypeInfo.hpp:110
Holds 1D and 2D arrays, the main work horse of the NumCpp library.
Definition NdArrayCore.hpp:135
size_type size() const noexcept
Definition NdArrayCore.hpp:4600
iterator end() noexcept
Definition NdArrayCore.hpp:1619
self_type transpose() const
Definition NdArrayCore.hpp:4959
bool issquare() const noexcept
Definition NdArrayCore.hpp:3085
bool isflat() const noexcept
Definition NdArrayCore.hpp:3021
self_type dot(const self_type &inOtherArray) const
Definition NdArrayCore.hpp:2791
size_type numCols() const noexcept
Definition NdArrayCore.hpp:3541
const Shape & shape() const noexcept
Definition NdArrayCore.hpp:4587
iterator begin() noexcept
Definition NdArrayCore.hpp:1311
Poly1d< dtype > operator-(const Poly1d< dtype > &inOtherPoly) const
Definition Poly1d.hpp:509
Poly1d< dtype > operator*(const Poly1d< dtype > &inOtherPoly) const
Definition Poly1d.hpp:552
static Poly1d< double > fit(const NdArray< dtype > &xValues, const NdArray< dtype > &yValues, const NdArray< dtype > &weights, uint8 polyOrder)
Definition Poly1d.hpp:264
Poly1d< dtype > & operator^=(uint32 inPower)
Definition Poly1d.hpp:605
Poly1d< dtype > operator+(const Poly1d< dtype > &inOtherPoly) const
Definition Poly1d.hpp:466
dtype eval(dtype xValue) const noexcept
Definition Poly1d.hpp:184
Poly1d< double > integ() const
Definition Poly1d.hpp:342
Poly1d< dtype > & operator*=(const Poly1d< dtype > &inOtherPoly)
Definition Poly1d.hpp:564
Poly1d(const NdArray< dtype > &inValues, IsRoots isRoots=IsRoots::NO)
Definition Poly1d.hpp:76
Poly1d< dtype > & operator-=(const Poly1d< dtype > &inOtherPoly)
Definition Poly1d.hpp:521
static Poly1d< double > fit(const NdArray< dtype > &xValues, const NdArray< dtype > &yValues, uint8 polyOrder)
Definition Poly1d.hpp:209
Poly1d< dtypeOut > astype() const
Definition Poly1d.hpp:126
NdArray< dtype > eval(const NdArray< dtype > &xValues) const noexcept
Definition Poly1d.hpp:196
Poly1d< dtype > & operator+=(const Poly1d< dtype > &inOtherPoly)
Definition Poly1d.hpp:478
NdArray< dtype > operator()(const NdArray< dtype > &xValues) const noexcept
Definition Poly1d.hpp:448
std::string str() const
Definition Poly1d.hpp:388
void print() const
Definition Poly1d.hpp:377
Poly1d< dtype > operator^(uint32 inPower) const
Definition Poly1d.hpp:593
uint32 order() const noexcept
Definition Poly1d.hpp:367
dtype operator()(dtype inValue) const noexcept
Definition Poly1d.hpp:431
double area(double a, double b) const
Definition Poly1d.hpp:108
friend std::ostream & operator<<(std::ostream &inOStream, const Poly1d< dtype > &inPoly)
Definition Poly1d.hpp:635
NdArray< dtype > coefficients() const
Definition Poly1d.hpp:143
Poly1d< dtype > deriv() const
Definition Poly1d.hpp:154
NdArray< double > inv(const NdArray< dtype > &inArray)
Definition inv.hpp:50
Definition chebyshev_t.hpp:39
OutputIt transform(InputIt first, InputIt last, OutputIt destination, UnaryOperation unaryFunction)
Definition StlAlgorithms.hpp:776
OutputIt copy(InputIt first, InputIt last, OutputIt destination) noexcept
Definition StlAlgorithms.hpp:98
std::string num2str(dtype inNumber)
Definition num2str.hpp:44
dtype power(dtype inValue, uint8 inPower) noexcept
Definition Utils/power.hpp:44
bool essentiallyEqual(dtype inValue1, dtype inValue2) noexcept
Definition essentiallyEqual.hpp:47
constexpr dtype power(dtype inValue, uint8 inExponent) noexcept
Definition Functions/power.hpp:49
std::uint8_t uint8
Definition Types.hpp:42
IsRoots
Is Roots boolean.
Definition Enums.hpp:92
@ YES
Definition Enums.hpp:93
@ NO
Definition Enums.hpp:94
std::uint32_t uint32
Definition Types.hpp:40