23template <
typename VarType>
30 name +
"_LeftVector", logLevel == CPS::Logger::Level::trace);
32 name +
"_RightVector", logLevel == CPS::Logger::Level::trace);
35template <
typename VarType>
40template <
typename VarType>
43 auto rightVector = component->getRightVector();
44 const Matrix &stamp = rightVector->get();
45 if (stamp.size() == 0)
48 std::vector<UInt> indices;
49 const Bool hasIndices = component->getRightVectorStampIndices(indices);
55template <
typename VarType>
57 Int stampColumn)
const {
64 rightVector(row) += stamp(row);
66 rightVector(row) += stamp(row, stampColumn);
68 }
else if (stampColumn < 0) {
71 rightVector += stamp.col(stampColumn);
76template <
typename VarType>
81template <
typename VarType>
85 throw std::logic_error(
86 "MNA state-space extractor has not been initialized.");
94 SPDLOG_LOGGER_INFO(
mSLog,
"---- Start initialization ----");
102 SPDLOG_LOGGER_INFO(
mSLog,
"Computing network harmonics in parallel.");
103 for (
Int freq = 0; freq <
mSystem.mFrequencies.size(); ++freq) {
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(),
117 if (
mSystem.mComponents.size() == 0)
127 "frequency-parallel MNA.");
153 std::dynamic_pointer_cast<CPS::SimPowerComp<VarType>>(comp);
155 pComp ? pComp->subComponents()
158 comp->createSubComponents();
161 for (
auto subComp : pComp->subComponents()) {
162 bool isNew = std::find(subCompsBefore.begin(), subCompsBefore.end(),
163 subComp) == subCompsBefore.end();
167 std::dynamic_pointer_cast<CPS::MNAInterface>(subComp))
168 createSubComponentsRec(subMna);
172 for (
auto comp : allMNAComps)
173 createSubComponentsRec(comp);
178 SPDLOG_LOGGER_INFO(
mSLog,
"-- Create empty MNA system matrices and vectors");
193 for (
auto comp :
mSystem.mComponents) {
194 auto powerComp = std::dynamic_pointer_cast<CPS::TopologicalPowerComp>(comp);
198 auto sigComp = std::dynamic_pointer_cast<CPS::SimSignalComp>(comp);
209 SPDLOG_LOGGER_INFO(
mSLog,
"--- Initialization finished ---");
210 SPDLOG_LOGGER_INFO(
mSLog,
"--- Initial system matrices and vectors ---");
217 SPDLOG_LOGGER_INFO(
mSLog,
"-- Initialize components from power flow");
225 for (
auto comp : allMNAComps) {
226 auto pComp = std::dynamic_pointer_cast<SimPowerComp<Real>>(comp);
229 pComp->checkForUnconnectedTerminals();
231 pComp->initializeFromNodesAndTerminals(
mSystem.mSystemFrequency);
239 for (
auto comp : allMNAComps) {
248 for (
UInt nodeIdx = 0; nodeIdx <
mNodes.size(); ++nodeIdx)
253 SPDLOG_LOGGER_INFO(
mSLog,
"-- Initialize components from power flow");
262 for (
auto comp : allMNAComps) {
263 auto pComp = std::dynamic_pointer_cast<SimPowerComp<Complex>>(comp);
266 pComp->checkForUnconnectedTerminals();
268 pComp->initializeFromNodesAndTerminals(
mSystem.mSystemFrequency);
275 SPDLOG_LOGGER_INFO(
mSLog,
"-- Initialize MNA properties of components");
291 for (
UInt nodeIdx = 0; nodeIdx <
mNodes.size(); ++nodeIdx) {
296 for (
auto comp : allMNAComps) {
305 for (
UInt nodeIdx = 0; nodeIdx <
mNodes.size(); ++nodeIdx)
311 SPDLOG_LOGGER_INFO(
mSLog,
312 "-- Initialize MNA system matrices and source vector");
317 if (
mSwitches.size() >
sizeof(std::size_t) * 8) {
329template <
typename VarType>
332 for (std::size_t sw = 0; sw < (1ULL <<
mSwitches.size()); ++sw) {
333 for (
Int freq = 0; freq <
mSystem.mFrequencies.size(); ++freq) {
343 for (
Int freq = 0; freq <
mSystem.mFrequencies.size(); ++freq) {
349template <
typename VarType>
352 for (std::size_t i = 0; i < (1ULL <<
mSwitches.size()); i++) {
360 for (std::size_t i = 0; i < (1ULL <<
mSwitches.size()); i++) {
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))
380template <
typename VarType>
385 for (
auto varEntry : varElem->mVariableSystemMatrixEntries)
387 SPDLOG_LOGGER_INFO(
mSLog,
"List of index pairs of varying matrix entries: ");
389 SPDLOG_LOGGER_INFO(
mSLog,
"({}, {})", indexPair.first, indexPair.second);
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))
407template <
typename VarType>
410 throw std::logic_error(
411 "MNA state-space extraction supports EMT and DP domains only.");
415 throw std::logic_error(
416 "MNA state-space extraction does not support frequency-parallel "
421 stateSpaceComponents.insert(stateSpaceComponents.end(),
423 stateSpaceComponents.insert(stateSpaceComponents.end(),
427 const UInt mnaVectorSize =
static_cast<UInt>((**mLeftSideVector).rows());
435 "Initialized MNA state-space extractor with {:d} extraction states.",
439template <
typename VarType>
444 auto idObj = std::dynamic_pointer_cast<IdentifiedObject>(varElem);
446 mSLog,
"Component ({:s} {:s}) value changed -> Update System Matrix",
447 idObj->type(), idObj->name());
460template <
typename VarType>
464 const auto recomputationComp = std::find_if(
466 const auto switchComp =
467 std::dynamic_pointer_cast<CPS::MNASwitchInterface>(comp);
469 return !switchComp || !switchComp->supportsPrecomputedSystemMatrices();
478 if (hasRecomputationComp) {
479 const auto component =
480 std::dynamic_pointer_cast<CPS::IdentifiedObject>(*recomputationComp);
484 "System-matrix recomputation enabled automatically for {:s} '{:s}'.",
485 component->type(), component->name());
487 SPDLOG_LOGGER_INFO(
mSLog,
488 "System-matrix recomputation disabled automatically.");
494 SPDLOG_LOGGER_INFO(
mSLog,
"System-matrix recomputation enabled.");
500 "nonlinear Newton components.");
503 if (hasRecomputationComp) {
504 const auto component =
505 std::dynamic_pointer_cast<CPS::IdentifiedObject>(*recomputationComp);
509 "System-matrix recomputation disabled, but {:s} '{:s}' may require "
511 component->type(), component->name());
513 SPDLOG_LOGGER_INFO(
mSLog,
"System-matrix recomputation disabled.");
520 for (
auto baseNode :
mSystem.mNodes) {
522 if (!baseNode->isGround()) {
523 auto node = std::dynamic_pointer_cast<CPS::SimNode<VarType>>(baseNode);
525 SPDLOG_LOGGER_INFO(
mSLog,
"Added node {:s}", node->name());
529 for (
auto comp :
mSystem.mComponents) {
531 auto genComp = std::dynamic_pointer_cast<CPS::MNASyncGenInterface>(comp);
536 auto swComp = std::dynamic_pointer_cast<CPS::MNASwitchInterface>(comp);
539 auto mnaComp = std::dynamic_pointer_cast<CPS::MNAInterface>(swComp);
545 std::dynamic_pointer_cast<CPS::MNAVariableCompInterface>(comp);
547 std::dynamic_pointer_cast<CPS::MNANonlinearCompInterface>(comp);
551 "Nonlinear Newton components require variable-matrix EMT MNA.");
557 varComp->hasContinuouslyChangingSystemMatrix());
558 auto mnaComp = std::dynamic_pointer_cast<CPS::MNAInterface>(varComp);
563 if (!(swComp || varComp)) {
564 auto mnaComp = std::dynamic_pointer_cast<CPS::MNAInterface>(comp);
568 auto sigComp = std::dynamic_pointer_cast<CPS::SimSignalComp>(comp);
576 UInt matrixNodeIndexIdx = 0;
577 for (
UInt idx = 0; idx <
mNodes.size(); ++idx) {
578 mNodes[idx]->setMatrixNodeIndex(0, matrixNodeIndexIdx);
580 SPDLOG_LOGGER_INFO(
mSLog,
"Assigned index {} to DC node {}",
581 matrixNodeIndexIdx, idx);
583 SPDLOG_LOGGER_INFO(
mSLog,
"Assigned index {} to phase A of node {}",
584 matrixNodeIndexIdx, idx);
585 ++matrixNodeIndexIdx;
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;
605 static_cast<UInt>(
mSystem.mFrequencies.size() - 1) *
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}",
626 for (
Int freq = 0; freq <
mSystem.mFrequencies.size(); ++freq) {
648 auto pComp = std::dynamic_pointer_cast<SimPowerComp<VarType>>(comp);
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());
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);
669 bool alreadyRegistered =
false;
670 for (
auto registeredNode :
mNodes) {
671 if (registeredNode == vnode) {
672 alreadyRegistered =
true;
676 if (alreadyRegistered)
679 SPDLOG_LOGGER_INFO(
mSLog,
"Collected virtual node {} of {}", node,
688 auto pComp = std::dynamic_pointer_cast<SimPowerComp<VarType>>(comp);
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,
706 SPDLOG_LOGGER_INFO(
mSLog,
"Created virtual nodes:");
708 SPDLOG_LOGGER_INFO(
mSLog,
"Number of network and virtual nodes: {:d}",
712template <
typename VarType>
714 SPDLOG_LOGGER_INFO(
mSLog,
"--- Run steady-state initialization ---");
718 initLeftVectorLog.
start();
721 initRightVectorLog.
start();
731 Int timeStepCount = 0;
738 SPDLOG_LOGGER_INFO(
mSLog,
739 "Time step is {:f}s for steady-state initialization",
742 for (
auto comp :
mSystem.mComponents) {
743 auto powerComp = std::dynamic_pointer_cast<CPS::TopologicalPowerComp>(comp);
745 powerComp->setBehaviour(initBehaviourPowerComps);
747 auto sigComp = std::dynamic_pointer_cast<CPS::SimSignalComp>(comp);
749 sigComp->setBehaviour(initBehaviourSignalComps);
760 for (
auto node :
mNodes) {
761 for (
auto task : node->mnaTasks())
762 tasks.push_back(task);
765 for (
auto task : comp->mnaTasks()) {
766 tasks.push_back(task);
771 for (
auto task : comp->getTasks()) {
772 tasks.push_back(task);
784 sched.
step(time, timeStepCount);
795 time = time + initTimeStep;
801 maxDiff = diff.lpNorm<Eigen::Infinity>();
802 max = (**mLeftSideVector).template lpNorm<Eigen::Infinity>();
808 SPDLOG_LOGGER_INFO(
mSLog,
"Max difference: {:f} or {:f}% at time {:f}",
809 maxDiff, maxDiff / max, time);
814 SPDLOG_LOGGER_INFO(
mSLog,
"--- Finished steady-state initialization ---");
821 for (
auto task : comp->mnaTasks()) {
826 for (
auto task : comp->mnaTasks()) {
830 for (
auto node :
mNodes) {
831 for (
auto task : node->mnaTasks())
835 for (
auto task : comp->getTasks()) {
841 for (
UInt i = 0; i <
mSystem.mFrequencies.size(); ++i)
845 for (
auto task : comp->mnaTasks())
862template <
typename VarType>
spdlog::level::level_enum Level
static String matrixToString(const Matrix &mat)
std::shared_ptr< MNAInterface > Ptr
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).
std::bitset< SWITCH_NUM > mCurrentSwitchStatus
Current status of all switches encoded as bitset.
virtual void setSystem(const CPS::SystemTopology &system) override
CPS::Domain mDomain
Simulation domain, which can be dynamic phasor (DP) or EMT.
void resolveSystemMatrixRecomputationMode()
Resolve the requested system-matrix recomputation mode.
Matrix & rightSideVector()
void identifyTopologyObjects()
Identify Nodes and SimPowerComps and SimSignalComps.
std::vector< Matrix > mRightSideVectorHarm
Source vector of known quantities.
void addRightVectorStamps(Matrix &rightVector, Int stampColumn=-1) const
Accumulate component RHS stamps, using sparse indices when available.
void steadyStateInitialization()
Matrix mRightSideVector
Source vector of known quantities.
Bool mStateSpaceExtraction
Enables extraction of the MNA-coupled discrete-time state matrix.
CPS::SystemTopology mSystem
System topology.
virtual std::shared_ptr< CPS::Task > createStateSpaceExtractionTask()=0
Create state-space extraction task for this solver implementation.
Matrix & leftSideVector()
Matrix * mLeftSideVectorValue
Cached payload for the per-step solver hot path.
std::vector< Bool > mVariableCompAlwaysDirty
void initializeSystemWithVariableMatrix()
Initialization of system matrices and source vector.
virtual void initialize() override
Calls subroutines to set up everything that is required before simulation.
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)
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.
std::vector< std::vector< UInt > > mRightVectorStampIndices
Sparse row indices for stamps that can provide their structural support.
UInt mNumNetMatrixNodeIndices
Number of network nodes, considering individual phases.
UInt mNumNetNodes
Number of network nodes, single line equivalent.
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.
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.
UInt mNumVirtualMatrixNodeIndices
Number of virtual nodes, considering individual phases.
CPS::MNASyncGenInterface::List mSyncGen
List of synchronous generators that need iterate to solve the differential equations.
CPS::MNAInterface::List mMNAIntfSwitches
List of switches if they must be accessed as MNAInterface objects.
std::shared_ptr< DataLogger > mRightVectorLog
Right side vector logger.
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.
CPS::MNAVariableCompInterface::List mVariableComps
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.
virtual void stampVariableSystemMatrix()=0
Stamps components into the variable system matrix.
std::shared_ptr< DataLogger > mLeftVectorLog
Left side vector logger.
UInt mNumMatrixNodeIndices
Number of network and virtual nodes, considering individual phases.
void initializeSystemWithParallelFrequencies()
Initialization of system matrices and source vector.
CPS::MNANonlinearCompInterface::List mNonlinearComps
void collectVirtualNodes()
UInt mNumHarmMatrixNodeIndices
Number of nodes, excluding the primary frequency.
UInt mNumNodes
Number of network and virtual nodes, single line equivalent.
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.
void assignMatrixNodeIndices()
Assign simulation node index according to index in the vector.
UInt mNumVirtualNodes
Number of virtual nodes, single line equivalent.
std::vector< CPS::Attribute< Matrix >::Ptr > mRightVectorStamps
List of all right side vector contributions.
void addRightVectorStamp(const CPS::MNAInterface::Ptr &component)
Add a component's RHS stamp and cache any known structural row indices.
void initializeSystemWithPrecomputedMatrices()
Initialization of system matrices and source vector.
CPS::Attribute< Matrix >::Ptr mLeftSideVector
Solution vector of unknown quantities.
CPS::SimSignalComp::List mSimSignalComps
List of signal type components that do not directly interact with the MNA solver.
virtual void createEmptySystemMatrix()=0
Create system matrix.
std::vector< Bool > mRightVectorStampUsesIndices
Whether each RHS stamp has valid sparse row indices.
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.
void doStateSpaceExtraction(Bool value=true)
Enable or disable MNA state-space extraction.
CPS::MNASwitchInterface::List mSwitches
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.
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)
std::unordered_map< CPS::Task::Ptr, std::deque< CPS::Task::Ptr > > Edges
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.
Real mSteadStIniAccLimit
steady state initialization accuracy limit
Bool mSystemMatrixRecomputationEnabled
Effective system-matrix recomputation setting used by the solver.
Real mTimeStep
Time step for fixed step solvers.
CPS::Logger::Log mSLog
Logger.
CPS::Logger::Level mLogLevel
Logging level.
Bool mIsInInitialization
Determines if solver is in initialization phase, which requires different behavior.
Solver(String name, CPS::Logger::Level logLevel)
Real mSteadStIniTimeLimit
steady state initialization time limit
Bool mInitFromNodesAndTerminals
Bool mFrequencyParallel
Activates parallelized computation of frequencies.
Bool mZeroSkipping
Skip exact zero contributions during matrix assembly (enabled by default).
Bool mSteadyStateInit
Activates steady state initialization.
SystemMatrixRecomputationMode mSystemMatrixRecomputationMode
Requested system-matrix recomputation mode.
SystemMatrixRecomputationMode
System-matrix recomputation mode for MNA solvers.