DPsim
Loading...
Searching...
No Matches
MNASolverDirect.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
13#ifdef WITH_HIP
14#include <dpsim/HipSparseBiCGStabAdapter.h>
15#include <dpsim/HipSparseQrAdapter.h>
16#endif
17
18#include <algorithm>
19#include <cctype>
20#include <numeric>
21#include <unordered_set>
22
23using namespace DPsim;
24using namespace CPS;
25
26namespace {
27String safeLogFileComponent(const String &name) {
28 String safeName;
29 safeName.reserve(name.size());
30 for (unsigned char character : name) {
31 if (std::isalnum(character) || character == '-' || character == '_')
32 safeName.push_back(static_cast<char>(character));
33 else
34 safeName.push_back('_');
35 }
36 return safeName.empty() ? "solver" : safeName;
37}
38} // namespace
39
40namespace DPsim {
41
42template <typename VarType>
44 CPS::Logger::Level logLevel)
45 : MnaSolver<VarType>(name, domain, logLevel) {
46#ifdef WITH_KLU
48#elif defined(WITH_SPARSE)
50#else
52#endif
53}
54
55template <typename VarType>
57 mSwitchedMatrices[std::bitset<SWITCH_NUM>(index)][0].setZero();
58}
59
60template <typename VarType>
62 Int freqIdx) {
63 mSwitchedMatrices[std::bitset<SWITCH_NUM>(swIdx)][freqIdx].setZero();
64}
65
66template <typename VarType>
68 std::size_t index, std::vector<std::shared_ptr<CPS::MNAInterface>> &comp) {
69 auto bit = std::bitset<SWITCH_NUM>(index);
70 auto &sys = mSwitchedMatrices[bit][0];
71 for (auto component : comp) {
72 component->mnaApplySystemMatrixStamp(sys);
73 }
74 for (UInt i = 0; i < mSwitches.size(); ++i)
75 mSwitches[i]->mnaApplySwitchSystemMatrixStamp(bit[i], sys, 0);
76
77 // Compute LU-factorization for system matrix
78 mDirectLinearSolvers[bit][0]->preprocessing(sys,
80 auto start = std::chrono::steady_clock::now();
81 mDirectLinearSolvers[bit][0]->factorize(sys);
82 auto end = std::chrono::steady_clock::now();
83 std::chrono::duration<Real> diff = end - start;
84 mFactorizeTimes.push_back(diff.count());
85}
86
87template <typename VarType>
89 std::size_t swIdx, Int freqIdx, CPS::MNAInterface::List &components,
91 const auto bit = std::bitset<SWITCH_NUM>(swIdx);
92 auto &systemMatrix = mSwitchedMatrices[bit][freqIdx];
93 for (auto component : components)
94 component->mnaApplySystemMatrixStampHarm(systemMatrix, freqIdx);
95 systemMatrix.makeCompressed();
96 for (UInt i = 0; i < switches.size(); ++i)
97 switches[i]->mnaApplySwitchSystemMatrixStamp(bit[i], systemMatrix, freqIdx);
98
99 auto &directSolver = mDirectLinearSolvers[bit][freqIdx];
100 directSolver->preprocessing(systemMatrix, mListVariableSystemMatrixEntries);
101 const auto start = std::chrono::steady_clock::now();
102 directSolver->factorize(systemMatrix);
103 const auto end = std::chrono::steady_clock::now();
104 mFactorizeTimes.push_back(std::chrono::duration<Real>(end - start).count());
105}
106
107template <typename VarType>
109
110 // Matrix value caches are keyed by the address of mVariableSystemMatrix.
111 // Eigen may reuse that address for a later solver instance, so discard any
112 // cache left by a previous instance before the first matrix stamps.
114
117 // TODO: a direct linear solver configuration is only applied if system matrix recomputation is used
118 this->mDirectLinearSolverVariableSystemMatrix->setConfiguration(
120 if (auto dense = std::dynamic_pointer_cast<DenseLUAdapter>(
122 dense->setDetailedProfiling(Solver::mLogSolveTimes);
123
124 SPDLOG_LOGGER_INFO(mSLog,
125 "Number of variable Elements: {}"
126 "\nNumber of MNA components: {}",
127 mVariableComps.size(), mMNAComponents.size());
128
129 // Build base matrix with only static elements
130 mBaseSystemMatrix.setZero();
131 for (auto statElem : mMNAComponents)
132 statElem->mnaApplySystemMatrixStamp(mBaseSystemMatrix);
133 SPDLOG_LOGGER_INFO(mSLog, "Base matrix with only static elements: {}",
135 mSLog->flush();
136
137 // Continue from base matrix
139
140 // Now stamp initial state of variable elements and switches into matrix
141 SPDLOG_LOGGER_INFO(mSLog, "Stamping variable elements");
142 {
143 // Preserve every potentially changing coefficient in the sparse pattern,
144 // including entries that are zero in the initial operating point. The
145 // pattern must remain fixed when the value cache is used during EMT steps.
146 CPS::Math::ScopedZeroSkipping zeroSkippingScope(false);
147 for (auto varElem : mMNAIntfVariableComps)
148 varElem->mnaApplySystemMatrixStamp(mVariableSystemMatrix);
149 }
150
151 // Keep structural slots for entries that can change later, even if their
152 // initial stamp is zero and zero skipping is enabled.
153 for (const auto &entry : mListVariableSystemMatrixEntries)
154 mVariableSystemMatrix.coeffRef(entry.first, entry.second) += 0.;
155
156 // Keep the reset matrix on exactly the same sparse pattern and in the same
157 // coefficient order as the variable matrix. Variable-only entries must be
158 // retained as explicit zeros here: recomputeSystemMatrix() copies values by
159 // array position, and the static-only pattern can have a different ordering
160 // once variable stamps have inserted additional entries.
162 std::fill_n(mBaseSystemMatrix.valuePtr(), mBaseSystemMatrix.nonZeros(), 0.);
163 for (auto statElem : mMNAComponents)
164 statElem->mnaApplySystemMatrixStamp(mBaseSystemMatrix);
165
166 SPDLOG_LOGGER_INFO(mSLog, "Initial system matrix with variable elements {}",
168 /* TODO: find replacement for flush() */
169 mSLog->flush();
170
171 // Calculate factorization of current matrix
175
176 auto start = std::chrono::steady_clock::now();
178 auto end = std::chrono::steady_clock::now();
179 std::chrono::duration<Real> diff = end - start;
180 mFactorizeTimes.push_back(diff.count());
181}
182
186
187template <typename VarType>
189 Real time, Int timeStepCount) {
190 auto profileStart = std::chrono::steady_clock::now();
191 // Reset source vector
192#ifdef WITH_HIP
193 if (!mHipDeviceAssemblyReady)
194#endif
195 mRightSideVector.setZero();
196 auto profileEnd = std::chrono::steady_clock::now();
198 recordProfileMeasurement("rhs_zero", profileStart, profileEnd);
199
200#ifdef WITH_HIP
201 updateHipSG4PreStep(time);
202#endif
203
204 // Add together the right side vector (computed by the components'
205 // pre-step tasks)
206 profileStart = std::chrono::steady_clock::now();
207#ifdef WITH_HIP
208 if (!mHipDeviceAssemblyReady)
209#endif
211 profileEnd = std::chrono::steady_clock::now();
213 recordProfileMeasurement("rhs_assembly", profileStart, profileEnd);
214
215 // Get switch and variable comp status and update system matrix and lu factorization accordingly
216 profileStart = std::chrono::steady_clock::now();
217#ifdef WITH_HIP
218 if (mHipDeviceAssemblyReady)
220 else
222#else
224#endif
225 profileEnd = std::chrono::steady_clock::now();
227 recordProfileMeasurement("variable_change_detection", profileStart,
228 profileEnd);
231#ifdef WITH_HIP
232 if (mHipSparseDeviceSolver)
233 for (auto &adapter : mHipSG4Adapters)
234 adapter->scatterDeviceMatrix();
235 if (mHipDeviceAssemblyReady && mHipSparseDeviceSolver)
236 mHipSparseDeviceSolver->refactorizeDevice();
237#endif
238
239 // Calculate new solution vector
240 auto start = std::chrono::steady_clock::now();
241 bool synchronizeNodeOutputs = true;
242#ifdef WITH_HIP
243 synchronizeNodeOutputs =
244 !mHipDeviceAssemblyReady || mSLog->should_log(spdlog::level::info);
245 if (mHipSparseDeviceSolver) {
246 if (mHipDeviceAssemblyReady)
247 mHipSparseDeviceSolver->clearDeviceRightHandSide();
248 else
249 mHipSparseDeviceSolver->uploadRightHandSide(mRightSideVector);
250 for (auto &adapter : mHipSG4Adapters)
251 adapter->accumulateDeviceRhs();
252 mHipSparseDeviceSolver->solveDevice(synchronizeNodeOutputs);
253 if (synchronizeNodeOutputs)
254 mHipSparseDeviceSolver->copyDeviceSolutionToHost(*mLeftSideVectorValue);
255 } else
256#endif
257 {
260 }
261 auto end = std::chrono::steady_clock::now();
262 std::chrono::duration<Real> diff = end - start;
263 mSolveTimes.push_back(diff.count());
265 recordProfileMeasurement("numeric_solve", start, end);
266
267#ifdef WITH_HIP
268 if (mHipSparseDeviceSolver) {
269 for (auto &adapter : mHipSG4Adapters)
270 adapter->postStepDevice(*mLeftSideVectorValue,
271 mHipSparseDeviceSolver->deviceSolution(),
272 synchronizeNodeOutputs);
273 } else {
274 updateHipSG4PostStep(*mLeftSideVectorValue);
275 }
276#endif
277
278 // The linear solve above uses the tangent prepared by component pre-steps.
279 // Repeat only for opt-in nonlinear components; existing variable SSN models
280 // keep their previous single-linearization behavior.
281 if (!mNonlinearComps.empty()) {
282 constexpr Int maxNewtonIterations = 40;
283 bool converged = false;
284 for (Int iteration = 0; iteration < maxNewtonIterations; ++iteration) {
285 bool allConverged = true;
286 for (auto &component : mNonlinearComps)
287 allConverged =
288 component->mnaCheckNonlinearConvergence(**mLeftSideVector) &&
289 allConverged;
290 if (allConverged) {
291 converged = true;
292 break;
293 }
294 for (auto &component : mNonlinearComps)
295 component->mnaPrepareNonlinearIteration();
298 mRightSideVector.setZero();
299 for (const auto &stamp : mRightVectorStamps)
300 mRightSideVector += stamp->get();
303 }
304 if (!converged)
305 throw CPS::SystemError(
306 "Nonlinear MNA Newton iteration failed to converge at time " +
307 std::to_string(time));
308 }
309
310 // TODO split into separate task? (dependent on x, updating all v attributes)
311 profileStart = std::chrono::steady_clock::now();
312 if (synchronizeNodeOutputs)
313 for (UInt nodeIdx = 0; nodeIdx < mNumNetNodes; ++nodeIdx)
314 mNodes[nodeIdx]->mnaUpdateVoltage(*mLeftSideVectorValue);
315 profileEnd = std::chrono::steady_clock::now();
317 recordProfileMeasurement("node_voltage_propagation", profileStart,
318 profileEnd);
319
320 // Components' states will be updated by the post-step tasks
321}
322
323template <typename VarType>
325 CPS::Math::ScopedZeroSkipping zeroSkippingScope(this->mZeroSkipping);
326 const auto profileStart = std::chrono::steady_clock::now();
327 // The sparse structure is fixed after initialization. Reset only the
328 // coefficient values instead of copying/reallocating the full sparse
329 // matrix on every timestep.
330 std::copy_n(mBaseSystemMatrix.valuePtr(), mBaseSystemMatrix.nonZeros(),
331 mVariableSystemMatrix.valuePtr());
332
333 // Now stamp variable elements and switches into matrix
334 for (auto comp : mMNAIntfVariableComps)
335 comp->mnaApplySystemMatrixStamp(mVariableSystemMatrix);
336 const auto profileEnd = std::chrono::steady_clock::now();
338 recordProfileMeasurement("matrix_reset_and_variable_stamping", profileStart,
339 profileEnd);
340
341 // Refactorization of matrix assuming that structure remained
342 // constant by omitting analyzePattern
343 auto start = std::chrono::steady_clock::now();
344 mDirectLinearSolverVariableSystemMatrix->partialRefactorize(
346 auto end = std::chrono::steady_clock::now();
347 std::chrono::duration<Real> diff = end - start;
348 mRecomputationTimes.push_back(diff.count());
350 recordProfileMeasurement("partial_refactorization", start, end);
352}
353
354template <typename VarType>
369
371 if (mSwitches.size() > SWITCH_NUM)
372 throw SystemError("Too many Switches.");
373
379 } else {
380 for (std::size_t i = 0; i < (1ULL << mSwitches.size()); i++) {
381 auto bit = std::bitset<SWITCH_NUM>(i);
382 mSwitchedMatrices[bit].push_back(
384 mDirectLinearSolvers[bit].push_back(
386 }
387 }
388}
389
391 if (mSwitches.size() > SWITCH_NUM)
392 throw SystemError("Too many Switches.");
393
394 if (mFrequencyParallel) {
395 for (UInt i = 0; i < std::pow(2, mSwitches.size()); ++i) {
396 for (Int freq = 0; freq < mSystem.mFrequencies.size(); ++freq) {
397 auto bit = std::bitset<SWITCH_NUM>(i);
398 mSwitchedMatrices[bit].push_back(SparseMatrix(
400 mDirectLinearSolvers[bit].push_back(
402 }
403 }
409 } else {
410 for (std::size_t i = 0; i < (1ULL << mSwitches.size()); i++) {
411 auto bit = std::bitset<SWITCH_NUM>(i);
412 mSwitchedMatrices[bit].push_back(SparseMatrix(
414 mDirectLinearSolvers[bit].push_back(
416 }
417 }
418}
419
420template <typename VarType>
421std::shared_ptr<CPS::Task> MnaSolverDirect<VarType>::createSolveTask() {
423#ifdef WITH_HIP
424 initializeHipSG4Adapters();
425#endif
426 return std::make_shared<MnaSolverDirect<VarType>::SolveTask>(*this);
427}
428
429template <typename VarType>
432#ifdef WITH_HIP
433 initializeHipSG4Adapters();
434#endif
435 return std::make_shared<MnaSolverDirect<VarType>::SolveTaskRecomp>(*this);
436}
437
438#ifdef WITH_HIP
439template <typename VarType>
441 if (mHipSG4AdaptersInitialized)
442 return;
443 if (mImplementationInUse != DirectLinearSolverImpl::HIPDense &&
444 mImplementationInUse != DirectLinearSolverImpl::HIPSparseBiCGStab &&
445 mImplementationInUse != DirectLinearSolverImpl::HIPSparseLURefactor &&
446 mImplementationInUse != DirectLinearSolverImpl::HIPSparseQR)
447 return;
448 mHipSG4AdaptersInitialized = true;
449 std::vector<std::shared_ptr<CPS::EMT::Ph3::SynchronGenerator4OrderVBR>>
450 supportedGenerators;
451 std::unordered_set<const CPS::MNAInterface *> seen;
452 auto initializeComponent = [this, &supportedGenerators,
453 &seen](const auto &component) {
454 if (!component || !seen.insert(component.get()).second)
455 return;
456 if (auto generator = std::dynamic_pointer_cast<
458 if (generator->supportsHipBatch())
459 supportedGenerators.push_back(std::move(generator));
460 };
461 for (const auto &component : mMNAComponents)
462 initializeComponent(component);
463 for (const auto &component : mMNAIntfVariableComps)
464 initializeComponent(component);
465 if (!supportedGenerators.empty())
466 mHipSG4Adapters.emplace_back(
467 std::make_unique<HipSG4BatchAdapter>(std::move(supportedGenerators)));
468 if ((mImplementationInUse == DirectLinearSolverImpl::HIPSparseBiCGStab ||
469 mImplementationInUse == DirectLinearSolverImpl::HIPSparseLURefactor) &&
470 !mHipSG4Adapters.empty()) {
471 bool allRightStampsManaged = !mRightVectorStampOperations.empty();
472 for (const auto &operation : mRightVectorStampOperations) {
473 if (!operation.compact) {
474 allRightStampsManaged = false;
475 break;
476 }
477 auto *generator =
478 dynamic_cast<CPS::EMT::Ph3::SynchronGenerator4OrderVBR *>(
479 operation.compact);
480 const bool isSg4 = generator && generator->supportsHipBatch();
481 if (!isSg4) {
482 allRightStampsManaged = false;
483 break;
484 }
485 }
486 if (!allRightStampsManaged)
487 throw std::runtime_error(
488 "HIP sparse solvers require fully supported device-side RHS "
489 "assembly; select the IEEE118 allssn aggregate configuration.");
490 mHipSparseDeviceSolver = dynamic_cast<HipSparseDeviceSolver *>(
491 mDirectLinearSolverVariableSystemMatrix.get());
492 if (!mHipSparseDeviceSolver)
493 throw std::runtime_error(
494 "HIP sparse implementation did not create its device solver");
495 for (auto &adapter : mHipSG4Adapters) {
496 adapter->configureDeviceAssembly(
497 mVariableSystemMatrix, mBaseSystemMatrix,
498 mHipSparseDeviceSolver->deviceValues(),
499 mHipSparseDeviceSolver->deviceRightHandSide());
500 }
501 mHipDeviceAssemblyReady = true;
502 }
503}
504
505template <typename VarType>
507 for (auto &adapter : mHipSG4Adapters)
508 adapter->preStep(time);
509}
510
511template <typename VarType>
513 for (auto &adapter : mHipSG4Adapters)
514 adapter->postStep(leftVector);
515}
516#endif
517
518template <typename VarType>
520 std::unordered_map<const Matrix *, CPS::MNAInterface *> compactStamps;
521 auto collect = [&compactStamps](const auto &components) {
522 for (const auto &component : components) {
523 if (!component->mnaHasCompactRightSideVectorStamp())
524 continue;
525 auto stamp = component->getRightVector();
526 if (stamp->get().size() != 0)
527 compactStamps.emplace(&stamp->get(), component.get());
528 }
529 };
530 collect(mMNAComponents);
531 collect(mMNAIntfVariableComps);
532
533 // Resolve compact-vs-dense accumulation once. The solve loop then follows
534 // this ordered list directly instead of hashing every RHS stamp each step.
537 for (const auto &stamp : mRightVectorStamps) {
538 const Matrix *stampMatrix = &stamp->get();
539 const auto compact = compactStamps.find(stampMatrix);
540 if (compact != compactStamps.end())
541 mRightVectorStampOperations.push_back({nullptr, compact->second});
542 else
543 mRightVectorStampOperations.push_back({stampMatrix, nullptr});
544 }
545}
546
547template <typename VarType>
549 using Clock = std::chrono::steady_clock;
550 const bool profile = Solver::mLogSolveTimes;
551 const auto start = profile ? Clock::now() : Clock::time_point{};
552 std::chrono::nanoseconds compactTime{};
553 for (const auto &operation : mRightVectorStampOperations) {
554 if (operation.compact) {
555 const auto compactStart = profile ? Clock::now() : Clock::time_point{};
556 operation.compact->mnaAddCompactRightSideVectorStamp(rightVector);
557 if (profile)
558 compactTime += std::chrono::duration_cast<std::chrono::nanoseconds>(
559 Clock::now() - compactStart);
561 } else {
562 rightVector += *operation.dense;
564 }
565 }
566 if (profile) {
567 const auto end = Clock::now();
568 recordProfileMeasurement("rhs_compact_stamp_callbacks", start,
569 start + compactTime);
570 recordProfileMeasurement("rhs_dense_stamp_accumulation",
571 start + compactTime, end);
572 }
573}
574
575template <typename VarType>
576std::shared_ptr<CPS::Task>
578 return std::make_shared<MnaSolverDirect<VarType>::SolveTaskHarm>(*this,
579 freqIdx);
580}
581
582template <typename VarType>
583std::shared_ptr<CPS::Task>
588
589template <typename VarType>
590std::shared_ptr<CPS::Task> MnaSolverDirect<VarType>::createLogTask() {
591 return std::make_shared<MnaSolverDirect<VarType>::LogTask>(*this);
592}
593
594template <typename VarType>
595void MnaSolverDirect<VarType>::solve(Real time, Int timeStepCount) {
596 const bool profile = Solver::mLogSolveTimes;
597 const auto previousSwitchStatus = mCurrentSwitchStatus;
598 // Reset source vector
599 auto profileStart = profile ? std::chrono::steady_clock::now()
600 : std::chrono::steady_clock::time_point{};
601 mRightSideVector.setZero();
602 if (profile)
603 recordProfileMeasurement("rhs_zero", profileStart,
604 std::chrono::steady_clock::now());
605
606#ifdef WITH_HIP
607 updateHipSG4PreStep(time);
608#endif
609
610 // Add together the right side vector (computed by the components' pre-step tasks)
612
613 if (!mIsInInitialization) {
614 profileStart = profile ? std::chrono::steady_clock::now()
615 : std::chrono::steady_clock::time_point{};
617 if (profile)
618 recordProfileMeasurement("switch_status_update", profileStart,
619 std::chrono::steady_clock::now());
620 }
621
622 if (mSwitchedMatrices.size() > 0) {
623 std::chrono::steady_clock::time_point start;
624 if (profile)
625 start = std::chrono::steady_clock::now();
626
629
630 if (profile) {
631 auto end = std::chrono::steady_clock::now();
632 std::chrono::duration<Real> diff = end - start;
633 mSolveTimes.push_back(diff.count());
634 recordProfileMeasurement("numeric_solve", start, end);
635 }
636 }
637
638 // CHECK: Is this really required? Or can operations actually become part of
639 // correctorStep and mnaPostStep?
640 profileStart = profile ? std::chrono::steady_clock::now()
641 : std::chrono::steady_clock::time_point{};
642 for (auto syncGen : mSyncGen)
643 syncGen->updateVoltage(*mLeftSideVectorValue);
644 if (profile)
645 recordProfileMeasurement("iterative_generator_voltage_update", profileStart,
646 std::chrono::steady_clock::now());
647
648 // Reset number of iterations
649 mIter = 0;
650
651 // Additional solve steps for iterative models
652 if (mSyncGen.size() > 0) {
653 UInt numCompsRequireIter;
654 do {
655 // count synchronous generators that require iteration
656 numCompsRequireIter = 0;
657 profileStart = profile ? std::chrono::steady_clock::now()
658 : std::chrono::steady_clock::time_point{};
659 for (auto syncGen : mSyncGen)
660 if (syncGen->requiresIteration())
661 numCompsRequireIter++;
662 if (profile)
663 recordProfileMeasurement("iterative_generator_convergence_check",
664 profileStart,
665 std::chrono::steady_clock::now());
666
667 // recompute solve step if at least one component demands iteration
668 if (numCompsRequireIter > 0) {
669 mIter++;
670
671 // Reset source vector
672 mRightSideVector.setZero();
673
676
677 profileStart = profile ? std::chrono::steady_clock::now()
678 : std::chrono::steady_clock::time_point{};
679 for (auto syncGen : mSyncGen)
680 syncGen->correctorStep();
681 if (profile)
682 recordProfileMeasurement("iterative_generator_corrector",
683 profileStart,
684 std::chrono::steady_clock::now());
685
686 // Add together the right side vector (computed by the components' pre-step tasks)
688
689 if (mSwitchedMatrices.size() > 0) {
690 auto start = std::chrono::steady_clock::now();
693 auto end = std::chrono::steady_clock::now();
694 std::chrono::duration<Real> diff = end - start;
695 mSolveTimes.push_back(diff.count());
696 if (profile)
697 recordProfileMeasurement("numeric_solve", start, end);
698 }
699
700 // CHECK: Is this really required? Or can operations actually become part of
701 // correctorStep and mnaPostStep?
702 profileStart = profile ? std::chrono::steady_clock::now()
703 : std::chrono::steady_clock::time_point{};
704 for (auto syncGen : mSyncGen)
705 syncGen->updateVoltage(*mLeftSideVectorValue);
706 if (profile)
707 recordProfileMeasurement("iterative_generator_voltage_update",
708 profileStart,
709 std::chrono::steady_clock::now());
710 }
711 } while (numCompsRequireIter > 0);
712 }
713
714#ifdef WITH_HIP
715 updateHipSG4PostStep(*mLeftSideVectorValue);
716#endif
717
718 mSystemMatrixChanged = (mCurrentSwitchStatus != previousSwitchStatus);
719
720 // TODO split into separate task? (dependent on x, updating all v attributes)
721 profileStart = profile ? std::chrono::steady_clock::now()
722 : std::chrono::steady_clock::time_point{};
723 for (UInt nodeIdx = 0; nodeIdx < mNumNetNodes; ++nodeIdx)
724 mNodes[nodeIdx]->mnaUpdateVoltage(*mLeftSideVectorValue);
725 if (profile)
726 recordProfileMeasurement("node_voltage_propagation", profileStart,
727 std::chrono::steady_clock::now());
728
729 // Components' states will be updated by the post-step tasks
730}
731
732template <typename VarType>
734 Int freqIdx) {
735 mRightSideVectorHarm[freqIdx].setZero();
736
737 // Sum of right side vectors (computed by the components' pre-step tasks)
738 for (const auto &stamp : mRightVectorStamps)
739 mRightSideVectorHarm[freqIdx] += stamp->get().col(freqIdx);
740
741 // Frequency solve tasks execute concurrently. Derive the switch-state key
742 // locally instead of mutating the shared mCurrentSwitchStatus bitset from
743 // each frequency worker.
744 std::bitset<SWITCH_NUM> switchStatus;
745 for (UInt i = 0; i < mSwitches.size(); ++i)
746 switchStatus.set(i, mSwitches[i]->mnaIsClosed());
747
748 mDirectLinearSolvers[switchStatus][freqIdx]->solveInto(
749 mRightSideVectorHarm[freqIdx], **mLeftSideVectorHarm[freqIdx]);
750}
751
752template <typename VarType> void MnaSolverDirect<VarType>::logSystemMatrices() {
753 if (mFrequencyParallel) {
754 for (UInt i = 0; i < mSwitchedMatrices[std::bitset<SWITCH_NUM>(0)].size();
755 ++i) {
756 SPDLOG_LOGGER_INFO(mSLog, "System matrix for frequency: {:d} \n{:s}", i,
758 mSwitchedMatrices[std::bitset<SWITCH_NUM>(0)][i]));
759 }
760
761 for (UInt i = 0; i < mRightSideVectorHarm.size(); ++i) {
762 SPDLOG_LOGGER_INFO(mSLog, "Right side vector for frequency: {:d} \n{:s}",
764 }
765
767 SPDLOG_LOGGER_INFO(mSLog, "Summarizing matrices: ");
768 SPDLOG_LOGGER_INFO(mSLog, "Base matrix with only static elements: {}",
770 SPDLOG_LOGGER_INFO(mSLog, "Initial system matrix with variable elements {}",
772 SPDLOG_LOGGER_INFO(mSLog, "Right side vector: {}",
774 } else {
775 if (mSwitches.size() < 1) {
776 SPDLOG_LOGGER_INFO(mSLog, "System matrix: \n{}",
777 mSwitchedMatrices[std::bitset<SWITCH_NUM>(0)][0]);
778 } else {
779 SPDLOG_LOGGER_INFO(mSLog, "Initial switch status: {:s}",
780 mCurrentSwitchStatus.to_string());
781
782 for (auto sys : mSwitchedMatrices) {
783 SPDLOG_LOGGER_INFO(mSLog, "Switching System matrix {:s} \n{:s}",
784 sys.first.to_string(),
785 Logger::matrixToString(sys.second[0]));
786 }
787 }
788 SPDLOG_LOGGER_INFO(mSLog, "Right side vector: \n{}", mRightSideVector);
789 }
790}
791
792template <typename VarType> void MnaSolverDirect<VarType>::logLUTimes() {
793 const auto safeName = safeLogFileComponent(this->mName);
796 logSolveTime();
797 for (const auto &entry : mProfileMeasurements) {
798 const auto &measurement = entry.second;
799 const double averageNs =
800 measurement.count == 0
801 ? 0.
802 : static_cast<double>(measurement.total.count()) /
803 measurement.count;
804 SPDLOG_LOGGER_INFO(mSLog,
805 "DEEP_TIMING_PHASE,{},{:.9f},{:.3f},{:.3f},{:.3f},{}",
806 entry.first, measurement.total.count() * 1e-9,
807 averageNs * 1e-3, measurement.minimum.count() * 1e-3,
808 measurement.maximum.count() * 1e-3, measurement.count);
809 }
810 std::ofstream phaseFile(CPS::Logger::logDir() + "/" + safeName +
811 "_SolverPhaseTimes.csv");
812 phaseFile << "phase,total_s,avg_us,min_us,max_us,calls\n";
813 for (const auto &entry : mProfileMeasurements) {
814 const auto &measurement = entry.second;
815 const double count = static_cast<double>(measurement.count);
816 phaseFile << entry.first << "," << measurement.total.count() * 1e-9 << ","
817 << (count ? measurement.total.count() / count * 1e-3 : 0.) << ","
818 << measurement.minimum.count() * 1e-3 << ","
819 << measurement.maximum.count() * 1e-3 << "," << measurement.count
820 << "\n";
821 }
822 phaseFile << "rhs_dense_stamp_component_calls,0,0,0,0,"
824 phaseFile << "rhs_compact_stamp_component_calls,0,0,0,0,"
826 for (const auto &operation : mRightVectorStampOperations)
827 if (operation.compact)
828 operation.compact->mnaWriteProfile(phaseFile);
829 if (auto dense = std::dynamic_pointer_cast<DenseLUAdapter>(
831 dense->writeDetailedProfile(phaseFile);
832 if (auto dense = std::dynamic_pointer_cast<DenseLUAdapter>(
834 std::ofstream diagnostics(CPS::Logger::logDir() + "/" + safeName +
835 "_SolverDiagnostics.csv");
836 dense->writeDetailedDiagnostics(diagnostics);
837 }
838 std::ofstream matrixFile(CPS::Logger::logDir() + "/" + safeName +
839 "_SolverMatrixStats.csv");
840 const SparseMatrix *profiledMatrix = &mVariableSystemMatrix;
841 const char *matrixSource = "variable_system_matrix";
843 const auto activeMatrix = mSwitchedMatrices.find(mCurrentSwitchStatus);
844 if (activeMatrix != mSwitchedMatrices.end() &&
845 !activeMatrix->second.empty()) {
846 profiledMatrix = &activeMatrix->second.front();
847 matrixSource = "active_switched_matrix";
848 }
849 }
850 matrixFile
851 << "source,rows,cols,nonzeros,structural_density,variable_entries\n";
852 const double matrixSize = static_cast<double>(profiledMatrix->rows());
853 const double matrixEntries = matrixSize * matrixSize;
854 matrixFile << matrixSource << "," << profiledMatrix->rows() << ","
855 << profiledMatrix->cols() << "," << profiledMatrix->nonZeros()
856 << ","
857 << (matrixEntries ? profiledMatrix->nonZeros() / matrixEntries
858 : 0.)
859 << "," << mListVariableSystemMatrixEntries.size() << "\n";
860 if (!mFactorizeTimes.empty()) {
861 const Real total = std::accumulate(mFactorizeTimes.begin(),
862 mFactorizeTimes.end(), Real(0.));
863 const auto bounds =
864 std::minmax_element(mFactorizeTimes.begin(), mFactorizeTimes.end());
865 phaseFile << "initial_factorization," << total << ","
866 << total * 1e6 / mFactorizeTimes.size() << ","
867 << *bounds.first * 1e6 << "," << *bounds.second * 1e6 << ","
868 << mFactorizeTimes.size() << "\n";
869 }
870}
871
872template <typename VarType>
874 const String &phase, std::chrono::steady_clock::time_point start,
875 std::chrono::steady_clock::time_point end) {
876 const auto elapsed =
877 std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);
878 auto &measurement = mProfileMeasurements[phase];
879 if (measurement.count == 0) {
880 measurement.minimum = elapsed;
881 measurement.maximum = elapsed;
882 } else {
883 measurement.minimum = std::min(measurement.minimum, elapsed);
884 measurement.maximum = std::max(measurement.maximum, elapsed);
885 }
886 measurement.total += elapsed;
887 ++measurement.count;
888}
889
890template <typename VarType> void MnaSolverDirect<VarType>::logSolveTime() {
891 Real solveSum = 0.0;
892 Real solveMax = 0.0;
893 for (auto meas : mSolveTimes) {
894 solveSum += meas;
895 if (meas > solveMax)
896 solveMax = meas;
897 }
898 SPDLOG_LOGGER_INFO(mSLog, "Cumulative solve times: {:.12f}", solveSum);
899 SPDLOG_LOGGER_INFO(mSLog, "Average solve time: {:.12f}",
900 solveSum / static_cast<double>(mSolveTimes.size()));
901 SPDLOG_LOGGER_INFO(mSLog, "Maximum solve time: {:.12f}", solveMax);
902 SPDLOG_LOGGER_INFO(mSLog, "Number of solves: {:d}", mSolveTimes.size());
903}
904
905template <typename VarType>
907 for (auto meas : mFactorizeTimes) {
908 SPDLOG_LOGGER_INFO(mSLog, "LU factorization time: {:.12f}", meas);
909 }
910}
911
912template <typename VarType>
914 Real recompSum = 0.0;
915 Real recompMax = 0.0;
916 for (auto meas : mRecomputationTimes) {
917 recompSum += meas;
918 if (meas > recompMax)
919 recompMax = meas;
920 }
921 // Sometimes, refactorization is not used
922 if (mRecomputationTimes.size() != 0) {
923 SPDLOG_LOGGER_INFO(mSLog, "Cumulative refactorization times: {:.12f}",
924 recompSum);
925 SPDLOG_LOGGER_INFO(mSLog, "Average refactorization time: {:.12f}",
926 recompSum / ((double)mRecomputationTimes.size()));
927 SPDLOG_LOGGER_INFO(mSLog, "Maximum refactorization time: {:.12f}",
928 recompMax);
929 SPDLOG_LOGGER_INFO(mSLog, "Number of refactorizations: {:d}",
930 mRecomputationTimes.size());
931 }
932}
933
934template <typename VarType>
935std::shared_ptr<DirectLinearSolver>
938 switch (this->mImplementationInUse) {
940 return std::make_shared<DenseLUAdapter>(mSLog);
941#ifdef WITH_SPARSE
943 return std::make_shared<SparseLUAdapter>(mSLog);
944#endif // WITH_SPARSE
945#ifdef WITH_KLU
947 return std::make_shared<KLUAdapter>(mSLog);
948#endif
949#ifdef WITH_CUDA
951 return std::make_shared<GpuDenseAdapter>(mSLog);
952#ifdef WITH_CUDA_SPARSE
954 return std::make_shared<GpuSparseAdapter>(mSLog);
955#endif
956#ifdef WITH_MAGMA
958 return std::make_shared<GpuMagmaAdapter>(mSLog);
959#endif
960#endif
961#ifdef WITH_METAL
963 return std::make_shared<MetalDenseAdapter>(mSLog);
965 return std::make_shared<MetalSparseBiCGSTABAdapter>(mSLog);
966#endif
967#ifdef WITH_HIP
969 return std::make_shared<HipSparseQrAdapter>(mSLog);
971 return std::make_shared<HipDenseAdapter>(mSLog);
973 return std::make_shared<HipSparseBiCGStabAdapter>(mSLog);
975#ifdef WITH_KLU
976 return std::make_shared<HipSparseLURefactorAdapter>(mSLog);
977#else
978 throw CPS::SystemError(
979 "HIP sparse LU refactorization requires the KLU seed solver");
980#endif
981#endif
982 default:
983 throw CPS::SystemError("unsupported linear solver implementation.");
984 }
985}
986
987template <typename VarType>
992
993template <typename VarType>
998
999} // namespace DPsim
1000
1001template class DPsim::MnaSolverDirect<Real>;
1002template class DPsim::MnaSolverDirect<Complex>;
#define SWITCH_NUM
Definition MNASolver.h:36
Voltage-Behind-Reactance (VBR) implementation of 4th order synchronous generator model.
spdlog::level::level_enum Level
Definition Logger.h:33
std::shared_ptr< spdlog::logger > Log
Definition Logger.h:34
static String logDir()
Definition Logger.cpp:81
static String matrixToString(const Matrix &mat)
Definition Logger.cpp:31
std::vector< Ptr > List
static void clearSparseMatrixValueCache(SparseMatrixRow &mat)
static void prepareSparseMatrixValueCache(SparseMatrixRow &mat)
Solver class using Modified Nodal Analysis (MNA).
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
CPS::SystemTopology mSystem
System topology.
Definition MNASolver.h:65
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
UInt mNumTotalMatrixNodeIndices
Total number of network and virtual nodes, considering individual phases and additional frequencies.
Definition MNASolver.h:60
CPS::MNASyncGenInterface::List mSyncGen
List of synchronous generators that need iterate to solve the differential equations.
Definition MNASolver.h:82
void updateSwitchStatus()
Collects the status of switches to select correct system matrix.
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
UInt mNumMatrixNodeIndices
Number of network and virtual nodes, considering individual phases.
Definition MNASolver.h:52
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
String mName
Name for logging.
Definition Solver.h:54
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 mLogSolveTimes
Collect step time for logging.
Definition Solver.h:58
Bool mFrequencyParallel
Activates parallelized computation of frequencies.
Definition Solver.h:64
Bool mZeroSkipping
Skip exact zero contributions during matrix assembly (enabled by default).
Definition Solver.h:84
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::SparseMatrixRow SparseMatrix
Definition Definitions.h:26
DirectLinearSolverImpl
@ HIPSparseLURefactor
@ HIPSparseBiCGStab
@ MetalSparseBiCGSTAB
CPS::UInt UInt
Definition Definitions.h:23