DPsim
Loading...
Searching...
No Matches
PFSolver.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#include <dpsim/PFSolver.h>
12#include <iostream>
13
14using namespace DPsim;
15using namespace CPS;
16
18 CPS::Real timeStep, CPS::Logger::Level logLevel)
19 : Solver(name + "_PF", logLevel) {
20 mSystem = system;
21 mTimeStep = timeStep;
22}
23
25 SPDLOG_LOGGER_INFO(mSLog, "#### INITIALIZATION OF POWERFLOW SOLVER ");
26 // mComponentsAtNode is a view derived from mComponents; rebuild it here so
27 // the solver never sees entries for removed or re-added components (#635)
28 mSystem.componentsAtNodeList();
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))
32 mSynchronGenerators.push_back(gen);
33 else if (std::shared_ptr<CPS::SP::Ph1::Load> load =
34 std::dynamic_pointer_cast<CPS::SP::Ph1::Load>(comp))
35 mLoads.push_back(load);
36 else if (std::shared_ptr<CPS::SP::Ph1::Transformer> trafo =
37 std::dynamic_pointer_cast<CPS::SP::Ph1::Transformer>(comp))
38 mTransformers.push_back(trafo);
39 else if (std::shared_ptr<CPS::SP::Ph1::PiLine> line =
40 std::dynamic_pointer_cast<CPS::SP::Ph1::PiLine>(comp))
41 mLines.push_back(line);
42 else if (std::shared_ptr<CPS::SP::Ph1::NetworkInjection> extnet =
43 std::dynamic_pointer_cast<CPS::SP::Ph1::NetworkInjection>(
44 comp))
45 mExternalGrids.push_back(extnet);
46 else if (std::shared_ptr<CPS::SP::Ph1::Shunt> shunt =
47 std::dynamic_pointer_cast<CPS::SP::Ph1::Shunt>(comp))
48 mShunts.push_back(shunt);
49 else if (std::shared_ptr<CPS::SP::Ph1::SolidStateTransformer> sst =
50 std::dynamic_pointer_cast<CPS::SP::Ph1::SolidStateTransformer>(
51 comp))
52 mSolidStateTransformers.push_back(sst);
53 else if (std::shared_ptr<CPS::SP::Ph1::AvVoltageSourceInverterDQ> vsi =
54 std::dynamic_pointer_cast<
56 mAverageVoltageSourceInverters.push_back(vsi);
57 }
58 }
59
66
68 mX.setZero(mNumUnknowns);
69 mF.setZero(mNumUnknowns);
70}
71
75
77 auto sparseJ = mJ.sparseView();
78 Eigen::SparseLU<SparseMatrix> lu(sparseJ);
79 mX = lu.solve(mF);
80}
81
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 {}",
88 mSystem.mNodes[idx]->uid(),
89 mSystem.mNodes[idx]->matrixNodeIndex());
90 ++matrixNodeIndexIdx;
91 }
92 SPDLOG_LOGGER_INFO(mSLog, "Number of simulation nodes: {:d}",
93 matrixNodeIndexIdx);
94}
95
97 for (auto comp : mSystem.mComponents) {
98 std::dynamic_pointer_cast<SimPowerComp<Complex>>(comp)
99 ->updateMatrixNodeIndices();
100 }
101
102 SPDLOG_LOGGER_INFO(
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);
106 if (!pComp)
107 continue;
109 pComp->initializeFromNodesAndTerminals(mSystem.mSystemFrequency);
110 }
111
112 SPDLOG_LOGGER_INFO(mSLog,
113 "-- Calculate per unit parameters for all components");
114 for (auto extnet : mExternalGrids) {
115 extnet->calculatePerUnitParameters(mBaseApparentPower,
116 mSystem.mSystemOmega);
117 }
118 for (auto line : mLines) {
119 line->calculatePerUnitParameters(mBaseApparentPower, mSystem.mSystemOmega);
120 }
121 for (auto trans : mTransformers) {
122 trans->calculatePerUnitParameters(mBaseApparentPower, mSystem.mSystemOmega);
123 }
124 for (auto shunt : mShunts) {
125 shunt->calculatePerUnitParameters(mBaseApparentPower, mSystem.mSystemOmega);
126 }
127 for (auto load : mLoads) {
128 load->calculatePerUnitParameters(mBaseApparentPower, mSystem.mSystemOmega);
129 }
130 for (auto gen : mSynchronGenerators) {
131 gen->calculatePerUnitParameters(mBaseApparentPower, mSystem.mSystemOmega);
132 }
133 for (auto sst : mSolidStateTransformers) {
134 sst->calculatePerUnitParameters(mBaseApparentPower, mSystem.mSystemOmega);
135 }
136}
137
139 Real maxPower = 0.;
140 if (!mSynchronGenerators.empty()) {
141 for (auto gen : mSynchronGenerators)
142 if (std::abs(gen->attributeTyped<Real>("P_set")->get()) > maxPower)
143 maxPower = std::abs(gen->attributeTyped<Real>("P_set")->get());
144 } else if (!mTransformers.empty()) {
145 for (auto trafo : mTransformers)
146 if (trafo->attributeTyped<Real>("S")->get() > maxPower)
147 maxPower = trafo->attributeTyped<Real>("S")->get();
148 }
149 if (maxPower != 0.)
150 mBaseApparentPower = pow(10, 1 + floor(log10(maxPower)));
151 else {
153 SPDLOG_LOGGER_WARN(mSLog,
154 "No suitable quantity found for setting "
155 "mBaseApparentPower. Using {} VA.",
157 }
158 SPDLOG_LOGGER_INFO(mSLog, "Base power = {} VA", mBaseApparentPower);
159}
160
162 mPQBuses.clear();
163 mPVBuses.clear();
164 mVDBuses.clear();
165
166 SPDLOG_LOGGER_INFO(mSLog, "-- Determine powerflow bus type for each node");
167
168 // Determine powerflow bus type of each node through analysis of system topology
169 for (auto node : mSystem.mNodes) {
170 bool connectedPV = false;
171 bool connectedPQ = false;
172 bool connectedVD = false;
173
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)) {
177 if (load->mPowerflowBusType == CPS::PowerflowBusType::PQ) {
178 connectedPQ = true;
179 }
180 } else if (std::shared_ptr<CPS::SP::Ph1::SynchronGenerator> gen =
181 std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(
182 comp)) {
183 if (gen->mPowerflowBusType == CPS::PowerflowBusType::PV) {
184 connectedPV = true;
185 } else if (gen->mPowerflowBusType == CPS::PowerflowBusType::VD) {
186 connectedVD = true;
187 } else if (gen->mPowerflowBusType == CPS::PowerflowBusType::PQ) {
188 connectedPQ = true;
189 }
190 } else if (std::shared_ptr<CPS::SP::Ph1::NetworkInjection> extnet =
191 std::dynamic_pointer_cast<CPS::SP::Ph1::NetworkInjection>(
192 comp)) {
193 if (extnet->mPowerflowBusType == CPS::PowerflowBusType::VD) {
194 connectedVD = true;
195 } else if (extnet->mPowerflowBusType == CPS::PowerflowBusType::PV) {
196 connectedPV = true;
197 }
198 }
199 }
200
201 // determine powerflow bus types according connected type of connected components
202 // only PQ type component connected -> set as PQ bus
203 if (!connectedPV && connectedPQ && !connectedVD) {
204 SPDLOG_LOGGER_INFO(
205 mSLog, "{}: only PQ type component connected -> set as PQ bus",
206 node->name());
207 mPQBuses.push_back(node);
208 } // no component connected -> set as PQ bus (P & Q will be zero)
209 else if (!connectedPV && !connectedPQ && !connectedVD) {
210 SPDLOG_LOGGER_INFO(mSLog, "{}: no component connected -> set as PQ bus",
211 node->name());
212 mPQBuses.push_back(node);
213 } // only PV type component connected -> set as PV bus
214 else if (connectedPV && !connectedPQ && !connectedVD) {
215 SPDLOG_LOGGER_INFO(
216 mSLog, "{}: only PV type component connected -> set as PV bus",
217 node->name());
218 mPVBuses.push_back(node);
219 } // PV and PQ type component connected -> set as PV bus (TODO: bus type should be modifiable by user afterwards)
220 else if (connectedPV && connectedPQ && !connectedVD) {
221 SPDLOG_LOGGER_INFO(
222 mSLog, "{}: PV and PQ type component connected -> set as PV bus",
223 node->name());
224 mPVBuses.push_back(node);
225 } // only VD type component connected -> set as VD bus
226 else if (!connectedPV && !connectedPQ && connectedVD) {
227 SPDLOG_LOGGER_INFO(
228 mSLog, "{}: only VD type component connected -> set as VD bus",
229 node->name());
230 mVDBuses.push_back(node);
231 } // VD and PV type component connect -> set as VD bus
232 else if (connectedPV && !connectedPQ && connectedVD) {
233 SPDLOG_LOGGER_INFO(
234 mSLog, "{}: VD and PV type component connect -> set as VD bus",
235 node->name());
236 mVDBuses.push_back(node);
237 } // VD, PV and PQ type component connect -> set as VD bus
238 else if (connectedPV && connectedPQ && connectedVD) {
239 SPDLOG_LOGGER_INFO(
240 mSLog, "{}: VD, PV and PQ type component connect -> set as VD bus",
241 node->name());
242 mVDBuses.push_back(node);
243 } else {
244 std::stringstream ss;
245 ss << "Node>>" << node->name()
246 << ": combination of connected components is invalid";
247 throw std::invalid_argument(ss.str());
248 }
249 }
250
252
253 // Snapshot so each solve can reset before Q-limit switching (solver is reused).
256
257 SPDLOG_LOGGER_INFO(mSLog, "#### Create index vectors for power flow solver:");
258 SPDLOG_LOGGER_INFO(mSLog, "PQ Buses: {}", logVector(mPQBusIndices));
259 SPDLOG_LOGGER_INFO(mSLog, "PV Buses: {}", logVector(mPVBusIndices));
260 SPDLOG_LOGGER_INFO(mSLog, "VD Buses: {}", logVector(mVDBusIndices));
261}
262
264 // Rebuild index vectors from the PQ/PV/VD lists (initial + after each Q-limit switch).
265 mPQBusIndices.clear();
266 mPVBusIndices.clear();
267 mVDBusIndices.clear();
268 for (auto node : mPQBuses)
269 mPQBusIndices.push_back(node->matrixNodeIndex());
270 for (auto node : mPVBuses)
271 mPVBusIndices.push_back(node->matrixNodeIndex());
272 for (auto node : mVDBuses)
273 mVDBusIndices.push_back(node->matrixNodeIndex());
274
275 mNumPQBuses = mPQBusIndices.size();
276 mNumPVBuses = mPVBusIndices.size();
277 mNumVDBuses = mVDBusIndices.size();
279
280 // Aggregate PQ bus and PV bus index vectors for easy handling in solver
281 mPQPVBusIndices.clear();
283 mPQPVBusIndices.insert(mPQPVBusIndices.end(), mPQBusIndices.begin(),
284 mPQBusIndices.end());
285 mPQPVBusIndices.insert(mPQPVBusIndices.end(), mPVBusIndices.begin(),
286 mPVBusIndices.end());
287}
288
290 // Reset to the pre-switching classification so a fresh solve starts clean.
295}
296
298 // Re-derive index vectors and resize storage; sol_V/sol_D carry over as a warm start.
301 mX.setZero(mNumUnknowns);
302 mF.setZero(mNumUnknowns);
303}
304
307 if (auto vsi =
308 std::dynamic_pointer_cast<CPS::SP::Ph1::AvVoltageSourceInverterDQ>(
309 comp))
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();
320 return 0;
321 }
322 if (auto gen =
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();
327 if (auto extnet =
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());
333 return 0;
334}
335
337
338 SPDLOG_LOGGER_INFO(mSLog, "-- Determine base voltages for each node "
339 "according to connected components");
340 mSLog->flush();
341
342 // Zones: nodes joined by a line share one voltage level; transformers are boundaries.
343 std::vector<UInt> zoneParent(mSystem.mNodes.size());
344 for (UInt i = 0; i < zoneParent.size(); ++i)
345 zoneParent[i] = i;
346 auto findZone = [&](UInt node) -> UInt {
347 while (zoneParent[node] != node) {
348 zoneParent[node] = zoneParent[zoneParent[node]];
349 node = zoneParent[node];
350 }
351 return node;
352 };
353 auto uniteZones = [&](UInt a, UInt b) {
354 zoneParent[findZone(a)] = findZone(b);
355 };
356
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());
365 }
366
367 // Generator/Transformer/NetworkInjection/VSI ratings are authoritative;
368 // everything else (incl. Load's solved-voltage proxy) is a looser fallback.
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);
377
378 CPS::Real voltage = componentBaseVoltage(comp, node);
379 if (std::abs(voltage) <= 1e-6)
380 continue;
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>(
386 comp);
387 auto &bucket = isAuthoritative ? authoritative : fallback;
388 bucket[zone].emplace_back(voltage, comp->name());
389 }
390 }
391
392 // Disagreement beyond tolerance means two voltage levels are wired together without a transformer.
393 auto verify =
394 [&](const std::vector<std::pair<CPS::Real, CPS::String>> &candidates,
395 CPS::Real reference, const CPS::String &refSource,
396 CPS::Real tolerance) {
397 for (auto &candidate : candidates) {
398 CPS::Real relDiff =
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());
408 }
409 }
410 };
411
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;
418 }
419 // Fallback checked against the zone's rating, or each other if there is none.
420 for (auto &entry : fallback) {
421 auto it = zoneVoltage.find(entry.first);
422 bool hasAuthoritative = it != zoneVoltage.end();
423 CPS::Real reference =
424 hasAuthoritative ? it->second : entry.second.front().first;
425 const CPS::String &refSource = hasAuthoritative
426 ? "the zone's authoritative rating"
427 : entry.second.front().second;
428 verify(entry.second, reference, refSource, mBaseVoltageLooseTolerance);
429 if (!hasAuthoritative)
430 zoneVoltage[entry.first] = reference;
431 }
432
433 // Assign the resolved zone voltage to every node in it.
434 for (auto node : mSystem.mNodes) {
435 auto it = zoneVoltage.find(findZone(node->matrixNodeIndex()));
436 mBaseVoltageAtNode[node] = it != zoneVoltage.end() ? it->second : 0;
437 }
438
439 // Sync each Load's nominal voltage to its zone's resolved value.
440 for (auto &entry : zoneVoltage) {
441 auto it = zoneLoads.find(entry.first);
442 if (it == zoneLoads.end())
443 continue;
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(),
448 entry.second);
449 }
450 }
451
452 UInt numMissing = 0;
453 UInt numZero = 0;
454
455 for (auto node : mSystem.mNodes) {
456
457 auto it = mBaseVoltageAtNode.find(node);
458
459 if (it == mBaseVoltageAtNode.end()) {
460 SPDLOG_LOGGER_WARN(mSLog, "No base voltage entry for {}", node->name());
461
462 numMissing++;
463 continue;
464 }
465
466 if (std::abs(it->second) < 1e-6) {
467 SPDLOG_LOGGER_WARN(mSLog, "Zero base voltage for {}", node->name());
468
469 numZero++;
470 }
471 }
472
473 SPDLOG_LOGGER_INFO(mSLog, "Base voltage summary: missing={}, zero={}",
474 numMissing, numZero);
475}
476
478 if (!mExternalGrids.empty()) {
479 if (mExternalGrids[0]->node(0)->name() == name) {
480 mExternalGrids[0]->modifyPowerFlowBusType(CPS::PowerflowBusType::VD);
481 }
482 } else {
483 for (auto gen : mSynchronGenerators) {
484 if (gen->node(0)->name() == name) {
485 gen->modifyPowerFlowBusType(CPS::PowerflowBusType::VD);
486 return;
487 }
488 }
489 throw std::invalid_argument("Invalid slack bus, no external grid or "
490 "synchronous generator attached");
491 }
492}
493
495 CPS::String name, CPS::PowerflowBusType powerFlowBusType) {
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>(
503 comp))
504 gen->modifyPowerFlowBusType(powerFlowBusType);
505 }
506 }
507}
508
510 mBehaviour = behaviour;
512 SPDLOG_LOGGER_INFO(mSLog, "-- Set solver behaviour to Initialization");
513 // TODO: solver setting specific to initialization (e.g. one single PF run)
514
515 SPDLOG_LOGGER_INFO(mSLog, "-- Set component behaviour to Initialization");
516 for (auto comp : mSystem.mComponents) {
517 auto powerComp =
518 std::dynamic_pointer_cast<CPS::TopologicalPowerComp>(comp);
519 if (powerComp)
520 powerComp->setBehaviour(
522 }
523 } else {
524 SPDLOG_LOGGER_INFO(mSLog, "-- Set solver behaviour to Simulation");
525 // TODO: solver setting specific to simulation
526
527 SPDLOG_LOGGER_INFO(mSLog, "-- Set component behaviour to PFSimulation");
528 for (auto comp : mSystem.mComponents) {
529 auto powerComp =
530 std::dynamic_pointer_cast<CPS::TopologicalPowerComp>(comp);
531 if (powerComp)
532 powerComp->setBehaviour(TopologicalPowerComp::Behaviour::PFSimulation);
533 }
534 }
535}
536
538 int n = mSystem.mNodes.size();
539 if (n > 0) {
541 for (auto line : mLines) {
542 line->pfApplyAdmittanceMatrixStamp(mY);
543 }
544 for (auto trans : mTransformers) {
545 //to check if this transformer could be ignored
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());
549 continue;
550 }
551 trans->pfApplyAdmittanceMatrixStamp(mY);
552 }
553 for (auto shunt : mShunts) {
554 shunt->pfApplyAdmittanceMatrixStamp(mY);
555 }
556 }
557 if (mLines.empty() && mTransformers.empty()) {
558 throw std::invalid_argument("There are no bus");
559 }
560}
561
562CPS::Real PFSolver::G(int i, int j) { return mY.coeff(i, j).real(); }
563
564CPS::Real PFSolver::B(int i, int j) { return mY.coeff(i, j).imag(); }
565
567 // Converged if all mismatches are below the tolerance
568 for (CPS::UInt i = 0; i < mNumUnknowns; i++) {
569 if (!Math::isFinite(mF(i))) {
570 SPDLOG_LOGGER_WARN(mSLog, "mF[{}] not finite (NaN/Inf)", i);
571 return false;
572 }
573 if (abs(mF(i)) > mTolerance)
574 return false;
575 }
576 return true;
577}
578
580
581 // Reset values for new power flow run
582 isConverged = false;
583 mIterations = 0;
584 mX.setZero();
585 mF.setZero();
586
587 // Calculate the mismatch according to the initial solution
589
590 // Check whether model already converged
592
593 for (unsigned i = 1; i < mMaxIterations && !isConverged; ++i) {
594
596
597 // Solve system mJ*mX = mF
599
600 // Calculate new solution based on mX increments obtained from equation system
602
603 // Calculate the mismatch according to the current solution
605
606 SPDLOG_LOGGER_DEBUG(mSLog, "Mismatch vector at iteration {}: \n {}", i, mF);
607 mSLog->flush();
608
609 // Check convergence
611 mIterations = i;
612 }
613 return isConverged;
614}
615
617 Bool converged = runNewtonRaphson();
618
620 return converged;
621
622 // Outer loop: switch PV<->PQ on Q-limit violations, re-solve until no bus switches.
623 Bool settled = false;
624 for (CPS::UInt outer = 0; converged && outer < mMaxOuterIterations; ++outer) {
625 if (!enforceReactiveLimits()) {
626 settled = true;
627 break; // all generators within their reactive limits
628 }
630 converged = runNewtonRaphson();
631 }
632
633 if (converged && !settled) {
634 // Unsettled PV/PQ classification must not look converged to setSolution().
635 SPDLOG_LOGGER_WARN(
636 mSLog,
637 "Q-limit outer loop did not settle within {} iterations; "
638 "PV/PQ classification may still be oscillating",
640 isConverged = false;
641 converged = false;
642 }
643 return converged;
644}
645
646void PFSolver::SolveTask::execute(Real time, Int timeStepCount) {
647 // apply keepLastSolution to save computation time
648 mSolver.generateInitialSolution(time, mSolver.mKeepLastSolution);
649 mSolver.solvePowerflow();
650 mSolver.setSolution();
651}
652
654 return Task::List{std::make_shared<SolveTask>(*this)};
655}
spdlog::level::level_enum Level
Definition Logger.h:33
static bool isFinite(Real value)
Definition MathUtils.cpp:63
std::vector< Ptr > List
Definition Task.h:28
std::shared_ptr< TopologicalNode > Ptr
std::shared_ptr< TopologicalPowerComp > Ptr
void execute(Real time, Int timeStepCount)
Definition PFSolver.cpp:646
void determinePFBusType()
Determine bus type for all buses.
Definition PFSolver.cpp:161
void reclassifyBuses()
Re-derive index vectors and resize the system after PV<->PQ switching.
Definition PFSolver.cpp:297
CPS::Real mBaseApparentPowerFallback
Fallback base apparent power if no generator or transformer rating is found.
Definition PFSolver.h:102
Bool runNewtonRaphson()
Run a single Newton-Raphson solve with the current bus classification.
Definition PFSolver.cpp:579
void resetToOriginalClassification()
Restore the original PV/PQ classification before a fresh solve.
Definition PFSolver.cpp:289
std::vector< std::shared_ptr< CPS::SP::Ph1::Load > > mLoads
Vector of load components.
Definition PFSolver.h:70
CPS::TopologicalNode::List mPQBuses
Vector of nodes characterized as PQ buses.
Definition PFSolver.h:32
UInt mNumPQBuses
Number of PQ nodes.
Definition PFSolver.h:24
virtual void solveJacobianSystem()
Solve the linearized system mJ*mX = mF into mX; sparse subclass overrides.
Definition PFSolver.cpp:76
UInt mNumVDBuses
Number of PV nodes.
Definition PFSolver.h:28
Real mTolerance
Solver tolerance.
Definition PFSolver.h:84
CPS::String logVector(std::vector< CPS::UInt > indexVector)
Logging for integer vectors.
Definition PFSolver.h:168
std::vector< std::shared_ptr< CPS::SP::Ph1::PiLine > > mLines
Vector of line components.
Definition PFSolver.h:72
CPS::Task::List getTasks() override
Get tasks for scheduler.
Definition PFSolver.cpp:653
void assignMatrixNodeIndices()
Assignment of matrix indices for nodes.
Definition PFSolver.cpp:82
std::vector< CPS::UInt > mVDBusIndices
Vector with indices of VD buses.
Definition PFSolver.h:45
virtual void setUpJacobianStorage()
Allocate Jacobian storage; dense by default, sparse subclass overrides.
Definition PFSolver.cpp:72
void initializeComponents()
Initialization of individual components.
Definition PFSolver.cpp:96
std::vector< std::shared_ptr< CPS::SP::Ph1::SynchronGenerator > > mSynchronGenerators
Vector of synchronous generator components.
Definition PFSolver.h:68
CPS::TopologicalNode::List mPVBusesOrig
Definition PFSolver.h:39
void propagateAndVerifyBaseVoltage()
Determine, verify and propagate each node's base voltage per electrical zone.
Definition PFSolver.cpp:336
std::vector< CPS::UInt > mPQBusIndices
Vector with indices of PQ buses.
Definition PFSolver.h:41
void modifyPowerFlowBusComponent(CPS::String name, CPS::PowerflowBusType powerFlowBusType)
Allows to modify the powerflow bus type of a specific component.
Definition PFSolver.cpp:494
std::vector< std::shared_ptr< CPS::SP::Ph1::NetworkInjection > > mExternalGrids
Vector of external grid components.
Definition PFSolver.h:76
std::vector< std::shared_ptr< CPS::SP::Ph1::SolidStateTransformer > > mSolidStateTransformers
Vector of solid state transformer components.
Definition PFSolver.h:65
std::vector< CPS::UInt > mPVBusIndices
Vector with indices of PV buses.
Definition PFSolver.h:43
void setVDNode(CPS::String name)
Set a node to VD using its name.
Definition PFSolver.cpp:477
std::vector< std::shared_ptr< CPS::SP::Ph1::Transformer > > mTransformers
Vector of transformer components.
Definition PFSolver.h:62
std::vector< std::shared_ptr< CPS::SP::Ph1::Shunt > > mShunts
Vector of shunt components.
Definition PFSolver.h:74
CPS::Bool checkConvergence()
Check whether below tolerance.
Definition PFSolver.cpp:566
CPS::Matrix mJ
Jacobian matrix.
Definition PFSolver.h:53
CPS::UInt mMaxIterations
Maximum number of iterations.
Definition PFSolver.h:86
CPS::Real componentBaseVoltage(CPS::TopologicalPowerComp::Ptr comp, CPS::TopologicalNode::Ptr node)
Base voltage a single component reports for node, or 0 if unknown.
Definition PFSolver.cpp:305
CPS::Vector mX
Solution vector.
Definition PFSolver.h:55
std::vector< std::shared_ptr< CPS::SP::Ph1::AvVoltageSourceInverterDQ > > mAverageVoltageSourceInverters
Vector of average voltage source inverters.
Definition PFSolver.h:79
void rebuildBusIndexAggregates()
Rebuild index vectors + counts from the PQ/PV/VD node lists.
Definition PFSolver.cpp:263
CPS::Real mBaseApparentPower
Base power of per-unit system.
Definition PFSolver.h:100
void setBaseApparentPower()
Set apparent base power of per-unit system.
Definition PFSolver.cpp:138
virtual void calculateMismatch()=0
Calculate mismatch.
CPS::SparseMatrixCompRow mY
Admittance matrix.
Definition PFSolver.h:50
UInt mNumPVBuses
Number of PV nodes.
Definition PFSolver.h:26
CPS::Real B(int i, int j)
Gets the imaginary part of admittance matrix element.
Definition PFSolver.cpp:564
void composeAdmittanceMatrix()
Compose admittance matrix.
Definition PFSolver.cpp:537
CPS::TopologicalNode::List mPQBusesOrig
Original PQ/PV classification (snapshot before Q-limit switching)
Definition PFSolver.h:38
CPS::Bool isConverged
Convergence flag.
Definition PFSolver.h:104
CPS::Vector mF
Vector of mismatch values.
Definition PFSolver.h:57
CPS::UInt mIterations
Actual number of iterations.
Definition PFSolver.h:88
CPS::UInt mMaxOuterIterations
Maximum number of Q-limit outer iterations.
Definition PFSolver.h:92
virtual CPS::Bool enforceReactiveLimits()
Switch generators violating their Q limits between PV/PQ; base impl is a no-op.
Definition PFSolver.h:160
PFSolver(CPS::String name, CPS::SystemTopology system, Real timeStep, CPS::Logger::Level logLevel)
Constructor to be used in simulation examples.
Definition PFSolver.cpp:17
CPS::SystemTopology mSystem
System list.
Definition PFSolver.h:60
virtual void calculateJacobian()=0
Calculate the Jacobian.
void setSolverAndComponentBehaviour(Solver::Behaviour behaviour) override
set solver and component to initialization or simulation behaviour
Definition PFSolver.cpp:509
std::map< CPS::TopologicalNode::Ptr, CPS::Real > mBaseVoltageAtNode
Map providing determined base voltages for each node.
Definition PFSolver.h:81
void initialize() override
Initialization of the solver.
Definition PFSolver.cpp:24
CPS::Real mBaseVoltageLooseTolerance
Relative tolerance for non-authoritative (e.g. Load) base-voltage candidates vs. the zone's rating.
Definition PFSolver.h:96
CPS::Real mBaseVoltageStrictTolerance
Relative tolerance between authoritative base-voltage sources (generator/transformer/network-injectio...
Definition PFSolver.h:98
virtual void updateSolution()=0
Update solution in each iteration.
Bool solvePowerflow()
Solves the powerflow problem.
Definition PFSolver.cpp:616
CPS::Bool mEnforceReactiveLimits
Enforce generator reactive-power limits via PV<->PQ outer-loop switching.
Definition PFSolver.h:90
CPS::TopologicalNode::List mVDBuses
Vector of nodes characterized as VD buses.
Definition PFSolver.h:36
CPS::TopologicalNode::List mPVBuses
Vector of nodes characterized as PV buses.
Definition PFSolver.h:34
UInt mNumUnknowns
Number of unknowns, defining system dimension.
Definition PFSolver.h:30
virtual void clearReactiveLimitState()
Clear Q-limit bookkeeping; overridden by PFSolverPowerPolar.
Definition PFSolver.h:142
CPS::Real G(int i, int j)
Gets the real part of admittance matrix element.
Definition PFSolver.cpp:562
std::vector< CPS::UInt > mPQPVBusIndices
Vector with indices of both PQ and PV buses.
Definition PFSolver.h:47
Real mTimeStep
Time step for fixed step solvers.
Definition Solver.h:57
Behaviour mBehaviour
Solver behaviour initialization or simulation.
Definition Solver.h:80
CPS::Logger::Log mSLog
Logger.
Definition Solver.h:55
Solver(String name, CPS::Logger::Level logLevel)
Definition Solver.h:83
Bool mInitFromNodesAndTerminals
Definition Solver.h:72
@ Initialization
Definition Solver.h:35
PowerflowBusType
std::string String
Definition Definitions.h:65
Eigen::SparseMatrix< Complex, Eigen::ColMajor > SparseMatrixComp
Sparse matrix for complex numbers.
Definition Definitions.h:76
double Real
Definition Definitions.h:62
bool Bool
Definition Definitions.h:64
unsigned int UInt
Definition Definitions.h:60
CPS::Real Real
Definition Definitions.h:18
CPS::Int Int
Definition Definitions.h:22
CPS::Bool Bool
Definition Definitions.h:21
CPS::UInt UInt
Definition Definitions.h:23