DPsim
Loading...
Searching...
No Matches
PFSolverPowerPolar.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
9#include <algorithm>
10#include <tuple>
11
13
14using namespace DPsim;
15using namespace CPS;
16
18 const CPS::SystemTopology &system,
19 CPS::Real timeStep,
20 CPS::Logger::Level logLevel)
21 : PFSolver(name, system, timeStep, logLevel) {}
22
24 bool keep_last_solution) {
25 // Undo Q-limit PV<->PQ conversions left over from a previous solve.
28
29 const UInt n = mSystem.mNodes.size();
30
31 bool can_keep = keep_last_solution && mHasLastConvergedSolution &&
32 mLastConvergedV.size() == n && mLastConvergedD.size() == n;
33
34 SPDLOG_LOGGER_INFO(mSLog,
35 "PF initialization: keep_last_solution={}, can_keep={}",
36 keep_last_solution, can_keep);
37
38 resize_sol(n);
40
41 if (can_keep) {
44 }
45
46 // update components
47 for (auto comp : mSystem.mComponents) {
48 if (auto load = std::dynamic_pointer_cast<CPS::SP::Ph1::Load>(comp)) {
49 if (load->use_profile)
50 load->updatePQ(time);
51
52 load->calculatePerUnitParameters(mBaseApparentPower,
53 mSystem.mSystemOmega);
54 }
55
56 if (auto gen =
57 std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(comp)) {
58 gen->calculatePerUnitParameters(mBaseApparentPower, mSystem.mSystemOmega);
59 }
60 }
61
62 // PQ buses
63 for (auto pq : mPQBuses) {
64 UInt idx = pq->matrixNodeIndex();
65
66 sol_P(idx) = 0.0;
67 sol_Q(idx) = 0.0;
68
69 if (!can_keep) {
70 sol_V(idx) = 1.0;
71 sol_D(idx) = 0.0;
72 }
73
74 for (auto comp : mSystem.mComponentsAtNode[pq]) {
75 if (auto load = std::dynamic_pointer_cast<CPS::SP::Ph1::Load>(comp)) {
76 sol_P(idx) -= load->attributeTyped<CPS::Real>("P_pu")->get();
77 sol_Q(idx) -= load->attributeTyped<CPS::Real>("Q_pu")->get();
78 } else if (auto sst = std::dynamic_pointer_cast<
80 sol_P(idx) -= sst->getNodalInjection(pq).real();
81 sol_Q(idx) -= sst->getNodalInjection(pq).imag();
82 } else if (auto vsi = std::dynamic_pointer_cast<
84 sol_P(idx) +=
85 vsi->attributeTyped<CPS::Real>("P_ref")->get() / mBaseApparentPower;
86 sol_Q(idx) +=
87 vsi->attributeTyped<CPS::Real>("Q_ref")->get() / mBaseApparentPower;
88 } else if (auto gen =
89 std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(
90 comp)) {
91 sol_P(idx) += gen->attributeTyped<CPS::Real>("P_set_pu")->get();
92 sol_Q(idx) += gen->attributeTyped<CPS::Real>("Q_set_pu")->get();
93 }
94 }
95
96 sol_S_complex(idx) = CPS::Complex(sol_P(idx), sol_Q(idx));
97 sol_V_complex(idx) = Math::polar(sol_V(idx), sol_D(idx));
98 }
99
100 // PV buses
101 for (auto pv : mPVBuses) {
102 UInt idx = pv->matrixNodeIndex();
103
104 sol_P(idx) = 0.0;
105 sol_Q(idx) = 0.0;
106
107 if (!can_keep) {
108 sol_D(idx) = 0.0;
109 sol_V(idx) = 1.0;
110 }
111
112 for (auto comp : mSystem.mComponentsAtNode[pv]) {
113 if (auto gen = std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(
114 comp)) {
115 sol_P(idx) += gen->attributeTyped<CPS::Real>("P_set_pu")->get();
116 sol_V(idx) = gen->attributeTyped<CPS::Real>("V_set_pu")->get();
117 } else if (auto load =
118 std::dynamic_pointer_cast<CPS::SP::Ph1::Load>(comp)) {
119 sol_P(idx) -= load->attributeTyped<CPS::Real>("P_pu")->get();
120 sol_Q(idx) -= load->attributeTyped<CPS::Real>("Q_pu")->get();
121 } else if (auto vsi = std::dynamic_pointer_cast<
123 sol_P(idx) +=
124 vsi->attributeTyped<CPS::Real>("P_ref")->get() / mBaseApparentPower;
125 } else if (auto extnet =
126 std::dynamic_pointer_cast<CPS::SP::Ph1::NetworkInjection>(
127 comp)) {
128 sol_P(idx) += extnet->attributeTyped<CPS::Real>("p_inj")->get() /
130 sol_V(idx) = extnet->attributeTyped<CPS::Real>("V_set_pu")->get();
131 }
132 }
133
134 sol_S_complex(idx) = CPS::Complex(sol_P(idx), sol_Q(idx));
135 sol_V_complex(idx) = Math::polar(sol_V(idx), sol_D(idx));
136 }
137
138 // VD / slack buses
139 for (auto vd : mVDBuses) {
140 UInt idx = vd->matrixNodeIndex();
141
142 sol_P(idx) = 0.0;
143 sol_Q(idx) = 0.0;
144 sol_D(idx) = 0.0;
145 sol_V(idx) = 1.0;
146
147 for (auto comp : mSystem.mComponentsAtNode[vd]) {
148 if (auto extnet =
149 std::dynamic_pointer_cast<CPS::SP::Ph1::NetworkInjection>(comp)) {
150 sol_V(idx) = extnet->attributeTyped<CPS::Real>("V_set_pu")->get();
151 } else if (auto load =
152 std::dynamic_pointer_cast<CPS::SP::Ph1::Load>(comp)) {
153 sol_P(idx) -= load->attributeTyped<CPS::Real>("P_pu")->get();
154 sol_Q(idx) -= load->attributeTyped<CPS::Real>("Q_pu")->get();
155 } else if (auto gen =
156 std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(
157 comp)) {
158 sol_P(idx) += gen->attributeTyped<CPS::Real>("P_set_pu")->get();
159 sol_Q(idx) += gen->attributeTyped<CPS::Real>("Q_set_pu")->get();
160 sol_V(idx) = gen->attributeTyped<CPS::Real>("V_set_pu")->get();
161 }
162 }
163
164 sol_S_complex(idx) = CPS::Complex(sol_P(idx), sol_Q(idx));
165 sol_V_complex(idx) = Math::polar(sol_V(idx), sol_D(idx));
166 }
167
168 solutionInitialized = true;
170
171 Pesp = sol_P;
172 Qesp = sol_Q;
173}
174
176 UInt npqpv = mNumPQBuses + mNumPVBuses;
177 UInt k;
178 mF.setZero();
179
180 for (UInt a = 0; a < npqpv; ++a) {
181 // For PQ and PV buses calculate active power mismatch
182 k = mPQPVBusIndices[a];
183 mF(a) = Pesp.coeff(k) - P(k);
184
185 //only for PQ buses calculate reactive power mismatch
186 if (a < mNumPQBuses)
187 mF(a + npqpv) = Qesp.coeff(k) - Q(k);
188 }
189}
190
192 UInt npqpv = mNumPQBuses + mNumPVBuses;
193 double val;
194 UInt k, j;
195 UInt da, db;
196
197 mJ.setZero();
198
199 //J1
200 for (UInt a = 0; a < npqpv; ++a) { //rows
201 k = mPQPVBusIndices[a];
202 //diagonal
203 mJ.coeffRef(a, a) = -Q(k) - B(k, k) * sol_V.coeff(k) * sol_V.coeff(k);
204
205 //non diagonal elements
206 for (UInt b = 0; b < npqpv; ++b) {
207 if (b != a) {
208 j = mPQPVBusIndices[b];
209 if (mZeroSkipping && G(k, j) == 0.0 && B(k, j) == 0.0)
210 continue;
211 val = sol_V.coeff(k) * sol_V.coeff(j) *
212 (G(k, j) * sin(sol_D.coeff(k) - sol_D.coeff(j)) -
213 B(k, j) * cos(sol_D.coeff(k) - sol_D.coeff(j)));
214 //if (val != 0.0)
215 mJ.coeffRef(a, b) = val;
216 }
217 }
218 }
219
220 //J2
221 da = 0;
222 db = npqpv;
223 for (UInt a = 0; a < npqpv; ++a) { //rows
224 k = mPQPVBusIndices[a];
225 //diagonal
226 //std::cout << "J2D:" << (a + da) << "," << (a + db) << std::endl;
227 if (a < mNumPQBuses)
228 mJ.coeffRef(a + da, a + db) =
229 P(k) + G(k, k) * sol_V.coeff(k) * sol_V.coeff(k);
230
231 //non diagonal elements
232 for (UInt b = 0; b < mNumPQBuses; ++b) {
233 if (b != a) {
234 j = mPQPVBusIndices[b];
235 if (mZeroSkipping && G(k, j) == 0.0 && B(k, j) == 0.0)
236 continue;
237 val = sol_V.coeff(k) * sol_V.coeff(j) *
238 (G(k, j) * cos(sol_D.coeff(k) - sol_D.coeff(j)) +
239 B(k, j) * sin(sol_D.coeff(k) - sol_D.coeff(j)));
240 //if (val != 0.0)
241 //std::cout << "J2ij:" << (a + da) << "," << (b + db) << std::endl;
242 mJ.coeffRef(a + da, b + db) = val;
243 }
244 }
245 }
246
247 //J3
248 da = npqpv;
249 db = 0;
250 for (UInt a = 0; a < mNumPQBuses; ++a) { //rows
251 k = mPQPVBusIndices[a];
252 //diagonal
253 //std::cout << "J3:" << (a + da) << "," << (a + db) << std::endl;
254 mJ.coeffRef(a + da, a + db) =
255 P(k) - G(k, k) * sol_V.coeff(k) * sol_V.coeff(k);
256
257 //non diagonal elements
258 for (UInt b = 0; b < npqpv; ++b) {
259 if (b != a) {
260 j = mPQPVBusIndices[b];
261 if (mZeroSkipping && G(k, j) == 0.0 && B(k, j) == 0.0)
262 continue;
263 val = sol_V.coeff(k) * sol_V.coeff(j) *
264 (G(k, j) * cos(sol_D.coeff(k) - sol_D.coeff(j)) +
265 B(k, j) * sin(sol_D.coeff(k) - sol_D.coeff(j)));
266 //if (val != 0.0)
267 //std::cout << "J3:" << (a + da) << "," << (b + db) << std::endl;
268 mJ.coeffRef(a + da, b + db) = -val;
269 }
270 }
271 }
272
273 //J4
274 da = npqpv;
275 db = npqpv;
276 for (UInt a = 0; a < mNumPQBuses; ++a) { //rows
277 k = mPQPVBusIndices[a];
278 //diagonal
279 //std::cout << "J4:" << (a + da) << "," << (a + db) << std::endl;
280 mJ.coeffRef(a + da, a + db) =
281 Q(k) - B(k, k) * sol_V.coeff(k) * sol_V.coeff(k);
282
283 //non diagonal elements
284 for (UInt b = 0; b < mNumPQBuses; ++b) {
285 if (b != a) {
286 j = mPQPVBusIndices[b];
287 if (mZeroSkipping && G(k, j) == 0.0 && B(k, j) == 0.0)
288 continue;
289 val = sol_V.coeff(k) * sol_V.coeff(j) *
290 (G(k, j) * sin(sol_D.coeff(k) - sol_D.coeff(j)) -
291 B(k, j) * cos(sol_D.coeff(k) - sol_D.coeff(j)));
292 if (val != 0.0) {
293 //std::cout << "J4:" << (a + da) << "," << (b + db) << std::endl;
294 mJ.coeffRef(a + da, b + db) = val;
295 }
296 }
297 }
298 }
299}
300
302 UInt npqpv = mNumPQBuses + mNumPVBuses;
303
304 // Scale the whole step by one factor to bound the max change without altering direction.
305 const double maxDVpu = 0.1; // max |dV| per step [pu]
306 const double maxDThetaRad = 0.2; // max |dTheta| per step [rad]
307
308 // mX: [0,npqpv) angle incr (PQ+PV), then rel. voltage dV/V (PQ only).
309 double scale = 1.0;
310 for (UInt a = 0; a < npqpv; ++a) {
311 double dTheta = std::abs(mX.coeff(a));
312 if (dTheta > maxDThetaRad)
313 scale = std::min(scale, maxDThetaRad / dTheta);
314 }
315 for (UInt b = 0; b < mNumPQBuses; ++b) {
316 double dVrel = std::abs(mX.coeff(npqpv + b));
317 if (dVrel > maxDVpu)
318 scale = std::min(scale, maxDVpu / dVrel);
319 }
320
321 for (UInt a = 0; a < npqpv; ++a) {
322 UInt k = mPQPVBusIndices[a];
323 sol_D(k) += scale * mX.coeff(a);
324 // additive-relative update, consistent with the Jacobian
325 if (a < mNumPQBuses)
326 sol_V(k) *= (1.0 + scale * mX.coeff(a + npqpv));
327 }
328
329 for (auto node : mSystem.mNodes) {
330 UInt idx = node->matrixNodeIndex();
331 sol_V_complex(idx) = Math::polar(sol_V(idx), sol_D(idx));
332 }
333}
334
336
337 if (!isConverged) {
338 SPDLOG_LOGGER_WARN(mSLog, "Not converged within {} iterations",
340
341 SPDLOG_LOGGER_WARN(mSLog, "Writing last iterate to result state "
342 "(not stored as warm-start solution).");
343 } else {
347
351
352 SPDLOG_LOGGER_INFO(mSLog, "Converged in {} iterations", mIterations);
353 }
354
355 SPDLOG_LOGGER_INFO(mSLog, "Solution written to result state:");
356
357 SPDLOG_LOGGER_INFO(mSLog, "Name\tP\t\tQ\t\tV\t\tD");
358
359 for (auto node : mSystem.mNodes) {
360 UInt idx = node->matrixNodeIndex();
361
362 SPDLOG_LOGGER_INFO(
363 mSLog, "{}\t{}\t{}\t{}\t{}",
364 std::dynamic_pointer_cast<CPS::SimNode<CPS::Complex>>(node)->name(),
365 sol_P[idx], sol_Q[idx], sol_V[idx], sol_D[idx]);
366 }
367
368 mSLog->flush();
369
370 for (UInt i = 0; i < mSystem.mNodes.size(); ++i) {
371 sol_S_complex(i) = CPS::Complex(sol_P.coeff(i), sol_Q.coeff(i));
372 sol_V_complex(i) = Math::polar(sol_V.coeff(i), sol_D.coeff(i));
373 }
374
375 for (auto node : mSystem.mNodes) {
376 auto simNode = std::dynamic_pointer_cast<CPS::SimNode<CPS::Complex>>(node);
377
378 UInt idx = node->matrixNodeIndex();
379
380 simNode->setVoltage(sol_V_complex(idx) * mBaseVoltageAtNode[node]);
381
382 simNode->setPower(sol_S_complex(idx) * mBaseApparentPower);
383 }
384
387}
388
390 for (auto line : mLines) {
391 VectorComp v(2);
392 v(0) = sol_V_complex.coeff(line->node(0)->matrixNodeIndex());
393 v(1) = sol_V_complex.coeff(line->node(1)->matrixNodeIndex());
395 VectorComp current = line->Y_element() * v;
397 VectorComp flow_on_branch =
398 Math::elementwiseProduct(v, current.conjugate());
399 line->updateBranchFlow(current, flow_on_branch);
400 }
401 for (auto trafo : mTransformers) {
402 VectorComp v(2);
403 v(0) = sol_V_complex.coeff(trafo->node(0)->matrixNodeIndex());
404 v(1) = sol_V_complex.coeff(trafo->node(1)->matrixNodeIndex());
406 VectorComp current = trafo->Y_element() * v;
408 VectorComp flow_on_branch =
409 Math::elementwiseProduct(v, current.conjugate());
410 trafo->updateBranchFlow(current, flow_on_branch);
411 }
412}
413
415 for (auto node : mSystem.mNodes) {
416 std::list<std::shared_ptr<CPS::SP::Ph1::PiLine>> lines;
417 for (auto comp : mSystem.mComponentsAtNode[node]) {
418 if (std::shared_ptr<CPS::SP::Ph1::PiLine> line =
419 std::dynamic_pointer_cast<CPS::SP::Ph1::PiLine>(comp)) {
420 line->storeNodalInjection(sol_S_complex.coeff(node->matrixNodeIndex()));
421 lines.push_back(line);
422 break;
423 }
424 }
425 if (lines.empty()) {
426 for (auto comp : mSystem.mComponentsAtNode[node]) {
427 if (std::shared_ptr<CPS::SP::Ph1::Transformer> trafo =
428 std::dynamic_pointer_cast<CPS::SP::Ph1::Transformer>(comp)) {
429 trafo->storeNodalInjection(
430 sol_S_complex.coeff(node->matrixNodeIndex()));
431 break;
432 }
433 }
434 }
435 }
436}
437
439 Real val = 0.0;
440 for (UInt j = 0; j < mSystem.mNodes.size(); ++j) {
441 val += sol_V.coeff(j) * (G(k, j) * cos(sol_D.coeff(k) - sol_D.coeff(j)) +
442 B(k, j) * sin(sol_D.coeff(k) - sol_D.coeff(j)));
443 }
444 return sol_V.coeff(k) * val;
445}
446
448 Real val = 0.0;
449 for (UInt j = 0; j < mSystem.mNodes.size(); ++j) {
450 val += sol_V.coeff(j) * (G(k, j) * sin(sol_D.coeff(k) - sol_D.coeff(j)) -
451 B(k, j) * cos(sol_D.coeff(k) - sol_D.coeff(j)));
452 }
453 return sol_V.coeff(k) * val;
454}
455
457 for (auto topoNode : mVDBuses) {
458 auto node_idx = topoNode->matrixNodeIndex();
459
460 // Net nodal injection into the network: S_inj = V * conj(YV)
461 CPS::Complex I(0.0, 0.0);
462 for (UInt j = 0; j < mSystem.mNodes.size(); ++j)
463 I += mY.coeff(node_idx, j) * sol_Vcx(j);
464
465 CPS::Complex S = sol_Vcx(node_idx) * conj(I);
466
467 // Generator/source power: S_gen = S_inj + S_load
468 CPS::Complex Sgen = S;
469 for (auto comp : mSystem.mComponentsAtNode[topoNode]) {
470 if (auto loadPtr = std::dynamic_pointer_cast<CPS::SP::Ph1::Load>(comp)) {
471 Sgen += CPS::Complex(**(loadPtr->mActivePowerPerUnit),
472 **(loadPtr->mReactivePowerPerUnit));
473 }
474 }
475
476 // Update connected VD source/generator with actual generated power
477 for (auto comp : mSystem.mComponentsAtNode[topoNode]) {
478 if (auto extnetPtr =
479 std::dynamic_pointer_cast<CPS::SP::Ph1::NetworkInjection>(comp)) {
480 extnetPtr->updatePowerInjection(Sgen * mBaseApparentPower);
481 break;
482 }
483
484 if (auto sgPtr =
485 std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(
486 comp)) {
487 sgPtr->updatePowerInjection(Sgen * mBaseApparentPower);
488 break;
489 }
490 }
491
492 // Store net nodal injection, not generator power
493 sol_P(node_idx) = S.real();
494 sol_Q(node_idx) = S.imag();
495 }
496}
498 for (auto topoNode : mPVBuses) {
499 auto node_idx = topoNode->matrixNodeIndex();
500
501 // Net nodal injection into the network: S_inj = V * conj(YV)
502 CPS::Complex I(0.0, 0.0);
503 for (UInt j = 0; j < mSystem.mNodes.size(); ++j)
504 I += mY.coeff(node_idx, j) * sol_Vcx(j);
505
506 CPS::Complex S = sol_Vcx(node_idx) * conj(I);
507
508 // Generator power: S_gen = S_inj + S_load
509 CPS::Complex Sgen = S;
510 for (auto comp : mSystem.mComponentsAtNode[topoNode]) {
511 if (auto loadPtr = std::dynamic_pointer_cast<CPS::SP::Ph1::Load>(comp)) {
512 Sgen += CPS::Complex(**(loadPtr->mActivePowerPerUnit),
513 **(loadPtr->mReactivePowerPerUnit));
514 }
515 }
516
517 // Update PV generator with actual generator Q
518 for (auto comp : mSystem.mComponentsAtNode[topoNode]) {
519 if (auto sgPtr =
520 std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(
521 comp)) {
522 sgPtr->updateReactivePowerInjection(Sgen * mBaseApparentPower);
523 break;
524 }
525 }
526
527 // Store net nodal Q injection, not generator Q
528 sol_Q(node_idx) = S.imag();
529 }
530}
531
534 CPS::Real q = 0.0;
535 for (auto comp : mSystem.mComponentsAtNode[node])
536 if (auto load = std::dynamic_pointer_cast<CPS::SP::Ph1::Load>(comp))
537 q += load->attributeTyped<CPS::Real>("Q_pu")->get();
538 return q;
539}
540
543 UInt k = node->matrixNodeIndex();
544 CPS::Complex I(0.0, 0.0);
545 for (UInt j = 0; j < mSystem.mNodes.size(); ++j)
546 I += mY.coeff(k, j) * sol_Vcx(j);
547 // Net nodal injection S = generator - load; add load back for generator Q.
548 CPS::Complex S = sol_Vcx(k) * conj(I);
549 return S.imag() + loadReactivePowerPerUnit(node);
550}
551
553 // Returns false if the bus has no generator or no finite Q limit.
554 auto busLimits = [&](CPS::TopologicalNode::Ptr node, CPS::Real &qMaxPU,
555 CPS::Real &qMinPU, CPS::Real &vSetPU) -> bool {
556 qMaxPU = 0.0;
557 qMinPU = 0.0;
558 vSetPU = 0.0;
559 bool hasGen = false, anyFinite = false;
560 for (auto comp : mSystem.mComponentsAtNode[node]) {
561 if (auto gen = std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(
562 comp)) {
563 CPS::Real gMax = gen->attributeTyped<CPS::Real>("Q_max_pu")->get();
564 CPS::Real gMin = gen->attributeTyped<CPS::Real>("Q_min_pu")->get();
565 qMaxPU += gMax;
566 qMinPU += gMin;
567 vSetPU = gen->attributeTyped<CPS::Real>("V_set_pu")->get();
568 hasGen = true;
569 // isFinite is bit-pattern based, so it's immune to -Ofast/-ffast-math.
570 if (CPS::Math::isFinite(gMax) || CPS::Math::isFinite(gMin))
571 anyFinite = true;
572 }
573 }
574 return hasGen && anyFinite;
575 };
576
577 auto frozen = [&](CPS::TopologicalNode::Ptr node) {
578 auto it = mQLimitSwitchCount.find(node);
579 return it != mQLimitSwitchCount.end() &&
580 it->second >= mMaxQLimitSwitchesPerBus;
581 };
582
583 std::vector<std::tuple<CPS::TopologicalNode::Ptr, bool, CPS::Real>> toPQ;
584 std::vector<CPS::TopologicalNode::Ptr> toPV;
585
586 // PV -> PQ: voltage-controlling generators that hit a reactive limit.
587 for (auto node : mPVBuses) {
588 if (frozen(node))
589 continue;
590 CPS::Real qMaxPU, qMinPU, vSetPU;
591 if (!busLimits(node, qMaxPU, qMinPU, vSetPU))
592 continue;
594 if (CPS::Math::isFinite(qMaxPU) && qGen > qMaxPU)
595 toPQ.emplace_back(node, true, qMaxPU);
596 else if (CPS::Math::isFinite(qMinPU) && qGen < qMinPU)
597 toPQ.emplace_back(node, false, qMinPU);
598 }
599
600 // PQ -> PV: pinned generators whose constraint is no longer binding.
601 for (auto &kv : mQLimitConvertedAtMax) {
602 auto node = kv.first;
603 bool atMax = kv.second;
604 if (frozen(node))
605 continue;
606 CPS::Real qMaxPU, qMinPU, vSetPU;
607 if (!busLimits(node, qMaxPU, qMinPU, vSetPU))
608 continue;
609 CPS::Real v = sol_V(node->matrixNodeIndex());
610 if (atMax && v > vSetPU)
611 toPV.push_back(node);
612 else if (!atMax && v < vSetPU)
613 toPV.push_back(node);
614 }
615
616 // Apply PV -> PQ switches (pin reactive injection at the limit).
617 for (auto &c : toPQ) {
618 auto node = std::get<0>(c);
619 bool atMax = std::get<1>(c);
620 CPS::Real qLimPU = std::get<2>(c);
621 mPVBuses.erase(std::remove(mPVBuses.begin(), mPVBuses.end(), node),
622 mPVBuses.end());
623 mPQBuses.push_back(node);
624 UInt idx = node->matrixNodeIndex();
625 Qesp(idx) = qLimPU - loadReactivePowerPerUnit(node);
626 sol_Q(idx) = Qesp(idx);
627 mQLimitConvertedAtMax[node] = atMax;
629 SPDLOG_LOGGER_WARN(
630 mSLog, "Q-limit: bus {} frozen at {} after {} switches", node->name(),
631 atMax ? "Qmax" : "Qmin", mQLimitSwitchCount[node]);
632 else
633 SPDLOG_LOGGER_INFO(mSLog, "Q-limit: PV bus {} -> PQ pinned at {}",
634 node->name(), atMax ? "Qmax" : "Qmin");
635 }
636
637 // Apply PQ -> PV switches (restore voltage control).
638 for (auto &node : toPV) {
639 mPQBuses.erase(std::remove(mPQBuses.begin(), mPQBuses.end(), node),
640 mPQBuses.end());
641 mPVBuses.push_back(node);
642 CPS::Real qMaxPU, qMinPU, vSetPU;
643 busLimits(node, qMaxPU, qMinPU, vSetPU);
644 sol_V(node->matrixNodeIndex()) = vSetPU;
645 mQLimitConvertedAtMax.erase(node);
646 ++mQLimitSwitchCount[node];
647 SPDLOG_LOGGER_INFO(mSLog, "Q-limit: PQ bus {} -> PV (constraint relaxed)",
648 node->name());
649 }
650
651 return !toPQ.empty() || !toPV.empty();
652}
653
658
660 // calculates apparent power injection at PQ buses flowing to other nodes (i.e. S_inj_to_other = S_inj - S_shunt, with S_inj = S_gen - S_load)
661 for (auto topoNode : mPQBuses) {
662 auto node_idx = topoNode->matrixNodeIndex();
663
664 // calculate power flowing out of the node into the admittance matrix (i.e. S_inj)
665 CPS::Complex I(0.0, 0.0);
666 for (UInt j = 0; j < mSystem.mNodes.size(); ++j)
667 I += mY.coeff(node_idx, j) * sol_Vcx(j);
668 CPS::Complex S = sol_Vcx(node_idx) * conj(I);
669
670 // Subtracting shunt power to obtain power injection flowing from this node to the other nodes (i.e. S_inj_to_other)
671 CPS::Real V = sol_V.coeff(node_idx);
672 for (auto comp : mSystem.mComponentsAtNode[topoNode])
673 if (auto shuntPtr = std::dynamic_pointer_cast<CPS::SP::Ph1::Shunt>(comp))
674 // capacitive susceptance is positive --> q is injected into the node
675 S += std::pow(V, 2) * Complex(-**(shuntPtr->mConductancePerUnit),
676 **(shuntPtr->mSusceptancePerUnit));
677
678 // TODO: check whether S_inj_to_other should be stored in sol_P and sol_Q or rather S_inj
679 sol_P(node_idx) = S.real();
680 sol_Q(node_idx) = S.imag();
681 }
682}
683
685 sol_P = CPS::Vector(n);
686 sol_Q = CPS::Vector(n);
687 sol_V = CPS::Vector(n);
688 sol_D = CPS::Vector(n);
689 sol_P.setZero(n);
690 sol_Q.setZero(n);
691 sol_V.setZero(n);
692 sol_D.setZero(n);
693}
694
701
703 return sol_V.coeff(k) * cos(sol_D.coeff(k));
704}
705
707 return sol_V.coeff(k) * sin(sol_D.coeff(k));
708}
709
spdlog::level::level_enum Level
Definition Logger.h:33
static Complex polar(Real abs, Real phase)
Definition MathUtils.cpp:99
static auto elementwiseProduct(const Eigen::MatrixBase< DerivedA > &a, const Eigen::MatrixBase< DerivedB > &b)
Elementwise product of two same-shaped Eigen expressions.
Definition MathUtils.h:55
static bool isFinite(Real value)
std::shared_ptr< TopologicalNode > Ptr
void resetToOriginalClassification()
Restore the original PV/PQ classification before a fresh solve.
Definition PFSolver.cpp:296
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
std::vector< std::shared_ptr< CPS::SP::Ph1::PiLine > > mLines
Vector of line components.
Definition PFSolver.h:72
std::vector< std::shared_ptr< CPS::SP::Ph1::Transformer > > mTransformers
Vector of transformer components.
Definition PFSolver.h:62
CPS::Matrix mJ
Jacobian matrix.
Definition PFSolver.h:53
CPS::Vector mX
Solution vector.
Definition PFSolver.h:55
CPS::Bool solutionInitialized
Flag whether solution vectors are initialized.
Definition PFSolver.h:106
CPS::Real mBaseApparentPower
Base power of per-unit system.
Definition PFSolver.h:100
CPS::SparseMatrixCompRow mY
Admittance matrix.
Definition PFSolver.h:50
CPS::UInt mMaxQLimitSwitchesPerBus
Maximum number of PV<->PQ switches per bus before it is frozen (anti-oscillation)
Definition PFSolver.h:94
CPS::Bool solutionComplexInitialized
Flag whether complex solution vectors are initialized.
Definition PFSolver.h:108
UInt mNumPVBuses
Number of PV nodes.
Definition PFSolver.h:26
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
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
std::map< CPS::TopologicalNode::Ptr, CPS::Real > mBaseVoltageAtNode
Map providing determined base voltages for each node.
Definition PFSolver.h:81
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
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
CPS::Vector sol_P
Solution vector of active power.
void clearReactiveLimitState() override
Clear the Q-limit conversion bookkeeping between solves.
void resize_complex_sol(CPS::Int n)
Resize complex solution vector.
void calculateBranchFlow()
Calculate branch flows from current solution and store them in line and transformer components.
CPS::Real generatorReactivePowerPerUnit(CPS::TopologicalNode::Ptr node)
Generator reactive-power injection at a bus [pu], used by the Q-limit check.
void calculateQAtPVBuses()
Calculate the reactive power at all PV buses from current solution.
CPS::VectorComp sol_S_complex
Solution vector of representing sol_P and sol_Q as complex quantity.
PFSolverPowerPolar(CPS::String name, const CPS::SystemTopology &system, CPS::Real timeStep, CPS::Logger::Level logLevel)
Constructor to be used in simulation examples.
CPS::Real loadReactivePowerPerUnit(CPS::TopologicalNode::Ptr node)
Total local load reactive power at a bus [pu].
CPS::Vector sol_D
Solution vector of voltage angle.
CPS::Real sol_Vi(CPS::UInt k)
Calculate imaginary part of voltage from sol_V and sol_D.
std::map< CPS::TopologicalNode::Ptr, CPS::UInt > mQLimitSwitchCount
Total PV<->PQ switches per bus over the solve (anti-oscillation cap)
void calculatePAndQAtSlackBus()
Calculate P and Q at slack bus from current solution.
CPS::Vector sol_Q
Solution vector of reactive power.
CPS::Real Q(CPS::UInt k)
Calculate the reactive power at a bus from current solution.
void calculateMismatch() override
Calculate mismatch.
CPS::Bool enforceReactiveLimits() override
Q-limit PV<->PQ switching pass (overrides the base no-op)
CPS::Complex sol_Vcx(CPS::UInt k)
Calculate complex voltage from sol_V and sol_D.
void generateInitialSolution(Real time, bool keep_last_solution=false) override
Generate initial solution for current time step.
std::map< CPS::TopologicalNode::Ptr, bool > mQLimitConvertedAtMax
Buses switched PV->PQ by the Q-limit loop -> pinned at Qmax (true) or Qmin (false)
void calculateJacobian() override
Calculate the Jacobian.
void updateSolution() override
Update solution in each iteration.
void resize_sol(CPS::Int n)
Resize solution vector.
CPS::Real sol_Vr(CPS::UInt k)
Calculate real part of voltage from sol_V and sol_D.
CPS::Real P(CPS::UInt k)
Calculate active power at a bus from current solution.
void calculateNodalInjection()
Calculate nodal power injections and store them in first line or transformer (in case no line is conn...
CPS::Vector sol_V
Solution vector of voltage magnitude.
void calculatePAndQInjectionPQBuses()
Calculate complex power flowing from this node to the other nodes.
CPS::VectorComp sol_V_complex
Solution vector of representing sol_V and sol_D as complex quantity.
void setSolution() override
Set final solution.
CPS::Logger::Log mSLog
Logger.
Definition Solver.h:60
Bool mZeroSkipping
Skip exact zero contributions during matrix assembly (enabled by default).
Definition Solver.h:84
std::string String
Definition Definitions.h:63
double Real
Definition Definitions.h:60
Eigen::Matrix< Complex, Eigen::Dynamic, 1 > VectorComp
Dense vector for complex numbers.
Definition Definitions.h:66
Eigen::Matrix< Real, Eigen::Dynamic, 1 > Vector
Dense vector for real numbers.
Definition Definitions.h:68
std::complex< Real > Complex
Definition Definitions.h:61
bool Bool
Definition Definitions.h:62
CPS::Complex Complex
Definition Definitions.h:19
CPS::Real Real
Definition Definitions.h:18
CPS::Int Int
Definition Definitions.h:22
CPS::UInt UInt
Definition Definitions.h:23