19 :
Solver(name +
"_PF", logLevel) {
25 SPDLOG_LOGGER_INFO(
mSLog,
"#### INITIALIZATION OF POWERFLOW SOLVER ");
29 for (
auto comp :
mSystem.mComponents) {
30 if (std::shared_ptr<CPS::SP::Ph1::SynchronGenerator> gen =
31 std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(comp))
33 else if (std::shared_ptr<CPS::SP::Ph1::Load> load =
34 std::dynamic_pointer_cast<CPS::SP::Ph1::Load>(comp))
36 else if (std::shared_ptr<CPS::SP::Ph1::Transformer> trafo =
37 std::dynamic_pointer_cast<CPS::SP::Ph1::Transformer>(comp))
39 else if (std::shared_ptr<CPS::SP::Ph1::PiLine> line =
40 std::dynamic_pointer_cast<CPS::SP::Ph1::PiLine>(comp))
42 else if (std::shared_ptr<CPS::SP::Ph1::NetworkInjection> extnet =
43 std::dynamic_pointer_cast<CPS::SP::Ph1::NetworkInjection>(
46 else if (std::shared_ptr<CPS::SP::Ph1::Shunt> shunt =
47 std::dynamic_pointer_cast<CPS::SP::Ph1::Shunt>(comp))
49 else if (std::shared_ptr<CPS::SP::Ph1::SolidStateTransformer> sst =
50 std::dynamic_pointer_cast<CPS::SP::Ph1::SolidStateTransformer>(
53 else if (std::shared_ptr<CPS::SP::Ph1::AvVoltageSourceInverterDQ> vsi =
54 std::dynamic_pointer_cast<
77 auto sparseJ =
mJ.sparseView();
78 Eigen::SparseLU<SparseMatrix> lu(sparseJ);
83 SPDLOG_LOGGER_INFO(
mSLog,
"Assigning simulation nodes to topology nodes:");
84 UInt matrixNodeIndexIdx = 0;
85 for (
UInt idx = 0; idx <
mSystem.mNodes.size(); ++idx) {
86 mSystem.mNodes[idx]->setMatrixNodeIndex(0, matrixNodeIndexIdx);
87 SPDLOG_LOGGER_INFO(
mSLog,
"Node {}: MatrixNodeIndex {}",
89 mSystem.mNodes[idx]->matrixNodeIndex());
92 SPDLOG_LOGGER_INFO(
mSLog,
"Number of simulation nodes: {:d}",
97 for (
auto comp :
mSystem.mComponents) {
98 std::dynamic_pointer_cast<SimPowerComp<Complex>>(comp)
99 ->updateMatrixNodeIndices();
103 mSLog,
"-- Initialize components from terminals or nodes of topology");
104 for (
auto comp :
mSystem.mComponents) {
105 auto pComp = std::dynamic_pointer_cast<SimPowerComp<Complex>>(comp);
109 pComp->initializeFromNodesAndTerminals(
mSystem.mSystemFrequency);
112 SPDLOG_LOGGER_INFO(
mSLog,
113 "-- Calculate per unit parameters for all components");
118 for (
auto line :
mLines) {
127 for (
auto load :
mLoads) {
142 if (std::abs(gen->attributeTyped<
Real>(
"P_set")->get()) > maxPower)
143 maxPower = std::abs(gen->attributeTyped<
Real>(
"P_set")->get());
146 if (trafo->attributeTyped<
Real>(
"S")->get() > maxPower)
147 maxPower = trafo->attributeTyped<
Real>(
"S")->get();
153 SPDLOG_LOGGER_WARN(
mSLog,
154 "No suitable quantity found for setting "
155 "mBaseApparentPower. Using {} VA.",
166 SPDLOG_LOGGER_INFO(
mSLog,
"-- Determine powerflow bus type for each node");
169 for (
auto node :
mSystem.mNodes) {
170 bool connectedPV =
false;
171 bool connectedPQ =
false;
172 bool connectedVD =
false;
174 for (
auto comp :
mSystem.mComponentsAtNode[node]) {
175 if (std::shared_ptr<CPS::SP::Ph1::Load> load =
176 std::dynamic_pointer_cast<CPS::SP::Ph1::Load>(comp)) {
180 }
else if (std::shared_ptr<CPS::SP::Ph1::SynchronGenerator> gen =
181 std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(
190 }
else if (std::shared_ptr<CPS::SP::Ph1::NetworkInjection> extnet =
191 std::dynamic_pointer_cast<CPS::SP::Ph1::NetworkInjection>(
203 if (!connectedPV && connectedPQ && !connectedVD) {
205 mSLog,
"{}: only PQ type component connected -> set as PQ bus",
209 else if (!connectedPV && !connectedPQ && !connectedVD) {
210 SPDLOG_LOGGER_INFO(
mSLog,
"{}: no component connected -> set as PQ bus",
214 else if (connectedPV && !connectedPQ && !connectedVD) {
216 mSLog,
"{}: only PV type component connected -> set as PV bus",
220 else if (connectedPV && connectedPQ && !connectedVD) {
222 mSLog,
"{}: PV and PQ type component connected -> set as PV bus",
226 else if (!connectedPV && !connectedPQ && connectedVD) {
228 mSLog,
"{}: only VD type component connected -> set as VD bus",
232 else if (connectedPV && !connectedPQ && connectedVD) {
234 mSLog,
"{}: VD and PV type component connect -> set as VD bus",
238 else if (connectedPV && connectedPQ && connectedVD) {
240 mSLog,
"{}: VD, PV and PQ type component connect -> set as VD bus",
244 std::stringstream ss;
245 ss <<
"Node>>" << node->name()
246 <<
": combination of connected components is invalid";
247 throw std::invalid_argument(ss.str());
257 SPDLOG_LOGGER_INFO(
mSLog,
"#### Create index vectors for power flow solver:");
308 std::dynamic_pointer_cast<CPS::SP::Ph1::AvVoltageSourceInverterDQ>(
310 return vsi->getBaseVoltage();
311 if (
auto rxline = std::dynamic_pointer_cast<CPS::SP::Ph1::RXLine>(comp))
312 return rxline->getBaseVoltage();
313 if (
auto line = std::dynamic_pointer_cast<CPS::SP::Ph1::PiLine>(comp))
314 return line->getBaseVoltage();
315 if (
auto trans = std::dynamic_pointer_cast<CPS::SP::Ph1::Transformer>(comp)) {
316 if (trans->terminal(0)->node()->name() == node->name())
317 return trans->getNominalVoltageEnd1();
318 if (trans->terminal(1)->node()->name() == node->name())
319 return trans->getNominalVoltageEnd2();
323 std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(comp))
324 return gen->getBaseVoltage();
325 if (
auto load = std::dynamic_pointer_cast<CPS::SP::Ph1::Load>(comp))
326 return load->getNomVoltage();
328 std::dynamic_pointer_cast<CPS::SP::Ph1::NetworkInjection>(comp))
329 return extnet->getBaseVoltage();
330 if (
auto shunt = std::dynamic_pointer_cast<CPS::SP::Ph1::Shunt>(comp))
331 return shunt->getBaseVoltage();
332 SPDLOG_LOGGER_WARN(
mSLog,
"Unable to get base voltage at {}", node->name());
338 SPDLOG_LOGGER_INFO(
mSLog,
"-- Determine base voltages for each node "
339 "according to connected components");
343 std::vector<UInt> zoneParent(
mSystem.mNodes.size());
344 for (
UInt i = 0; i < zoneParent.size(); ++i)
346 auto findZone = [&](
UInt node) ->
UInt {
347 while (zoneParent[node] != node) {
348 zoneParent[node] = zoneParent[zoneParent[node]];
349 node = zoneParent[node];
353 auto uniteZones = [&](
UInt a,
UInt b) {
354 zoneParent[findZone(a)] = findZone(b);
357 for (
auto comp :
mSystem.mComponents) {
358 if (
auto line = std::dynamic_pointer_cast<CPS::SP::Ph1::PiLine>(comp))
359 uniteZones(line->node(0)->matrixNodeIndex(),
360 line->node(1)->matrixNodeIndex());
361 else if (
auto rxline =
362 std::dynamic_pointer_cast<CPS::SP::Ph1::RXLine>(comp))
363 uniteZones(rxline->node(0)->matrixNodeIndex(),
364 rxline->node(1)->matrixNodeIndex());
369 std::map<UInt, std::vector<std::pair<CPS::Real, CPS::String>>> authoritative;
370 std::map<UInt, std::vector<std::pair<CPS::Real, CPS::String>>> fallback;
371 std::map<UInt, std::vector<std::shared_ptr<CPS::SP::Ph1::Load>>> zoneLoads;
372 for (
auto node :
mSystem.mNodes) {
373 UInt zone = findZone(node->matrixNodeIndex());
374 for (
auto comp :
mSystem.mComponentsAtNode[node]) {
375 if (
auto load = std::dynamic_pointer_cast<CPS::SP::Ph1::Load>(comp))
376 zoneLoads[zone].push_back(load);
379 if (std::abs(voltage) <= 1e-6)
381 bool isAuthoritative =
382 std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(comp) ||
383 std::dynamic_pointer_cast<CPS::SP::Ph1::Transformer>(comp) ||
384 std::dynamic_pointer_cast<CPS::SP::Ph1::NetworkInjection>(comp) ||
385 std::dynamic_pointer_cast<CPS::SP::Ph1::AvVoltageSourceInverterDQ>(
387 auto &bucket = isAuthoritative ? authoritative : fallback;
388 bucket[zone].emplace_back(voltage, comp->name());
394 [&](
const std::vector<std::pair<CPS::Real, CPS::String>> &candidates,
397 for (
auto &candidate : candidates) {
399 std::abs(candidate.first - reference) /
400 std::max(std::abs(candidate.first), std::abs(reference));
401 if (relDiff > tolerance) {
402 std::stringstream ss;
403 ss <<
"Base voltage mismatch within one electrical zone (nodes "
404 "connected without an intervening transformer): "
405 << refSource <<
" implies " << reference <<
"V but "
406 << candidate.second <<
" implies " << candidate.first <<
"V";
407 throw std::invalid_argument(ss.str());
412 std::map<UInt, CPS::Real> zoneVoltage;
413 for (
auto &entry : authoritative) {
414 CPS::Real refVoltage = entry.second.front().first;
415 verify(entry.second, refVoltage, entry.second.front().second,
417 zoneVoltage[entry.first] = refVoltage;
420 for (
auto &entry : fallback) {
421 auto it = zoneVoltage.find(entry.first);
422 bool hasAuthoritative = it != zoneVoltage.end();
424 hasAuthoritative ? it->second : entry.second.front().first;
426 ?
"the zone's authoritative rating"
427 : entry.second.front().second;
429 if (!hasAuthoritative)
430 zoneVoltage[entry.first] = reference;
434 for (
auto node :
mSystem.mNodes) {
435 auto it = zoneVoltage.find(findZone(node->matrixNodeIndex()));
440 for (
auto &entry : zoneVoltage) {
441 auto it = zoneLoads.find(entry.first);
442 if (it == zoneLoads.end())
444 for (
auto &load : it->second) {
445 if (std::abs(load->getNomVoltage() - entry.second) > 1e-6)
446 load->setParameters(load->attributeTyped<
CPS::Real>(
"P")->get(),
447 load->attributeTyped<
CPS::Real>(
"Q")->get(),
455 for (
auto node :
mSystem.mNodes) {
460 SPDLOG_LOGGER_WARN(
mSLog,
"No base voltage entry for {}", node->name());
466 if (std::abs(it->second) < 1e-6) {
467 SPDLOG_LOGGER_WARN(
mSLog,
"Zero base voltage for {}", node->name());
473 SPDLOG_LOGGER_INFO(
mSLog,
"Base voltage summary: missing={}, zero={}",
474 numMissing, numZero);
484 if (gen->node(0)->name() == name) {
489 throw std::invalid_argument(
"Invalid slack bus, no external grid or "
490 "synchronous generator attached");
496 for (
auto comp :
mSystem.mComponents) {
497 if (comp->name() == name) {
498 if (std::shared_ptr<CPS::SP::Ph1::NetworkInjection> extnet =
499 std::dynamic_pointer_cast<CPS::SP::Ph1::NetworkInjection>(comp))
500 extnet->modifyPowerFlowBusType(powerFlowBusType);
501 else if (std::shared_ptr<CPS::SP::Ph1::SynchronGenerator> gen =
502 std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(
504 gen->modifyPowerFlowBusType(powerFlowBusType);
512 SPDLOG_LOGGER_INFO(
mSLog,
"-- Set solver behaviour to Initialization");
515 SPDLOG_LOGGER_INFO(
mSLog,
"-- Set component behaviour to Initialization");
516 for (
auto comp :
mSystem.mComponents) {
518 std::dynamic_pointer_cast<CPS::TopologicalPowerComp>(comp);
520 powerComp->setBehaviour(
524 SPDLOG_LOGGER_INFO(
mSLog,
"-- Set solver behaviour to Simulation");
527 SPDLOG_LOGGER_INFO(
mSLog,
"-- Set component behaviour to PFSimulation");
528 for (
auto comp :
mSystem.mComponents) {
530 std::dynamic_pointer_cast<CPS::TopologicalPowerComp>(comp);
541 for (
auto line :
mLines) {
542 line->pfApplyAdmittanceMatrixStamp(
mY);
546 if (**trans->mResistance == 0 && **trans->mInductance == 0) {
547 SPDLOG_LOGGER_INFO(
mSLog,
"{} {} ignored for R = 0 and L = 0",
548 trans->type(), trans->name());
551 trans->pfApplyAdmittanceMatrixStamp(
mY);
554 shunt->pfApplyAdmittanceMatrixStamp(
mY);
558 throw std::invalid_argument(
"There are no bus");
570 SPDLOG_LOGGER_WARN(
mSLog,
"mF[{}] not finite (NaN/Inf)", i);
606 SPDLOG_LOGGER_DEBUG(
mSLog,
"Mismatch vector at iteration {}: \n {}", i,
mF);
623 Bool settled =
false;
633 if (converged && !settled) {
637 "Q-limit outer loop did not settle within {} iterations; "
638 "PV/PQ classification may still be oscillating",
648 mSolver.generateInitialSolution(time, mSolver.mKeepLastSolution);
649 mSolver.solvePowerflow();
650 mSolver.setSolution();
654 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
Eigen::SparseMatrix< Complex, Eigen::ColMajor > SparseMatrixComp
Sparse matrix for complex numbers.