DPsim
Loading...
Searching...
No Matches
MNASolver.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 <algorithm>
10#include <dpsim/MNASolver.h>
12#include <functional>
13#include <memory>
14#include <stdexcept>
15#include <type_traits>
16#include <utility>
17
18using namespace DPsim;
19using namespace CPS;
20
21namespace DPsim {
22
23template <typename VarType>
25 CPS::Logger::Level logLevel)
26 : Solver(name, logLevel), mDomain(domain) {
27
28 // Raw source and solution vector logging
29 mLeftVectorLog = std::make_shared<DataLogger>(
30 name + "_LeftVector", logLevel == CPS::Logger::Level::trace);
31 mRightVectorLog = std::make_shared<DataLogger>(
32 name + "_RightVector", logLevel == CPS::Logger::Level::trace);
33}
34
35template <typename VarType>
37 mSystem = system;
38}
39
40template <typename VarType>
42 const CPS::MNAInterface::Ptr &component) {
43 auto rightVector = component->getRightVector();
44 const Matrix &stamp = rightVector->get();
45 if (stamp.size() == 0)
46 return;
47
48 std::vector<UInt> indices;
49 const Bool hasIndices = component->getRightVectorStampIndices(indices);
50 mRightVectorStamps.push_back(std::move(rightVector));
51 mRightVectorStampIndices.push_back(std::move(indices));
52 mRightVectorStampUsesIndices.push_back(hasIndices);
53}
54
55template <typename VarType>
57 Int stampColumn) const {
58 for (std::size_t stampIdx = 0; stampIdx < mRightVectorStamps.size();
59 ++stampIdx) {
60 const Matrix &stamp = mRightVectorStamps[stampIdx]->get();
61 if (mRightVectorStampUsesIndices[stampIdx]) {
62 for (UInt row : mRightVectorStampIndices[stampIdx]) {
63 if (stampColumn < 0)
64 rightVector(row) += stamp(row);
65 else
66 rightVector(row) += stamp(row, stampColumn);
67 }
68 } else if (stampColumn < 0) {
69 rightVector += stamp;
70 } else {
71 rightVector += stamp.col(stampColumn);
72 }
73 }
74}
75
76template <typename VarType>
80
81template <typename VarType>
85 throw std::logic_error(
86 "MNA state-space extractor has not been initialized.");
87
89}
90
91template <typename VarType> void MnaSolver<VarType>::initialize() {
93 // TODO: check that every system matrix has the same dimensions
94 SPDLOG_LOGGER_INFO(mSLog, "---- Start initialization ----");
95 mLeftVectorLog->start();
96 mRightVectorLog->start();
97
98 // Register attribute for solution vector
100 // Best case we have some kind of sub-attributes for attribute vectors / tensor attributes...
101 if (mFrequencyParallel) {
102 SPDLOG_LOGGER_INFO(mSLog, "Computing network harmonics in parallel.");
103 for (Int freq = 0; freq < mSystem.mFrequencies.size(); ++freq) {
105 }
106 } else {
109 }
110
111 SPDLOG_LOGGER_INFO(mSLog, "-- Process topology");
112 for (auto comp : mSystem.mComponents)
113 SPDLOG_LOGGER_INFO(mSLog, "Added {:s} '{:s}' to simulation.", comp->type(),
114 comp->name());
115
116 // Otherwise LU decomposition will fail
117 if (mSystem.mComponents.size() == 0)
118 throw SolverException();
119
120 // We need to differentiate between power and signal components and
121 // ground nodes should be ignored.
124
126 throw CPS::SystemError("System-matrix recomputation is not supported with "
127 "frequency-parallel MNA.");
128 }
129
130 // Ensure all subcomponents (and their virtual nodes) are registered before
131 // collectVirtualNodes() sizes the system matrices. Recurses into nested
132 // sub-components so e.g. SST -> Load -> {R, L, C} is fully created.
133 CPS::MNAInterface::List allMNAComps;
134 allMNAComps.insert(allMNAComps.end(), mMNAComponents.begin(),
135 mMNAComponents.end());
136 allMNAComps.insert(allMNAComps.end(), mMNAIntfVariableComps.begin(),
138 allMNAComps.insert(allMNAComps.end(), mMNAIntfSwitches.begin(),
139 mMNAIntfSwitches.end());
140
141 // Some composites (e.g. AvVoltageSourceInverterDQ) eagerly create and
142 // register their subcomponents in their own constructor, before those
143 // subcomponents are connected (connect() only happens later, in
144 // initializeParentFromNodesAndTerminals()). Calling createSubComponents()
145 // on such a not-yet-connected subcomponent crashes, since it relies on
146 // its own terminals being wired up. Only subcomponents that are newly
147 // registered as a direct result of THIS createSubComponents() call (the
148 // lazy create+connect+register pattern, e.g. SST -> Load -> {R, L, C})
149 // are guaranteed to already be connected, so only recurse into those.
150 std::function<void(CPS::MNAInterface::Ptr)> createSubComponentsRec =
151 [&](CPS::MNAInterface::Ptr comp) {
152 auto pComp =
153 std::dynamic_pointer_cast<CPS::SimPowerComp<VarType>>(comp);
154 typename CPS::SimPowerComp<VarType>::List subCompsBefore =
155 pComp ? pComp->subComponents()
157
158 comp->createSubComponents();
159
160 if (pComp) {
161 for (auto subComp : pComp->subComponents()) {
162 bool isNew = std::find(subCompsBefore.begin(), subCompsBefore.end(),
163 subComp) == subCompsBefore.end();
164 if (!isNew)
165 continue;
166 if (auto subMna =
167 std::dynamic_pointer_cast<CPS::MNAInterface>(subComp))
168 createSubComponentsRec(subMna);
169 }
170 }
171 };
172 for (auto comp : allMNAComps)
173 createSubComponentsRec(comp);
174 // These steps complete the network information.
177
178 SPDLOG_LOGGER_INFO(mSLog, "-- Create empty MNA system matrices and vectors");
181
182 // Initialize components from powerflow solution and
183 // calculate MNA specific initialization values.
185
186 if (mSteadyStateInit) {
187 mIsInInitialization = true;
189 }
190 mIsInInitialization = false;
191
192 // Some components feature a different behaviour for simulation and initialization
193 for (auto comp : mSystem.mComponents) {
194 auto powerComp = std::dynamic_pointer_cast<CPS::TopologicalPowerComp>(comp);
195 if (powerComp)
196 powerComp->setBehaviour(TopologicalPowerComp::Behaviour::MNASimulation);
197
198 auto sigComp = std::dynamic_pointer_cast<CPS::SimSignalComp>(comp);
199 if (sigComp)
200 sigComp->setBehaviour(SimSignalComp::Behaviour::Simulation);
201 }
202
203 // Initialize system matrices and source vector.
205
208
209 SPDLOG_LOGGER_INFO(mSLog, "--- Initialization finished ---");
210 SPDLOG_LOGGER_INFO(mSLog, "--- Initial system matrices and vectors ---");
212
213 mSLog->flush();
214}
215
217 SPDLOG_LOGGER_INFO(mSLog, "-- Initialize components from power flow");
218
219 CPS::MNAInterface::List allMNAComps;
220 allMNAComps.insert(allMNAComps.end(), mMNAComponents.begin(),
221 mMNAComponents.end());
222 allMNAComps.insert(allMNAComps.end(), mMNAIntfVariableComps.begin(),
224
225 for (auto comp : allMNAComps) {
226 auto pComp = std::dynamic_pointer_cast<SimPowerComp<Real>>(comp);
227 if (!pComp)
228 continue;
229 pComp->checkForUnconnectedTerminals();
231 pComp->initializeFromNodesAndTerminals(mSystem.mSystemFrequency);
232 }
233
234 // Initialize signal components.
235 for (auto comp : mSimSignalComps)
236 comp->initialize(mSystem.mSystemOmega, mTimeStep);
237
238 // Initialize MNA specific parts of components.
239 for (auto comp : allMNAComps) {
240 comp->mnaInitialize(mSystem.mSystemOmega, mTimeStep, mLeftSideVector);
242 }
243
244 for (auto comp : mMNAIntfSwitches)
245 comp->mnaInitialize(mSystem.mSystemOmega, mTimeStep, mLeftSideVector);
246
247 // Initialize nodes
248 for (UInt nodeIdx = 0; nodeIdx < mNodes.size(); ++nodeIdx)
249 mNodes[nodeIdx]->initialize();
250}
251
253 SPDLOG_LOGGER_INFO(mSLog, "-- Initialize components from power flow");
254
255 CPS::MNAInterface::List allMNAComps;
256 allMNAComps.insert(allMNAComps.end(), mMNAComponents.begin(),
257 mMNAComponents.end());
258 allMNAComps.insert(allMNAComps.end(), mMNAIntfVariableComps.begin(),
260
261 // Initialize power components with frequencies and from powerflow results
262 for (auto comp : allMNAComps) {
263 auto pComp = std::dynamic_pointer_cast<SimPowerComp<Complex>>(comp);
264 if (!pComp)
265 continue;
266 pComp->checkForUnconnectedTerminals();
268 pComp->initializeFromNodesAndTerminals(mSystem.mSystemFrequency);
269 }
270
271 // Initialize signal components.
272 for (auto comp : mSimSignalComps)
273 comp->initialize(mSystem.mSystemOmega, mTimeStep);
274
275 SPDLOG_LOGGER_INFO(mSLog, "-- Initialize MNA properties of components");
276 if (mFrequencyParallel) {
277 // Initialize MNA specific parts of components.
278 for (auto comp : mMNAComponents) {
279 // Initialize MNA specific parts of components.
280 comp->mnaInitializeHarm(mSystem.mSystemOmega, mTimeStep,
283 }
284 // Switch interfaces are stored separately from mMNAComponents, but their
285 // matrix node indices and DP state must still be initialized before the
286 // solver builds the per-frequency matrices for each switch combination.
287 for (auto sw : mMNAIntfSwitches)
288 sw->mnaInitializeHarm(mSystem.mSystemOmega, mTimeStep,
290 // Initialize nodes
291 for (UInt nodeIdx = 0; nodeIdx < mNodes.size(); ++nodeIdx) {
292 mNodes[nodeIdx]->mnaInitializeHarm(mLeftSideVectorHarm);
293 }
294 } else {
295 // Initialize MNA specific parts of components.
296 for (auto comp : allMNAComps) {
297 comp->mnaInitialize(mSystem.mSystemOmega, mTimeStep, mLeftSideVector);
299 }
300
301 for (auto comp : mMNAIntfSwitches)
302 comp->mnaInitialize(mSystem.mSystemOmega, mTimeStep, mLeftSideVector);
303
304 // Initialize nodes
305 for (UInt nodeIdx = 0; nodeIdx < mNodes.size(); ++nodeIdx)
306 mNodes[nodeIdx]->initialize();
307 }
308}
309
310template <typename VarType> void MnaSolver<VarType>::initializeSystem() {
311 SPDLOG_LOGGER_INFO(mSLog,
312 "-- Initialize MNA system matrices and source vector");
313 mRightSideVector.setZero();
314
315 // just a sanity check in case we change the static
316 // initialization of the switch number in the future
317 if (mSwitches.size() > sizeof(std::size_t) * 8) {
318 throw SystemError("Too many Switches.");
319 }
320
325 else
327}
328
329template <typename VarType>
331 // iterate over all possible switch state combinations and frequencies
332 for (std::size_t sw = 0; sw < (1ULL << mSwitches.size()); ++sw) {
333 for (Int freq = 0; freq < mSystem.mFrequencies.size(); ++freq) {
334 switchedMatrixEmpty(sw, freq);
336 }
337 }
338
339 if (mSwitches.size() > 0)
341
342 // Initialize source vector
343 for (Int freq = 0; freq < mSystem.mFrequencies.size(); ++freq) {
344 for (auto comp : mMNAComponents)
345 comp->mnaApplyRightSideVectorStampHarm(mRightSideVectorHarm[freq], freq);
346 }
347}
348
349template <typename VarType>
351 // iterate over all possible switch state combinations
352 for (std::size_t i = 0; i < (1ULL << mSwitches.size()); i++) {
354 }
355
356 if (mSwitches.size() < 1) {
358 } else {
359 // Generate switching state dependent system matrices
360 for (std::size_t i = 0; i < (1ULL << mSwitches.size()); i++) {
362 }
364 }
365
366 // Initialize source vector for debugging
367 // CAUTION: this does not always deliver proper source vector initialization
368 // as not full pre-step is executed (not involving necessary electrical or signal
369 // subcomp updates before right vector calculation)
370 for (auto comp : mMNAComponents) {
371 comp->mnaApplyRightSideVectorStamp(mRightSideVector);
372 auto idObj = std::dynamic_pointer_cast<IdentifiedObject>(comp);
373 SPDLOG_LOGGER_DEBUG(mSLog, "Stamping {:s} {:s} into source vector",
374 idObj->type(), idObj->name());
375 if (mSLog->should_log(spdlog::level::trace))
377 }
378}
379
380template <typename VarType>
382
383 // Collect index pairs of varying matrix entries from components
384 for (auto varElem : mVariableComps)
385 for (auto varEntry : varElem->mVariableSystemMatrixEntries)
386 mListVariableSystemMatrixEntries.push_back(varEntry);
387 SPDLOG_LOGGER_INFO(mSLog, "List of index pairs of varying matrix entries: ");
388 for (auto indexPair : mListVariableSystemMatrixEntries)
389 SPDLOG_LOGGER_INFO(mSLog, "({}, {})", indexPair.first, indexPair.second);
390
392
393 // Initialize source vector for debugging
394 // CAUTION: this does not always deliver proper source vector initialization
395 // as not full pre-step is executed (not involving necessary electrical or signal
396 // subcomp updates before right vector calculation)
397 for (auto comp : mMNAComponents) {
398 comp->mnaApplyRightSideVectorStamp(mRightSideVector);
399 auto idObj = std::dynamic_pointer_cast<IdentifiedObject>(comp);
400 SPDLOG_LOGGER_DEBUG(mSLog, "Stamping {:s} {:s} into source vector",
401 idObj->type(), idObj->name());
402 if (mSLog->should_log(spdlog::level::trace))
404 }
405}
406
407template <typename VarType>
410 throw std::logic_error(
411 "MNA state-space extraction supports EMT and DP domains only.");
412 }
413
414 if (mFrequencyParallel) {
415 throw std::logic_error(
416 "MNA state-space extraction does not support frequency-parallel "
417 "MNA systems.");
418 }
419
420 CPS::MNAInterface::List stateSpaceComponents;
421 stateSpaceComponents.insert(stateSpaceComponents.end(),
422 mMNAComponents.begin(), mMNAComponents.end());
423 stateSpaceComponents.insert(stateSpaceComponents.end(),
424 mMNAIntfVariableComps.begin(),
426
427 const UInt mnaVectorSize = static_cast<UInt>((**mLeftSideVector).rows());
428
429 mStateSpaceExtractor = std::make_shared<MNAStateSpaceExtractor>();
430 mStateSpaceExtractor->initialize(stateSpaceComponents, mnaVectorSize,
431 mTimeStep);
432
433 SPDLOG_LOGGER_INFO(
434 mSLog,
435 "Initialized MNA state-space extractor with {:d} extraction states.",
436 mStateSpaceExtractor->getStateCount());
437}
438
439template <typename VarType>
441 for (UInt i = 0; i < mVariableComps.size(); ++i) {
442 auto &varElem = mVariableComps[i];
443 if (mVariableCompAlwaysDirty[i] || varElem->hasParameterChanged()) {
444 auto idObj = std::dynamic_pointer_cast<IdentifiedObject>(varElem);
445 SPDLOG_LOGGER_DEBUG(
446 mSLog, "Component ({:s} {:s}) value changed -> Update System Matrix",
447 idObj->type(), idObj->name());
448 return true;
449 }
450 }
451 return false;
452}
453
454template <typename VarType> void MnaSolver<VarType>::updateSwitchStatus() {
455 for (UInt i = 0; i < mSwitches.size(); ++i) {
456 mCurrentSwitchStatus.set(i, mSwitches[i]->mnaIsClosed());
457 }
458}
459
460template <typename VarType>
463
464 const auto recomputationComp = std::find_if(
465 mVariableComps.begin(), mVariableComps.end(), [](const auto &comp) {
466 const auto switchComp =
467 std::dynamic_pointer_cast<CPS::MNASwitchInterface>(comp);
468
469 return !switchComp || !switchComp->supportsPrecomputedSystemMatrices();
470 });
471
472 const Bool hasRecomputationComp = recomputationComp != mVariableComps.end();
473
475 case Mode::Auto:
476 mSystemMatrixRecomputationEnabled = hasRecomputationComp;
477
478 if (hasRecomputationComp) {
479 const auto component =
480 std::dynamic_pointer_cast<CPS::IdentifiedObject>(*recomputationComp);
481
482 SPDLOG_LOGGER_INFO(
483 mSLog,
484 "System-matrix recomputation enabled automatically for {:s} '{:s}'.",
485 component->type(), component->name());
486 } else {
487 SPDLOG_LOGGER_INFO(mSLog,
488 "System-matrix recomputation disabled automatically.");
489 }
490 break;
491
492 case Mode::Enabled:
494 SPDLOG_LOGGER_INFO(mSLog, "System-matrix recomputation enabled.");
495 break;
496
497 case Mode::Disabled:
498 if (!mNonlinearComps.empty())
499 throw CPS::SystemError("Cannot disable matrix recomputation with "
500 "nonlinear Newton components.");
502
503 if (hasRecomputationComp) {
504 const auto component =
505 std::dynamic_pointer_cast<CPS::IdentifiedObject>(*recomputationComp);
506
507 SPDLOG_LOGGER_WARN(
508 mSLog,
509 "System-matrix recomputation disabled, but {:s} '{:s}' may require "
510 "it.",
511 component->type(), component->name());
512 } else {
513 SPDLOG_LOGGER_INFO(mSLog, "System-matrix recomputation disabled.");
514 }
515 break;
516 }
517}
518
519template <typename VarType> void MnaSolver<VarType>::identifyTopologyObjects() {
520 for (auto baseNode : mSystem.mNodes) {
521 // Add nodes to the list and ignore ground nodes.
522 if (!baseNode->isGround()) {
523 auto node = std::dynamic_pointer_cast<CPS::SimNode<VarType>>(baseNode);
524 mNodes.push_back(node);
525 SPDLOG_LOGGER_INFO(mSLog, "Added node {:s}", node->name());
526 }
527 }
528
529 for (auto comp : mSystem.mComponents) {
530
531 auto genComp = std::dynamic_pointer_cast<CPS::MNASyncGenInterface>(comp);
532 if (genComp) {
533 mSyncGen.push_back(genComp);
534 }
535
536 auto swComp = std::dynamic_pointer_cast<CPS::MNASwitchInterface>(comp);
537 if (swComp) {
538 mSwitches.push_back(swComp);
539 auto mnaComp = std::dynamic_pointer_cast<CPS::MNAInterface>(swComp);
540 if (mnaComp)
541 mMNAIntfSwitches.push_back(mnaComp);
542 }
543
544 auto varComp =
545 std::dynamic_pointer_cast<CPS::MNAVariableCompInterface>(comp);
546 auto nonlinear =
547 std::dynamic_pointer_cast<CPS::MNANonlinearCompInterface>(comp);
548 if (nonlinear) {
549 if (!varComp || mDomain != CPS::Domain::EMT)
550 throw CPS::SystemError(
551 "Nonlinear Newton components require variable-matrix EMT MNA.");
552 mNonlinearComps.push_back(nonlinear);
553 }
554 if (varComp) {
555 mVariableComps.push_back(varComp);
556 mVariableCompAlwaysDirty.push_back(
557 varComp->hasContinuouslyChangingSystemMatrix());
558 auto mnaComp = std::dynamic_pointer_cast<CPS::MNAInterface>(varComp);
559 if (mnaComp)
560 mMNAIntfVariableComps.push_back(mnaComp);
561 }
562
563 if (!(swComp || varComp)) {
564 auto mnaComp = std::dynamic_pointer_cast<CPS::MNAInterface>(comp);
565 if (mnaComp)
566 mMNAComponents.push_back(mnaComp);
567
568 auto sigComp = std::dynamic_pointer_cast<CPS::SimSignalComp>(comp);
569 if (sigComp)
570 mSimSignalComps.push_back(sigComp);
571 }
572 }
573}
574
575template <typename VarType> void MnaSolver<VarType>::assignMatrixNodeIndices() {
576 UInt matrixNodeIndexIdx = 0;
577 for (UInt idx = 0; idx < mNodes.size(); ++idx) {
578 mNodes[idx]->setMatrixNodeIndex(0, matrixNodeIndexIdx);
579 if (mNodes[idx]->phaseType() == CPS::PhaseType::DC)
580 SPDLOG_LOGGER_INFO(mSLog, "Assigned index {} to DC node {}",
581 matrixNodeIndexIdx, idx);
582 else
583 SPDLOG_LOGGER_INFO(mSLog, "Assigned index {} to phase A of node {}",
584 matrixNodeIndexIdx, idx);
585 ++matrixNodeIndexIdx;
586 if (mNodes[idx]->phaseType() == CPS::PhaseType::ABC) {
587 mNodes[idx]->setMatrixNodeIndex(1, matrixNodeIndexIdx);
588 SPDLOG_LOGGER_INFO(mSLog, "Assigned index {} to phase B of node {}",
589 matrixNodeIndexIdx, idx);
590 ++matrixNodeIndexIdx;
591 mNodes[idx]->setMatrixNodeIndex(2, matrixNodeIndexIdx);
592 SPDLOG_LOGGER_INFO(mSLog, "Assigned index {} to phase C of node {}",
593 matrixNodeIndexIdx, idx);
594 ++matrixNodeIndexIdx;
595 }
596 // This should be true when the final network node is reached, not considering virtual nodes
597 if (idx == mNumNetNodes - 1)
598 mNumNetMatrixNodeIndices = matrixNodeIndexIdx;
599 }
600 // Total number of network nodes including virtual nodes is matrixNodeIndexIdx + 1, which is why the variable is incremented after assignment
601 mNumMatrixNodeIndices = matrixNodeIndexIdx;
605 static_cast<UInt>(mSystem.mFrequencies.size() - 1) *
608 static_cast<UInt>(mSystem.mFrequencies.size()) * mNumMatrixNodeIndices;
609
610 SPDLOG_LOGGER_INFO(mSLog, "Assigned simulation nodes to topology nodes:");
611 SPDLOG_LOGGER_INFO(mSLog, "Number of network simulation nodes: {:d}",
613 SPDLOG_LOGGER_INFO(mSLog, "Number of simulation nodes: {:d}",
615 SPDLOG_LOGGER_INFO(mSLog, "Number of harmonic simulation nodes: {:d}",
617}
618
620 mRightSideVector = Matrix::Zero(mNumMatrixNodeIndices, 1);
621 **mLeftSideVector = Matrix::Zero(mNumMatrixNodeIndices, 1);
622}
623
625 if (mFrequencyParallel) {
626 for (Int freq = 0; freq < mSystem.mFrequencies.size(); ++freq) {
627 mRightSideVectorHarm.push_back(
628 Matrix::Zero(2 * (mNumMatrixNodeIndices), 1));
629 if (mLeftSideVectorHarm.size() <= static_cast<std::size_t>(freq))
631 **mLeftSideVectorHarm[freq] = Matrix::Zero(2 * mNumMatrixNodeIndices, 1);
632 }
633 } else {
634 mRightSideVector = Matrix::Zero(
636 **mLeftSideVector = Matrix::Zero(
638 }
639}
640
641template <typename VarType> void MnaSolver<VarType>::collectVirtualNodes() {
642 // We have not added virtual nodes yet so the list has only network nodes
643 mNumNetNodes = (UInt)mNodes.size();
644 // virtual nodes are placed after network nodes
645 UInt virtualNode = mNumNetNodes - 1;
646
647 for (auto comp : mMNAComponents) {
648 auto pComp = std::dynamic_pointer_cast<SimPowerComp<VarType>>(comp);
649 if (!pComp)
650 continue;
651
652 // Check if component requires virtual node and if so get a reference
653 if (pComp->hasVirtualNodes()) {
654 for (UInt node = 0; node < pComp->virtualNodesNumber(); ++node) {
655 mNodes.push_back(pComp->virtualNode(node));
656 SPDLOG_LOGGER_INFO(mSLog, "Collected virtual node {} of {}",
657 virtualNode, node, pComp->name());
658 }
659 }
660
661 // Repeat the same steps for virtual nodes of sub components
662 // TODO: recursive behavior
663 if (pComp->hasSubComponents()) {
664 for (auto pSubComp : pComp->subComponents()) {
665 for (UInt node = 0; node < pSubComp->virtualNodesNumber(); ++node) {
666 auto vnode = pSubComp->virtualNode(node);
667 // Skip if already registered (e.g. parent reused its VN via
668 // setVirtualNodeAt).
669 bool alreadyRegistered = false;
670 for (auto registeredNode : mNodes) {
671 if (registeredNode == vnode) {
672 alreadyRegistered = true;
673 break;
674 }
675 }
676 if (alreadyRegistered)
677 continue;
678 mNodes.push_back(vnode);
679 SPDLOG_LOGGER_INFO(mSLog, "Collected virtual node {} of {}", node,
680 pSubComp->name());
681 }
682 }
683 }
684 }
685
686 // collect virtual nodes of variable components
687 for (auto comp : mVariableComps) {
688 auto pComp = std::dynamic_pointer_cast<SimPowerComp<VarType>>(comp);
689 if (!pComp)
690 continue;
691
692 // Check if component requires virtual node and if so get a reference
693 if (pComp->hasVirtualNodes()) {
694 for (UInt node = 0; node < pComp->virtualNodesNumber(); ++node) {
695 mNodes.push_back(pComp->virtualNode(node));
696 SPDLOG_LOGGER_INFO(mSLog,
697 "Collected virtual node {} of Varible Comp {}", node,
698 pComp->name());
699 }
700 }
701 }
702
703 // Update node number to create matrices and vectors
704 mNumNodes = (UInt)mNodes.size();
706 SPDLOG_LOGGER_INFO(mSLog, "Created virtual nodes:");
707 SPDLOG_LOGGER_INFO(mSLog, "Number of network nodes: {:d}", mNumNetNodes);
708 SPDLOG_LOGGER_INFO(mSLog, "Number of network and virtual nodes: {:d}",
709 mNumNodes);
710}
711
712template <typename VarType>
714 SPDLOG_LOGGER_INFO(mSLog, "--- Run steady-state initialization ---");
715
716 DataLogger initLeftVectorLog(mName + "_InitLeftVector",
717 mLogLevel != CPS::Logger::Level::off);
718 initLeftVectorLog.start();
719 DataLogger initRightVectorLog(mName + "_InitRightVector",
720 mLogLevel != CPS::Logger::Level::off);
721 initRightVectorLog.start();
722
723 TopologicalPowerComp::Behaviour initBehaviourPowerComps =
725 SimSignalComp::Behaviour initBehaviourSignalComps =
727
728 // TODO: enable use of timestep distinct from simulation timestep
729 Real initTimeStep = mTimeStep;
730
731 Int timeStepCount = 0;
732 Real time = 0;
733 Real maxDiff = 1.0;
734 Real max = 1.0;
735 Matrix diff = Matrix::Zero(2 * mNumNodes, 1);
736 Matrix prevLeftSideVector = Matrix::Zero(2 * mNumNodes, 1);
737
738 SPDLOG_LOGGER_INFO(mSLog,
739 "Time step is {:f}s for steady-state initialization",
740 initTimeStep);
741
742 for (auto comp : mSystem.mComponents) {
743 auto powerComp = std::dynamic_pointer_cast<CPS::TopologicalPowerComp>(comp);
744 if (powerComp)
745 powerComp->setBehaviour(initBehaviourPowerComps);
746
747 auto sigComp = std::dynamic_pointer_cast<CPS::SimSignalComp>(comp);
748 if (sigComp)
749 sigComp->setBehaviour(initBehaviourSignalComps);
750 }
751
754
755 // Use sequential scheduler
757 CPS::Task::List tasks;
758 Scheduler::Edges inEdges, outEdges;
759
760 for (auto node : mNodes) {
761 for (auto task : node->mnaTasks())
762 tasks.push_back(task);
763 }
764 for (auto comp : mMNAComponents) {
765 for (auto task : comp->mnaTasks()) {
766 tasks.push_back(task);
767 }
768 }
769 // TODO signal components should be moved out of MNA solver
770 for (auto comp : mSimSignalComps) {
771 for (auto task : comp->getTasks()) {
772 tasks.push_back(task);
773 }
774 }
775 tasks.push_back(createSolveTask());
776
777 sched.resolveDeps(tasks, inEdges, outEdges);
778 sched.createSchedule(tasks, inEdges, outEdges);
779
780 while (time < mSteadStIniTimeLimit) {
781 // Reset source vector
782 mRightSideVector.setZero();
783
784 sched.step(time, timeStepCount);
785
786 if (mDomain == CPS::Domain::EMT) {
787 initLeftVectorLog.logEMTNodeValues(time, leftSideVector());
788 initRightVectorLog.logEMTNodeValues(time, rightSideVector());
789 } else {
790 initLeftVectorLog.logPhasorNodeValues(time, leftSideVector());
791 initRightVectorLog.logPhasorNodeValues(time, rightSideVector());
792 }
793
794 // Calculate new simulation time
795 time = time + initTimeStep;
796 ++timeStepCount;
797
798 // Calculate difference
799 diff = prevLeftSideVector - **mLeftSideVector;
800 prevLeftSideVector = **mLeftSideVector;
801 maxDiff = diff.lpNorm<Eigen::Infinity>();
802 max = (**mLeftSideVector).template lpNorm<Eigen::Infinity>();
803 // If difference is smaller than some epsilon, break
804 if ((maxDiff / max) < mSteadStIniAccLimit)
805 break;
806 }
807
808 SPDLOG_LOGGER_INFO(mSLog, "Max difference: {:f} or {:f}% at time {:f}",
809 maxDiff, maxDiff / max, time);
810
811 // Reset system for actual simulation
812 mRightSideVector.setZero();
813
814 SPDLOG_LOGGER_INFO(mSLog, "--- Finished steady-state initialization ---");
815}
816
817template <typename VarType> Task::List MnaSolver<VarType>::getTasks() {
818 Task::List l;
819
820 for (auto comp : mMNAComponents) {
821 for (auto task : comp->mnaTasks()) {
822 l.push_back(task);
823 }
824 }
825 for (auto comp : mMNAIntfSwitches) {
826 for (auto task : comp->mnaTasks()) {
827 l.push_back(task);
828 }
829 }
830 for (auto node : mNodes) {
831 for (auto task : node->mnaTasks())
832 l.push_back(task);
833 }
834 for (auto comp : mSimSignalComps) {
835 for (auto task : comp->getTasks()) {
836 l.push_back(task);
837 }
838 }
839
840 if (mFrequencyParallel) {
841 for (UInt i = 0; i < mSystem.mFrequencies.size(); ++i)
842 l.push_back(createSolveTaskHarm(i));
844 for (auto comp : this->mMNAIntfVariableComps) {
845 for (auto task : comp->mnaTasks())
846 l.push_back(task);
847 }
848 l.push_back(createSolveTaskRecomp());
850 l.push_back(createStateSpaceExtractionTask());
851 }
852 } else {
853 l.push_back(createSolveTask());
855 l.push_back(createStateSpaceExtractionTask());
856 }
857 l.push_back(createLogTask());
858 }
859 return l;
860}
861
862template <typename VarType>
863void MnaSolver<VarType>::log(Real time, Int timeStepCount) {
864 if (mLogLevel == Logger::Level::off)
865 return;
866
867 if (mDomain == CPS::Domain::EMT) {
868 mLeftVectorLog->logEMTNodeValues(time, leftSideVector());
869 mRightVectorLog->logEMTNodeValues(time, rightSideVector());
870 } else {
871 mLeftVectorLog->logPhasorNodeValues(time, leftSideVector());
872 mRightVectorLog->logPhasorNodeValues(time, rightSideVector());
873 }
874}
875
876} // namespace DPsim
877
878template class DPsim::MnaSolver<Real>;
879template class DPsim::MnaSolver<Complex>;
spdlog::level::level_enum Level
Definition Logger.h:33
static String matrixToString(const Matrix &mat)
Definition Logger.cpp:31
std::vector< Ptr > List
std::shared_ptr< MNAInterface > Ptr
std::vector< Ptr > List
std::vector< Ptr > List
Definition Task.h:28
void logEMTNodeValues(Real time, const Matrix &data)
void logPhasorNodeValues(Real time, const Matrix &data, Int freqNum=1)
virtual void start() override
Solver class using Modified Nodal Analysis (MNA).
Definition MNASolver.h:40
std::bitset< SWITCH_NUM > mCurrentSwitchStatus
Current status of all switches encoded as bitset.
Definition MNASolver.h:80
virtual void setSystem(const CPS::SystemTopology &system) override
Definition MNASolver.cpp:36
CPS::Domain mDomain
Simulation domain, which can be dynamic phasor (DP) or EMT.
Definition MNASolver.h:44
void resolveSystemMatrixRecomputationMode()
Resolve the requested system-matrix recomputation mode.
Matrix & rightSideVector()
Definition MNASolver.h:245
void identifyTopologyObjects()
Identify Nodes and SimPowerComps and SimSignalComps.
std::vector< Matrix > mRightSideVectorHarm
Source vector of known quantities.
Definition MNASolver.h:97
void addRightVectorStamps(Matrix &rightVector, Int stampColumn=-1) const
Accumulate component RHS stamps, using sparse indices when available.
Definition MNASolver.cpp:56
void steadyStateInitialization()
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
CPS::SystemTopology mSystem
System topology.
Definition MNASolver.h:65
virtual std::shared_ptr< CPS::Task > createStateSpaceExtractionTask()=0
Create state-space extraction task for this solver implementation.
Matrix & leftSideVector()
Definition MNASolver.h:243
Matrix * mLeftSideVectorValue
Cached payload for the per-step solver hot path.
Definition MNASolver.h:224
std::vector< Bool > mVariableCompAlwaysDirty
Definition MNASolver.h:105
void initializeSystemWithVariableMatrix()
Initialization of system matrices and source vector.
virtual void initialize() override
Calls subroutines to set up everything that is required before simulation.
Definition MNASolver.cpp:91
virtual void logSystemMatrices()=0
Logging of system matrices and source vector.
virtual void initializeSystem()
Initialization of system matrices and source vector.
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
std::vector< std::vector< UInt > > mRightVectorStampIndices
Sparse row indices for stamps that can provide their structural support.
Definition MNASolver.h:91
UInt mNumNetMatrixNodeIndices
Number of network nodes, considering individual phases.
Definition MNASolver.h:54
UInt mNumNetNodes
Number of network nodes, single line equivalent.
Definition MNASolver.h:48
virtual void switchedMatrixStamp(std::size_t index, std::vector< std::shared_ptr< CPS::MNAInterface > > &comp)=0
Applies a component stamp to the matrix with the given switch index.
MNAStateSpaceExtractor::Ptr mStateSpaceExtractor
Extractor for the MNA-coupled state-space model.
Definition MNASolver.h:137
virtual void log(Real time, Int timeStepCount) override
Logs left and right vector.
UInt mNumTotalMatrixNodeIndices
Total number of network and virtual nodes, considering individual phases and additional frequencies.
Definition MNASolver.h:60
UInt mNumVirtualMatrixNodeIndices
Number of virtual nodes, considering individual phases.
Definition MNASolver.h:56
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::shared_ptr< DataLogger > mRightVectorLog
Right side vector logger.
Definition MNASolver.h:123
virtual std::shared_ptr< CPS::Task > createSolveTaskHarm(UInt freqIdx)=0
Create a solve task for this solver implementation.
void initializeComponents()
Initialization of individual components.
void updateSwitchStatus()
Collects the status of switches to select correct system matrix.
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
virtual std::shared_ptr< CPS::Task > createSolveTaskRecomp()=0
Create a solve task for recomputation solver.
CPS::MNAInterface::List mMNAComponents
List of MNA components with static stamp into system matrix.
Definition MNASolver.h:71
virtual void stampVariableSystemMatrix()=0
Stamps components into the variable system matrix.
std::shared_ptr< DataLogger > mLeftVectorLog
Left side vector logger.
Definition MNASolver.h:121
UInt mNumMatrixNodeIndices
Number of network and virtual nodes, considering individual phases.
Definition MNASolver.h:52
void initializeSystemWithParallelFrequencies()
Initialization of system matrices and source vector.
CPS::MNANonlinearCompInterface::List mNonlinearComps
Definition MNASolver.h:83
void collectVirtualNodes()
UInt mNumHarmMatrixNodeIndices
Number of nodes, excluding the primary frequency.
Definition MNASolver.h:58
UInt mNumNodes
Number of network and virtual nodes, single line equivalent.
Definition MNASolver.h:46
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
void assignMatrixNodeIndices()
Assign simulation node index according to index in the vector.
UInt mNumVirtualNodes
Number of virtual nodes, single line equivalent.
Definition MNASolver.h:50
std::vector< CPS::Attribute< Matrix >::Ptr > mRightVectorStamps
List of all right side vector contributions.
Definition MNASolver.h:89
void addRightVectorStamp(const CPS::MNAInterface::Ptr &component)
Add a component's RHS stamp and cache any known structural row indices.
Definition MNASolver.cpp:41
void initializeSystemWithPrecomputedMatrices()
Initialization of system matrices and source vector.
CPS::Attribute< Matrix >::Ptr mLeftSideVector
Solution vector of unknown quantities.
Definition MNASolver.h:222
CPS::SimSignalComp::List mSimSignalComps
List of signal type components that do not directly interact with the MNA solver.
Definition MNASolver.h:78
virtual void createEmptySystemMatrix()=0
Create system matrix.
std::vector< Bool > mRightVectorStampUsesIndices
Whether each RHS stamp has valid sparse row indices.
Definition MNASolver.h:93
virtual std::shared_ptr< CPS::Task > createLogTask()=0
Create a solve task for this solver implementation.
const MNAStateSpaceExtractor & getStateSpaceExtractor() const
Read-only access to the MNA state-space extractor.
Definition MNASolver.cpp:83
void doStateSpaceExtraction(Bool value=true)
Enable or disable MNA state-space extraction.
Definition MNASolver.cpp:77
CPS::MNASwitchInterface::List mSwitches
Definition MNASolver.h:74
void createEmptyVectors()
Create left and right side vector.
virtual void switchedMatrixEmpty(std::size_t index)=0
Sets all entries in the matrix with the given switch index to zero.
virtual std::shared_ptr< CPS::Task > createSolveTask()=0
Create a solve task for this solver implementation.
CPS::SimNode< VarType >::List mNodes
List of simulation nodes.
Definition MNASolver.h:67
void initializeStateSpaceExtractor()
Initialization of state-space extraction.
virtual CPS::Task::List getTasks() override
Get tasks for scheduler.
void resolveDeps(CPS::Task::List &tasks, Edges &inEdges, Edges &outEdges)
Definition Scheduler.cpp:92
std::unordered_map< CPS::Task::Ptr, std::deque< CPS::Task::Ptr > > Edges
Definition Scheduler.h:32
void step(Real time, Int timeStepCount)
Performs a single simulation step.
void createSchedule(const CPS::Task::List &tasks, const Edges &inEdges, const Edges &outEdges)
Creates the schedule for the given dependency graph.
String mName
Name for logging.
Definition Solver.h:54
Real mSteadStIniAccLimit
steady state initialization accuracy limit
Definition Solver.h:70
Bool mSystemMatrixRecomputationEnabled
Effective system-matrix recomputation setting used by the solver.
Definition Solver.h:82
Real mTimeStep
Time step for fixed step solvers.
Definition Solver.h:62
CPS::Logger::Log mSLog
Logger.
Definition Solver.h:60
CPS::Logger::Level mLogLevel
Logging level.
Definition Solver.h:56
Bool mIsInInitialization
Determines if solver is in initialization phase, which requires different behavior.
Definition Solver.h:74
Solver(String name, CPS::Logger::Level logLevel)
Definition Solver.h:90
Real mSteadStIniTimeLimit
steady state initialization time limit
Definition Solver.h:68
Bool mInitFromNodesAndTerminals
Definition Solver.h:77
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
Bool mSteadyStateInit
Activates steady state initialization.
Definition Solver.h:72
SystemMatrixRecomputationMode mSystemMatrixRecomputationMode
Requested system-matrix recomputation mode.
Definition Solver.h:79
SystemMatrixRecomputationMode
System-matrix recomputation mode for MNA solvers.
Definition Solver.h:43
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::UInt UInt
Definition Definitions.h:23