Vulpes  0.1.0
Versatile and parallel compUtational Library for high-order discontinuous Polytopal Element Simulations
Loading...
Searching...
No Matches
sparse_polynomial.hpp
Go to the documentation of this file.
1// ----------------------------------------------------------------------
2//
3// Copyright (C) 2024 - 2026 by the Vulpes authors.
4// This file is part of Vulpes.
5//
6// Vulpes is free software; you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10//
11// Vulpes is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14// General Public License for more details.
15//
16// You should have received a copy of the GNU General Public License
17// along with Vulpes. If not, see <http://www.gnu.org/licenses/>.
18//
19// ----------------------------------------------------------------------
20
21// Author: Nicola De March <nicola.demarch@polimi.it>
22// Author: Matteo Caldana <matteo.caldana@polimi.it>
23
24#ifndef VULPES_POLYNOMIALS_SPARSE_POLYNOMIAL_HPP_
25#define VULPES_POLYNOMIALS_SPARSE_POLYNOMIAL_HPP_
26
27#include <algorithm>
28#include <cstddef>
29#include <ostream>
30#include <set>
31#include <utility>
32#include <vector>
33
38
39namespace vulpes {
40namespace polynomial {
41
58template <std::size_t Dim, typename IndexType, typename CoefType, bool IsScaled>
60 : public PolynomialBase<
61 CoefType,
62 Dim,
63 SparsePolynomial<Dim, IndexType, CoefType, IsScaled>> {
64 public:
65 inline static constexpr std::size_t dim = Dim;
66
68 using ScalarType = CoefType;
69
70 SparsePolynomial() = default;
71
76 explicit SparsePolynomial(const CoefType& coef)
77 : m_monomials({MonomialType{coef}}) {};
78
82 explicit SparsePolynomial(const MonomialType& coef) : m_monomials({coef}) {};
83
92 const std::array<const Polynomial<CoefType>*, Dim>& polynomials) {
93 std::array<std::size_t, Dim> sizes;
94 std::size_t size_nd = 1;
95 for (std::size_t d = 0; d < Dim; ++d) {
96 sizes[d] = polynomials[d]->size();
97 size_nd *= sizes[d];
98 }
99 // loop on each element of the cartesian product
100 for (std::size_t i = 0; i < size_nd; ++i) {
101 // get the list of indices
102 std::array<IndexType, Dim> idxs;
103 // this is like writing `i` in radix
104 std::size_t idx = i;
105 CoefType monomial_coef = CoefType(1);
106 for (std::size_t d = 0; d < Dim; ++d) {
107 idxs[d] = idx % sizes[d];
108 monomial_coef *= (*polynomials[d])[idxs[d]];
109 idx /= sizes[d];
110 }
111 if (monomial_coef != CoefType(0)) {
112 m_monomials.emplace_back(idxs, monomial_coef);
113 }
114 }
115 }
116
117 CoefType evaluate(const Eigen::Vector<CoefType, Dim>& point) const {
118 return evaluate(point.data());
119 }
120
121 CoefType evaluate(const CoefType* point) const {
122 CoefType result = CoefType(0);
123 for (const auto& monomial : m_monomials) {
124 result += monomial.evaluate(point);
125 }
126 return result;
127 }
128
129 template <std::size_t IntegralDim>
131 const datastructure::
132 SimplexDataView<IntegralDim, true, CoefType, std::size_t>&
133 monomial_integrals,
134 const CoefType* val_ptr) const {
135 static_assert(IntegralDim < Dim);
136 constexpr auto EvalDim = Dim - IntegralDim;
137 // cache table of evaluations powers
138 const IndexType ncols = std::max((IndexType)2, m_max_exp + 1);
139 Eigen::Matrix<CoefType, EvalDim, -1> eval_table(EvalDim, ncols);
140 eval_table.col(0) = Eigen::Vector<CoefType, EvalDim>::Ones();
141 eval_table.col(1) =
142 Eigen::Map<const Eigen::Vector<CoefType, EvalDim>>(val_ptr);
143 for (Eigen::Index i = 2; i < eval_table.cols(); ++i) {
144 eval_table.col(i) =
145 eval_table.col(i - 1).array() * eval_table.col(1).array();
146 }
147 // evaluate/integrate all monomials
148 CoefType integral = 0.0;
149 for (const auto& monomial : m_monomials) {
150 CoefType monomial_integral = monomial.m_coefficient;
151 // integrate part
152 if constexpr (IntegralDim == 1) {
153 monomial_integral *= monomial_integrals[monomial.m_exponent[0]];
154 } else if constexpr (IntegralDim == 2) {
155 monomial_integral *=
156 monomial_integrals(monomial.m_exponent[0], monomial.m_exponent[1]);
157 } else if constexpr (IntegralDim == 3) {
158 monomial_integral *= monomial_integrals(
159 monomial.m_exponent[0], monomial.m_exponent[1],
160 monomial.m_exponent[2]);
161 } else {
162 static_assert(Dim * 0 && "NotImplemented");
163 }
164 // evaluate part
165 for (std::size_t d = 0; d < EvalDim; ++d) {
166 monomial_integral *=
167 eval_table(d, monomial.m_exponent[d + IntegralDim]);
168 }
169 integral += monomial_integral;
170 }
171 return integral;
172 }
173
174 CoefType integrate(
176 monomial_integrals) const {
177 assert(m_monomials.size() <= monomial_integrals.numel());
178 CoefType integral = 0.0;
179 for (const auto& monomial : m_monomials) {
180 if constexpr (Dim == 1) {
181 integral +=
182 monomial.m_coefficient * monomial_integrals[monomial.m_exponent[0]];
183 } else if constexpr (Dim == 2) {
184 integral +=
185 monomial.m_coefficient *
186 monomial_integrals(monomial.m_exponent[0], monomial.m_exponent[1]);
187 } else if constexpr (Dim == 3) {
188 integral += monomial.m_coefficient * monomial_integrals(
189 monomial.m_exponent[0],
190 monomial.m_exponent[1],
191 monomial.m_exponent[2]);
192 } else {
193 static_assert(Dim * 0 && "NotImplemented");
194 }
195 }
196 return integral;
197 }
198
199 SparsePolynomial derivative(std::size_t component) const {
200 SparsePolynomial result;
201 for (const auto& monomial : m_monomials) {
202 const auto monomial_der = monomial.derivative(component);
203 if (!monomial_der.empty()) {
204 result.m_monomials.push_back(monomial_der);
205 }
206 }
207 return result;
208 }
209
210 auto& data() { return m_monomials; }
211 const auto& data() const { return m_monomials; }
212
213 Eigen::Vector<SparsePolynomial, Dim> gradient() const {
214 Eigen::Vector<SparsePolynomial, Dim> result;
215 for (std::size_t d = 0; d < Dim; ++d) {
216 result[d] = this->derivative(d);
217 }
218 return result;
219 }
220
222 m_max_exp = 0;
223 for (const auto& m : m_monomials) {
224 auto it = std::max_element(m.exp().cbegin(), m.exp().cend());
225 m_max_exp = std::max(m_max_exp, *it);
226 }
227 }
228
231 using SparsePolynomial1D =
233 using MonomialType1D = SparsePolynomial1D::MonomialType;
234 // table of (ax + b)^n
235 static std::vector<SparsePolynomial1D> table_1d_linear;
236 // init static table
237 if (table_1d_linear.size() == 0) {
238 table_1d_linear.push_back(SparsePolynomial1D{1});
239 // (ax + b)
240 static SparsePolynomial1D linear_1d;
241 linear_1d.data().push_back(
242 MonomialType1D{std::array<IndexType, 3>{1, 1, 0}, 1});
243 linear_1d.data().push_back(
244 MonomialType1D{std::array<IndexType, 3>{0, 0, 1}, 1});
245 table_1d_linear.push_back(linear_1d);
246 }
247 // update the table
248 IndexType max_exp = 0;
249 for (const auto& m : m_monomials) {
250 auto it = std::max_element(m.exp().cbegin(), m.exp().cend());
251 max_exp = std::max(max_exp, *it);
252 }
253 for (std::size_t i = table_1d_linear.size(); i <= max_exp; ++i) {
254 table_1d_linear.push_back(table_1d_linear.back() * table_1d_linear[1]);
255 }
256 // make the product
258 for (const auto& m : m_monomials) {
259 auto prod = SparsePolynomial{m.coef()}.template liftDimension<Dim, Dim>();
260 // constexpr for loop -> for(d = 0; d < Dim; ++d)
261 [&]<std::size_t... d>(std::index_sequence<d...>) {
262 ((prod *= table_1d_linear[m.exp()[d]]
263 .template liftDimension<3 * d, 3 * (Dim - 1 - d)>()),
264 ...);
265 }(std::make_index_sequence<Dim>{});
266 for (const auto& mono_lifted : prod.data()) {
267 result.data().push_back(mono_lifted);
268 }
269 }
270 // permute the indexes so to have first all the initial variables
271 // then the diagonal of the jacobian and then the translation
272 if constexpr (Dim == 1) {
273 result.permuteVariables({1, 0, 2});
274 } else if constexpr (Dim == 2) {
275 result.permuteVariables({1, 4, 0, 3, 2, 5});
276 } else if constexpr (Dim == 3) {
277 result.permuteVariables({1, 4, 7, 0, 3, 6, 2, 5, 8});
278 } else {
279 static_assert(Dim * 0 && "NotImplemented Error");
280 }
281 return result;
282 }
283
284 template <std::size_t PreDim, std::size_t PostDim>
287 constexpr auto OutDim = Dim + PreDim + PostDim;
288 using OutMonomial =
291 std::array<IndexType, OutDim> exponent = {0};
292 for (const auto& m : m_monomials) {
293 std::copy(m.exp().cbegin(), m.exp().cend(), exponent.begin() + PreDim);
294 result.data().push_back(OutMonomial{exponent, m.coef()});
295 }
296 return result;
297 }
298
299 void permuteVariables(const std::array<std::size_t, Dim>& permutation) {
300 std::array<IndexType, Dim> tmp_exp;
301 for (auto& m : m_monomials) {
302 for (std::size_t d = 0; d < Dim; ++d) {
303 tmp_exp[d] = m.exp()[permutation[d]];
304 }
305 m.m_exponent = tmp_exp;
306 }
307 }
308
312 template <typename U>
315 for (const auto& monomial : m_monomials) {
316 result.data().push_back(monomial.template to<U>());
317 }
318 return result;
319 }
320
322 return add<true>(other);
323 }
324
326 return add<false>(other);
327 }
328
336 decltype(m_monomials) result_monomials;
337 for (const auto& monomial1 : m_monomials) {
338 for (const auto& monomial2 : other.m_monomials) {
339 // Multiply the coefficients
340 CoefType new_coef = monomial1.m_coefficient * monomial2.m_coefficient;
341 std::array<IndexType, Dim> new_exponent;
342 for (std::size_t i = 0; i < Dim; ++i) {
343 new_exponent[i] = monomial1.m_exponent[i] + monomial2.m_exponent[i];
344 }
345 // We need to check if the monomial already exists (if not scaled)
346 if constexpr (IsScaled) {
347 result_monomials.emplace_back(new_exponent, new_coef);
348 } else {
349 // WARNING
350 // Linear search for merging, worth only if polynomial has few values
351 bool found = false;
352 for (auto& existing_monomial : result_monomials) {
353 if (existing_monomial.m_exponent == new_exponent) {
354 existing_monomial.m_coefficient += new_coef;
355 found = true;
356 break;
357 }
358 }
359 // If no existing monomial was found, add the new monomial to the
360 // result
361 if (!found) {
362 result_monomials.emplace_back(new_exponent, new_coef);
363 }
364 }
365 }
366 }
367
368 m_monomials = std::move(result_monomials);
369 return *this;
370 }
371
372 SparsePolynomial& operator*=(const CoefType& scalar) {
373 for (auto& monomial : m_monomials) {
374 monomial.m_coefficient *= scalar;
375 }
376 return *this;
377 }
378
379 friend std::ostream& operator<<(
380 std::ostream& os, const SparsePolynomial& polynomial) {
381 os << "SparsePolynomial {\n";
382 for (const auto& monomial : polynomial.m_monomials) {
383 os << " " << monomial << "\n";
384 }
385 os << "}";
386 return os;
387 }
388
394 friend bool operator==(
395 const SparsePolynomial& lhs, const SparsePolynomial& rhs) {
396 const std::set<MonomialType> lhs_set(
397 lhs.m_monomials.begin(), lhs.m_monomials.end());
398 const std::set<MonomialType> rhs_set(
399 rhs.m_monomials.begin(), rhs.m_monomials.end());
400 return lhs_set == rhs_set;
401 }
402
403 protected:
407 template <bool IsAddition>
409 for (const auto& other_monomial : other.m_monomials) {
410 if constexpr (IsScaled) {
411 m_monomials.push_back(other_monomial);
412 } else {
413 bool found = false;
414 for (auto& monomial : m_monomials) {
415 if (monomial.m_exponent == other_monomial.m_exponent) {
416 if constexpr (IsAddition) {
417 monomial.m_coefficient += other_monomial.m_coefficient;
418 } else {
419 monomial.m_coefficient -= other_monomial.m_coefficient;
420 }
421 found = true;
422 break;
423 }
424 }
425 if (!found) {
426 if constexpr (IsAddition) {
427 m_monomials.push_back(other_monomial);
428 } else {
429 auto negated_monomial = other_monomial;
430 negated_monomial.m_coefficient = -negated_monomial.m_coefficient;
431 m_monomials.push_back(negated_monomial);
432 }
433 }
434 }
435 }
436 return *this;
437 }
438
439 IndexType m_max_exp = 0;
440 std::vector<MonomialType> m_monomials;
441};
442
443} // namespace polynomial
444} // namespace vulpes
445
446#endif // VULPES_POLYNOMIALS_SPARSE_POLYNOMIAL_HPP_
Class representing a (possibly scaled) monomial.
Definition monomial.hpp:256
Base template class for a general polynomial.
Definition polynomial.hpp:46
Template class to represent and operate on polynomials.
Definition polynomial1d.hpp:44
Template class to represent and operate on polynomials in nD.
Definition sparse_polynomial.hpp:63
CoefType integrateAndEvaluate(const datastructure::SimplexDataView< IntegralDim, true, CoefType, std::size_t > &monomial_integrals, const CoefType *val_ptr) const
Definition sparse_polynomial.hpp:130
SparsePolynomial & operator-=(const SparsePolynomial &other)
Definition sparse_polynomial.hpp:325
CoefType evaluate(const Eigen::Vector< CoefType, Dim > &point) const
Definition sparse_polynomial.hpp:117
internal::real_t ScalarType
Definition sparse_polynomial.hpp:68
static constexpr std::size_t dim
Definition sparse_polynomial.hpp:65
void updateMaxExp()
Definition sparse_polynomial.hpp:221
SparsePolynomial & add(const SparsePolynomial &other)
Sum or subtract two sparse polynomials.
Definition sparse_polynomial.hpp:408
void permuteVariables(const std::array< std::size_t, Dim > &permutation)
Definition sparse_polynomial.hpp:299
SparsePolynomial< Dim+PreDim+PostDim, IndexType, CoefType, IsScaled > liftDimension() const
Definition sparse_polynomial.hpp:286
SparsePolynomial< Dim, IndexType, U, IsScaled > to() const
Cast the polynomial to a different underlying type.
Definition sparse_polynomial.hpp:313
friend std::ostream & operator<<(std::ostream &os, const SparsePolynomial &polynomial)
Definition sparse_polynomial.hpp:379
SparsePolynomial(const MonomialType &coef)
Construct a sparse polynomial with a single monomial.
Definition sparse_polynomial.hpp:82
auto & data()
Definition sparse_polynomial.hpp:210
Eigen::Vector< SparsePolynomial, Dim > gradient() const
Definition sparse_polynomial.hpp:213
friend bool operator==(const SparsePolynomial &lhs, const SparsePolynomial &rhs)
Equality operator.
Definition sparse_polynomial.hpp:394
SparsePolynomial(const CoefType &coef)
Construct a sparse polynomial with one constant monomial with given coefficient, that is a constant.
Definition sparse_polynomial.hpp:76
SparsePolynomial(const std::array< const Polynomial< CoefType > *, Dim > &polynomials)
Construct a sparse polynomial as a tensor product of Dim 1D polynomials.
Definition sparse_polynomial.hpp:91
SparsePolynomial & operator+=(const SparsePolynomial &other)
Definition sparse_polynomial.hpp:321
SparsePolynomial & operator*=(const CoefType &scalar)
Definition sparse_polynomial.hpp:372
SparsePolynomial & operator*=(const SparsePolynomial &other)
Multiplication by another polynomial.
Definition sparse_polynomial.hpp:335
const auto & data() const
Definition sparse_polynomial.hpp:211
CoefType integrate(const datastructure::SimplexDataView< Dim, true, CoefType, std::size_t > &monomial_integrals) const
Definition sparse_polynomial.hpp:174
SparsePolynomial derivative(std::size_t component) const
Definition sparse_polynomial.hpp:199
std::vector< MonomialType > m_monomials
Definition sparse_polynomial.hpp:440
CoefType evaluate(const CoefType *point) const
Definition sparse_polynomial.hpp:121
monomial::Monomial< Dim, uint8_t, internal::real_t, IsScaled > MonomialType
Definition sparse_polynomial.hpp:67
SparsePolynomial< Dim *3, IndexType, CoefType, IsScaled > applyCartesianMapping() const
Definition sparse_polynomial.hpp:230
Definition crs_map.hpp:36
std::conditional_t< Dim==2, TriMatrix< Simplex, false, DataType, IndexType, const DataType * >, std::conditional_t< Dim==3, TetraTensor< Simplex, false, DataType, IndexType, const DataType * >, const DataType * > > SimplexDataView
Definition tensor.hpp:507
Definition monomial.hpp:44
Definition monomial.hpp:39
Definition cell_manager.hpp:38