chombo-discharge
Loading...
Searching...
No Matches
CD_LeastSquaresImplem.H
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2021-2026 SINTEF Energy Research
3 *
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 */
6
12
13#ifndef CD_LEASTSQUARESIMPLEM_H
14#define CD_LEASTSQUARESIMPLEM_H
15
16// Our includes
17#include <CD_LaPackUtils.H>
18#include <CD_LeastSquares.H>
19#include <CD_MultiIndex.H>
20#include <CD_NamespaceHeader.H>
21
22inline Vector<Real>
23LeastSquares::makeDiagWeights(const Vector<RealVect>& a_displacements, const int a_pow)
24{
25 Vector<Real> ret(a_displacements.size(), 1.0);
26
27 if (a_pow > 0) {
28 // Normalize every distance with the largest one, which is 1 if all displacements are zero. We do not use physical
29 // distances when weighting the equations.
30 const Real normDist = LeastSquares::getLengthScale(a_displacements);
31
32 // Set weightings = 1/(1 + |displacement|/normDist)^a_pow
33 for (int i = 0; i < a_displacements.size(); i++) {
34 const Real len = a_displacements[i].vectorLength() / normDist;
35 const Real w = std::pow(1 + len, -a_pow);
36
37 ret[i] = w;
38 }
39 }
40
41 return ret;
42}
43
44template <typename T>
45std::map<IntVect, std::pair<VoFStencil, VoFStencil>>
46LeastSquares::computeDualLevelStencils(const IntVectSet& a_derivs,
47 const IntVectSet& a_knownTerms,
48 const Vector<VolIndex>& a_fineVofs,
49 const Vector<VolIndex>& a_coarVofs,
50 const Vector<RealVect>& a_fineDisplacements,
51 const Vector<RealVect>& a_coarDisplacements,
52 const int a_p,
53 const int a_order)
54{
55 const Vector<Real> fineWeights = LeastSquares::makeDiagWeights(a_fineDisplacements, a_p);
56 const Vector<Real> coarWeights = LeastSquares::makeDiagWeights(a_coarDisplacements, a_p);
57
59 a_knownTerms,
60 a_fineVofs,
61 a_coarVofs,
62 a_fineDisplacements,
63 a_coarDisplacements,
64 fineWeights,
65 coarWeights,
66 a_order);
67}
68
69template <typename T>
70std::map<IntVect, std::pair<VoFStencil, VoFStencil>>
71LeastSquares::computeDualLevelStencils(const IntVectSet& a_derivs,
72 const IntVectSet& a_knownTerms,
73 const Vector<VolIndex>& a_fineVofs,
74 const Vector<VolIndex>& a_coarVofs,
75 const Vector<RealVect>& a_fineDisplacements,
76 const Vector<RealVect>& a_coarDisplacements,
77 const Vector<Real>& a_fineWeights,
78 const Vector<Real>& a_coarWeights,
79 const int a_order)
80{
81 // TLDR: This routine does a two-level least squares solve of a system of equations, each equation describing
82 // a Taylor series expansion up to specified order (a_order). This routine "solves" this overdetermined system
83 // using weighted least squares so that we can obtain terms in the Taylor series. The user will have specified
84 // the desired unknowns (a_derivs) to be returned in stencil form as well as any terms that were already
85 // known (a_knownTerms).
86 //
87 // The least squares solve is done by LaPack, and so the least squares system matrix is filled in Fortran
88 // order. The actual "solve" consists of using the Moore-Penrose pseudoinverse and once we have inverted
89 // the system we can form stencils for each of the specified terms in the Taylor series.
90 //
91 // This routine does not contain much code, but can be difficult to understand.
92
93 CH_assert(a_order > 0);
94 CH_assert(a_fineVofs.size() == a_fineDisplacements.size());
95 CH_assert(a_coarVofs.size() == a_coarDisplacements.size());
96 CH_assert(a_fineVofs.size() == a_fineWeights.size());
97 CH_assert(a_coarVofs.size() == a_coarWeights.size());
98
99 // Initialize return stuff
100 std::map<IntVect, std::pair<VoFStencil, VoFStencil>> ret;
101 for (IVSIterator ivsIt(a_derivs); ivsIt.ok(); ++ivsIt) {
102 ret.emplace(ivsIt(), std::make_pair(VoFStencil(), VoFStencil()));
103 }
104
105 if (a_derivs.numPts() > 0) {
106
107 // This is because some unknowns (rows) can be eliminated.
108 const int M = LeastSquares::getTaylorExpansionSize(a_order) - a_knownTerms.numPts();
109 const int Kfine = a_fineDisplacements.size();
110 const int Kcoar = a_coarDisplacements.size();
111 const int K = Kfine + Kcoar;
112
113 const IntVectSet isect = a_derivs & a_knownTerms;
114
115 if (K < M) {
116 MayDay::Abort("LeastSquares::computeDualLevelStencils -- not enough equations to achieve desired order!");
117 }
118 if (!isect.isEmpty()) {
119 MayDay::Abort(
120 "LeastSquares::computeDualLevelStencils - you have specified the same terms as both unknown and known");
121 }
122
123 // Build the A-matrix in column major order (this is what Fortran wants) so we can use
124 // LaPackUtils::computePseudoInverse.
125 // ----------------------------------------------------------------------------------------------------------------------
126 // If we have an (unweighted) full system then our system A*x = b is
127 //
128 // A x b
129 // === === ===
130 // [1 (x-x0) 0.5(x-x0)^2 ...] [f(x) ] [f(x0)]
131 // [1 (x-x1) 0.5(x-x1)^2 ...] [df/dx ] [f(x1)]
132 // [1 (x-x2) 0.5(x-x2)^2 ...] [d^2f/dx^2](x) = [f(x2)]
133 // [: : : ] [ : ] [ : ]
134 // [: : : ] [ : ] [ : ]
135 //
136 // Extensions to 2D/3D simply use multi-index notation, and weights are simply multiplied into each row, i.e. we
137 // solve (w*A) * x = (w*b). Inverting the system gives x = [w * A^+ * w] * b where A^+ is the Moore-Penrose
138 // pseudoinverse. We put the result of [w * A^+ * w] into a stencil.
139 //
140 // Note that columns can be eliminated through knownTerms, in which case we remove unknowns (i.e., rows) from the
141 // system. This will also correspond to a modification of the right-hand side, but the required modifications are
142 // not accessible in this routine, and so the user will have to make sense of them.
143
144 // The system is built from the displacements in units of the largest displacement on either level, L, so that the
145 // columns of A are O(1); see computeSingleLevelStencils. The stencil for a term of order n is divided by L^n below.
146 const Real lengthScale = std::max(LeastSquares::getLengthScale(a_fineDisplacements),
147 LeastSquares::getLengthScale(a_coarDisplacements));
148
149 int i = 0; // Exists just because we fill memory linearly.
150 Vector<T> linA(K * M, 0.0); // Equal to (w*A)
151 Vector<T> linAplus(M * K, 0.0); // Equal to (w*A)^+
152
153 // Loop over column
154 for (MultiIndex mi(a_order); mi.ok(); ++mi) {
155 if (!a_knownTerms.contains(mi.getCurrentIndex())) {
156
157 // Fill column, write the system using the fine vofs first, then the coarse vofs.
158 for (int k = 0; k < K; k++) {
159 if (k < Kfine) {
160 linA[i] = a_fineWeights[k] * mi.pow(a_fineDisplacements[k] / lengthScale) / mi.factorial();
161 }
162 else {
163 linA[i] = a_coarWeights[k - Kfine] * mi.pow(a_coarDisplacements[k - Kfine] / lengthScale) / mi.factorial();
164 }
165 i++;
166 }
167 }
168 }
169
170 // Compute the pseudo-inverse. No stencil is returned if A is rank deficient; see computeSingleLevelStencils.
171 int rank = 0;
172 const bool foundSVD = LaPackUtils::computePseudoInverse(linAplus.stdVector(), rank, linA.stdVector(), K, M);
173
174 if (!foundSVD) {
175 MayDay::Warning("LeastSquares::computeDualLevelStencils - could not perform singular value decomposition");
176 }
177 else if (rank == M) {
178 // When we have eliminated rows in the linear system we can't use MultiIndex to map directly, this occurs because
179 // if we eliminated unknowns (rows) our system can be something like (if we eliminated term f(x)):
180 //
181 // [(x-x0) 0.5(x-x0)^2 ...] [df/dx ] [f(x0) - f(x)]
182 // [(x-x1) 0.5(x-x1)^2 ...] [d^2f/dx^2] [f(x1) - f(x)]
183 // [(x-x2) 0.5(x-x2)^2 ...] [ ](x) = [f(x2) - f(x)]
184 // [ : : ] [ : ] [ : ]
185 // [ : : ] [ : ] [ : ]
186 //
187 // The MultiIndex won't know about this, and will (correctly!), believe that the first row corresponds to
188 // multi-index (0,0,0). Since that is truly not the case, we map the rows in A to multi-indices and use that to
189 // identify the row in (w*A)^+ that corresponds to a specific unknown in the Taylor series. This is what happens
190 // below.
191 std::map<IntVect, int> rowMap;
192 int row = 0;
193 for (MultiIndex mi(a_order); mi.ok(); ++mi) {
194
195 // This is the order in which A was built.
196 if (!a_knownTerms.contains(mi.getCurrentIndex())) {
197 rowMap.emplace(mi.getCurrentIndex(), row);
198 row++;
199 }
200 }
201
202 // Recall that linAplus is M*K so the stride is always M, starting at some specified row.
203 for (IVSIterator ivsIt(a_derivs); ivsIt.ok(); ++ivsIt) {
204 const IntVect deriv = ivsIt();
205
206 if (rowMap.find(ivsIt()) != rowMap.end()) {
207 row = rowMap.at(ivsIt());
208 }
209 else {
210 MayDay::Error("LeastSquares::computeDualLevelStencils -- map is out of range but this shouldn't happen!");
211 }
212
213 std::pair<VoFStencil, VoFStencil>& sten = ret.at(deriv);
214
215 sten.first.clear();
216 sten.second.clear();
217
218 // Map the pseudoinverse into something that is usable by a stencil. Note that linAplus is (w*A)^+, but we want
219 // the term [(w*A)^+ * w], so we also need to multiply in the weights here (because the right-hand side was also
220 // weighted).
221 const Real scale = std::pow(lengthScale, -deriv.sum());
222
223 for (int k = 0; k < K; k++) {
224 const int idx = row + k * M;
225 if (k < Kfine) {
226 sten.first.add(a_fineVofs[k], scale * a_fineWeights[k] * linAplus[idx]);
227 }
228 else {
229 sten.second.add(a_coarVofs[k - Kfine], scale * a_coarWeights[k - Kfine] * linAplus[idx]);
230 }
231 }
232 }
233 }
234 }
235
236 return ret;
237}
238
239#include <CD_NamespaceFooter.H>
240
241#endif
Interface to some LaPack routines.
Agglomeration of various routines that use least squares computations.
Declaration of a SpaceDim multi-index type for use with higher order Taylor series.
static Vector< Real > makeDiagWeights(const Vector< RealVect > &a_displacements, int a_pow)
Create a list of weights. This routine returns a list of diagonal weights for a least squares system....
Definition CD_LeastSquaresImplem.H:23
static Real getLengthScale(const Vector< RealVect > &a_displacements) noexcept
Get the length scale that the least squares systems are built in.
Definition CD_LeastSquares.cpp:420
static std::map< IntVect, std::pair< VoFStencil, VoFStencil > > computeDualLevelStencils(const IntVectSet &a_derivs, const IntVectSet &a_knownTerms, const Vector< VolIndex > &a_fineVofs, const Vector< VolIndex > &a_coarVofs, const Vector< RealVect > &a_fineDisplacements, const Vector< RealVect > &a_coarDisplacements, int a_p, int a_order)
Compute a least squares interpolation to a specified order. This version separates the stencils into ...
Definition CD_LeastSquaresImplem.H:46
static int getTaylorExpansionSize(int a_order)
Get the size of a Taylor expansion for a given order.
Definition CD_LeastSquares.cpp:432
SpaceDim multi-index type for use with higher order Taylor series.
Definition CD_MultiIndex.H:32
bool ok() const
Check that multi-index is ok.
Definition CD_MultiIndex.cpp:94
bool computePseudoInverse(std::vector< double > &a_linAplus, int &a_rank, const std::vector< double > &a_linA, const int &a_M, const int &a_N)
Compute the pseudoinverse of matrix through singular value decomposition.
Definition CD_LaPackUtils.cpp:164