DPsim
Loading...
Searching...
No Matches
DenseLUAdapter.cpp
Go to the documentation of this file.
1/* Copyright 2017-2021 Institute for Automation of Complex Power Systems,
2 * EONERC, RWTH Aachen University
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7 *********************************************************************************/
8
10
11#include <algorithm>
12
13using namespace DPsim;
14
15namespace DPsim {
16
18
19void DenseLUAdapter::applyConfiguration() {
20 mUseStaticPreconditioner = mConfiguration.getStaticPreconditioner();
21}
22
24 SparseMatrix &systemMatrix,
25 std::vector<std::pair<UInt, UInt>> &listVariableSystemMatrixEntries) {
26 (void)systemMatrix;
27 mVariableEntries = listVariableSystemMatrixEntries;
28 std::sort(mVariableEntries.begin(), mVariableEntries.end());
29 mVariableEntries.erase(
30 std::unique(mVariableEntries.begin(), mVariableEntries.end()),
31 mVariableEntries.end());
32}
33
35 mReferenceMatrix = Matrix(systemMatrix);
36 mCurrentMatrix = mReferenceMatrix;
37 mResidual.resize(mReferenceMatrix.rows(), 1);
38 mCorrection.resize(mReferenceMatrix.rows(), 1);
39 LUFactorized.compute(mReferenceMatrix);
40 mStaticPreconditionerActive =
41 mUseStaticPreconditioner && !mVariableEntries.empty();
42 // For small dense systems, applying the fixed inverse with a matrix-vector
43 // product is cheaper than repeating two triangular substitutions for every
44 // iterative correction. Keep the LU factors as the reference factorization
45 // and exact fallback; only the correction application uses this cached map.
46 constexpr Eigen::Index maxInverseCorrectionDimension = 256;
47 mUseInverseForCorrections =
48 mStaticPreconditionerActive &&
49 mReferenceMatrix.rows() <= maxInverseCorrectionDimension;
50 if (mUseInverseForCorrections) {
51 const Matrix identity =
52 Matrix::Identity(mReferenceMatrix.rows(), mReferenceMatrix.cols());
53 mCorrectionInverse = LUFactorized.solve(identity);
54 } else {
55 mCorrectionInverse.resize(0, 0);
56 }
57}
58
60 if (!mStaticPreconditionerActive) {
61 LUFactorized.compute(Matrix(systemMatrix));
62 return;
63 }
64 // Only declared variable entries can differ from the reference matrix.
65 // Keep all static dense coefficients in place instead of copying the whole
66 // reduced matrix before updating the generator stamps.
67 for (const auto &[row, column] : mVariableEntries)
68 mCurrentMatrix(row, column) = systemMatrix.coeff(row, column);
69}
70
72 SparseMatrix &systemMatrix,
73 std::vector<std::pair<UInt, UInt>> &listVariableSystemMatrixEntries) {
74 if (!mStaticPreconditionerActive) {
75 LUFactorized.compute(Matrix(systemMatrix));
76 return;
77 }
78 mVariableEntries = listVariableSystemMatrixEntries;
79 std::sort(mVariableEntries.begin(), mVariableEntries.end());
80 mVariableEntries.erase(
81 std::unique(mVariableEntries.begin(), mVariableEntries.end()),
82 mVariableEntries.end());
83 for (const auto &[row, column] : mVariableEntries)
84 mCurrentMatrix(row, column) = systemMatrix.coeff(row, column);
85}
86
87Matrix DenseLUAdapter::solve(Matrix &mRightHandSideVector) {
88 Matrix solution;
89 solveInto(mRightHandSideVector, solution);
90 return solution;
91}
92
93void DenseLUAdapter::solveInto(Matrix &rightSideVector, Matrix &solution) {
94 using Clock = std::chrono::steady_clock;
95 ++mSolveCalls;
96 if (!mStaticPreconditionerActive) {
97 const auto start = mDetailedProfiling ? Clock::now() : Clock::time_point{};
98 solution = LUFactorized.solve(rightSideVector);
99 if (mDetailedProfiling) {
100 mInitialSolveTime.total +=
101 std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now() -
102 start);
103 ++mInitialSolveTime.calls;
104 }
105 return;
106 }
107
108 auto start = mDetailedProfiling ? Clock::now() : Clock::time_point{};
109 solution = LUFactorized.solve(rightSideVector);
110 if (mDetailedProfiling) {
111 mInitialSolveTime.total +=
112 std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now() -
113 start);
114 ++mInitialSolveTime.calls;
115 }
116
117 start = mDetailedProfiling ? Clock::now() : Clock::time_point{};
118 const Real rhsScale =
119 std::max<Real>(1., rightSideVector.cwiseAbs().maxCoeff());
120 const Real tolerance = 1e-12 * rhsScale;
121 if (mUseInverseForCorrections) {
122 // The cached inverse is a floating-point approximation to A0^-1. Form
123 // the actual current-system residual so its solve error is not lost by
124 // the simplified defect-correction recurrence used with triangular LU
125 // solves.
126 mResidual.noalias() = rightSideVector - mReferenceMatrix * solution;
127 for (const auto &[row, column] : mVariableEntries) {
128 const Real delta =
129 mCurrentMatrix(row, column) - mReferenceMatrix(row, column);
130 mResidual(row) -= delta * solution(column);
131 }
132 } else {
133 mResidual.setZero();
134 for (const auto &[row, column] : mVariableEntries) {
135 const Real delta =
136 mCurrentMatrix(row, column) - mReferenceMatrix(row, column);
137 mResidual(row) -= delta * solution(column);
138 }
139 }
140 if (mDetailedProfiling) {
141 mResidualBuildTime.total +=
142 std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now() -
143 start);
144 ++mResidualBuildTime.calls;
145 }
146
147 std::size_t solveIterations = 0;
148 for (UInt iteration = 0; iteration < 12; ++iteration) {
149 if (mResidual.cwiseAbs().maxCoeff() <= tolerance) {
150 mMaximumRefinementIterations =
151 std::max(mMaximumRefinementIterations, solveIterations);
152 return;
153 }
154 ++solveIterations;
155 ++mRefinementIterations;
156 start = mDetailedProfiling ? Clock::now() : Clock::time_point{};
157 if (mUseInverseForCorrections)
158 mCorrection.noalias() = mCorrectionInverse * mResidual;
159 else
160 mCorrection = LUFactorized.solve(mResidual);
161 if (mDetailedProfiling) {
162 mCorrectionSolveTime.total +=
163 std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now() -
164 start);
165 ++mCorrectionSolveTime.calls;
166 }
167 start = mDetailedProfiling ? Clock::now() : Clock::time_point{};
168 solution += mCorrection;
169 if (mUseInverseForCorrections) {
170 mResidual.noalias() -= mReferenceMatrix * mCorrection;
171 for (const auto &[row, column] : mVariableEntries) {
172 const Real delta =
173 mCurrentMatrix(row, column) - mReferenceMatrix(row, column);
174 mResidual(row) -= delta * mCorrection(column);
175 }
176 } else {
177 mResidual.setZero();
178 for (const auto &[row, column] : mVariableEntries) {
179 const Real delta =
180 mCurrentMatrix(row, column) - mReferenceMatrix(row, column);
181 mResidual(row) -= delta * mCorrection(column);
182 }
183 }
184 if (mDetailedProfiling) {
185 mResidualUpdateTime.total +=
186 std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now() -
187 start);
188 ++mResidualUpdateTime.calls;
189 }
190 }
191
192 // Refinement is an optimization only. Fall back to an exact solve if the
193 // previous LU is not an adequate preconditioner for the new matrix.
194 ++mFallbackCount;
195 mMaximumRefinementIterations =
196 std::max(mMaximumRefinementIterations, solveIterations);
197 start = mDetailedProfiling ? Clock::now() : Clock::time_point{};
198 LUFactorized.compute(mCurrentMatrix);
199 if (mDetailedProfiling) {
200 mFallbackFactorizationTime.total +=
201 std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now() -
202 start);
203 ++mFallbackFactorizationTime.calls;
204 }
205 mReferenceMatrix = mCurrentMatrix;
206 if (mUseInverseForCorrections) {
207 const Matrix identity =
208 Matrix::Identity(mReferenceMatrix.rows(), mReferenceMatrix.cols());
209 mCorrectionInverse = LUFactorized.solve(identity);
210 }
211 start = mDetailedProfiling ? Clock::now() : Clock::time_point{};
212 solution = LUFactorized.solve(rightSideVector);
213 if (mDetailedProfiling) {
214 mFallbackSolveTime.total +=
215 std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now() -
216 start);
217 ++mFallbackSolveTime.calls;
218 }
219}
220
221void DenseLUAdapter::writeDetailedProfile(std::ostream &profile) const {
222 const auto write = [&profile](const char *name, const Timing &timing) {
223 const double total = timing.total.count() * 1e-9;
224 const double averageUs =
225 timing.calls ? timing.total.count() * 1e-3 / timing.calls : 0.;
226 profile << name << "," << total << "," << averageUs << ",0,0,"
227 << timing.calls << "\n";
228 };
229 write("dense_lu_initial_solve", mInitialSolveTime);
230 write("dense_lu_residual_build", mResidualBuildTime);
231 write("dense_lu_correction_solves", mCorrectionSolveTime);
232 write("dense_lu_residual_update", mResidualUpdateTime);
233 write("dense_lu_fallback_factorization", mFallbackFactorizationTime);
234 write("dense_lu_fallback_solve", mFallbackSolveTime);
235}
236
237void DenseLUAdapter::writeDetailedDiagnostics(std::ostream &diagnostics) const {
238 diagnostics << "metric,value,unit\n"
239 << "solve_calls," << mSolveCalls << ",calls\n"
240 << "refinement_iterations_total," << mRefinementIterations
241 << ",iterations\n"
242 << "refinement_iterations_average_per_step,"
243 << (mSolveCalls
244 ? static_cast<double>(mRefinementIterations) / mSolveCalls
245 : 0.)
246 << ",iterations/solve\n"
247 << "refinement_iterations_max_per_step,"
248 << mMaximumRefinementIterations << ",iterations\n"
249 << "inverse_correction_operator_selected,"
250 << (mUseInverseForCorrections ? 1 : 0) << ",bool\n"
251 << "fallback_refactorizations," << mFallbackCount << ",calls\n";
252}
253} // namespace DPsim
void writeDetailedProfile(std::ostream &profile) const
void factorize(SparseMatrix &systemMatrix) override
factorization function with partial pivoting
void partialRefactorize(SparseMatrix &systemMatrix, std::vector< std::pair< UInt, UInt > > &listVariableSystemMatrixEntries) override
partial refactorization withouth partial pivoting
void writeDetailedDiagnostics(std::ostream &diagnostics) const
void solveInto(Matrix &rightSideVector, Matrix &solution) override
~DenseLUAdapter() override
Destructor.
void preprocessing(SparseMatrix &systemMatrix, std::vector< std::pair< UInt, UInt > > &listVariableSystemMatrixEntries) override
preprocessing function pre-ordering and scaling the matrix
void refactorize(SparseMatrix &systemMatrix) override
refactorization without partial pivoting
Matrix solve(Matrix &rightSideVector) override
solution function for a right hand side
DirectLinearSolverConfiguration mConfiguration
Object that carries configuration options.
CPS::Real Real
Definition Definitions.h:18
CPS::Matrix Matrix
Definition Definitions.h:24
CPS::SparseMatrixRow SparseMatrix
Definition Definitions.h:26
CPS::UInt UInt
Definition Definitions.h:23