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
26 SPDLOG_LOGGER_INFO(mSLog, "#### INITIALIZATION OF POWERFLOW SOLVER ");
27 // mComponentsAtNode is a view derived from mComponents; rebuild it here so
28 // the solver never sees entries for removed or re-added components (#635)
29 mSystem.componentsAtNodeList();
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))
33 mSynchronGenerators.push_back(gen);
34 else if (std::shared_ptr<CPS::SP::Ph1::Load> load =
35 std::dynamic_pointer_cast<CPS::SP::Ph1::Load>(comp))
36 mLoads.push_back(load);
37 else if (std::shared_ptr<CPS::SP::Ph1::Transformer> trafo =
38 std::dynamic_pointer_cast<CPS::SP::Ph1::Transformer>(comp))
39 mTransformers.push_back(trafo);
40 else if (std::shared_ptr<CPS::SP::Ph1::PiLine> line =
41 std::dynamic_pointer_cast<CPS::SP::Ph1::PiLine>(comp))
42 mLines.push_back(line);
43 else if (std::shared_ptr<CPS::SP::Ph1::NetworkInjection> extnet =
44 std::dynamic_pointer_cast<CPS::SP::Ph1::NetworkInjection>(
45 comp))
46 mExternalGrids.push_back(extnet);
47 else if (std::shared_ptr<CPS::SP::Ph1::Shunt> shunt =
48 std::dynamic_pointer_cast<CPS::SP::Ph1::Shunt>(comp))
49 mShunts.push_back(shunt);
50 else if (std::shared_ptr<CPS::SP::Ph1::SolidStateTransformer> sst =
51 std::dynamic_pointer_cast<CPS::SP::Ph1::SolidStateTransformer>(
52 comp))
53 mSolidStateTransformers.push_back(sst);
54 else if (std::shared_ptr<CPS::SP::Ph1::AvVoltageSourceInverterDQ> vsi =
55 std::dynamic_pointer_cast<
57 mAverageVoltageSourceInverters.push_back(vsi);
58 }
59 }
60
67
69 mX.setZero(mNumUnknowns);
70 mF.setZero(mNumUnknowns);
71}
72
76
78 auto sparseJ = mJ.sparseView();
79 Eigen::SparseLU<SparseMatrix> lu(sparseJ);
80 mX = lu.solve(mF);
81}
82
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 {}",
89 mSystem.mNodes[idx]->uid(),
90 mSystem.mNodes[idx]->matrixNodeIndex());
91 ++matrixNodeIndexIdx;
92 }
93 SPDLOG_LOGGER_INFO(mSLog, "Number of simulation nodes: {:d}",
94 matrixNodeIndexIdx);
95}
96
98 for (auto comp : mSystem.mComponents) {
99 std::dynamic_pointer_cast<SimPowerComp<Complex>>(comp)
100 ->updateMatrixNodeIndices();
101 }
102
103 SPDLOG_LOGGER_INFO(
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);
107 if (!pComp)
108 continue;
110 pComp->initializeFromNodesAndTerminals(mSystem.mSystemFrequency);
111 }
112
113 SPDLOG_LOGGER_INFO(mSLog,
114 "-- Calculate per unit parameters for all components");
115 for (auto extnet : mExternalGrids) {
116 extnet->calculatePerUnitParameters(mBaseApparentPower,
117 mSystem.mSystemOmega);
118 }
119 for (auto line : mLines) {
120 line->calculatePerUnitParameters(mBaseApparentPower, mSystem.mSystemOmega);
121 }
122 for (auto trans : mTransformers) {
123 trans->calculatePerUnitParameters(mBaseApparentPower, mSystem.mSystemOmega);
124 }
125 for (auto shunt : mShunts) {
126 shunt->calculatePerUnitParameters(mBaseApparentPower, mSystem.mSystemOmega);
127 }
128 for (auto load : mLoads) {
129 load->calculatePerUnitParameters(mBaseApparentPower, mSystem.mSystemOmega);
130 }
131 for (auto gen : mSynchronGenerators) {
132 gen->calculatePerUnitParameters(mBaseApparentPower, mSystem.mSystemOmega);
133 }
134 for (auto sst : mSolidStateTransformers) {
135 sst->calculatePerUnitParameters(mBaseApparentPower, mSystem.mSystemOmega);
136 }
137}
138
140 Real maxPower = 0.;
141 if (!mSynchronGenerators.empty()) {
142 for (auto gen : mSynchronGenerators)
143 if (std::abs(gen->attributeTyped<Real>("P_set")->get()) > maxPower)
144 maxPower = std::abs(gen->attributeTyped<Real>("P_set")->get());
145 } else if (!mTransformers.empty()) {
146 for (auto trafo : mTransformers)
147 if (trafo->attributeTyped<Real>("S")->get() > maxPower)
148 maxPower = trafo->attributeTyped<Real>("S")->get();
149 }
150 if (maxPower != 0.)
151 mBaseApparentPower = pow(10, 1 + floor(log10(maxPower)));
152 else {
154 SPDLOG_LOGGER_WARN(mSLog,
155 "No suitable quantity found for setting "
156 "mBaseApparentPower. Using {} VA.",
158 }
159 SPDLOG_LOGGER_INFO(mSLog, "Base power = {} VA", mBaseApparentPower);
160}
161
163 mPQBuses.clear();
164 mPVBuses.clear();
165 mVDBuses.clear();
166
167 SPDLOG_LOGGER_INFO(mSLog, "-- Determine powerflow bus type for each node");
168
169 // Determine powerflow bus type of each node through analysis of system topology
170 for (auto node : mSystem.mNodes) {
171 bool connectedPV = false;
172 bool connectedPQ = false;
173 bool connectedVD = false;
174
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)) {
178 if (load->mPowerflowBusType == CPS::PowerflowBusType::PQ) {
179 connectedPQ = true;
180 }
181 } else if (std::shared_ptr<CPS::SP::Ph1::SynchronGenerator> gen =
182 std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(
183 comp)) {
184 if (gen->mPowerflowBusType == CPS::PowerflowBusType::PV) {
185 connectedPV = true;
186 } else if (gen->mPowerflowBusType == CPS::PowerflowBusType::VD) {
187 connectedVD = true;
188 } else if (gen->mPowerflowBusType == CPS::PowerflowBusType::PQ) {
189 connectedPQ = true;
190 }
191 } else if (std::shared_ptr<CPS::SP::Ph1::NetworkInjection> extnet =
192 std::dynamic_pointer_cast<CPS::SP::Ph1::NetworkInjection>(
193 comp)) {
194 if (extnet->mPowerflowBusType == CPS::PowerflowBusType::VD) {
195 connectedVD = true;
196 } else if (extnet->mPowerflowBusType == CPS::PowerflowBusType::PV) {
197 connectedPV = true;
198 }
199 }
200 }
201
202 // determine powerflow bus types according connected type of connected components
203 // only PQ type component connected -> set as PQ bus
204 if (!connectedPV && connectedPQ && !connectedVD) {
205 SPDLOG_LOGGER_INFO(
206 mSLog, "{}: only PQ type component connected -> set as PQ bus",
207 node->name());
208 mPQBuses.push_back(node);
209 } // no component connected -> set as PQ bus (P & Q will be zero)
210 else if (!connectedPV && !connectedPQ && !connectedVD) {
211 SPDLOG_LOGGER_INFO(mSLog, "{}: no component connected -> set as PQ bus",
212 node->name());
213 mPQBuses.push_back(node);
214 } // only PV type component connected -> set as PV bus
215 else if (connectedPV && !connectedPQ && !connectedVD) {
216 SPDLOG_LOGGER_INFO(
217 mSLog, "{}: only PV type component connected -> set as PV bus",
218 node->name());
219 mPVBuses.push_back(node);
220 } // PV and PQ type component connected -> set as PV bus (TODO: bus type should be modifiable by user afterwards)
221 else if (connectedPV && connectedPQ && !connectedVD) {
222 SPDLOG_LOGGER_INFO(
223 mSLog, "{}: PV and PQ type component connected -> set as PV bus",
224 node->name());
225 mPVBuses.push_back(node);
226 } // only VD type component connected -> set as VD bus
227 else if (!connectedPV && !connectedPQ && connectedVD) {
228 SPDLOG_LOGGER_INFO(
229 mSLog, "{}: only VD type component connected -> set as VD bus",
230 node->name());
231 mVDBuses.push_back(node);
232 } // VD and PV type component connect -> set as VD bus
233 else if (connectedPV && !connectedPQ && connectedVD) {
234 SPDLOG_LOGGER_INFO(
235 mSLog, "{}: VD and PV type component connect -> set as VD bus",
236 node->name());
237 mVDBuses.push_back(node);
238 } // VD and PQ type component connected -> set as VD bus
239 else if (!connectedPV && connectedPQ && connectedVD) {
240 SPDLOG_LOGGER_INFO(
241 mSLog, "{}: VD and PQ type component connected -> set as VD bus",
242 node->name());
243 mVDBuses.push_back(node);
244 } // VD, PV and PQ type component connect -> set as VD bus
245 else if (connectedPV && connectedPQ && connectedVD) {
246 SPDLOG_LOGGER_INFO(
247 mSLog, "{}: VD, PV and PQ type component connect -> set as VD bus",
248 node->name());
249 mVDBuses.push_back(node);
250 } else {
251 std::stringstream ss;
252 ss << "Node>>" << node->name()
253 << ": combination of connected components is invalid";
254 throw std::invalid_argument(ss.str());
255 }
256 }
257
259
260 // Snapshot so each solve can reset before Q-limit switching (solver is reused).
263
264 SPDLOG_LOGGER_INFO(mSLog, "#### Create index vectors for power flow solver:");
265 SPDLOG_LOGGER_INFO(mSLog, "PQ Buses: {}", logVector(mPQBusIndices));
266 SPDLOG_LOGGER_INFO(mSLog, "PV Buses: {}", logVector(mPVBusIndices));
267 SPDLOG_LOGGER_INFO(mSLog, "VD Buses: {}", logVector(mVDBusIndices));
268}
269
271 // Rebuild index vectors from the PQ/PV/VD lists (initial + after each Q-limit switch).
272 mPQBusIndices.clear();
273 mPVBusIndices.clear();
274 mVDBusIndices.clear();
275 for (auto node : mPQBuses)
276 mPQBusIndices.push_back(node->matrixNodeIndex());
277 for (auto node : mPVBuses)
278 mPVBusIndices.push_back(node->matrixNodeIndex());
279 for (auto node : mVDBuses)
280 mVDBusIndices.push_back(node->matrixNodeIndex());
281
282 mNumPQBuses = mPQBusIndices.size();
283 mNumPVBuses = mPVBusIndices.size();
284 mNumVDBuses = mVDBusIndices.size();
286
287 // Aggregate PQ bus and PV bus index vectors for easy handling in solver
288 mPQPVBusIndices.clear();
290 mPQPVBusIndices.insert(mPQPVBusIndices.end(), mPQBusIndices.begin(),
291 mPQBusIndices.end());
292 mPQPVBusIndices.insert(mPQPVBusIndices.end(), mPVBusIndices.begin(),
293 mPVBusIndices.end());
294}
295
297 // Reset to the pre-switching classification so a fresh solve starts clean.
302}
303
305 // Re-derive index vectors and resize storage; sol_V/sol_D carry over as a warm start.
308 mX.setZero(mNumUnknowns);
309 mF.setZero(mNumUnknowns);
310}
311
314 if (auto vsi =
315 std::dynamic_pointer_cast<CPS::SP::Ph1::AvVoltageSourceInverterDQ>(
316 comp))
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();
327 return 0;
328 }
329 if (auto gen =
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();
334 if (auto extnet =
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());
340 return 0;
341}
342
344
345 SPDLOG_LOGGER_INFO(mSLog, "-- Determine base voltages for each node "
346 "according to connected components");
347 mSLog->flush();
348
349 // Zones: nodes joined by a line share one voltage level; transformers are boundaries.
350 std::vector<UInt> zoneParent(mSystem.mNodes.size());
351 for (UInt i = 0; i < zoneParent.size(); ++i)
352 zoneParent[i] = i;
353 auto findZone = [&](UInt node) -> UInt {
354 while (zoneParent[node] != node) {
355 zoneParent[node] = zoneParent[zoneParent[node]];
356 node = zoneParent[node];
357 }
358 return node;
359 };
360 auto uniteZones = [&](UInt a, UInt b) {
361 zoneParent[findZone(a)] = findZone(b);
362 };
363
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());
372 }
373
374 // Generator/Transformer/NetworkInjection/VSI ratings are authoritative;
375 // everything else (incl. Load's solved-voltage proxy) is a looser fallback.
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);
384
385 CPS::Real voltage = componentBaseVoltage(comp, node);
386 if (std::abs(voltage) <= 1e-6)
387 continue;
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>(
393 comp);
394 auto &bucket = isAuthoritative ? authoritative : fallback;
395 bucket[zone].emplace_back(voltage, comp->name());
396 }
397 }
398
399 // Disagreement beyond tolerance means two voltage levels are wired together without a transformer.
400 auto verify =
401 [&](const std::vector<std::pair<CPS::Real, CPS::String>> &candidates,
402 CPS::Real reference, const CPS::String &refSource,
403 CPS::Real tolerance) {
404 for (auto &candidate : candidates) {
405 CPS::Real relDiff =
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());
415 }
416 }
417 };
418
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;
425 }
426 // Fallback checked against the zone's rating, or each other if there is none.
427 for (auto &entry : fallback) {
428 auto it = zoneVoltage.find(entry.first);
429 bool hasAuthoritative = it != zoneVoltage.end();
430 CPS::Real reference =
431 hasAuthoritative ? it->second : entry.second.front().first;
432 const CPS::String &refSource = hasAuthoritative
433 ? "the zone's authoritative rating"
434 : entry.second.front().second;
435 verify(entry.second, reference, refSource, mBaseVoltageLooseTolerance);
436 if (!hasAuthoritative)
437 zoneVoltage[entry.first] = reference;
438 }
439
440 // Assign the resolved zone voltage to every node in it.
441 for (auto node : mSystem.mNodes) {
442 auto it = zoneVoltage.find(findZone(node->matrixNodeIndex()));
443 mBaseVoltageAtNode[node] = it != zoneVoltage.end() ? it->second : 0;
444 }
445
446 // Sync each Load's nominal voltage to its zone's resolved value.
447 for (auto &entry : zoneVoltage) {
448 auto it = zoneLoads.find(entry.first);
449 if (it == zoneLoads.end())
450 continue;
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(),
455 entry.second);
456 }
457 }
458
459 UInt numMissing = 0;
460 UInt numZero = 0;
461
462 for (auto node : mSystem.mNodes) {
463
464 auto it = mBaseVoltageAtNode.find(node);
465
466 if (it == mBaseVoltageAtNode.end()) {
467 SPDLOG_LOGGER_WARN(mSLog, "No base voltage entry for {}", node->name());
468
469 numMissing++;
470 continue;
471 }
472
473 if (std::abs(it->second) < 1e-6) {
474 SPDLOG_LOGGER_WARN(mSLog, "Zero base voltage for {}", node->name());
475
476 numZero++;
477 }
478 }
479
480 SPDLOG_LOGGER_INFO(mSLog, "Base voltage summary: missing={}, zero={}",
481 numMissing, numZero);
482}
483
485 if (!mExternalGrids.empty()) {
486 if (mExternalGrids[0]->node(0)->name() == name) {
487 mExternalGrids[0]->modifyPowerFlowBusType(CPS::PowerflowBusType::VD);
488 }
489 } else {
490 for (auto gen : mSynchronGenerators) {
491 if (gen->node(0)->name() == name) {
492 gen->modifyPowerFlowBusType(CPS::PowerflowBusType::VD);
493 return;
494 }
495 }
496 throw std::invalid_argument("Invalid slack bus, no external grid or "
497 "synchronous generator attached");
498 }
499}
500
502 CPS::String name, CPS::PowerflowBusType powerFlowBusType) {
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>(
510 comp))
511 gen->modifyPowerFlowBusType(powerFlowBusType);
512 }
513 }
514}
515
517 mBehaviour = behaviour;
519 SPDLOG_LOGGER_INFO(mSLog, "-- Set solver behaviour to Initialization");
520 // TODO: solver setting specific to initialization (e.g. one single PF run)
521
522 SPDLOG_LOGGER_INFO(mSLog, "-- Set component behaviour to Initialization");
523 for (auto comp : mSystem.mComponents) {
524 auto powerComp =
525 std::dynamic_pointer_cast<CPS::TopologicalPowerComp>(comp);
526 if (powerComp)
527 powerComp->setBehaviour(
529 }
530 } else {
531 SPDLOG_LOGGER_INFO(mSLog, "-- Set solver behaviour to Simulation");
532 // TODO: solver setting specific to simulation
533
534 SPDLOG_LOGGER_INFO(mSLog, "-- Set component behaviour to PFSimulation");
535 for (auto comp : mSystem.mComponents) {
536 auto powerComp =
537 std::dynamic_pointer_cast<CPS::TopologicalPowerComp>(comp);
538 if (powerComp)
539 powerComp->setBehaviour(TopologicalPowerComp::Behaviour::PFSimulation);
540 }
541 }
542}
543
545 int n = mSystem.mNodes.size();
546 if (n > 0) {
548 for (auto line : mLines) {
549 line->pfApplyAdmittanceMatrixStamp(mY);
550 }
551 for (auto trans : mTransformers) {
552 //to check if this transformer could be ignored
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());
556 continue;
557 }
558 trans->pfApplyAdmittanceMatrixStamp(mY);
559 }
560 for (auto shunt : mShunts) {
561 shunt->pfApplyAdmittanceMatrixStamp(mY);
562 }
563 }
564 if (mLines.empty() && mTransformers.empty()) {
565 throw std::invalid_argument("There are no bus");
566 }
567}
568
569CPS::Real PFSolver::G(int i, int j) { return mY.coeff(i, j).real(); }
570
571CPS::Real PFSolver::B(int i, int j) { return mY.coeff(i, j).imag(); }
572
574 // Converged if all mismatches are below the tolerance
575 for (CPS::UInt i = 0; i < mNumUnknowns; i++) {
576 if (!Math::isFinite(mF(i))) {
577 SPDLOG_LOGGER_WARN(mSLog, "mF[{}] not finite (NaN/Inf)", i);
578 return false;
579 }
580 if (abs(mF(i)) > mTolerance)
581 return false;
582 }
583 return true;
584}
585
587
588 // Reset values for new power flow run
589 isConverged = false;
590 mIterations = 0;
591 mX.setZero();
592 mF.setZero();
593
594 // Calculate the mismatch according to the initial solution
596
597 // Check whether model already converged
599
600 for (unsigned i = 1; i < mMaxIterations && !isConverged; ++i) {
601
603
604 // Solve system mJ*mX = mF
606
607 // Calculate new solution based on mX increments obtained from equation system
609
610 // Calculate the mismatch according to the current solution
612
613 SPDLOG_LOGGER_DEBUG(mSLog, "Mismatch vector at iteration {}: \n {}", i, mF);
614 mSLog->flush();
615
616 // Check convergence
618 mIterations = i;
619 }
620 return isConverged;
621}
622
624 Bool converged = runNewtonRaphson();
625
627 return converged;
628
629 // Outer loop: switch PV<->PQ on Q-limit violations, re-solve until no bus switches.
630 Bool settled = false;
631 for (CPS::UInt outer = 0; converged && outer < mMaxOuterIterations; ++outer) {
632 if (!enforceReactiveLimits()) {
633 settled = true;
634 break; // all generators within their reactive limits
635 }
637 converged = runNewtonRaphson();
638 }
639
640 if (converged && !settled) {
641 // Unsettled PV/PQ classification must not look converged to setSolution().
642 SPDLOG_LOGGER_WARN(
643 mSLog,
644 "Q-limit outer loop did not settle within {} iterations; "
645 "PV/PQ classification may still be oscillating",
647 isConverged = false;
648 converged = false;
649 }
650 return converged;
651}
652
653void PFSolver::SolveTask::execute(Real time, Int timeStepCount) {
654 // apply keepLastSolution to save computation time
655 mSolver.generateInitialSolution(time, mSolver.mKeepLastSolution);
656 mSolver.solvePowerflow();
657 mSolver.setSolution();
658}
659
661 return Task::List{std::make_shared<SolveTask>(*this)};
662}
spdlog::level::level_enum Level
Definition Logger.h:33
static bool isFinite(Real value)
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:653
void determinePFBusType()
Determine bus type for all buses.
Definition PFSolver.cpp:162
void reclassifyBuses()
Re-derive index vectors and resize the system after PV<->PQ switching.
Definition PFSolver.cpp:304
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:586
void resetToOriginalClassification()
Restore the original PV/PQ classification before a fresh solve.
Definition PFSolver.cpp:296
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:77
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:660
void assignMatrixNodeIndices()
Assignment of matrix indices for nodes.
Definition PFSolver.cpp:83
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:73
void initializeComponents()
Initialization of individual components.
Definition PFSolver.cpp:97
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:343
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:501
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:484
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:573
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:312
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:270
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:139
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:571
void composeAdmittanceMatrix()
Compose admittance matrix.
Definition PFSolver.cpp:544
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:516
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:623
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:569
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:62
Behaviour mBehaviour
Solver behaviour initialization or simulation.
Definition Solver.h:87
CPS::Logger::Log mSLog
Logger.
Definition Solver.h:60
Solver(String name, CPS::Logger::Level logLevel)
Definition Solver.h:90
Bool mInitFromNodesAndTerminals
Definition Solver.h:77
Bool mZeroSkipping
Skip exact zero contributions during matrix assembly (enabled by default).
Definition Solver.h:84
@ Initialization
Definition Solver.h:40
PowerflowBusType
std::string String
Definition Definitions.h:63
Eigen::SparseMatrix< Complex, Eigen::ColMajor > SparseMatrixComp
Sparse matrix for complex numbers.
Definition Definitions.h:74
double Real
Definition Definitions.h:60
bool Bool
Definition Definitions.h:62
unsigned int UInt
Definition Definitions.h:58
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