DPsim
Loading...
Searching...
No Matches
DP_Ph1_Switch.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 <cmath>
11#include <stdexcept>
12
14
15using namespace CPS;
16
18 : MNASimPowerComp<Complex>(uid, name, false, true, logLevel),
20 mOpeningRequested(mAttributes->create<Bool>("opening_requested")),
21 mPoleClosed(mAttributes->create<Bool>("pole_closed")),
22 mInstantCurrent(mAttributes->create<Real>("i_instantaneous")),
23 mZeroCrossingTime(mAttributes->create<Real>("zero_crossing_time")),
25 mAttributes->create<Bool>("exponential_transition_active")),
27 mAttributes->create<Bool>("exponential_transition_closing")),
28 mExponentialProgress(mAttributes->create<Real>("exponential_progress")),
30 mAttributes->create<Real>("exponential_transition_start_time")),
32 mAttributes->create<Real>("exponential_transition_end_time")),
33 mEffectiveResistance(mAttributes->create<Real>("effective_resistance")) {
35 **mIntfVoltage = MatrixComp::Zero(1, 1);
36 **mIntfCurrent = MatrixComp::Zero(1, 1);
37
38 **mOpeningRequested = false;
39 **mPoleClosed = false;
40
41 **mInstantCurrent = 0.0;
42
43 resetZeroCrossingTime();
44
51}
52
54 auto copy = Switch::make(name, mLogLevel);
55 copy->setParameters(**mOpenResistance, **mClosedResistance, **mIsClosed);
56 copy->setSwitchingMode(mSwitchingMode);
57 copy->setZeroCrossingTolerance(mZeroCrossingTolerance);
58 copy->setExponentialSwitchingTime(mExponentialSwitchingTime);
59 return copy;
60}
61
63 mSwitchingMode = mode;
64
66 **mOpeningRequested = false;
67 resetZeroCrossingTime();
68
69 mPreviousCurrentValid = false;
70 mResetZeroCrossingHistory = false;
71
72 resetExponentialTransition();
73 synchronizeEffectiveResistance(**mIsClosed);
74}
75
77 if (tolerance < 0.0) {
78 throw std::invalid_argument(
79 "DP::Ph1::Switch zero-crossing tolerance must be non-negative.");
80 }
81
82 mZeroCrossingTolerance = tolerance;
83}
84
86 if (switchingTime <= 0.0) {
87 throw std::invalid_argument(
88 "DP::Ph1::Switch exponential switching time must be positive.");
89 }
90
91 mExponentialSwitchingTime = switchingTime;
92}
93
96
97 // An opening command during a closing ramp abandons that ramp. The pole is
98 // still open at that point, so the switch simply stays open.
100 resetExponentialTransition();
101 **mPoleClosed = false;
102 synchronizeEffectiveResistance(false);
103 **mOpeningRequested = false;
104
105 SPDLOG_LOGGER_INFO(mSLog,
106 "DP opening command received during an exponential "
107 "closing transition. Transition abandoned.");
108 return;
109 }
110
111 if (mSwitchingMode == SwitchingMode::Ideal) {
112 **mOpeningRequested = false;
113 **mPoleClosed = false;
114 resetZeroCrossingTime();
115 resetExponentialTransition();
116 synchronizeEffectiveResistance(false);
117 return;
118 }
119
120 if (!**mPoleClosed) {
121 **mOpeningRequested = false;
122 return;
123 }
124
125 if (mSwitchingMode == SwitchingMode::CurrentZero) {
126 **mOpeningRequested = true;
127 resetZeroCrossingTime();
128 resetExponentialTransition();
129 mResetZeroCrossingHistory = true;
130
131 SPDLOG_LOGGER_INFO(mSLog,
132 "DP current-zero opening command received. "
133 "Waiting for the reconstructed physical current zero.");
134 return;
135 }
136
137 validateExponentialResistanceParameters();
138 **mOpeningRequested = true;
139 resetZeroCrossingTime();
140 resetExponentialTransition();
142 synchronizeEffectiveResistance(true);
143 **mPoleClosed = true;
144
145 SPDLOG_LOGGER_INFO(mSLog,
146 "DP exponential ZCS-emulation opening command received. "
147 "Switching duration={:.6e}s.",
148 mExponentialSwitchingTime);
149}
150
153
154 **mOpeningRequested = false;
155 resetZeroCrossingTime();
156 mResetZeroCrossingHistory = false;
157
158 if (mSwitchingMode != SwitchingMode::ExponentialZCSEmulation) {
159 **mPoleClosed = true;
160 resetExponentialTransition();
161 synchronizeEffectiveResistance(true);
162
163 SPDLOG_LOGGER_INFO(mSLog, "DP switch closing command: pole closed.");
164 return;
165 }
166
168 resetExponentialTransition();
169 synchronizeEffectiveResistance(true);
170 return;
171 }
172
173 // Energising a branch is the mirror image of interrupting it: the same
174 // resistance path is traversed from R_open towards R_closed. The DP envelope
175 // cannot represent the voltage step across a capacitance any more than it can
176 // represent an interrupted inductive current, so closing is ramped as well.
177 validateExponentialResistanceParameters();
178 resetExponentialTransition();
181 **mExponentialProgress = 1.0;
182 synchronizeEffectiveResistance(false);
183 **mPoleClosed = false;
184
185 SPDLOG_LOGGER_INFO(mSLog,
186 "DP exponential ZCS-emulation closing command received. "
187 "Switching duration={:.6e}s.",
188 mExponentialSwitchingTime);
189}
190
192
193 Real impedance = (**mIsClosed) ? **mClosedResistance : **mOpenResistance;
194 (**mIntfVoltage)(0, 0) = initialSingleVoltage(1) - initialSingleVoltage(0);
195 (**mIntfCurrent)(0, 0) = (**mIntfVoltage)(0, 0) / impedance;
196
197 // Power-flow initialization defines the initial physical breaker state.
199 **mOpeningRequested = false;
200 resetZeroCrossingTime();
201 resetExponentialTransition();
202 synchronizeEffectiveResistance(**mIsClosed);
203
204 SPDLOG_LOGGER_INFO(mSLog,
205 "\n--- Initialization from powerflow ---"
206 "\nVoltage across: {:s}"
207 "\nCurrent: {:s}"
208 "\nTerminal 0 voltage: {:s}"
209 "\nTerminal 1 voltage: {:s}"
210 "\nSwitching mode: {:s}"
211 "\nInitial breaker state: {:s}"
212 "\n--- Initialization from powerflow finished ---",
217 mSwitchingMode == SwitchingMode::Ideal
218 ? "Ideal"
219 : (mSwitchingMode == SwitchingMode::CurrentZero
220 ? "CurrentZero"
221 : "ExponentialZCSEmulation"),
222 **mIsClosed ? "closed" : "open");
223}
224
226 Attribute<Matrix>::Ptr leftVector) {
228 mTimeStep = timeStep;
229 **mRightVector = Matrix::Zero(0, 0);
230
231 // omega is the DP reference-frame angular frequency supplied by the solver.
232 mShiftOmega = omega;
233
234 // Final safeguard in case setSwitchingMode() was called before setParameters().
236 synchronizeEffectiveResistance(**mIsClosed);
237 resetExponentialTransition();
238
239 mPoleClosedPrev = **mPoleClosed;
241
242 **mInstantCurrent = reconstructInstantaneousCurrent(0.0);
243
244 mPreviousInstantaneousCurrent = **mInstantCurrent;
245 mEffectiveResistancePrev = **mEffectiveResistance;
246
247 mPreviousCurrentTime = 0.0;
248 mPreviousCurrentValid = true;
249 mResetZeroCrossingHistory = false;
250}
251
253 Real omega, Real timeStep,
254 std::vector<Attribute<Matrix>::Ptr> leftVectors) {
255 // Harmonic initialization bypasses mnaCompInitialize() in the shared MNA
256 // wrapper. Reuse its setup so the switch has valid node indices and state
257 // before the solver stamps each precomputed switch/frequency matrix.
258 mnaCompInitialize(omega, timeStep,
259 leftVectors.empty() ? Attribute<Matrix>::Ptr{}
260 : leftVectors.front());
261}
262
270
272 Bool closed, SparseMatrixRow &systemMatrix, Int freqIdx) {
273 // Conventional precomputed two-state path. The CurrentZero and exponential
274 // modes bypass this by returning supportsPrecomputedSystemMatrices() == false.
275 Complex conductance = (closed) ? Complex(1. / **mClosedResistance, 0)
276 : Complex(1. / **mOpenResistance, 0);
277
278 MNAStampUtils::stampAdmittance(conductance, systemMatrix, matrixNodeIndex(0),
281}
282
284
286 if (mSwitchingMode == SwitchingMode::Ideal)
287 return **mIsClosed;
288
289 return **mPoleClosed;
290}
291
295
297 // Voltage across component is defined as V1 - V0
298 (**mIntfVoltage)(0, 0) = 0;
299 if (terminalNotGrounded(1))
300 (**mIntfVoltage)(0, 0) =
302 if (terminalNotGrounded(0))
303 (**mIntfVoltage)(0, 0) =
304 (**mIntfVoltage)(0, 0) -
306}
307
309 (**mIntfCurrent)(0, 0) = currentConductance() * (**mIntfVoltage)(0, 0);
310}
311
313 AttributeBase::List &prevStepDependencies,
314 AttributeBase::List &attributeDependencies,
315 AttributeBase::List &modifiedAttributes,
316 Attribute<Matrix>::Ptr &leftVector) {
317
318 attributeDependencies.push_back(leftVector);
319 modifiedAttributes.push_back(mIntfVoltage);
320 modifiedAttributes.push_back(mIntfCurrent);
321
322 modifiedAttributes.push_back(mOpeningRequested);
323 modifiedAttributes.push_back(mPoleClosed);
324
325 modifiedAttributes.push_back(mInstantCurrent);
326 modifiedAttributes.push_back(mZeroCrossingTime);
327
328 modifiedAttributes.push_back(mExponentialTransitionActive);
329 modifiedAttributes.push_back(mExponentialTransitionClosing);
330 modifiedAttributes.push_back(mExponentialProgress);
331 modifiedAttributes.push_back(mExponentialTransitionStartTime);
332 modifiedAttributes.push_back(mExponentialTransitionEndTime);
333 modifiedAttributes.push_back(mEffectiveResistance);
334}
335
337 Attribute<Matrix>::Ptr &leftVector) {
338 mnaCompUpdateVoltage(**leftVector);
339 mnaCompUpdateCurrent(**leftVector);
340
341 **mInstantCurrent = reconstructInstantaneousCurrent(time);
342
343 if (mSwitchingMode == SwitchingMode::CurrentZero) {
344 updateZeroCrossingState(time);
345 } else if (mSwitchingMode == SwitchingMode::ExponentialZCSEmulation) {
346 updateExponentialTransition(time);
347 }
348}
349
351 if (mSwitchingMode == SwitchingMode::Ideal) {
352 // Check if state of switch changed
353 if (mIsClosedPrev != **mIsClosed) {
355 return true; //recompute system matrix
356 }
357
358 return false; // do not recompute system matrix
359 }
360
361 if (mSwitchingMode == SwitchingMode::ExponentialZCSEmulation) {
362 if (**mEffectiveResistance != mEffectiveResistancePrev) {
363 mEffectiveResistancePrev = **mEffectiveResistance;
364 return true;
365 }
366
367 return false;
368 }
369
370 if (**mPoleClosed != mPoleClosedPrev) {
371 mPoleClosedPrev = **mPoleClosed;
372 return true;
373 }
374
375 return false;
376}
377
378void DP::Ph1::Switch::setPoleClosed(Bool closed) {
379 **mPoleClosed = closed;
380
381 // Keep the resistance diagnostics synchronized with the discrete
382 // CurrentZero pole state. Exponential mode manages R(t) independently.
383 if (mSwitchingMode == SwitchingMode::CurrentZero)
384 synchronizeEffectiveResistance(closed);
385}
386
387void DP::Ph1::Switch::resetZeroCrossingTime() { **mZeroCrossingTime = -1.0; }
388
389void DP::Ph1::Switch::synchronizeEffectiveResistance(Bool closed) {
390 **mEffectiveResistance = closed ? **mClosedResistance : **mOpenResistance;
391}
392
393void DP::Ph1::Switch::resetExponentialTransition() {
394 **mExponentialTransitionActive = false;
395 **mExponentialTransitionClosing = false;
396 **mExponentialProgress = 0.0;
397 **mExponentialTransitionStartTime = -1.0;
398 **mExponentialTransitionEndTime = -1.0;
399 mExponentialTransitionStarted = false;
400}
401
402void DP::Ph1::Switch::validateExponentialResistanceParameters() const {
403 if (mExponentialSwitchingTime <= 0.0) {
404 throw std::invalid_argument(
405 "DP::Ph1::Switch exponential switching time must be positive.");
406 }
407
408 if (**mClosedResistance <= 0.0 || **mOpenResistance <= 0.0) {
409 throw std::invalid_argument("DP::Ph1::Switch exponential mode requires "
410 "positive open and closed resistances.");
411 }
412}
413
414Real DP::Ph1::Switch::exponentialResistance(Real alpha) const {
415 const Real rClosed = **mClosedResistance;
416 const Real rOpen = **mOpenResistance;
417 const Real boundedAlpha = std::max(0.0, std::min(1.0, alpha));
418
419 return std::exp(std::log(rClosed) +
420 boundedAlpha * (std::log(rOpen) - std::log(rClosed)));
421}
422
423void DP::Ph1::Switch::updateExponentialTransition(Real time) {
424 if (!**mExponentialTransitionActive)
425 return;
426
427 if (!mExponentialTransitionStarted) {
428 mExponentialTransitionStarted = true;
429 **mExponentialTransitionStartTime = time;
430 **mExponentialTransitionEndTime = time + mExponentialSwitchingTime;
431 }
432
433 const Real targetTime = time + mTimeStep;
434 const Real elapsed = (targetTime - **mExponentialTransitionStartTime) /
435 mExponentialSwitchingTime;
436 const Real boundedElapsed = std::max(0.0, std::min(1.0, elapsed));
437
438 const Bool closing = **mExponentialTransitionClosing;
439
440 // alpha is the position on the resistance path: 0 at R_closed, 1 at R_open.
441 const Real alpha = closing ? 1.0 - boundedElapsed : boundedElapsed;
442
443 **mExponentialProgress = alpha;
444 **mEffectiveResistance = exponentialResistance(alpha);
445
446 if (boundedElapsed >= 1.0) {
447 synchronizeEffectiveResistance(closing);
448 **mPoleClosed = closing;
449 **mOpeningRequested = false;
450 **mExponentialTransitionActive = false;
451 **mExponentialTransitionClosing = false;
452
453 SPDLOG_LOGGER_INFO(
454 mSLog,
455 "DP exponential ZCS-emulation {:s} completed: start={:.9f}s, "
456 "end={:.9f}s, duration={:.6e}s.",
457 closing ? "closing" : "opening", **mExponentialTransitionStartTime,
458 **mExponentialTransitionEndTime, mExponentialSwitchingTime);
459 }
460}
461
462Complex DP::Ph1::Switch::currentConductance() const {
463 if (mSwitchingMode == SwitchingMode::Ideal) {
464 return (**mIsClosed) ? Complex(1. / **mClosedResistance, 0)
465 : Complex(1. / **mOpenResistance, 0);
466 }
467
468 if (mSwitchingMode == SwitchingMode::CurrentZero) {
469 return (**mPoleClosed) ? Complex(1. / **mClosedResistance, 0)
470 : Complex(1. / **mOpenResistance, 0);
471 }
472
473 return Complex(1. / **mEffectiveResistance, 0);
474}
475
476Real DP::Ph1::Switch::reconstructInstantaneousCurrent(Real time) const {
477 // Restore the reference-frequency carrier removed by the DP formulation.
478 // DP::Ph1 envelopes keep the power-flow amplitude scaling, so no RMS-to-peak
479 // conversion is applied here; the zero crossing instant does not depend on it.
480 const Complex carrier = std::polar<Real>(1.0, mShiftOmega * time);
481
482 return std::real((**mIntfCurrent)(0, 0) * carrier);
483}
484
485Bool DP::Ph1::Switch::currentCrossedZero(Real previousCurrent,
486 Real current) const {
487 if (std::abs(current) <= mZeroCrossingTolerance)
488 return true;
489
490 return (previousCurrent > mZeroCrossingTolerance &&
491 current < -mZeroCrossingTolerance) ||
492 (previousCurrent < -mZeroCrossingTolerance &&
493 current > mZeroCrossingTolerance);
494}
495
496Real DP::Ph1::Switch::interpolateZeroCrossingTime(Real previousCurrent,
497 Real current,
498 Real previousTime,
499 Real currentTime) const {
500 const Real denominator = std::abs(previousCurrent) + std::abs(current);
501
502 if (denominator <= mZeroCrossingTolerance)
503 return currentTime;
504
505 const Real fraction = std::abs(previousCurrent) / denominator;
506
507 return previousTime + fraction * (currentTime - previousTime);
508}
509
510void DP::Ph1::Switch::updateZeroCrossingState(Real time) {
511 const Real current = **mInstantCurrent;
512
513 // Keep a current history while no opening command is active.
514 if (!**mOpeningRequested) {
515 mPreviousInstantaneousCurrent = current;
516 mPreviousCurrentTime = time;
517 mPreviousCurrentValid = true;
518 return;
519 }
520
521 // First post-command sample: do not compare against the pre-command sample.
522 if (mResetZeroCrossingHistory || !mPreviousCurrentValid) {
523 if (**mPoleClosed && std::abs(current) <= mZeroCrossingTolerance) {
524 setPoleClosed(false);
525 **mZeroCrossingTime = time;
526
527 SPDLOG_LOGGER_INFO(mSLog,
528 "DP pole opened at sampled physical current zero: "
529 "t={:.9f}s, i={:.6e}A",
530 time, current);
531 }
532
533 mPreviousInstantaneousCurrent = current;
534 mPreviousCurrentTime = time;
535 mPreviousCurrentValid = true;
536 mResetZeroCrossingHistory = false;
537
538 if (!**mPoleClosed)
539 **mOpeningRequested = false;
540
541 return;
542 }
543
544 if (**mPoleClosed &&
545 currentCrossedZero(mPreviousInstantaneousCurrent, current)) {
546 const Real zeroTime = interpolateZeroCrossingTime(
547 mPreviousInstantaneousCurrent, current, mPreviousCurrentTime, time);
548
549 setPoleClosed(false);
550 **mZeroCrossingTime = zeroTime;
551
552 SPDLOG_LOGGER_INFO(mSLog,
553 "DP physical current zero detected: "
554 "t_z={:.9f}s, i_prev={:.6e}A, i={:.6e}A. Pole opened.",
555 zeroTime, mPreviousInstantaneousCurrent, current);
556 }
557
558 mPreviousInstantaneousCurrent = current;
559 mPreviousCurrentTime = time;
560 mPreviousCurrentValid = true;
561
562 if (!**mPoleClosed) {
563 **mOpeningRequested = false;
564
565 SPDLOG_LOGGER_INFO(mSLog, "DP current-zero interruption completed: "
566 "the breaker pole is open.");
567 }
568}
std::vector< Ptr > List
Definition Attribute.h:123
AttributePointer< Attribute< T > > Ptr
Definition Attribute.h:249
const Attribute< Real >::Ptr mClosedResistance
Resistance if switch is closed [ohm].
const Attribute< Real >::Ptr mOpenResistance
Resistance if switch is open [ohm].
virtual void closeSwitch()
virtual void openSwitch()
const Attribute< Bool >::Ptr mIsClosed
Defines if Switch is open or closed.
SimPowerComp< Complex >::Ptr clone(String name) override
Returns a modified copy of the component with the given suffix added to the name and without.
const Attribute< Real >::Ptr mInstantCurrent
Reconstructed physical instantaneous current [A].
void setSwitchingMode(SwitchingMode mode)
void initializeFromNodesAndTerminals(Real frequency) override
Initializes component from power flow data.
const Attribute< Bool >::Ptr mPoleClosed
void closeSwitch() override
Bool mnaIsClosed() override
Check if switch is closed.
void setExponentialSwitchingTime(Real switchingTime)
void mnaCompApplySystemMatrixStamp(SparseMatrixRow &systemMatrix) override
Stamps system matrix.
void mnaCompApplyRightSideVectorStamp(Matrix &rightVector) override
Stamps right side (source) vector.
Bool hasParameterChanged() override
Returns true if one of the element paramters has changed.
void mnaCompAddPostStepDependencies(AttributeBase::List &prevStepDependencies, AttributeBase::List &attributeDependencies, AttributeBase::List &modifiedAttributes, Attribute< Matrix >::Ptr &leftVector) override
Add MNA post step dependencies.
const Attribute< Real >::Ptr mEffectiveResistance
Effective resistance currently stamped into the MNA matrix [ohm].
Switch(String uid, String name, Logger::Level loglevel=Logger::Level::off)
Defines UID, name, component parameters and logging level.
const Attribute< Real >::Ptr mZeroCrossingTime
const Attribute< Bool >::Ptr mExponentialTransitionActive
Exponential-transition diagnostics.
const Attribute< Bool >::Ptr mOpeningRequested
void mnaCompUpdateCurrent(const Matrix &leftVector) override
Update interface current from MNA system result.
const Attribute< Bool >::Ptr mExponentialTransitionClosing
True while the active exponential transition is a closing transition.
void setZeroCrossingTolerance(Real tolerance)
const Attribute< Real >::Ptr mExponentialTransitionEndTime
void mnaCompApplySwitchSystemMatrixStamp(Bool closed, SparseMatrixRow &systemMatrix, Int freqIdx) override
Stamps system matrix considering the defined switch position.
void mnaCompInitialize(Real omega, Real timeStep, Attribute< Matrix >::Ptr leftVector) override
void mnaCompPostStep(Real time, Int timeStepCount, Attribute< Matrix >::Ptr &leftVector) override
MNA post step operations.
void openSwitch() override
void mnaCompInitializeHarm(Real omega, Real timeStep, std::vector< Attribute< Matrix >::Ptr > leftVectors) override
void mnaCompUpdateVoltage(const Matrix &leftVector) override
Update interface voltage from MNA system result.
const Attribute< Real >::Ptr mExponentialProgress
const Attribute< Real >::Ptr mExponentialTransitionStartTime
Bool supportsPrecomputedSystemMatrices() const override
String uid()
Returns unique id.
AttributeList::Ptr mAttributes
Attribute List.
spdlog::level::level_enum Level
Definition Logger.h:33
static String phasorToString(const Complex &num)
Definition Logger.cpp:57
MNASimPowerComp(String uid, String name, Bool hasPreStep, Bool hasPostStep, Logger::Level logLevel)
Attribute< Matrix >::Ptr mRightVector
static void stampAdmittance(Complex admittance, SparseMatrixRow &mat, UInt node1Index, UInt node2Index, Bool isTerminal1NotGrounded, Bool isTerminal2NotGrounded, const Logger::Log &mSLog, Int maxFreq=1, Int freqIdx=0)
static Complex complexFromVectorElement(const Matrix &mat, Matrix::Index row, Int maxFreq=1, Int freqIdx=0)
UInt matrixNodeIndex(UInt nodeIndex)
const Attribute< MatrixVar< Complex > >::Ptr mIntfCurrent
const Attribute< MatrixVar< Complex > >::Ptr mIntfVoltage
std::shared_ptr< SimPowerComp< VarType > > Ptr
Bool terminalNotGrounded(UInt index)
Complex initialSingleVoltage(UInt index)
Logger::Level mLogLevel
Component logger control for internal variables.
Logger::Log mSLog
Component logger.
static std::shared_ptr< Switch > make(Args &&...args)
Definition PtrFactory.h:19
Eigen::Matrix< Real, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor > Matrix
Dense matrix for real numbers.
Definition Definitions.h:79
std::string String
Definition Definitions.h:63
double Real
Definition Definitions.h:60
int Int
Definition Definitions.h:59
std::complex< Real > Complex
Definition Definitions.h:61
bool Bool
Definition Definitions.h:62
Eigen::SparseMatrix< Real, Eigen::RowMajor > SparseMatrixRow
Sparse matrix for real numbers (row major).
Definition Definitions.h:72