19 :
Solver(name +
"_PF", logLevel) {
26 SPDLOG_LOGGER_INFO(
mSLog,
"#### INITIALIZATION OF POWERFLOW SOLVER ");
30 for (
auto comp :
mSystem.mComponents) {
31 if (std::shared_ptr<CPS::SP::Ph1::SynchronGenerator> gen =
32 std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(comp))
34 else if (std::shared_ptr<CPS::SP::Ph1::Load> load =
35 std::dynamic_pointer_cast<CPS::SP::Ph1::Load>(comp))
37 else if (std::shared_ptr<CPS::SP::Ph1::Transformer> trafo =
38 std::dynamic_pointer_cast<CPS::SP::Ph1::Transformer>(comp))
40 else if (std::shared_ptr<CPS::SP::Ph1::PiLine> line =
41 std::dynamic_pointer_cast<CPS::SP::Ph1::PiLine>(comp))
43 else if (std::shared_ptr<CPS::SP::Ph1::NetworkInjection> extnet =
44 std::dynamic_pointer_cast<CPS::SP::Ph1::NetworkInjection>(
47 else if (std::shared_ptr<CPS::SP::Ph1::Shunt> shunt =
48 std::dynamic_pointer_cast<CPS::SP::Ph1::Shunt>(comp))
50 else if (std::shared_ptr<CPS::SP::Ph1::SolidStateTransformer> sst =
51 std::dynamic_pointer_cast<CPS::SP::Ph1::SolidStateTransformer>(
54 else if (std::shared_ptr<CPS::SP::Ph1::AvVoltageSourceInverterDQ> vsi =
55 std::dynamic_pointer_cast<
78 auto sparseJ =
mJ.sparseView();
79 Eigen::SparseLU<SparseMatrix> lu(sparseJ);
84 SPDLOG_LOGGER_INFO(
mSLog,
"Assigning simulation nodes to topology nodes:");
85 UInt matrixNodeIndexIdx = 0;
86 for (
UInt idx = 0; idx <
mSystem.mNodes.size(); ++idx) {
87 mSystem.mNodes[idx]->setMatrixNodeIndex(0, matrixNodeIndexIdx);
88 SPDLOG_LOGGER_INFO(
mSLog,
"Node {}: MatrixNodeIndex {}",
90 mSystem.mNodes[idx]->matrixNodeIndex());
93 SPDLOG_LOGGER_INFO(
mSLog,
"Number of simulation nodes: {:d}",
98 for (
auto comp :
mSystem.mComponents) {
99 std::dynamic_pointer_cast<SimPowerComp<Complex>>(comp)
100 ->updateMatrixNodeIndices();
104 mSLog,
"-- Initialize components from terminals or nodes of topology");
105 for (
auto comp :
mSystem.mComponents) {
106 auto pComp = std::dynamic_pointer_cast<SimPowerComp<Complex>>(comp);
110 pComp->initializeFromNodesAndTerminals(
mSystem.mSystemFrequency);
113 SPDLOG_LOGGER_INFO(
mSLog,
114 "-- Calculate per unit parameters for all components");
119 for (
auto line :
mLines) {
128 for (
auto load :
mLoads) {
143 if (std::abs(gen->attributeTyped<
Real>(
"P_set")->get()) > maxPower)
144 maxPower = std::abs(gen->attributeTyped<
Real>(
"P_set")->get());
147 if (trafo->attributeTyped<
Real>(
"S")->get() > maxPower)
148 maxPower = trafo->attributeTyped<
Real>(
"S")->get();
154 SPDLOG_LOGGER_WARN(
mSLog,
155 "No suitable quantity found for setting "
156 "mBaseApparentPower. Using {} VA.",
167 SPDLOG_LOGGER_INFO(
mSLog,
"-- Determine powerflow bus type for each node");
170 for (
auto node :
mSystem.mNodes) {
171 bool connectedPV =
false;
172 bool connectedPQ =
false;
173 bool connectedVD =
false;
175 for (
auto comp :
mSystem.mComponentsAtNode[node]) {
176 if (std::shared_ptr<CPS::SP::Ph1::Load> load =
177 std::dynamic_pointer_cast<CPS::SP::Ph1::Load>(comp)) {
181 }
else if (std::shared_ptr<CPS::SP::Ph1::SynchronGenerator> gen =
182 std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(
191 }
else if (std::shared_ptr<CPS::SP::Ph1::NetworkInjection> extnet =
192 std::dynamic_pointer_cast<CPS::SP::Ph1::NetworkInjection>(
204 if (!connectedPV && connectedPQ && !connectedVD) {
206 mSLog,
"{}: only PQ type component connected -> set as PQ bus",
210 else if (!connectedPV && !connectedPQ && !connectedVD) {
211 SPDLOG_LOGGER_INFO(
mSLog,
"{}: no component connected -> set as PQ bus",
215 else if (connectedPV && !connectedPQ && !connectedVD) {
217 mSLog,
"{}: only PV type component connected -> set as PV bus",
221 else if (connectedPV && connectedPQ && !connectedVD) {
223 mSLog,
"{}: PV and PQ type component connected -> set as PV bus",
227 else if (!connectedPV && !connectedPQ && connectedVD) {
229 mSLog,
"{}: only VD type component connected -> set as VD bus",
233 else if (connectedPV && !connectedPQ && connectedVD) {
235 mSLog,
"{}: VD and PV type component connect -> set as VD bus",
239 else if (!connectedPV && connectedPQ && connectedVD) {
241 mSLog,
"{}: VD and PQ type component connected -> set as VD bus",
245 else if (connectedPV && connectedPQ && connectedVD) {
247 mSLog,
"{}: VD, PV and PQ type component connect -> set as VD bus",
251 std::stringstream ss;
252 ss <<
"Node>>" << node->name()
253 <<
": combination of connected components is invalid";
254 throw std::invalid_argument(ss.str());
264 SPDLOG_LOGGER_INFO(
mSLog,
"#### Create index vectors for power flow solver:");
315 std::dynamic_pointer_cast<CPS::SP::Ph1::AvVoltageSourceInverterDQ>(
317 return vsi->getBaseVoltage();
318 if (
auto rxline = std::dynamic_pointer_cast<CPS::SP::Ph1::RXLine>(comp))
319 return rxline->getBaseVoltage();
320 if (
auto line = std::dynamic_pointer_cast<CPS::SP::Ph1::PiLine>(comp))
321 return line->getBaseVoltage();
322 if (
auto trans = std::dynamic_pointer_cast<CPS::SP::Ph1::Transformer>(comp)) {
323 if (trans->terminal(0)->node()->name() == node->name())
324 return trans->getNominalVoltagePrimary();
325 if (trans->terminal(1)->node()->name() == node->name())
326 return trans->getNominalVoltageSecondary();
330 std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(comp))
331 return gen->getBaseVoltage();
332 if (
auto load = std::dynamic_pointer_cast<CPS::SP::Ph1::Load>(comp))
333 return load->getNomVoltage();
335 std::dynamic_pointer_cast<CPS::SP::Ph1::NetworkInjection>(comp))
336 return extnet->getBaseVoltage();
337 if (
auto shunt = std::dynamic_pointer_cast<CPS::SP::Ph1::Shunt>(comp))
338 return shunt->getBaseVoltage();
339 SPDLOG_LOGGER_WARN(
mSLog,
"Unable to get base voltage at {}", node->name());
345 SPDLOG_LOGGER_INFO(
mSLog,
"-- Determine base voltages for each node "
346 "according to connected components");
350 std::vector<UInt> zoneParent(
mSystem.mNodes.size());
351 for (
UInt i = 0; i < zoneParent.size(); ++i)
353 auto findZone = [&](
UInt node) ->
UInt {
354 while (zoneParent[node] != node) {
355 zoneParent[node] = zoneParent[zoneParent[node]];
356 node = zoneParent[node];
360 auto uniteZones = [&](
UInt a,
UInt b) {
361 zoneParent[findZone(a)] = findZone(b);
364 for (
auto comp :
mSystem.mComponents) {
365 if (
auto line = std::dynamic_pointer_cast<CPS::SP::Ph1::PiLine>(comp))
366 uniteZones(line->node(0)->matrixNodeIndex(),
367 line->node(1)->matrixNodeIndex());
368 else if (
auto rxline =
369 std::dynamic_pointer_cast<CPS::SP::Ph1::RXLine>(comp))
370 uniteZones(rxline->node(0)->matrixNodeIndex(),
371 rxline->node(1)->matrixNodeIndex());
376 std::map<UInt, std::vector<std::pair<CPS::Real, CPS::String>>> authoritative;
377 std::map<UInt, std::vector<std::pair<CPS::Real, CPS::String>>> fallback;
378 std::map<UInt, std::vector<std::shared_ptr<CPS::SP::Ph1::Load>>> zoneLoads;
379 for (
auto node :
mSystem.mNodes) {
380 UInt zone = findZone(node->matrixNodeIndex());
381 for (
auto comp :
mSystem.mComponentsAtNode[node]) {
382 if (
auto load = std::dynamic_pointer_cast<CPS::SP::Ph1::Load>(comp))
383 zoneLoads[zone].push_back(load);
386 if (std::abs(voltage) <= 1e-6)
388 bool isAuthoritative =
389 std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(comp) ||
390 std::dynamic_pointer_cast<CPS::SP::Ph1::Transformer>(comp) ||
391 std::dynamic_pointer_cast<CPS::SP::Ph1::NetworkInjection>(comp) ||
392 std::dynamic_pointer_cast<CPS::SP::Ph1::AvVoltageSourceInverterDQ>(
394 auto &bucket = isAuthoritative ? authoritative : fallback;
395 bucket[zone].emplace_back(voltage, comp->name());
401 [&](
const std::vector<std::pair<CPS::Real, CPS::String>> &candidates,
404 for (
auto &candidate : candidates) {
406 std::abs(candidate.first - reference) /
407 std::max(std::abs(candidate.first), std::abs(reference));
408 if (relDiff > tolerance) {
409 std::stringstream ss;
410 ss <<
"Base voltage mismatch within one electrical zone (nodes "
411 "connected without an intervening transformer): "
412 << refSource <<
" implies " << reference <<
"V but "
413 << candidate.second <<
" implies " << candidate.first <<
"V";
414 throw std::invalid_argument(ss.str());
419 std::map<UInt, CPS::Real> zoneVoltage;
420 for (
auto &entry : authoritative) {
421 CPS::Real refVoltage = entry.second.front().first;
422 verify(entry.second, refVoltage, entry.second.front().second,
424 zoneVoltage[entry.first] = refVoltage;
427 for (
auto &entry : fallback) {
428 auto it = zoneVoltage.find(entry.first);
429 bool hasAuthoritative = it != zoneVoltage.end();
431 hasAuthoritative ? it->second : entry.second.front().first;
433 ?
"the zone's authoritative rating"
434 : entry.second.front().second;
436 if (!hasAuthoritative)
437 zoneVoltage[entry.first] = reference;
441 for (
auto node :
mSystem.mNodes) {
442 auto it = zoneVoltage.find(findZone(node->matrixNodeIndex()));
447 for (
auto &entry : zoneVoltage) {
448 auto it = zoneLoads.find(entry.first);
449 if (it == zoneLoads.end())
451 for (
auto &load : it->second) {
452 if (std::abs(load->getNomVoltage() - entry.second) > 1e-6)
453 load->setParameters(load->attributeTyped<
CPS::Real>(
"P")->get(),
454 load->attributeTyped<
CPS::Real>(
"Q")->get(),
462 for (
auto node :
mSystem.mNodes) {
467 SPDLOG_LOGGER_WARN(
mSLog,
"No base voltage entry for {}", node->name());
473 if (std::abs(it->second) < 1e-6) {
474 SPDLOG_LOGGER_WARN(
mSLog,
"Zero base voltage for {}", node->name());
480 SPDLOG_LOGGER_INFO(
mSLog,
"Base voltage summary: missing={}, zero={}",
481 numMissing, numZero);
491 if (gen->node(0)->name() == name) {
496 throw std::invalid_argument(
"Invalid slack bus, no external grid or "
497 "synchronous generator attached");
503 for (
auto comp :
mSystem.mComponents) {
504 if (comp->name() == name) {
505 if (std::shared_ptr<CPS::SP::Ph1::NetworkInjection> extnet =
506 std::dynamic_pointer_cast<CPS::SP::Ph1::NetworkInjection>(comp))
507 extnet->modifyPowerFlowBusType(powerFlowBusType);
508 else if (std::shared_ptr<CPS::SP::Ph1::SynchronGenerator> gen =
509 std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(
511 gen->modifyPowerFlowBusType(powerFlowBusType);
519 SPDLOG_LOGGER_INFO(
mSLog,
"-- Set solver behaviour to Initialization");
522 SPDLOG_LOGGER_INFO(
mSLog,
"-- Set component behaviour to Initialization");
523 for (
auto comp :
mSystem.mComponents) {
525 std::dynamic_pointer_cast<CPS::TopologicalPowerComp>(comp);
527 powerComp->setBehaviour(
531 SPDLOG_LOGGER_INFO(
mSLog,
"-- Set solver behaviour to Simulation");
534 SPDLOG_LOGGER_INFO(
mSLog,
"-- Set component behaviour to PFSimulation");
535 for (
auto comp :
mSystem.mComponents) {
537 std::dynamic_pointer_cast<CPS::TopologicalPowerComp>(comp);
548 for (
auto line :
mLines) {
549 line->pfApplyAdmittanceMatrixStamp(
mY);
553 if (**trans->mResistance == 0 && **trans->mInductance == 0) {
554 SPDLOG_LOGGER_INFO(
mSLog,
"{} {} ignored for R = 0 and L = 0",
555 trans->type(), trans->name());
558 trans->pfApplyAdmittanceMatrixStamp(
mY);
561 shunt->pfApplyAdmittanceMatrixStamp(
mY);
565 throw std::invalid_argument(
"There are no bus");
577 SPDLOG_LOGGER_WARN(
mSLog,
"mF[{}] not finite (NaN/Inf)", i);
613 SPDLOG_LOGGER_DEBUG(
mSLog,
"Mismatch vector at iteration {}: \n {}", i,
mF);
630 Bool settled =
false;
640 if (converged && !settled) {
644 "Q-limit outer loop did not settle within {} iterations; "
645 "PV/PQ classification may still be oscillating",
655 mSolver.generateInitialSolution(time, mSolver.mKeepLastSolution);
656 mSolver.solvePowerflow();
657 mSolver.setSolution();
661 return Task::List{std::make_shared<SolveTask>(*
this)};
spdlog::level::level_enum Level
static bool isFinite(Real value)
std::shared_ptr< TopologicalNode > Ptr
std::shared_ptr< TopologicalPowerComp > Ptr
void execute(Real time, Int timeStepCount)
void determinePFBusType()
Determine bus type for all buses.
void reclassifyBuses()
Re-derive index vectors and resize the system after PV<->PQ switching.
CPS::Real mBaseApparentPowerFallback
Fallback base apparent power if no generator or transformer rating is found.
Bool runNewtonRaphson()
Run a single Newton-Raphson solve with the current bus classification.
void resetToOriginalClassification()
Restore the original PV/PQ classification before a fresh solve.
std::vector< std::shared_ptr< CPS::SP::Ph1::Load > > mLoads
Vector of load components.
CPS::TopologicalNode::List mPQBuses
Vector of nodes characterized as PQ buses.
UInt mNumPQBuses
Number of PQ nodes.
virtual void solveJacobianSystem()
Solve the linearized system mJ*mX = mF into mX; sparse subclass overrides.
UInt mNumVDBuses
Number of PV nodes.
Real mTolerance
Solver tolerance.
CPS::String logVector(std::vector< CPS::UInt > indexVector)
Logging for integer vectors.
std::vector< std::shared_ptr< CPS::SP::Ph1::PiLine > > mLines
Vector of line components.
CPS::Task::List getTasks() override
Get tasks for scheduler.
void assignMatrixNodeIndices()
Assignment of matrix indices for nodes.
std::vector< CPS::UInt > mVDBusIndices
Vector with indices of VD buses.
virtual void setUpJacobianStorage()
Allocate Jacobian storage; dense by default, sparse subclass overrides.
void initializeComponents()
Initialization of individual components.
std::vector< std::shared_ptr< CPS::SP::Ph1::SynchronGenerator > > mSynchronGenerators
Vector of synchronous generator components.
CPS::TopologicalNode::List mPVBusesOrig
void propagateAndVerifyBaseVoltage()
Determine, verify and propagate each node's base voltage per electrical zone.
std::vector< CPS::UInt > mPQBusIndices
Vector with indices of PQ buses.
void modifyPowerFlowBusComponent(CPS::String name, CPS::PowerflowBusType powerFlowBusType)
Allows to modify the powerflow bus type of a specific component.
std::vector< std::shared_ptr< CPS::SP::Ph1::NetworkInjection > > mExternalGrids
Vector of external grid components.
std::vector< std::shared_ptr< CPS::SP::Ph1::SolidStateTransformer > > mSolidStateTransformers
Vector of solid state transformer components.
std::vector< CPS::UInt > mPVBusIndices
Vector with indices of PV buses.
void setVDNode(CPS::String name)
Set a node to VD using its name.
std::vector< std::shared_ptr< CPS::SP::Ph1::Transformer > > mTransformers
Vector of transformer components.
std::vector< std::shared_ptr< CPS::SP::Ph1::Shunt > > mShunts
Vector of shunt components.
CPS::Bool checkConvergence()
Check whether below tolerance.
CPS::Matrix mJ
Jacobian matrix.
CPS::UInt mMaxIterations
Maximum number of iterations.
CPS::Real componentBaseVoltage(CPS::TopologicalPowerComp::Ptr comp, CPS::TopologicalNode::Ptr node)
Base voltage a single component reports for node, or 0 if unknown.
CPS::Vector mX
Solution vector.
std::vector< std::shared_ptr< CPS::SP::Ph1::AvVoltageSourceInverterDQ > > mAverageVoltageSourceInverters
Vector of average voltage source inverters.
void rebuildBusIndexAggregates()
Rebuild index vectors + counts from the PQ/PV/VD node lists.
CPS::Real mBaseApparentPower
Base power of per-unit system.
void setBaseApparentPower()
Set apparent base power of per-unit system.
virtual void calculateMismatch()=0
Calculate mismatch.
CPS::SparseMatrixCompRow mY
Admittance matrix.
UInt mNumPVBuses
Number of PV nodes.
CPS::Real B(int i, int j)
Gets the imaginary part of admittance matrix element.
void composeAdmittanceMatrix()
Compose admittance matrix.
CPS::TopologicalNode::List mPQBusesOrig
Original PQ/PV classification (snapshot before Q-limit switching)
CPS::Bool isConverged
Convergence flag.
CPS::Vector mF
Vector of mismatch values.
CPS::UInt mIterations
Actual number of iterations.
CPS::UInt mMaxOuterIterations
Maximum number of Q-limit outer iterations.
virtual CPS::Bool enforceReactiveLimits()
Switch generators violating their Q limits between PV/PQ; base impl is a no-op.
PFSolver(CPS::String name, CPS::SystemTopology system, Real timeStep, CPS::Logger::Level logLevel)
Constructor to be used in simulation examples.
CPS::SystemTopology mSystem
System list.
virtual void calculateJacobian()=0
Calculate the Jacobian.
void setSolverAndComponentBehaviour(Solver::Behaviour behaviour) override
set solver and component to initialization or simulation behaviour
std::map< CPS::TopologicalNode::Ptr, CPS::Real > mBaseVoltageAtNode
Map providing determined base voltages for each node.
void initialize() override
Initialization of the solver.
CPS::Real mBaseVoltageLooseTolerance
Relative tolerance for non-authoritative (e.g. Load) base-voltage candidates vs. the zone's rating.
CPS::Real mBaseVoltageStrictTolerance
Relative tolerance between authoritative base-voltage sources (generator/transformer/network-injectio...
virtual void updateSolution()=0
Update solution in each iteration.
Bool solvePowerflow()
Solves the powerflow problem.
CPS::Bool mEnforceReactiveLimits
Enforce generator reactive-power limits via PV<->PQ outer-loop switching.
CPS::TopologicalNode::List mVDBuses
Vector of nodes characterized as VD buses.
CPS::TopologicalNode::List mPVBuses
Vector of nodes characterized as PV buses.
UInt mNumUnknowns
Number of unknowns, defining system dimension.
virtual void clearReactiveLimitState()
Clear Q-limit bookkeeping; overridden by PFSolverPowerPolar.
CPS::Real G(int i, int j)
Gets the real part of admittance matrix element.
std::vector< CPS::UInt > mPQPVBusIndices
Vector with indices of both PQ and PV buses.
Real mTimeStep
Time step for fixed step solvers.
Behaviour mBehaviour
Solver behaviour initialization or simulation.
CPS::Logger::Log mSLog
Logger.
Solver(String name, CPS::Logger::Level logLevel)
Bool mInitFromNodesAndTerminals
Bool mZeroSkipping
Skip exact zero contributions during matrix assembly (enabled by default).
Eigen::SparseMatrix< Complex, Eigen::ColMajor > SparseMatrixComp
Sparse matrix for complex numbers.