DPsim
Loading...
Searching...
No Matches
MNASolverDirect.h
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#pragma once
10
11#include <bitset>
12#include <chrono>
13#include <iostream>
14#include <list>
15#include <map>
16#include <memory>
17#include <unordered_map>
18#include <vector>
19
20#include <dpsim/Config.h>
21#include <dpsim/DataLogger.h>
25#include <dpsim/Solver.h>
26#ifdef WITH_SPARSE
28#endif
29#ifdef WITH_HIP
30#include <dpsim/HipDenseAdapter.h>
31#include <dpsim/HipSG4BatchAdapter.h>
32#include <dpsim/HipSparseBiCGStabAdapter.h>
33#include <dpsim/HipSparseDeviceSolver.h>
34#ifdef WITH_KLU
35#include <dpsim/HipSparseLURefactorAdapter.h>
36#endif
37#endif
38#ifdef WITH_KLU
39#include <dpsim/KLUAdapter.h>
40#endif
41#ifdef WITH_CUDA
43#ifdef WITH_CUDA_SPARSE
45#endif
46#ifdef WITH_MAGMA
48#endif
49#endif
50#ifdef WITH_METAL
51#include <dpsim/GPU/Apple/MetalDenseAdapter.h>
52#include <dpsim/GPU/Apple/MetalSparseBiCGSTABAdapter.h>
53#endif
59#include <dpsim/MNASolver.h>
60
61namespace DPsim {
62
79
81template <typename VarType> class MnaSolverDirect : public MnaSolver<VarType> {
82
83protected:
84 // #### Data structures for precomputed switch matrices (optionally with parallel frequencies) ####
86 std::unordered_map<std::bitset<SWITCH_NUM>, std::vector<SparseMatrix>>
89 std::unordered_map<std::bitset<SWITCH_NUM>,
90 std::vector<std::shared_ptr<DirectLinearSolver>>>
95 const Matrix *dense = nullptr;
97 };
98 std::vector<RightVectorStamp> mRightVectorStampOperations;
101
102 // #### Data structures for system recomputation over time ####
108 std::shared_ptr<DirectLinearSolver> mDirectLinearSolverVariableSystemMatrix;
113
118
119 using MnaSolver<VarType>::mSwitches;
120 using MnaSolver<VarType>::mMNAIntfSwitches;
121 using MnaSolver<VarType>::mMNAComponents;
122 using MnaSolver<VarType>::mVariableComps;
124 using MnaSolver<VarType>::mRightSideVector;
125 using MnaSolver<VarType>::mLeftSideVector;
126 using MnaSolver<VarType>::mLeftSideVectorValue;
127 using MnaSolver<VarType>::mCurrentSwitchStatus;
128 using MnaSolver<VarType>::mRightVectorStamps;
129 using MnaSolver<VarType>::mNumNetNodes;
130 using MnaSolver<VarType>::mNodes;
131 using MnaSolver<VarType>::mIsInInitialization;
132 using MnaSolver<VarType>::mRightSideVectorHarm;
133 using MnaSolver<VarType>::mLeftSideVectorHarm;
134 using MnaSolver<VarType>::mFrequencyParallel;
135 using MnaSolver<VarType>::mSLog;
138 using MnaSolver<VarType>::mNumRecomputations;
139 using MnaSolver<VarType>::mSyncGen;
140 using MnaSolver<VarType>::mNonlinearComps;
141 using MnaSolver<VarType>::mFactorizeTimes;
142 using MnaSolver<VarType>::mSolveTimes;
143 using MnaSolver<VarType>::mRecomputationTimes;
146 using MnaSolver<VarType>::mStateSpaceExtractor;
147
149 std::chrono::nanoseconds total{};
150 std::chrono::nanoseconds minimum{};
151 std::chrono::nanoseconds maximum{};
152 std::size_t count = 0;
153 };
154 std::map<String, ProfileMeasurement> mProfileMeasurements;
155#ifdef WITH_HIP
156 std::vector<std::unique_ptr<HipSG4BatchAdapter>> mHipSG4Adapters;
157 HipSparseDeviceSolver *mHipSparseDeviceSolver = nullptr;
158 bool mHipDeviceAssemblyReady = false;
159 bool mHipSG4AdaptersInitialized = false;
160 void initializeHipSG4Adapters();
161 void updateHipSG4PreStep(Real time);
162 void updateHipSG4PostStep(const Matrix &leftVector);
163#endif
164 void recordProfileMeasurement(const String &phase,
165 std::chrono::steady_clock::time_point start,
166 std::chrono::steady_clock::time_point end);
167
168 // #### General
170 void createEmptySystemMatrix() override;
172 void addRightVectorStamps(Matrix &rightVector);
173
174 // #### Methods for precomputed switch matrices (optionally with parallel frequencies) ####
176 void switchedMatrixEmpty(std::size_t index) override;
178 void switchedMatrixEmpty(std::size_t swIdx, Int freqIdx) override;
181 std::size_t index,
182 std::vector<std::shared_ptr<CPS::MNAInterface>> &comp) override;
184 void switchedMatrixStamp(std::size_t swIdx, Int freqIdx,
185 CPS::MNAInterface::List &components,
186 CPS::MNASwitchInterface::List &switches) override;
187
188 // #### Methods for system recomputation over time ####
190 void stampVariableSystemMatrix() override;
193 Int timeStepCount) override;
195 std::shared_ptr<CPS::Task> createSolveTaskRecomp() override;
197 virtual void recomputeSystemMatrix(Real time);
199 void extractStateSpace(Real time);
200
201 // #### Scheduler Task Methods ####
203 std::shared_ptr<CPS::Task> createSolveTask() override;
205 std::shared_ptr<CPS::Task> createLogTask() override;
207 std::shared_ptr<CPS::Task> createSolveTaskHarm(UInt freqIdx) override;
209 std::shared_ptr<CPS::Task> createStateSpaceExtractionTask() override;
211 void logSystemMatrices() override;
213 void solve(Real time, Int timeStepCount) override;
215 void solveWithHarmonics(Real time, Int timeStepCount, Int freqIdx) override;
216
218 void logSolveTime();
223
225 std::shared_ptr<DirectLinearSolver>
227
228public:
232 CPS::Logger::Level logLevel = CPS::Logger::Level::info);
233
235 virtual ~MnaSolverDirect();
236
238 void
240
243 DirectLinearSolverConfiguration &configuration) override;
244
246 void logLUTimes() override;
247
249 int mIter = 0;
250
251 // #### MNA Solver Tasks ####
253 class SolveTask : public CPS::Task {
254 public:
256 : Task(solver.mName + ".Solve"), mSolver(solver) {
258
259 for (auto it : solver.mMNAComponents) {
260 if (it->getRightVector()->get().size() != 0)
261 mAttributeDependencies.push_back(it->getRightVector());
262 }
263 // Switch interfaces are solved using the precomputed switch matrix
264 // bank, but their pre-step RHS stamps still feed the global solve.
265 for (auto it : solver.mMNAIntfSwitches) {
266 if (it->getRightVector()->get().size() != 0)
267 mAttributeDependencies.push_back(it->getRightVector());
268 }
269 for (auto node : solver.mNodes) {
270 mModifiedAttributes.push_back(node->mVoltage);
271 }
272 mModifiedAttributes.push_back(solver.mLeftSideVector);
273 }
274
275 void execute(Real time, Int timeStepCount) {
276 mSolver.solve(time, timeStepCount);
277 }
278 void executeFastImpl(Real time, Int timeStepCount) {
279 mSolver.solve(time, timeStepCount);
280 }
281
282 private:
284 };
285
287 class SolveTaskHarm : public CPS::Task {
288 public:
290 : Task(solver.mName + ".Solve"), mSolver(solver), mFreqIdx(freqIdx) {
292
293 for (auto it : solver.mMNAComponents) {
294 if (it->getRightVector()->get().size() != 0)
295 mAttributeDependencies.push_back(it->getRightVector());
296 }
297 for (auto it : solver.mMNAIntfSwitches) {
298 if (it->getRightVector()->get().size() != 0)
299 mAttributeDependencies.push_back(it->getRightVector());
300 }
301 for (auto node : solver.mNodes) {
302 mModifiedAttributes.push_back(node->mVoltage);
303 }
304 for (auto leftVec : solver.mLeftSideVectorHarm) {
305 mModifiedAttributes.push_back(leftVec);
306 }
307 }
308
309 void execute(Real time, Int timeStepCount) {
310 mSolver.solveWithHarmonics(time, timeStepCount, mFreqIdx);
311 }
312 void executeFastImpl(Real time, Int timeStepCount) {
313 mSolver.solveWithHarmonics(time, timeStepCount, mFreqIdx);
314 }
315
316 private:
318 UInt mFreqIdx;
319 };
320
322 class SolveTaskRecomp : public CPS::Task {
323 public:
325 : Task(solver.mName + ".Solve"), mSolver(solver) {
327
328 for (auto it : solver.mMNAComponents) {
329 if (it->getRightVector()->get().size() != 0)
330 mAttributeDependencies.push_back(it->getRightVector());
331 }
332 for (auto it : solver.mMNAIntfVariableComps) {
333 if (it->getRightVector()->get().size() != 0)
334 mAttributeDependencies.push_back(it->getRightVector());
335 }
336 for (auto node : solver.mNodes) {
337 mModifiedAttributes.push_back(node->mVoltage);
338 }
339 mModifiedAttributes.push_back(solver.mLeftSideVector);
340 }
341
342 void execute(Real time, Int timeStepCount) {
343 mSolver.solveWithSystemMatrixRecomputation(time, timeStepCount);
344 mSolver.log(time, timeStepCount);
345 }
346 void executeFastImpl(Real time, Int timeStepCount) {
347 mSolver.solveWithSystemMatrixRecomputation(time, timeStepCount);
348 mSolver.log(time, timeStepCount);
349 }
350
351 private:
353 };
354
357 public:
359 : Task(solver.mName + ".StateSpaceExtraction"), mSolver(solver) {
362 mAttributeDependencies.push_back(solver.mLeftSideVector);
363 if (solver.mStateSpaceExtractor) {
364 // Some contributors update their matrices in post-step;
365 // these dependencies prevent extraction from reading not updated matrices.
366 for (const auto &dependency :
367 solver.mStateSpaceExtractor->getAttributeDependencies())
368 mAttributeDependencies.push_back(dependency);
369 }
371 }
372
373 void execute(Real time, Int timeStepCount) {
374 mSolver.extractStateSpace(time);
375 }
376 void executeFastImpl(Real time, Int timeStepCount) {
377 mSolver.extractStateSpace(time);
378 }
379
380 private:
382 };
383
385 class LogTask : public CPS::Task {
386 public:
388 : Task(solver.mName + ".Log"), mSolver(solver) {
390 mAttributeDependencies.push_back(solver.mLeftSideVector);
392 }
393
394 void execute(Real time, Int timeStepCount) {
395 mSolver.log(time, timeStepCount);
396 }
397 void executeFastImpl(Real time, Int timeStepCount) {
398 mSolver.log(time, timeStepCount);
399 }
400
401 private:
403 };
404};
405} // namespace DPsim
spdlog::level::level_enum Level
Definition Logger.h:33
std::shared_ptr< spdlog::logger > Log
Definition Logger.h:34
Interface to be implemented by all models used by the MNA solver.
std::vector< Ptr > List
Tasks to be defined by every component.
Definition Task.h:25
std::vector< AttributeBase::Ptr > mModifiedAttributes
Definition Task.h:70
std::vector< AttributeBase::Ptr > mAttributeDependencies
Definition Task.h:69
Task()
Definition Task.h:30
std::string mName
Definition Task.h:68
void setFastExecutor(TaskType *task)
Definition Task.h:45
void execute(Real time, Int timeStepCount)
void executeFastImpl(Real time, Int timeStepCount)
LogTask(MnaSolverDirect< VarType > &solver)
void executeFastImpl(Real time, Int timeStepCount)
void execute(Real time, Int timeStepCount)
SolveTaskHarm(MnaSolverDirect< VarType > &solver, UInt freqIdx)
void execute(Real time, Int timeStepCount)
SolveTask(MnaSolverDirect< VarType > &solver)
void executeFastImpl(Real time, Int timeStepCount)
void executeFastImpl(Real time, Int timeStepCount)
SolveTaskRecomp(MnaSolverDirect< VarType > &solver)
void execute(Real time, Int timeStepCount)
StateSpaceExtractionTask(MnaSolverDirect< VarType > &solver)
void executeFastImpl(Real time, Int timeStepCount)
void execute(Real time, Int timeStepCount)
std::size_t mDenseRightVectorStampCalls
std::shared_ptr< CPS::Task > createSolveTask() override
Create a solve task for this solver implementation.
void stampVariableSystemMatrix() override
Stamps components into the variable system matrix.
void logSolveTime()
Logging of the right-hand-side solution time.
std::vector< RightVectorStamp > mRightVectorStampOperations
void logFactorizationTime()
Logging of the LU factorization time.
void extractStateSpace(Real time)
Runs state-space extraction using the active linear solver.
void solve(Real time, Int timeStepCount) override
Solves system for single frequency.
void logRecomputationTime()
Logging of the LU refactorization time.
virtual void recomputeSystemMatrix(Real time)
Recomputes systems matrix.
SparseMatrix mVariableSystemMatrix
System matrix including stamp of static and variable elements.
SparseMatrix mBaseSystemMatrix
System matrix including all static elements.
std::unordered_map< std::bitset< SWITCH_NUM >, std::vector< SparseMatrix > > mSwitchedMatrices
Map of system matrices where the key is the bitset describing the switch states.
std::shared_ptr< DirectLinearSolver > createDirectSolverImplementation(CPS::Logger::Log mSLog)
Returns a pointer to an object of type DirectLinearSolver.
void addRightVectorStamps(Matrix &rightVector)
void setDirectLinearSolverConfiguration(DirectLinearSolverConfiguration &configuration) override
Sets the linear solver configuration.
DirectLinearSolverImpl mImplementationInUse
LU factorization indicator.
std::shared_ptr< DirectLinearSolver > mDirectLinearSolverVariableSystemMatrix
LU factorization of variable system matrix.
void recordProfileMeasurement(const String &phase, std::chrono::steady_clock::time_point start, std::chrono::steady_clock::time_point end)
void setDirectLinearSolverImplementation(DirectLinearSolverImpl implementation)
Sets the linear solver to "implementation" and creates an object.
Bool mSystemMatrixChanged
Tracks active MNA system-matrix changes from the last solve step.
std::shared_ptr< CPS::Task > createSolveTaskHarm(UInt freqIdx) override
Create a solve task for this solver implementation.
std::size_t mCompactRightVectorStampCalls
std::shared_ptr< CPS::Task > createSolveTaskRecomp() override
Create a solve task for recomputation solver.
void logSystemMatrices() override
Logging of system matrices and source vector.
Bool mVariableComponentChanged
Tracks variable-component changes from the last solve step.
void createEmptySystemMatrix() override
Create system matrix.
std::shared_ptr< CPS::Task > createLogTask() override
Create a solve task for this solver implementation.
void logLUTimes() override
log LU decomposition times
void switchedMatrixEmpty(std::size_t index) override
Sets all entries in the matrix with the given switch index to zero.
void solveWithSystemMatrixRecomputation(Real time, Int timeStepCount) override
Solves the system with variable system matrix.
std::shared_ptr< CPS::Task > createStateSpaceExtractionTask() override
Create state-space extraction task for this solver implementation.
void switchedMatrixStamp(std::size_t index, std::vector< std::shared_ptr< CPS::MNAInterface > > &comp) override
Applies a component stamp to the matrix with the given switch index.
std::unordered_map< std::bitset< SWITCH_NUM >, std::vector< std::shared_ptr< DirectLinearSolver > > > mDirectLinearSolvers
Map of direct linear solvers related to the system matrices.
MnaSolverDirect(String name, CPS::Domain domain=CPS::Domain::DP, CPS::Logger::Level logLevel=CPS::Logger::Level::info)
DirectLinearSolverConfiguration mConfigurationInUse
LU factorization configuration.
void solveWithHarmonics(Real time, Int timeStepCount, Int freqIdx) override
Solves system for multiple frequencies.
std::map< String, ProfileMeasurement > mProfileMeasurements
virtual ~MnaSolverDirect()
Destructor.
std::bitset< SWITCH_NUM > mCurrentSwitchStatus
Current status of all switches encoded as bitset.
Definition MNASolver.h:80
std::vector< Matrix > mRightSideVectorHarm
Source vector of known quantities.
Definition MNASolver.h:97
Matrix mRightSideVector
Source vector of known quantities.
Definition MNASolver.h:86
Bool mStateSpaceExtraction
Enables extraction of the MNA-coupled discrete-time state matrix.
Definition MNASolver.h:134
Matrix * mLeftSideVectorValue
Cached payload for the per-step solver hot path.
Definition MNASolver.h:224
std::vector< Real > mRecomputationTimes
LU refactorization measurements.
Definition MNASolver.h:130
std::vector< Real > mFactorizeTimes
LU factorization measurements.
Definition MNASolver.h:126
std::vector< CPS::Attribute< Matrix >::Ptr > mLeftSideVectorHarm
Solution vector of unknown quantities (parallel frequencies)
Definition MNASolver.h:227
Bool hasVariableComponentChanged()
Checks whether the status of variable MNA elements have changed.
CPS::MNAInterface::List mMNAIntfVariableComps
List of variable components if they must be accessed as MNAInterface objects.
Definition MNASolver.h:107
UInt mNumNetNodes
Number of network nodes, single line equivalent.
Definition MNASolver.h:48
MNAStateSpaceExtractor::Ptr mStateSpaceExtractor
Extractor for the MNA-coupled state-space model.
Definition MNASolver.h:137
CPS::MNASyncGenInterface::List mSyncGen
List of synchronous generators that need iterate to solve the differential equations.
Definition MNASolver.h:82
CPS::MNAInterface::List mMNAIntfSwitches
List of switches if they must be accessed as MNAInterface objects.
Definition MNASolver.h:76
std::vector< Real > mSolveTimes
Right-hand side solution measurements.
Definition MNASolver.h:128
std::vector< std::pair< UInt, UInt > > mListVariableSystemMatrixEntries
List of index pairs of varying matrix entries.
Definition MNASolver.h:62
CPS::MNAVariableCompInterface::List mVariableComps
Definition MNASolver.h:104
Int mNumRecomputations
Number of system matrix recomputations.
Definition MNASolver.h:101
CPS::MNAInterface::List mMNAComponents
List of MNA components with static stamp into system matrix.
Definition MNASolver.h:71
CPS::MNANonlinearCompInterface::List mNonlinearComps
Definition MNASolver.h:83
MnaSolver(String name, CPS::Domain domain=CPS::Domain::DP, CPS::Logger::Level logLevel=CPS::Logger::Level::info)
Constructor should not be called by users but by Simulation.
Definition MNASolver.cpp:24
std::vector< CPS::Attribute< Matrix >::Ptr > mRightVectorStamps
List of all right side vector contributions.
Definition MNASolver.h:89
CPS::Attribute< Matrix >::Ptr mLeftSideVector
Solution vector of unknown quantities.
Definition MNASolver.h:222
CPS::MNASwitchInterface::List mSwitches
Definition MNASolver.h:74
CPS::SimNode< VarType >::List mNodes
List of simulation nodes.
Definition MNASolver.h:67
static CPS::AttributeBase::Ptr external
Definition Scheduler.h:68
Bool mSystemMatrixRecomputationEnabled
Effective system-matrix recomputation setting used by the solver.
Definition Solver.h:82
CPS::Logger::Log mSLog
Logger.
Definition Solver.h:60
Bool mIsInInitialization
Determines if solver is in initialization phase, which requires different behavior.
Definition Solver.h:74
Bool mFrequencyParallel
Activates parallelized computation of frequencies.
Definition Solver.h:64
CPS::Real Real
Definition Definitions.h:18
CPS::String String
Definition Definitions.h:20
CPS::Int Int
Definition Definitions.h:22
CPS::Matrix Matrix
Definition Definitions.h:24
CPS::Bool Bool
Definition Definitions.h:21
CPS::SparseMatrixRow SparseMatrix
Definition Definitions.h:26
DirectLinearSolverImpl
@ HIPSparseLURefactor
@ HIPSparseBiCGStab
@ MetalSparseBiCGSTAB
CPS::UInt UInt
Definition Definitions.h:23