PFSolver.cpp 11.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/** PFSolver
 * @author Jan Dinkelbach <jdinkelbach@eonerc.rwth-aachen.de>
 * @copyright 2019, Institute for Automation of Complex Power Systems, EONERC
 *
 * DPsim
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *********************************************************************************/

#include <dpsim/PFSolver.h>
#include <dpsim/SequentialScheduler.h>
#include <iostream>

using namespace DPsim;
using namespace CPS;

PFSolver::PFSolver(CPS::String name, CPS::SystemTopology system, CPS::Real timeStep, CPS::Logger::Level logLevel) :
	Solver(name, logLevel)
{
	mSLog = Logger::get(name + "_PF", logLevel);
	mSystem = system;
	mTimeStep = timeStep;
    initialize();
}

void PFSolver::initialize(){
	mSLog->info("#### INITIALIZATION OF POWERFLOW SOLVER ");
    for (auto comp : mSystem.mComponents) {
        if (std::shared_ptr<CPS::SP::Ph1::SynchronGenerator> gen = std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(comp))
            mSynchronGenerators.push_back(gen);
        else if (std::shared_ptr<CPS::SP::Ph1::Load> load = std::dynamic_pointer_cast<CPS::SP::Ph1::Load>(comp))
            mLoads.push_back(load);
        else if (std::shared_ptr<CPS::SP::Ph1::Transformer> trafo = std::dynamic_pointer_cast<CPS::SP::Ph1::Transformer>(comp))
            mTransformers.push_back(trafo);
        else if (std::shared_ptr<CPS::SP::Ph1::PiLine> line = std::dynamic_pointer_cast<CPS::SP::Ph1::PiLine>(comp))
            mLines.push_back(line);
        else if (std::shared_ptr<CPS::SP::Ph1::externalGridInjection> extnet = std::dynamic_pointer_cast<CPS::SP::Ph1::externalGridInjection>(comp))
            mExternalGrids.push_back(extnet);
		else if (std::shared_ptr<CPS::SP::Ph1::Shunt> shunt = std::dynamic_pointer_cast<CPS::SP::Ph1::Shunt>(comp))
            mShunts.push_back(shunt);
    }

	setBaseApparentPower();
    initializeComponents();      
    determinePFBusType();
    composeAdmittanceMatrix();

	mJ.setZero(mNumUnknowns,mNumUnknowns);
	mX.setZero(mNumUnknowns);
	mF.setZero(mNumUnknowns);
}

void PFSolver::initializeComponents(){
    for (auto comp : mSystem.mComponents) {
        std::dynamic_pointer_cast<PowerComponent<Complex>>(comp)->updateSimNodes();
    }

	mSLog->info("-- Initialize components from terminals or nodes of topology");
	for (auto comp : mSystem.mComponents) {
		auto pComp = std::dynamic_pointer_cast<PowerComponent<Complex>>(comp);
		if (!pComp)	continue;
		pComp->initializeFromPowerflow(mSystem.mSystemFrequency);
	}

	for (auto line : mLines) {
			line->calculatePerUnitParameters(mBaseApparentPower, mSystem.mSystemOmega);
	}
	for(auto trans : mTransformers) {
		//to check if this transformer could be ignored
		if (trans->attribute("R") == 0 && trans->attribute("L") == 0) {
			mSLog->info("{} {} ignored for R = 0 and L = 0",trans->type(), trans->name());
			continue;
		}
		trans->calculatePerUnitParameters(mBaseApparentPower, mSystem.mSystemOmega);
	}
	for(auto shunt : mShunts) {
		shunt->calculatePerUnitParameters(mBaseApparentPower, mSystem.mSystemOmega);
	}
	for(auto load : mLoads) {
		load->calculatePerUnitParameters(mBaseApparentPower, mSystem.mSystemOmega);
	}
Jan Dinkelbach's avatar
Jan Dinkelbach committed
93
94
95
	for(auto gen : mSynchronGenerators) {
		gen->calculatePerUnitParameters(mBaseApparentPower, mSystem.mSystemOmega);
	}
96
97
98
99
100
101
102
	
}

void PFSolver::setBaseApparentPower() {
	Real maxPower = 0.;
	if (!mSynchronGenerators.empty()) {
		for (auto gen : mSynchronGenerators)
Jan Dinkelbach's avatar
Jan Dinkelbach committed
103
104
			if (std::abs(gen->attribute<Real>("P_set")->get()) > maxPower)
				maxPower = std::abs(gen->attribute<Real>("P_set")->get());
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
	}
	else if (!mTransformers.empty()) {
		for (auto trafo : mTransformers)
			if (trafo->attribute<Real>("S")->get() > maxPower)
				maxPower = trafo->attribute<Real>("S")->get();
	}
    if (maxPower != 0.)
        mBaseApparentPower = pow(10, 1 + floor(log10(maxPower)));
	else
	{
		mBaseApparentPower = 100000000;
		mSLog->warn("No suitable quantity found for setting mBaseApparentPower. Using {} VA.", mBaseApparentPower);		
	}
	mSLog->info("Base power = {} VA", mBaseApparentPower);
}

void PFSolver::determinePFBusType() {
	mPQBusIndices.clear();
	mPVBusIndices.clear();
	mVDBusIndices.clear();

    // Determine powerflow bus type of each node through analysis of system topology
	for (auto node : mSystem.mNodes) {    
		bool connectedPV = false;
		bool connectedPQ = false;
		bool connectedVD = false;

		for (auto comp : mSystem.mComponentsAtNode[node]) {
			if (std::shared_ptr<CPS::SP::Ph1::Load> load = std::dynamic_pointer_cast<CPS::SP::Ph1::Load>(comp)) {
				if (load->mPowerflowBusType == CPS::PowerflowBusType::PQ) {
					connectedPQ = true;
				}
			}
			else if (std::shared_ptr<CPS::SP::Ph1::SynchronGenerator> gen = std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(comp)) {
				if (gen->mPowerflowBusType == CPS::PowerflowBusType::PV) {
					connectedPV = true;
				}
				else if (gen->mPowerflowBusType == CPS::PowerflowBusType::VD) {
					connectedVD = true;
				}
			}
			else if (std::shared_ptr<CPS::SP::Ph1::externalGridInjection> extnet = std::dynamic_pointer_cast<CPS::SP::Ph1::externalGridInjection>(comp)) {
				if (extnet->mPowerflowBusType == CPS::PowerflowBusType::VD) {
					connectedVD = true;
				}
			}
		}

		// determine powerflow bus types according connected type of connected components
		// only PQ type component connected -> set as PQ bus
		if (!connectedPV && connectedPQ && !connectedVD) { 
			mPQBusIndices.push_back(node->simNode());
			mPQBuses.push_back(node);
		} // no component connected -> set as PQ bus (P & Q will be zero)
		else if (!connectedPV && !connectedPQ && !connectedVD) {
			mPQBusIndices.push_back(node->simNode());
			mPQBuses.push_back(node);
		} // only PV type component connected -> set as PV bus
		else if (connectedPV && !connectedPQ && !connectedVD) {
			mPVBusIndices.push_back(node->simNode());
			mPVBuses.push_back(node);
		} // PV and PQ type component connected -> set as PV bus (TODO: bus type should be modifiable by user afterwards)
		else if (connectedPV && connectedPQ && !connectedVD) {
			mPVBusIndices.push_back(node->simNode());
			mPVBuses.push_back(node);
170
			mSLog->info("Note: node with uuid {} set as PV bus. Both PV and PQ type components were connected.", node->attribute<String>("uid")->get());	
171
172
173
174
		} // only VD type component connected -> set as VD bus
		else if (!connectedPV && !connectedPQ && connectedVD) {
			mVDBusIndices.push_back(node->simNode());
			mVDBuses.push_back(node);
175
176
177
178
179
		} // VD and PV type component connect -> set as VD bus
		else if (connectedPV && !connectedPQ && connectedVD) {
			mVDBusIndices.push_back(node->simNode());
			mVDBuses.push_back(node);
			mSLog->info("Note: node with uuid {} set as VD bus. Both VD and PV type components were connected.", node->attribute<String>("uid")->get());
180
181
182
183
184
185
		} // VD, PV and PQ type component connect -> set as VD bus
		else if (connectedPV && connectedPQ && connectedVD) {
			mVDBusIndices.push_back(node->simNode());
			mVDBuses.push_back(node);
			mSLog->info("Note: node with uuid {} set as VD bus. VD, PV and PQ type components were connected.", node->attribute<String>("uid")->get());
		} 
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
		else {
			std::stringstream ss;
			ss << "Node>>" << node->name() << ": combination of connected components is invalid";
			throw std::invalid_argument(ss.str());
		}
	}

    mNumPQBuses = mPQBusIndices.size();
	mNumPVBuses = mPVBusIndices.size();
    mNumVDBuses = mVDBusIndices.size();
    mNumUnknowns = 2*mNumPQBuses + mNumPVBuses;

	// Aggregate PQ bus and PV bus index vectors for easy handling in solver
	mPQPVBusIndices.reserve(mNumPQBuses + mNumPVBuses);
    mPQPVBusIndices.insert(mPQPVBusIndices.end(), mPQBusIndices.begin(), mPQBusIndices.end());
    mPQPVBusIndices.insert(mPQPVBusIndices.end(), mPVBusIndices.begin(), mPVBusIndices.end());

	mSLog->info("#### Create index vectors for power flow solver:");
    mSLog->info("PQ Buses: {}", logVector(mPQBusIndices));
    mSLog->info("PV Buses: {}", logVector(mPVBusIndices));
    mSLog->info("VD Buses: {}", logVector(mVDBusIndices));
}

void PFSolver::setVDNode(CPS::String name) {
	if (!mExternalGrids.empty()) {
		if (mExternalGrids[0]->node(0)->name() == name) {
			mExternalGrids[0]->modifyPowerFlowBusType(CPS::PowerflowBusType::VD);
		}
	} else {
		for (auto gen : mSynchronGenerators) {
			if (gen->node(0)->name() == name)
			{
				gen->modifyPowerFlowBusType(CPS::PowerflowBusType::VD);
				return;
			}
		}
		throw std::invalid_argument("Invalid slack bus, no external grid or synchronous generator attached");
	}
}

void PFSolver::modifyPowerFlowBusComponent(CPS::String name, CPS::PowerflowBusType powerFlowBusType) {
	for (auto comp : mSystem.mComponents) {
		if (comp->name() == name) {
			if (std::shared_ptr<CPS::SP::Ph1::externalGridInjection> extnet = std::dynamic_pointer_cast<CPS::SP::Ph1::externalGridInjection>(comp))
				extnet->modifyPowerFlowBusType(powerFlowBusType);
			else if(std::shared_ptr<CPS::SP::Ph1::SynchronGenerator> gen = std::dynamic_pointer_cast<CPS::SP::Ph1::SynchronGenerator>(comp))
				gen->modifyPowerFlowBusType(powerFlowBusType);
		}
	}
}

void PFSolver::composeAdmittanceMatrix() {
	int n = mSystem.mNodes.size();
	if (n > 0) {
		mY = CPS::SparseMatrixComp(n, n);
		for (auto line : mLines) {
			line->pfApplyAdmittanceMatrixStamp(mY);
		}
		for(auto trans : mTransformers) {
			//to check if this transformer could be ignored
			if (trans->attribute("R") == 0 && trans->attribute("L") == 0) {
				mSLog->info("{} {} ignored for R = 0 and L = 0",trans->type(), trans->name());
				continue;
			}
			trans->pfApplyAdmittanceMatrixStamp(mY);
		}
		for(auto shunt : mShunts) {
			shunt->pfApplyAdmittanceMatrixStamp(mY);
		}
	}
	if(mLines.empty() && mTransformers.empty()) {
		throw std::invalid_argument("There are no bus");
	}	
}

CPS::Real PFSolver::G(int i, int j) {
	return mY.coeff(i, j).real();
}

CPS::Real PFSolver::B(int i, int j) {
	return mY.coeff(i, j).imag();
}

CPS::Bool PFSolver::checkConvergence() {
	// Converged if all mismatches are below the tolerance
    for (CPS::UInt i = 0; i < mNumUnknowns; i++) {
        if (abs(mF(i)) > mTolerance)
            return false;
	}
    return true;
}

Bool PFSolver::solvePowerflow() {
	// Calculate the mismatch according to the initial solution
    calculateMismatch();

    // Check whether model already converged
    isConverged = checkConvergence();

    mIterations = 0;
    for (unsigned i = 1; i < mMaxIterations && !isConverged; ++i) {
		
        calculateJacobian();
		auto sparseJ = mJ.sparseView();

		// Solve system mJ*mX = mF
        Eigen::SparseLU<SparseMatrix>lu(sparseJ);

		mX = lu.solve(mF);	/* code */	        

		// Calculate new solution based on mX increments obtained from equation system
		updateSolution();

        // Calculate the mismatch according to the current solution
        calculateMismatch();

		mSLog->debug("Mismatch vector at iteration {}: \n {}", i, mF);
		mSLog->flush();

		// Check convergence
        isConverged = checkConvergence();
        mIterations = i;
    }
	return isConverged;
}

void PFSolver::SolveTask::execute(Real time, Int timeStepCount) {
	// apply keepLastSolution to save computation time
    mSolver.generateInitialSolution(time);
	mSolver.solvePowerflow();
	mSolver.setSolution();
}

Task::List PFSolver::getTasks() {
	return Task::List{std::make_shared<SolveTask>(*this)};
}