DPsim
Loading...
Searching...
No Matches
KLUAdapter.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
9#include <dpsim/KLUAdapter.h>
10
11using namespace DPsim;
12
13namespace DPsim {
15 if (mSymbolic)
16 klu_free_symbolic(&mSymbolic, &mCommon);
17 if (mNumeric)
18 klu_free_numeric(&mNumeric, &mCommon);
19 SPDLOG_LOGGER_INFO(mSLog, "Number of Pivot Faults: {}", mPivotFaults);
20}
21
23 klu_defaults(&mCommon);
24
25 // NOTE: klu_defaults should already set the preordering methods correctly.
26 // It is repeated here in case this is altered in SuiteSparse at some point
27
28 mCommon.scale = 2;
29 mPreordering = AMD_ORDERING;
30 mCommon.btf = 1;
31
32 mVaryingColumns.clear();
33 mVaryingRows.clear();
34}
35
39
41 SparseMatrix &systemMatrix,
42 std::vector<std::pair<UInt, UInt>> &listVariableSystemMatrixEntries) {
43 if (mSymbolic) {
44 klu_free_symbolic(&mSymbolic, &mCommon);
45 }
46
47 const Int n = Eigen::internal::convert_index<Int>(systemMatrix.rows());
48
49 // Build the KLU-native CSC representation once for this sparse pattern.
50 // Runtime refactorizations only copy values through mRowToKluValueIndex.
51 mKluMatrix = systemMatrix;
52 mKluMatrix.makeCompressed();
53 std::unordered_map<std::uint64_t, Int> cscValueIndices;
54 cscValueIndices.reserve(mKluMatrix.nonZeros());
55 for (Int col = 0; col < mKluMatrix.outerSize(); ++col) {
56 for (CPS::SparseMatrix::InnerIterator it(mKluMatrix, col); it; ++it) {
57 const std::uint64_t key = (static_cast<std::uint64_t>(it.row()) << 32) |
58 static_cast<std::uint64_t>(it.col());
59 cscValueIndices.emplace(
60 key, static_cast<Int>(&it.valueRef() - mKluMatrix.valuePtr()));
61 }
62 }
63 mRowToKluValueIndex.clear();
64 mRowToKluValueIndex.reserve(systemMatrix.nonZeros());
65 for (Int row = 0; row < systemMatrix.outerSize(); ++row) {
66 for (SparseMatrix::InnerIterator it(systemMatrix, row); it; ++it) {
67 const std::uint64_t key = (static_cast<std::uint64_t>(it.row()) << 32) |
68 static_cast<std::uint64_t>(it.col());
69 const auto cscIt = cscValueIndices.find(key);
70 if (cscIt == cscValueIndices.end())
71 throw std::runtime_error("KLU CSC conversion lost a matrix entry");
72 mRowToKluValueIndex.push_back(cscIt->second);
73 }
74 }
75 syncKluValues(systemMatrix);
76
77 auto Ap = Eigen::internal::convert_index<Int *>(mKluMatrix.outerIndexPtr());
78 auto Ai = Eigen::internal::convert_index<Int *>(mKluMatrix.innerIndexPtr());
79
80 mVaryingColumns.clear();
81 mVaryingRows.clear();
82
83 mChangedEntries = listVariableSystemMatrixEntries;
84 Int varying_entries =
85 Eigen::internal::convert_index<Int>(mChangedEntries.size());
86
87 for (auto &changedEntry : mChangedEntries) {
88 mVaryingRows.push_back(changedEntry.first);
89 mVaryingColumns.push_back(changedEntry.second);
90 }
91
92 // This call also works if mVaryingColumns, mVaryingRows are empty
93 int *colPtr = mVaryingColumns.empty() ? nullptr : &mVaryingColumns[0];
94 int *rowPtr = mVaryingRows.empty() ? nullptr : &mVaryingRows[0];
95
96 mSymbolic = klu_analyze_partial(n, Ap, Ai, colPtr, rowPtr, varying_entries,
97 mPreordering, &mCommon);
98
99 if (mVaryingColumns.empty()) {
100 SPDLOG_LOGGER_INFO(
101 mSLog,
102 "KLUAdapter: No variable COLUMN entries passed to klu_analyze_partial");
103 }
104 if (mVaryingRows.empty()) {
105 SPDLOG_LOGGER_INFO(
106 mSLog,
107 "KLUAdapter: No variable ROW entries passed to klu_analyze_partial");
108 }
109
110 /* Store non-zero value of current preprocessed matrix. only used until
111 * to-do in refactorize-function is resolved. Can be removed then.
112 */
113 nnz = Eigen::internal::convert_index<Int>(systemMatrix.nonZeros());
114}
115
117 if (mNumeric) {
118 klu_free_numeric(&mNumeric, &mCommon);
119 }
120
121 syncKluValues(systemMatrix);
122 auto Ap = Eigen::internal::convert_index<Int *>(mKluMatrix.outerIndexPtr());
123 auto Ai = Eigen::internal::convert_index<Int *>(mKluMatrix.innerIndexPtr());
124 auto Ax = Eigen::internal::convert_index<Real *>(mKluMatrix.valuePtr());
125
126 mNumeric = klu_factor(Ap, Ai, Ax, mSymbolic, &mCommon);
127
128 Int varying_entries =
129 Eigen::internal::convert_index<Int>(mChangedEntries.size());
130
131 /* Make sure that factorization path is not computed if there are no varying entries.
132 * Doing so should not be a problem, but it is safer to do it this way.
133 */
134 if (!(mVaryingColumns.empty()) && !(mVaryingRows.empty())) {
135 if (mPartialRefactorizationMethod ==
137 klu_compute_path(mSymbolic, mNumeric, &mCommon, Ap, Ai,
138 &mVaryingColumns[0], &mVaryingRows[0], varying_entries);
139 } else if (mPartialRefactorizationMethod ==
141 klu_determine_start(mSymbolic, mNumeric, &mCommon, Ap, Ai,
142 &mVaryingColumns[0], &mVaryingRows[0],
143 varying_entries);
144 }
145 }
146}
147
149 // TODO: Remove if-else when zero<->non-zero issue during matrix stamping has been fixed. Also remove in partialRefactorize then.
150 if (systemMatrix.nonZeros() != nnz) {
151 preprocessing(systemMatrix, mChangedEntries);
152 factorize(systemMatrix);
153 } else {
154 syncKluValues(systemMatrix);
155 auto Ap = Eigen::internal::convert_index<Int *>(mKluMatrix.outerIndexPtr());
156 auto Ai = Eigen::internal::convert_index<Int *>(mKluMatrix.innerIndexPtr());
157 auto Ax = Eigen::internal::convert_index<Real *>(mKluMatrix.valuePtr());
158 klu_refactor(Ap, Ai, Ax, mSymbolic, mNumeric, &mCommon);
159 }
160}
161
163 SparseMatrix &systemMatrix,
164 std::vector<std::pair<UInt, UInt>> &listVariableSystemMatrixEntries) {
165 if (systemMatrix.nonZeros() != nnz) {
166 preprocessing(systemMatrix, listVariableSystemMatrixEntries);
167 factorize(systemMatrix);
168 } else if (mPartialRefactorizationMethod !=
170 (mVaryingColumns.empty() || mVaryingRows.empty())) {
171 factorize(systemMatrix);
172 } else {
173 syncKluValues(systemMatrix);
174 auto Ap = Eigen::internal::convert_index<Int *>(mKluMatrix.outerIndexPtr());
175 auto Ai = Eigen::internal::convert_index<Int *>(mKluMatrix.innerIndexPtr());
176 auto Ax = Eigen::internal::convert_index<Real *>(mKluMatrix.valuePtr());
177
178 if (mPartialRefactorizationMethod ==
180 klu_partial_factorization_path(Ap, Ai, Ax, mSymbolic, mNumeric, &mCommon);
181 } else if (mPartialRefactorizationMethod ==
183 klu_partial_refactorization_restart(Ap, Ai, Ax, mSymbolic, mNumeric,
184 &mCommon);
185 } else {
186 klu_refactor(Ap, Ai, Ax, mSymbolic, mNumeric, &mCommon);
187 }
188
189 if (mCommon.status == KLU_PIVOT_FAULT) {
190 /* pivot became too small => fully factorize again */
191 mPivotFaults++;
192 factorize(systemMatrix);
193 }
194 }
195}
196
197Matrix KLUAdapter::solve(Matrix &rightSideVector) {
198 Matrix solution = rightSideVector;
199 solveInto(rightSideVector, solution);
200 return solution;
201}
202
203void KLUAdapter::solveInto(Matrix &rightSideVector, Matrix &solution) {
204 if (&rightSideVector != &solution)
205 solution = rightSideVector;
206
207 /* Number of right hands sides
208 * usually one, KLU can handle multiple right hand sides.
209 */
210 Int rhsCols = Eigen::internal::convert_index<Int>(rightSideVector.cols());
211
212 // Leading dimension, also called "n".
213 Int rhsRows = Eigen::internal::convert_index<Int>(rightSideVector.rows());
214
215 klu_solve(mSymbolic, mNumeric, rhsRows, rhsCols, solution.data(), &mCommon);
216}
217
218void KLUAdapter::syncKluValues(const SparseMatrix &systemMatrix) {
219 if (static_cast<std::size_t>(systemMatrix.nonZeros()) !=
220 mRowToKluValueIndex.size())
221 throw std::runtime_error(
222 "KLU matrix pattern changed without preprocessing");
223 const Real *source = systemMatrix.valuePtr();
224 Real *destination = mKluMatrix.valuePtr();
225 for (std::size_t i = 0; i < mRowToKluValueIndex.size(); ++i)
226 destination[mRowToKluValueIndex[i]] = source[i];
227}
228
229void KLUAdapter::printMatrixMarket(SparseMatrix &matrix, int counter) const {
230 std::string outputName = "A" + std::to_string(counter) + ".mtx";
231 Int n = Eigen::internal::convert_index<Int>(matrix.rows());
232
233 auto Ap = Eigen::internal::convert_index<const Int *>(matrix.outerIndexPtr());
234 auto Ai = Eigen::internal::convert_index<const Int *>(matrix.innerIndexPtr());
235 auto Ax = Eigen::internal::convert_index<const Real *>(matrix.valuePtr());
236 Int nz = Eigen::internal::convert_index<Int>(matrix.nonZeros());
237
238 std::ofstream ofs;
239 ofs.open(outputName);
240 /* TODO: Add logger to DirectLinearSolver to use libfmt's more powerful logging tools.
241 * Then also move matrix printing (of LU matrices) here in order to avoid C-level printing.
242 */
243 ofs.precision(14);
244 ofs << "%%MatrixMarket matrix coordinate real general" << std::endl;
245 ofs << n << " " << n << " " << nz << std::endl;
246 for (int i = 0; i < n; i++) {
247 for (int j = Ap[i]; j < Ap[i + 1]; j++) {
248 ofs << i + 1 << " " << Ai[j] + 1 << " " << Ax[j] << std::endl;
249 }
250 }
251 ofs.close();
252}
253
255 switch (mConfiguration.getScalingMethod()) {
257 mCommon.scale = 0;
258 break;
260 mCommon.scale = 1;
261 break;
263 mCommon.scale = 2;
264 break;
265 default:
266 mCommon.scale = 1;
267 }
268
269 SPDLOG_LOGGER_INFO(mSLog, "Matrix is scaled using " +
270 mConfiguration.getScalingMethodString());
271
272 // TODO: Implement support for COLAMD (modifiy SuiteSparse)
273 switch (mConfiguration.getFillInReductionMethod()) {
275 mPreordering = AMD_ORDERING;
276 break;
278 mPreordering = AMD_ORDERING_NV;
279 break;
281 mPreordering = AMD_ORDERING_RA;
282 break;
283 default:
284 mPreordering = AMD_ORDERING;
285 }
286
287 SPDLOG_LOGGER_INFO(mSLog,
288 "Matrix is fill reduced with " +
289 mConfiguration.getFillInReductionMethodString());
290
291 // NOTE: in case more partial refactorization methods are defined/developed, that are not implemented in KLU, this assigment would be invalid
292 mPartialRefactorizationMethod =
293 mConfiguration.getPartialRefactorizationMethod();
294
295 SPDLOG_LOGGER_INFO(
296 mSLog, "Matrix is refactored " +
297 mConfiguration.getPartialRefactorizationMethodString());
298
299 switch (mConfiguration.getBTF()) {
300 case USE_BTF::DO_BTF:
301 mCommon.btf = 1;
302 break;
303 case USE_BTF::NO_BTF:
304 mCommon.btf = 0;
305 break;
306 default:
307 mCommon.btf = 1;
308 }
309
310 SPDLOG_LOGGER_INFO(mSLog,
311 "Matrix is permuted " + mConfiguration.getBTFString());
312}
313} // namespace DPsim
std::shared_ptr< spdlog::logger > Log
Definition Logger.h:34
DirectLinearSolverConfiguration mConfiguration
Object that carries configuration options.
CPS::Logger::Log mSLog
Stores logger of solver class.
void applyConfiguration() override
Apply configuration.
void factorize(SparseMatrix &systemMatrix) override
factorization function with partial pivoting
Matrix solve(Matrix &rightSideVector) override
solution function for a right hand side
void solveInto(Matrix &rightSideVector, Matrix &solution) override
Solve into caller-owned storage to avoid per-step matrix allocation.
void refactorize(SparseMatrix &systemMatrix) override
refactorization without partial pivoting
void printMatrixMarket(SparseMatrix &systemMatrix, int counter) const
Function to print matrix in MatrixMarket's coo format.
void partialRefactorize(SparseMatrix &systemMatrix, std::vector< std::pair< UInt, UInt > > &listVariableSystemMatrixEntries) override
partial refactorization withouth partial pivoting
~KLUAdapter() override
Destructor.
KLUAdapter()
Constructor.
void preprocessing(SparseMatrix &systemMatrix, std::vector< std::pair< UInt, UInt > > &listVariableSystemMatrixEntries) override
preprocessing function pre-ordering and scaling the matrix
CPS::Real Real
Definition Definitions.h:18
CPS::Int Int
Definition Definitions.h:22
CPS::Matrix Matrix
Definition Definitions.h:24
CPS::SparseMatrixRow SparseMatrix
Definition Definitions.h:26