plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
MORLab/sss-master
testConnect.m
.m
sss-master/test/testScripts/testConnect.m
2,705
utf_8
ac32e06601d9799f78fe448a60f7a0d1
classdef testConnect < sssTest methods(Test) function testConnect1(testCase) if length(testCase.sysCell)>1 for i=1:2:length(testCase.sysCell)-1 sys1=testCase.sysCell{i}; sys2=testCase.sysCell{i+1}; sysConnect(testCase,sys1,sys2) end else sys1=loadSss('building.mat'); sys2=loadSss('random.mat'); sysConnect(testCase,sys1,sys2); end end end end function []=sysConnect(testCase,sys1,sys2) if sys1.m>5 || sys2.m>5 || sys1.p>5 || sys2.p>5 error('test is only for systems with sys.p<6 and sys.m<6'); end inputVector1={'u11','u12','u13','u14','u15'}; outputVector1={'y11','y12','y13','y14','y15'}; inputVector2={'u21','u22','u23','u24','u25'}; outputVector2={'y21','y22','y23','y24','y25'}; sys1.InputName=inputVector1(1:sys1.m)'; sys1.OutputName=outputVector1(1:sys1.p)'; sys2.InputName=inputVector2(1:sys2.m)'; sys2.OutputName=outputVector2(1:sys2.p)'; [actSys]=connect(sys1,sys2,[inputVector1(1:sys1.m),inputVector2(1:sys2.m)],[outputVector1(1:sys1.p),outputVector2(1:sys2.p)]); [expSys]=connect(ss(sys1),ss(sys2),[inputVector1(1:sys1.m),inputVector2(1:sys2.m)],[outputVector1(1:sys1.p),outputVector2(1:sys2.p)]); actSolution={full(actSys.E\actSys.A), full(actSys.B), full(actSys.C), full(actSys.D)}; expSolution={expSys.A, expSys.B, expSys.C, expSys.D}; verifyEqual(testCase, actSolution, expSolution, 'RelTol', 0.1,'AbsTol',0.000001, ... 'Difference between actual and expected exceeds relative tolerance'); verifyInstanceOf(testCase, full(actSys.A) , 'double', 'Instances not matching'); verifyInstanceOf(testCase, full(actSys.B) , 'double', 'Instances not matching'); verifyInstanceOf(testCase, full(actSys.C) , 'double', 'Instances not matching'); verifyInstanceOf(testCase, full(actSys.D) , 'double', 'Instances not matching'); verifyInstanceOf(testCase, full(actSys.E) , 'double', 'Instances not matching'); verifySize(testCase, actSys.A, size(expSys.A), 'Size not matching'); verifySize(testCase, actSys.B, size(expSys.B), 'Size not matching'); verifySize(testCase, actSys.C, size(expSys.C), 'Size not matching'); verifySize(testCase, actSys.D, size(expSys.D), 'Size not matching'); verifySize(testCase, actSys.E, size(expSys.A), 'Size not matching'); end
github
MORLab/sss-master
testEig.m
.m
sss-master/test/testScripts/testEig.m
1,528
utf_8
a15b4c6a912781926e57cd3c3698f6bf
classdef testEig < sssTest methods (Test) function testEig1(testCase) for i=1:length(testCase.sysCell) sys_sss=testCase.sysCell{i}; [actD]=eig(sys_sss); [expD]=eig(full(sys_sss.A), full(sys_sss.E)); %sort eigenvalues on real part actD_real=real(actD); actD_imag=imag(actD); tbl=table(actD_real, actD_imag); tbl=sortrows(tbl); actD_real=tbl.actD_real; actD_imag=tbl.actD_imag; expD_real=real(expD); expD_imag=imag(expD); tbl=table(expD_real, expD_imag); tbl=sortrows(tbl); expD_real=tbl.expD_real; expD_imag=tbl.expD_imag; actSolution={full(actD_real), sort(full(actD_imag))}; expSolution={expD_real, sort(expD_imag)}; verification (testCase, actSolution, expSolution); verifyInstanceOf(testCase, actD , 'double', 'Instances not matching'); verifySize(testCase, actD, size(expD), 'Size not matching'); end end end end function [] = verification (testCase, actSolution, expSolution) verifyEqual(testCase, actSolution, expSolution, 'RelTol', 0.2,'AbsTol',0.00001, ... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testDecayTime.m
.m
sss-master/test/testScripts/testDecayTime.m
2,018
utf_8
2919aed3382352bb5287d09c6f46eeb1
classdef testDecayTime < sssTest methods (Test) function stableSys(testCase) for i=1:length(testCase.sysCell) sys=testCase.sysCell{i}; warning('off','sss:decayTime:UnstableSys'); [actTmax]=decayTime(sys); if ~isnan(actTmax) % system stable pmin=-log(100)/actTmax; %real(smallest dominant pole) [h]=impulse(ss(pmin,1,1,0),0:actTmax:actTmax); %impulse answer of pmin h=abs(h); expSolution=h(1)*0.01; actSolution=h(2); verification (testCase, actSolution, expSolution); verifyInstanceOf(testCase, actTmax , 'double', 'Instances not matching'); verifySize(testCase, actTmax, [1 1], 'Size not matching'); else warning('off','sss:isstable:EigsFailed'); verification(testCase, isstable(sys), 0); end end end function unstableSys(testCase) warning('off','sss:decayTime:UnstableSys'); tmax=decayTime(sss(1,1,1)); % unstable system verification(testCase,isnan(tmax),true); end function plausibleTime(testCase) % Confirm through ss/impulse that the decay time computed is % not too far away from the actual one for i=1:length(testCase.sysCell) sys=testCase.sysCell{i}; t = decayTime(sys); [~,tI] = impulse(ss(sys)); dt = abs(t-tI(end))/t; verifyLessThan(testCase,dt,10) %allow difference to be off by a factor 10 end end end end function [] = verification (testCase, actSolution, expSolution) verifyEqual(testCase, actSolution, expSolution, 'RelTol', 0.1,'AbsTol',0.000001, ... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testDcGain.m
.m
sss-master/test/testScripts/testDcGain.m
1,520
utf_8
5b2abf30ca7c61c75e8e23d1f340796b
classdef testDcGain < sssTest % testDcGain - testing of dcgain.m % % ------------------------------------------------------------------ % This file is part of sssMOR, a Sparse State Space, Model Order % Reduction and System Analysis Toolbox developed at the Institute % of Automatic Control, Technische Universitaet Muenchen. % For updates and further information please visit www.rt.mw.tum.de % For any suggestions, submission and/or bug reports, mail us at % -> [email protected] <- % ------------------------------------------------------------------ % Authors: Alessandro Castagnotto, Maria Cruz Varona % Lisa Jeschek % Last Change: 20 May 2016 % Copyright (c) 2015 Chair of Automatic Control, TU Muenchen % ------------------------------------------------------------------ methods(Test) function testDcGain1(testCase) for i=1:length(testCase.sysCell) sys=testCase.sysCell{i}; if ~sys.isDae actSolution=dcgain(sys); expSolution=dcgain(ss(sys)); verification (testCase, actSolution, expSolution); end end end end end function [] = verification(testCase, actSolution, expSolution) verifyEqual(testCase, actSolution, expSolution,'RelTol',1.1e-3,'AbsTol',1e-3,... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testIssd.m
.m
sss-master/test/testScripts/testIssd.m
1,244
utf_8
54a18e40995a1c917337be73db3e6a4c
classdef testIssd < sssTest methods (Test) function testIssd1(testCase) for i=1:length(testCase.sysCell) sys=testCase.sysCell{i}; if ~sys.isDae size(sys.A) [actSolution]=issd(sys); if nnz(eig(full(sys.A+sys.A'),'vector')>=0) expSolution=0; else expSolution=1; end if sys.isDescriptor if nnz(eig(full(sys.E))<=0) expSolution=0; end end verification (testCase, actSolution, expSolution); verifyInstanceOf(testCase, actSolution , 'double', 'Instances not matching'); verifySize(testCase, actSolution, [1 1], 'Size not matching'); end end end end end function [] = verification (testCase, actSolution, expSolution) verifyEqual(testCase, actSolution, expSolution, 'RelTol', 0.1,'AbsTol',0.000001, ... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testSolveLse.m
.m
sss-master/test/testScripts/testSolveLse.m
3,728
utf_8
078f62818916f83f6bed74b588992cd1
classdef testSolveLse < sssTest methods(Test) function testSolveLseBasic(testCase) for i=1:length(testCase.sysCell) sys=testCase.sysCell{i}; if sys.isSiso && ~sys.isDae % test A\B actX1=solveLse(sys.A,sys.B); expX1=full(sys.A\sys.B); % test A\B and A'\C' Opts.lse='hess'; [actX2,actY2]=solveLse(sys.A,sys.B,sys.C,Opts); expX2=full(sys.A\sys.B); expY2=full(sys.A'\sys.C'); % test (A-5*E)\B and (A-5*E)'\C' Opts.lse='hess'; [actX3,actY3]=solveLse(sys.A,sys.B,sys.C,sys.E,[5,8,3],Opts); expX3=[full((sys.A-5*sys.E)\sys.B),full((sys.A-8*sys.E)\sys.B),full((sys.A-3*sys.E)\sys.B)]; expY3=[full((sys.A-5*sys.E)'\sys.C'),full((sys.A-8*sys.E)'\sys.C'),full((sys.A-3*sys.E)'\sys.C')]; % test Markov parameter E\B [actX4]=solveLse(sys.A,sys.B,sys.E,Inf); expX4=full(sys.E\sys.B); % test several shifts Opts.lse='sparse'; Opts.refine='wilkinson'; [actX5]=solveLse(sys.A,sys.B,sys.E,[3,4,4, 1+i, 1-i],Opts); expX5=full([(sys.A-3*sys.E)\sys.B,(sys.A-4*sys.E)\sys.B,... (sys.A-4*sys.E)\sys.B,(sys.A-(1+i)*sys.E)\sys.B,... (sys.A-(1-i)*sys.E)\sys.B]); % test iterative solver Opts.lse='iterative'; actX6=solveLse(sys.A,sys.B,sys.E,6,Opts); expX6=full((sys.A-6*sys.E)\sys.B); % test sys [actX7,actY7, Sx, Rx, Sy, Ly]=solveLse(sys,[2,4]); expX7=full([(sys.A-2*sys.E)\sys.B,(sys.A-4*sys.E)\sys.B]); expY7=full([(sys.A-2*sys.E)'\sys.C',(sys.A-4*sys.E)'\sys.C']); actSolution={actX1,actX2,actY2,actX3,actY3,actX4,actX5,actX6,actX7,actY7}; expSolution={expX1,expX2,expY2,expX3,expY3,expX4,expX5,expX6,expX7,expY7}; verification(testCase, actSolution, expSolution); end end end function testImpulseParsing(testCase) % System of order n=1 [actX1, actY1]=solveLse(1,2,3); expX1=2; expY1=3; [actX2, actY2]=solveLse(1,2,3,4,5); expX2=2/(1-5*4); expY2=3/(1-5*4); actSolution={actX1,actY1,actX2,actY2}; expSolution={expX1,expY1,expX2,expY2}; verification(testCase,actSolution,expSolution); % jCol s0=1:length(testCase.sysCell); for i=1:length(testCase.sysCell) sys=testCase.sysCell{i}; X=zeros(size(sys.A,1),length(testCase.sysCell)); if sys.isSiso && ~sys.isDae actX3=solveLse(i,X,sys.A,sys.B,sys.E,s0); expX3=(sys.A-s0(i)*sys.E)\sys.B; verification(testCase,actX3(:,i),full(expX3)); end end end end end function [] = verification(testCase, actSolution, expSolution) verifyEqual(testCase, actSolution, expSolution,'RelTol',1e-5,'AbsTol',1e-5,... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testPole.m
.m
sss-master/test/testScripts/testPole.m
2,547
utf_8
12f70209dfa033aade0eefcbbd24c65a
classdef testPole < sssTest % testPoles - testing of pole.m methods(Test) function testLM(testCase) for i=1:length(testCase.sysCell) sys=testCase.sysCell{i}; if ~sys.isDae Opts.type='lm'; k=20; p=pole(sys,k,Opts); % compare results of eig and eigs pEig=eig(full(sys.A),full(sys.E)); % remove poles at infinity pEig=pEig(abs(real(pEig))<1e6); tbl=table(-abs(p),p); tbl=sortrows(tbl); p=tbl.p; tbl=table(-abs(pEig),pEig); tbl=sortrows(tbl); pEig=tbl.pEig; %remove single complex element (for comparison) if abs(imag(sum(p)))>1e-12 p(abs(imag(p)-imag(sum(p)))<1e-16)=[]; end % make sure sorting is correct p=cplxpair(p); pEig=cplxpair(pEig(1:size(p,1))); verification(testCase, p,pEig(1:size(p,1))); end end end function testSM(testCase) for i=1:length(testCase.sysCell) sys=testCase.sysCell{i}; if ~sys.isDae Opts.type='sm'; k=10; p=pole(sys,k,Opts); % compare results of eig and eigs pEig=eig(full(sys.A),full(sys.E)); % remove poles at infinity pEig=pEig(abs(real(pEig))<1e6); tbl=table(abs(p),p); tbl=sortrows(tbl); p=tbl.p; tbl=table(abs(pEig),pEig); tbl=sortrows(tbl); pEig=tbl.pEig; % remove single complex element (for comparison) if abs(imag(sum(p)))>1e-12 p(abs(imag(p)-imag(sum(p)))<1e-16)=[]; end verification(testCase, p,pEig(1:size(p,1))); end end end end end function [] = verification(testCase, actSolution, expSolution) verifyEqual(testCase, actSolution, expSolution,'RelTol',1e-6,'AbsTol',1e-6,... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testSs.m
.m
sss-master/test/testScripts/testSs.m
1,726
utf_8
964a0b818df7b32d5b259e7cc3ea211e
classdef testSs < sssTest % testSs - testing of ss.m % % Description: % The function norm.m is tested (3 tests) on: % + Norm of a SISO benchmark system. % + Norm of a SISO random system. % + Norm of a MISO random system. % + Norm of a SIMO random system. % + Norm of MIMO benchmark system. % + Norm of a MIMO random system. % + Verifies for every case the following inputs/outputs: sys=ss(sysSparse) % % ------------------------------------------------------------------ % This file is part of sssMOR, a Sparse State Space, Model Order % Reduction and System Analysis Toolbox developed at the Institute % of Automatic Control, Technische Universitaet Muenchen. % For updates and further information please visit www.rt.mw.tum.de % For any suggestions, submission and/or bug reports, mail us at % -> [email protected] <- % ------------------------------------------------------------------ % Authors: Alessandro Castagnotto % Jorge Luiz Moreira Silva % Last Change: 26 Out 2015 % Copyright (c) 2015 Chair of Automatic Control, TU Muenchen % ------------------------------------------------------------------ methods(Test) function testBench(testCase) for i=1:length(testCase.sysCell) sysSparse=testCase.sysCell{i}; sys=ss(sysSparse); end end end end function [] = verification(testCase, actSolution, expSolution) verifyEqual(testCase, actSolution(1:4), expSolution(1:4),'RelTol',1e-3,... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testFreqresp.m
.m
sss-master/test/testScripts/testFreqresp.m
4,300
utf_8
38af8fa2efaed5bd9a4d266f61625a57
classdef testFreqresp < sssTest methods (Test) function testFreqresp1(testCase) %real frequencies for i=1:length(testCase.sysCell) sys_sss=testCase.sysCell{i}; if ~sys_sss.isDae sys_ss=ss(sys_sss); t=0:100:1000; t = [-t,t]; [actG, actOmega]=freqresp(sys_sss,t); [expG, expOmega]=freqresp(sys_ss,t); actSolution={actG, actOmega}; expSolution={expG, expOmega}; verification (testCase, actSolution, expSolution); verifyInstanceOf(testCase, actG , 'double', 'Instances not matching'); verifyInstanceOf(testCase, actOmega , 'double', 'Instances not matching'); verifySize(testCase, actG, size(expG), 'Size not matching'); verifySize(testCase, actOmega, size(expOmega), 'Size not matching'); end end end function testFreqresp2(testCase) %imaginary frequencies for i=1:length(testCase.sysCell) sys_sss=testCase.sysCell{i}; if ~sys_sss.isDae sys_ss=ss(sys_sss); t=1:100:1000; t=[-1i*t,1i*t]; [actG, actOmega]=freqresp(sys_sss,t); [expG, expOmega]=freqresp(ss(sys_ss),t); actSolution={actG, actOmega}; expSolution={expG, expOmega}; verification (testCase, actSolution, expSolution); verifyInstanceOf(testCase, actG , 'double', 'Instances not matching'); verifyInstanceOf(testCase, actOmega , 'double', 'Instances not matching'); verifySize(testCase, actG, size(expG), 'Size not matching'); verifySize(testCase, actOmega, size(expOmega), 'Size not matching'); end end end function testFreqresp3(testCase) %complex frequencies for i=1:length(testCase.sysCell) sys_sss=testCase.sysCell{i}; if ~sys_sss.isDae sys_ss=ss(sys_sss); t=1e2*randn(1,10) + 1e4*1i*randn(1,10); [actG, actOmega]=freqresp(sys_sss,t); [expG, expOmega]=freqresp(ss(sys_ss),t); actSolution={actG, actOmega}; expSolution={expG, expOmega}; verification (testCase, actSolution, expSolution); verifyInstanceOf(testCase, actG , 'double', 'Instances not matching'); verifyInstanceOf(testCase, actOmega , 'double', 'Instances not matching'); verifySize(testCase, actG, size(expG), 'Size not matching'); verifySize(testCase, actOmega, size(expOmega), 'Size not matching'); end end end function testOmegaRange(testCase) % input of frequnecy range for i=1:length(testCase.sysCell) sys = testCase.sysCell{i}; if ~sys.isDae w = {10,100}; [~,omega] = freqresp(sys,w); verifyEqual(testCase,omega(1),w{1}, 'Wrong frequency returned'); verifyEqual(testCase,omega(end),w{2},'Wrong frequency returned'); end end end function testStaticGain(testCase) % test a static gain model sys1=sss([],[],[],5); [actSolution1,omega]=freqresp(sys1); expSolution1=freqresp(ss(sys1),omega); sys2=sss(-speye(3),zeros(3,2),zeros(3),[1,2;3,4;5,6]); [actSolution2,omega]=freqresp(sys2); expSolution2=freqresp(ss(sys2),omega); verification(testCase,{actSolution1,actSolution2},{expSolution1,expSolution2}); end end end function [] = verification (testCase, actSolution, expSolution) verifyEqual(testCase, actSolution, expSolution, 'RelTol', 0.1,'AbsTol',0.000001, ... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testIsstable.m
.m
sss-master/test/testScripts/testIsstable.m
833
utf_8
394937bb989cedd92a61c4173a9df504
classdef testIsstable < sssTest methods (Test) function testIsstable1(testCase) for i=1:length(testCase.sysCell) sys=testCase.sysCell{i}; warning('off','sss:isstable:EigsFailed'); [actB] = isstable(sys); [expB]=isstable(ss(sys)); actSolution={logical(actB)}; expSolution={expB}; verification (testCase, actSolution, expSolution); end end end end function [] = verification (testCase, actSolution, expSolution) verifyEqual(testCase, actSolution, expSolution, 'RelTol', 0.1,'AbsTol',0.000001, ... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testSim.m
.m
sss-master/test/testScripts/testSim.m
13,137
utf_8
415ba0633fbcf791f16c37ce6a46895f
classdef testSim < sssTest % testSim - Testing of sim.m % % Description: % The function sim.m is tested on: % + Simulation of an artifitialy constructed, stable SSS, SISO benchmark % % + Simulation of a SSS, SISO benchmark system (building). % % + Simulation of a SSS, SISO benchmark system (heat-cond). % % + Simulation of a DSSS, SISO benchmark system (SpiralInductorPeec). % % + Simulation of a SSS, MIMO benchmark system (iss). % % + Simulation of a SSS, MIMO benchmark system (CDplayer). % % + Simulation of a DSSS, MIMO benchmark system (rail_1357). % % + Verification of the obtained results. % %------------------------------------------------------------------ % This file is part of sssMOR, a Sparse State Space, Model Order % Reduction and System Analysis Toolbox developed at the Institute % of Automatic Control, Technische Universitaet Muenchen. % For updates and further information please visit www.rt.mw.tum.de % For any suggestions, submission and/or bug reports, mail us at % -> [email protected] <- %------------------------------------------------------------------ % Authors: Maria Cruz Varona % Last Change: 05 Apr 2016 % Copyright (c) 2016 Chair of Automatic Control, TU Muenchen %------------------------------------------------------------------ methods(Test) function testSISOartificial(testCase) % create a artificial systems which has all eigenvalues on the % left side of the imaginary axis lambda = ones(100,1) + rand(100,1)*5; A = diag(-lambda); B = ones(100,1); C = ones(1,100); sys = sss(A,B,C); sys_ss = ss(sys); % create an input signal u as a iddata-object Ts = 1e-4; t = 0:Ts:10; u = idinput(length(t),'rgs',[0 0.5/(1/2/Ts)])'; datau = iddata([],u',Ts); % simulate with the sss-toolbox functions dataSparseRK4 = sim(sys, datau,'RK4'); dataSparseFoEuler = sim(sys, datau,'forwardEuler'); dataSparseBaEuler = sim(sys, datau,'backwardEuler'); dataSparseDiscrete = sim(c2d(sys,Ts), datau,'discrete'); % simulate with the ss-toolbox function (for verification) actSim = [dataSparseRK4.y,dataSparseFoEuler.y,dataSparseBaEuler.y,dataSparseDiscrete.y]; expSim = lsim(sys_ss,u,t); % % plot the result % figure; plot(t,actSim); hold on; plot(t,expSim); % xlabel('Time [s]'); ylabel('Amplitude'); % legend('RK4','ForwEuler','BackEuler','Discrete','lsim'); % check if all solutions are equal for iCase=1:4 verification(testCase, actSim(:,iCase), expSim); end end function testLsim(testCase) sys = sss('building'); u = [0:.1:100].'; ts = 0.01; %s tVec = 0:ts:ts*(length(u)-1); % sss [y1,t1,x1] = lsim(sys,u,ts); %call with ts [y2,t2,x2] = lsim(sys,u,tVec); %call with tVec % ss [yM, tM, xM] = lsim(ss(sys),u,tVec); % check sizes verifySize(testCase,y1,size(yM)); verifySize(testCase,y2,size(yM)); verifySize(testCase,t1,size(tM)); verifySize(testCase,t2,size(tM)); verifySize(testCase,x1,size(xM)); verifySize(testCase,x2,size(xM)); % check time vector limits tol = 1e-10; verifyEqual(testCase,t1(1), tM(1), 'AbsTol',tol); verifyEqual(testCase,t2(1), tM(1), 'AbsTol',tol); verifyEqual(testCase,t1(end), tM(end),'AbsTol',tol); verifyEqual(testCase,t2(end), tM(end),'AbsTol',tol); tol = 1e-3; % verify simulation results verifyLessThan(testCase,... [norm(tM-t1),norm(tM-t2),... norm(yM-y1),norm(yM-y2),... norm(xM-x1),norm(xM-x2)],... tol*ones(1,6)) end % function testSISObench1(testCase) % load('building.mat'); % sysSparse=sss(A,B,C); % sys=ss(full(A),full(B),full(C),zeros(1,1)); % nOutputs = sysSparse.p; % % % isstable = isstable(sysSparse) % % Ts = 1e-4; % t = 0:Ts:10; % u = idinput(length(t),'rgs',[0 0.5/(1/2/Ts)])'; % datau = iddata([],u',Ts); % % dataSparseRK4 = sim(sysSparse,datau,'RK4'); % dataSparseFoEuler = sim(sysSparse,datau,'forwardEuler'); % dataSparseBaEuler = sim(sysSparse,datau,'backwardEuler'); % dataSparseDiscrete = sim(c2d(sysSparse,Ts),datau,'discrete'); % % actSim = [dataSparseRK4.y,dataSparseFoEuler.y,dataSparseBaEuler.y,dataSparseDiscrete.y]; % expSim = lsim(sys,u,t); % % figure; plot(t,actSim); hold on; plot(t,expSim); % xlabel('Time [s]'); ylabel('Amplitude'); % legend('RK4','ForwEuler','BackEuler','Discrete','lsim'); % % for iCase=1:4 % verification(testCase, actSim(:,(iCase*nOutputs-nOutputs+1):iCase*nOutputs), expSim); % end % end % % function testSISObench2(testCase) % load('heat-cont.mat'); % sysSparse=sss(A,B,C); % sys=ss(full(A),full(B),full(C),zeros(1,1)); % nOutputs = sysSparse.p; % % % isstable = isstable(sysSparse) % % Ts = 1e-4; % t = 0:Ts:10; % % u = idinput(length(t),'rgs',[0 0.5/(1/2/Ts)])'; % u = double(t>=Ts); % datau = iddata([],u',Ts); % % dataSparseRK4 = sim(sysSparse,datau,'RK4'); % dataSparseFoEuler = sim(sysSparse,datau,'forwardEuler'); % dataSparseBaEuler = sim(sysSparse,datau,'backwardEuler'); % dataSparseDiscrete = sim(c2d(sysSparse,Ts),datau,'discrete'); % % actSim = [dataSparseRK4.y,dataSparseFoEuler.y,dataSparseBaEuler.y,dataSparseDiscrete.y]; % expSim = lsim(sys,u,t); % % figure; plot(t,actSim); hold on; plot(t,expSim); % xlabel('Time [s]'); ylabel('Amplitude'); % legend('RK4','ForwEuler','BackEuler','Discrete','lsim'); % % for iCase=1:4 % verification(testCase, actSim(:,(iCase*nOutputs-nOutputs+1):iCase*nOutputs), expSim); % end % end % % function testDSSSISObench(testCase) % load('SpiralInductorPeec.mat'); % sysSparse=sss(A,B,C,[],E); % sys=ss(sysSparse); % nOutputs = sysSparse.p; % % % isstable = isstable(sysSparse) % % Ts = 1e-10; % time constant of the system lies approx. by Tmax = 5e-8s % % Due to the Shannon-theorem: Ts = 1/2 * Tmax % t = 0:Ts:3e-7; % % u = idinput(length(t),'rgs',[0 0.5/(1/2/Ts)])'; % u = double(t>=Ts); % datau = iddata([],u',Ts); % % dataSparseRK4 = sim(sysSparse,datau,'RK4'); %bad results; needs probably a smaller sample time Ts % dataSparseFoEuler = sim(sysSparse,datau,'forwardEuler'); %bad results; needs probably a smaller sample time Ts % dataSparseBaEuler = sim(sysSparse,datau,'backwardEuler'); %good results % dataSparseDiscrete = sim(c2d(sysSparse,Ts),datau,'discrete'); %bad results; needs probably a smaller sample time Ts % % Sample time of Ts = 1e-18 still yield bad results % % actSim = [dataSparseRK4.y,dataSparseFoEuler.y,dataSparseBaEuler.y,dataSparseDiscrete.y]; % expSim = lsim(sys,u,t); % % % figure; plot(t,actSim); hold on; plot(t,expSim); % % xlabel('Time [s]'); ylabel('Amplitude'); % % legend('RK4','ForwEuler','BackEuler','Discrete','lsim'); % % figure; plot(t,dataSparseBaEuler.y); hold on; plot(t,expSim); % xlabel('Time [s]'); ylabel('Amplitude'); % legend('BackEuler','lsim'); % % for iCase=1:4 % verification(testCase, actSim(:,(iCase*nOutputs-nOutputs+1):iCase*nOutputs), expSim); % end % end % % function testMIMObench1(testCase) % load('iss.mat'); % sysSparse=sss(A,B,C); % sys=ss(full(A),full(B),full(C),zeros(3,3)); % nOutputs = sysSparse.p; % % % isstable = isstable(sysSparse); % % Ts = 1e-4; % t = 0:Ts:1; % % u = idinput(length(t),'rgs',[0 0.5/(1/2/Ts)])'; % u = double(t>=Ts); % % U = repmat(u,size(B,2),1); % dataU = iddata([],U',Ts); % % dataSparseRK4 = sim(sysSparse,dataU,'RK4'); %good results % dataSparseFoEuler = sim(sysSparse,dataU,'forwardEuler'); %good results % dataSparseBaEuler = sim(sysSparse,dataU,'backwardEuler'); %good results % dataSparseDiscrete = sim(c2d(sysSparse,Ts),dataU,'discrete'); %good results % % actSim = [dataSparseRK4.y,dataSparseFoEuler.y,dataSparseBaEuler.y,dataSparseDiscrete.y]; % expSim = lsim(sys,U,t); % % figure; plot(t,actSim); hold on; plot(t,expSim); % xlabel('Time [s]'); ylabel('Amplitude'); % % for iCase=1:4 % verification(testCase, actSim(:,(iCase*nOutputs-nOutputs+1):iCase*nOutputs), expSim); % end % end % % function testMIMObench2(testCase) % load('CDplayer.mat'); % sysSparse=sss(A,B,C); % sys=ss(full(A),full(B),full(C),zeros(2,2)); % nOutputs = sysSparse.p; % % % isstable = isstable(sysSparse); % % Ts = 1e-7; % t = 0:Ts:1; % % u = idinput(length(t),'rgs',[0 0.5/(1/2/Ts)])'; % u = double(t>=Ts); % % U = repmat(u,size(B,2),1); % dataU = iddata([],U',Ts); % % dataSparseRK4 = sim(sysSparse,dataU,'RK4'); %good results % dataSparseFoEuler = sim(sysSparse,dataU,'forwardEuler'); %good results % dataSparseBaEuler = sim(sysSparse,dataU,'backwardEuler'); %good results % dataSparseDiscrete = sim(c2d(sysSparse,Ts),dataU,'discrete'); %good results % % actSim = [dataSparseRK4.y,dataSparseFoEuler.y,dataSparseBaEuler.y,dataSparseDiscrete.y]; % expSim = lsim(sys,U,t); % % figure; plot(t,actSim); hold on; plot(t,expSim); % xlabel('Time [s]'); ylabel('Amplitude'); % % for iCase=1:4 % verification(testCase, actSim(:,(iCase*nOutputs-nOutputs+1):iCase*nOutputs), expSim); % end % end % % function testMIMObench3(testCase) % load('rail_1357.mat'); % sysSparse=sss(A,B,C,[],E); % sys=dss(full(A),full(B),full(C),zeros(size(C,1),size(B,2)),full(E)); % nOutputs = sysSparse.p; % % % isstable = isstable(sysSparse) % % Ts = 1e-4; % t = 0:Ts:2; % % u = idinput(length(t),'rgs',[0 0.5/(1/2/Ts)])'; % u = double(t>=Ts); % % U = repmat(u,size(B,2),1); % dataU = iddata([],U',Ts); % % dataSparseRK4 = sim(sysSparse,dataU,'RK4'); %good results % dataSparseFoEuler = sim(sysSparse,dataU,'forwardEuler'); %good results % dataSparseBaEuler = sim(sysSparse,dataU,'backwardEuler'); %good results % dataSparseDiscrete = sim(c2d(sysSparse,Ts),dataU,'discrete'); %good results % % actSim = [dataSparseRK4.y,dataSparseFoEuler.y,dataSparseBaEuler.y,dataSparseDiscrete.y]; % expSim = lsim(sys,U,t); % % figure; plot(t,actSim); hold on; plot(t,expSim); % xlabel('Time [s]'); ylabel('Amplitude'); % % for iCase=1:4 % verification(testCase, actSim(:,(iCase*nOutputs-nOutputs+1):iCase*nOutputs), expSim); % end % end end end function [] = verification(testCase, actSolution, expSolution) verifyEqual(testCase, actSolution, expSolution, 'RelTol', 1e-1, 'AbsTol', 1e-2, ... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testFrd.m
.m
sss-master/test/testScripts/testFrd.m
1,027
utf_8
05ff53e94f8ca4e0f60f280bcecd2880
classdef testFrd < sssTest methods (Test) function generalFunctionality(testCase) for i=1:length(testCase.sysCell) sys_sss=testCase.sysCell{i}; if ~sys_sss.isDae sys_ss=ss(sys_sss); [expSolution, ~, omega]=bode(sys_ss); frdobj=frd(sys_sss,omega); actSolution=abs(frdobj.responseData); verification(testCase, actSolution, expSolution); verifyInstanceOf(testCase, frdobj, 'frd', 'Instances not matching'); frdobj=frd(sys_sss); verifyInstanceOf(testCase, frdobj, 'frd', 'Instances not matching'); end end end end end function [] = verification (testCase, actSolution, expSolution) verifyEqual(testCase, actSolution, expSolution, 'RelTol', 0.1,'AbsTol',0.000001, ... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testStep.m
.m
sss-master/test/testScripts/testStep.m
5,895
utf_8
f702e79bf929fc5e30a1346183867184
classdef testStep < sssTest % testStep - testing of step.m % % ------------------------------------------------------------------ % This file is part of sssMOR, a Sparse State Space, Model Order % Reduction and System Analysis Toolbox developed at the Institute % of Automatic Control, Technische Universitaet Muenchen. % For updates and further information please visit www.rt.mw.tum.de % For any suggestions, submission and/or bug reports, mail us at % -> [email protected] <- % ------------------------------------------------------------------ % Authors: Alessandro Castagnotto, Maria Cruz Varona % Jorge Luiz Moreira Silva, Stefan Jaensch % Last Change: 18 Apr 2016 % Copyright (c) 2015 Chair of Automatic Control, TU Muenchen % ------------------------------------------------------------------ methods(Test) function testStep1(testCase) filePath = fileparts(mfilename('fullpath')); toolPath = fileparts(filePath); load([toolPath '/../benchmarks/iss.mat']) sys = ss(full(A),full(B),full(C),[]); [sys,g] = balreal(sys); sys = modred(ss(sys),g<1e-3)+1; sysSss = sss(sys); sysSssE = sss(sys.A*2,sys.B*2,sys.C,sysSss.D,eye(size(sys.A))*2); tFinal = 15; [actH,actT]=step(ss(sysSss),tFinal); expH = {}; expT = {}; ODEset = odeset; ODEset.AbsTol = 1e-7; ODEset.RelTol = 1e-7; [expH{end+1},expT{end+1}]=step(sysSss,actT); [expH{end+1},expT{end+1}]=step(sysSss,actT,struct('nMin',0,'ode','ode113','odeset',ODEset)); [expH{end+1},expT{end+1}]=step(sysSss,actT,struct('nMin',0,'ode','ode15s','odeset',ODEset)); [expH{end+1},expT{end+1}]=step(sysSss,actT,struct('nMin',0,'ode','ode23','odeset',ODEset)); [expH{end+1},expT{end+1}]=step(sysSss,actT,struct('nMin',0,'ode','ode45','odeset',ODEset)); [expH{end+1},expT{end+1}]=step(sysSssE,actT,struct('nMin',0)); actSolution={actH,actT}; for i = 1:length(expH) expSolution={expH{i},expT{i}}; verification (testCase, actSolution, expSolution); verifyInstanceOf(testCase, actH, 'double', 'Instances not matching'); verifyInstanceOf(testCase, actT , 'double', 'Instances not matching'); verifySize(testCase, actH, size(expH{i}), 'Size not matching'); verifySize(testCase, actT, size(expT{i}), 'Size not matching'); end end function testStepPlot(testCase) filePath = fileparts(mfilename('fullpath')); toolPath = fileparts(filePath); load([toolPath '/../benchmarks/iss.mat']) sys = ss(full(A),full(B),full(C),[]); [sys,g] = balreal(sys); sys = modred(ss(sys),g<1e-3)+1; sys.InputName = {'u1';'u2';'u3';}; sys.OutputName = {'y1';'y2';'y3';}; sys = sss(sys); sysSss = sys; sysSssE = sss(sys.A*2,sys.B*2,sys.C,sysSss.D,eye(size(sys.A))*2); sys1_1 = sys(1,1); sys12_3 = sys(1:2,3); sysSS = ss(sys); tFinal = 15; figure step(sysSss,sysSssE,sys1_1,sys12_3,sysSS,tFinal) title('testStepPlot'); end function testStepBasic(testCase) for i=1:length(testCase.sysCell) sys=testCase.sysCell{i}; if ~sys.isDae && ~strcmp(sys.Name,'CDplayer') ODEset = odeset; ODEset.AbsTol = 1e-10; ODEset.RelTol = 1e-10; [expSolution,t]=step(ss(sys)); actSolution=step(sys,t,struct('nMin',0,'odeset',ODEset)); verification(testCase,actSolution,expSolution); end end end function testStepTime(testCase) for i=1:length(testCase.sysCell) sys=testCase.sysCell{i}; if ~sys.isDae ODEset = odeset; ODEset.AbsTol = 1e-8; ODEset.RelTol = 1e-8; % time vector t=0.1:0.1:0.3; [actSolution]=step(sys,t,struct('nMin',0,'odeset',ODEset)); expSolution=step(ss(sys),t); verification(testCase,actSolution,expSolution); % final time Tfinal=0.3; [~,t]=step(sys,Tfinal,struct('nMin',0,'odeset',ODEset)); verifyEqual(testCase,t(end),Tfinal,'AbsTol',0.05); end end end function testStepMultiSys(testCase) for i=1:length(testCase.sysCell) sys=testCase.sysCell{i}; if ~sys.isDae close all sys2=sss('building'); t=0.01:0.01:0.03; Tfinal=0.01; % test different calls step(sys,sys2,t,struct('nMin',0,'tsMin',1e-3)); step(sys,ss(sys2),Tfinal,struct('nMin',0,'tsMin',1e-3)); step(sys,'b-',sys2,'r--',Tfinal,struct('nMin',0,'tsMin',1e-3)); end end end end end function [] = verification(testCase, actSolution, expSolution) verifyEqual(testCase, actSolution, expSolution,'RelTol',1.1e-3,'AbsTol',1e-3,... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testDiag.m
.m
sss-master/test/testScripts/testDiag.m
1,787
utf_8
dfb67f4b3b4105b7135cee0902394ac6
classdef testDiag < sssTest methods (Test) function testDiag1(testCase) for i=1:length(testCase.sysCell) sys=testCase.sysCell{i}; if ~sys.isDae [actSys]=diag(sys); [expSys]=canon(ss(sys),'modal'); actSolution={trace(full(actSys.A)),sort(real(eig(full(actSys.A)))), sort(imag(eig(full(actSys.A))))}; expSolution={trace(expSys.A),sort(real(eig(expSys.A))), sort(imag(eig(expSys.A)))}; verification (testCase, actSolution, expSolution); verifyInstanceOf(testCase, full(actSys.A) , 'double', 'Instances not matching'); verifyInstanceOf(testCase, full(actSys.B) , 'double', 'Instances not matching'); verifyInstanceOf(testCase, full(actSys.C) , 'double', 'Instances not matching'); verifyInstanceOf(testCase, full(actSys.E) , 'double', 'Instances not matching'); verifySize(testCase, actSys.A, size(sys.A), 'Size not matching'); verifySize(testCase, actSys.B, size(sys.B), 'Size not matching'); verifySize(testCase, actSys.C, size(sys.C), 'Size not matching'); verifySize(testCase, actSys.E, size(sys.E), 'Size not matching'); verifyLessThan(testCase, norm(full(actSys.E)-eye(size(actSys.E))),0.01, 'E not identity'); end end end end end function [] = verification (testCase, actSolution, expSolution) verifyEqual(testCase, actSolution, expSolution, 'RelTol', 0.1,'AbsTol',0.000001, ... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testMtimes.m
.m
sss-master/test/testScripts/testMtimes.m
3,251
utf_8
db2d8b3f45e4b20ecda6975dce3924f0
classdef testMtimes < sssTest % testMtimes - testing of mtimes.m % % Description: % The function rk.m is tested (3 tests) on: % + combination of two benchmark-systems. % + combination of two random-systems that are equal. % + combination of two random-systems that are different. % % ------------------------------------------------------------------ % This file is part of sssMOR, a Sparse State Space, Model Order % Reduction and System Analysis Toolbox developed at the Institute % of Automatic Control, Technische Universitaet Muenchen. % For updates and further information please visit www.rt.mw.tum.de % For any suggestions, submission and/or bug reports, mail us at % -> [email protected] <- % ------------------------------------------------------------------ % Authors: Alessandro Castagnotto % Jorge Luiz Moreira Silva % Last Change: 26 Out 2015 % Copyright (c) 2015 Chair of Automatic Control, TU Muenchen % ------------------------------------------------------------------ methods(Test) function testMTimes1(testCase) for i=1:length(testCase.sysCell) sys=testCase.sysCell{i}; resultSparse = mtimes(sys, sys'); result=mtimes(ss(sys),ss(sys')); verification(testCase, resultSparse, result); end end function testMTimes2(testCase) initSys2=1; for i=1:length(testCase.sysCell) if testCase.sysCell{i}.isSiso sys1=testCase.sysCell{i}; if initSys2==1 sys2=testCase.sysCell{i}; initSys2=0; end resultSparse = mtimes(sys1, sys2); result=mtimes(ss(sys1),ss(sys2)); verification(testCase, resultSparse, result); sys2=sys1; end end end function resultingClass(testCase) sys = testCase.sysCell{1}; sysRed = ssRed(sys.A,sys.B,sys.C); %sparse * ss -> sss prod = sys*ss(sys); verifyClass(testCase,prod,'sss'); %ssRed * sss -> sss prod = sys * sysRed; verifyClass(testCase,prod,'sss'); %ssRed * ssRed -> ssRed prod = sysRed * sysRed; verifyClass(testCase,prod,'ssRed'); end end end function [] = verification(testCase, actSolution, expSolution, m) verifyEqual(testCase, full(actSolution.A), full(expSolution.A),'RelTol',0.1,... 'Difference between actual and expected exceeds relative tolerance'); verifyEqual(testCase, full(actSolution.B), full(expSolution.B),'RelTol',0.1,... 'Difference between actual and expected exceeds relative tolerance'); verifyEqual(testCase, full(actSolution.C), full(expSolution.C),'RelTol',0.1,... 'Difference between actual and expected exceeds relative tolerance'); verifyEqual(testCase, full(actSolution.D), full(expSolution.D),'RelTol',0.1,... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testPlus.m
.m
sss-master/test/testScripts/testPlus.m
3,891
utf_8
bb0f3252d62f8e9257278562610e5c0b
classdef testPlus < sssTest % testPlus - testing of plus.m % % Description: % The function plus.m is tested (3 tests) on: % + combination of two benchmark-systems. % + combination of two random-systems that are equal. % + combination of two random-systems that are different. % % ------------------------------------------------------------------ % This file is part of sssMOR, a Sparse State Space, Model Order % Reduction and System Analysis Toolbox developed at the Institute % of Automatic Control, Technische Universitaet Muenchen. % For updates and further information please visit www.rt.mw.tum.de % For any suggestions, submission and/or bug reports, mail us at % -> [email protected] <- % ------------------------------------------------------------------ % Authors: Alessandro Castagnotto, Maria Cruz Varona % Jorge Luiz Moreira Silva % Last Change: 05 Nov 2015 % Copyright (c) 2015 Chair of Automatic Control, TU Muenchen % ------------------------------------------------------------------ methods(Test) function testplus1(testCase) for i=1:length(testCase.sysCell) sysSparse=testCase.sysCell{i}; sys=ss(sysSparse); resultSparse = plus(sysSparse, sysSparse); result=plus(sys,sys); verification(testCase, resultSparse, result); end end function testplus2(testCase) initSys2=1; for i=1:length(testCase.sysCell) if testCase.sysCell{i}.isSiso sys1=testCase.sysCell{i}; if initSys2==1 sys2=testCase.sysCell{i}; initSys2=0; end resultSparse = plus(sys1, sys2); result=plus(ss(sys1),ss(sys2)); verification(testCase, resultSparse, result); end end end function resultingClass(testCase) sys = testCase.sysCell{1}; sysRed = ssRed(sys.A,sys.B,sys.C); D = ones(sys.p,sys.m); %sparse + ss -> sss sum = sys+ss(sys); verifyClass(testCase,sum,'sss'); %ssRed + sss -> sss sum = sys + sysRed; verifyClass(testCase,sum,'sss'); %ssRed + ssRed -> ssRed sum = sysRed + sysRed; verifyClass(testCase,sum,'ssRed'); %sss + D -> sss sum = sys + D; verifyClass(testCase,sum,'sss'); verifyEqual(testCase,sum.D,sparse(sys.D+D)); %correct addition verifyEqual(testCase,sys.n,sum.n); %no dimension increase %ssRed + D -> ssRed sum = sysRed + D; verifyClass(testCase,sum,'ssRed'); verifyEqual(testCase,sum.D,sys.D+D); %correct addition verifyEqual(testCase,sys.n,sum.n); %no dimension increase end end end function [] = verification(testCase, actSolution, expSolution) verifyEqual(testCase, full(actSolution.A), full(expSolution.A),'RelTol',0.1,... 'Difference between actual and expected exceeds relative tolerance'); verifyEqual(testCase, full(actSolution.B), full(expSolution.B),'RelTol',0.1,... 'Difference between actual and expected exceeds relative tolerance'); verifyEqual(testCase, full(actSolution.C), full(expSolution.C),'RelTol',0.1,... 'Difference between actual and expected exceeds relative tolerance'); verifyEqual(testCase, full(actSolution.D), full(expSolution.D),'RelTol',0.1,... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testConnectSss.m
.m
sss-master/test/testScripts/testConnectSss.m
1,970
utf_8
a9544da5b594217627ba30bbd90daa93
classdef testConnectSss < sssTest methods(Test) function testConnectSss1(testCase) if length(testCase.sysCell)>1 for i=1:2:length(testCase.sysCell)-1 sys1=testCase.sysCell{i}; sys2=testCase.sysCell{i+1}; sysConnect(testCase,sys1,sys2) end else sys1=loadSss('building.mat'); sys2=loadSss('random.mat'); sysConnect(testCase,sys1,sys2); end end end end function []=sysConnect(testCase,sys1,sys2) sys=append(sys1,sys2); K=rand(sys.m, sys.p); [actSys]=connectSss(sys,K); [expSys]=feedback(ss(sys),-K); actSolution={full(actSys.A), full(actSys.B), full(actSys.C), full(actSys.D)}; expSolution={expSys.A, expSys.B, expSys.C, expSys.D}; verifyEqual(testCase, actSolution, expSolution, 'RelTol', 0.1,'AbsTol',0.000001, ... 'Difference between actual and expected exceeds relative tolerance'); verifyInstanceOf(testCase, full(actSys.A) , 'double', 'Instances not matching'); verifyInstanceOf(testCase, full(actSys.B) , 'double', 'Instances not matching'); verifyInstanceOf(testCase, full(actSys.C) , 'double', 'Instances not matching'); verifyInstanceOf(testCase, full(actSys.D) , 'double', 'Instances not matching'); verifyInstanceOf(testCase, full(actSys.E) , 'double', 'Instances not matching'); verifySize(testCase, actSys.A, size(expSys.A), 'Size not matching'); verifySize(testCase, actSys.B, size(expSys.B), 'Size not matching'); verifySize(testCase, actSys.C, size(expSys.C), 'Size not matching'); verifySize(testCase, actSys.D, size(expSys.D), 'Size not matching'); verifySize(testCase, actSys.E, size(expSys.A), 'Size not matching'); end
github
MORLab/sss-master
testSpy.m
.m
sss-master/test/testScripts/testSpy.m
1,716
utf_8
01664e875c5bf0f938c75e96523ba3be
classdef testSpy < sssTest % testSpy - testing of spy.m % % Description: % The function norm.m is tested (3 tests) on: % + Norm of a SISO benchmark system. % + Norm of a SISO random system. % + Norm of a MISO random system. % + Norm of a SIMO random system. % + Norm of MIMO benchmark system. % + Norm of a MIMO random system. % + Verifies for every case the following inputs/outputs: spy(sys) % % ------------------------------------------------------------------ % This file is part of sssMOR, a Sparse State Space, Model Order % Reduction and System Analysis Toolbox developed at the Institute % of Automatic Control, Technische Universitaet Muenchen. % For updates and further information please visit www.rt.mw.tum.de % For any suggestions, submission and/or bug reports, mail us at % -> [email protected] <- % ------------------------------------------------------------------ % Authors: Alessandro Castagnotto % Jorge Luiz Moreira Silva % Last Change: 26 Out 2015 % Copyright (c) 2015 Chair of Automatic Control, TU Muenchen % ------------------------------------------------------------------ methods(Test) function testBench(testCase) for i=1:length(testCase.sysCell) sysSparse=testCase.sysCell{i}; spy(sysSparse); end end end end function [] = verification(testCase, actSolution, expSolution) verifyEqual(testCase, actSolution(1:4), expSolution(1:4),'RelTol',1e-3,... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testBodeplot.m
.m
sss-master/test/testScripts/testBodeplot.m
1,805
utf_8
5a1508ae893615ede9bbc1abf609254b
classdef testBodeplot < sssTest methods(Test) function testBodeplot1(testCase) for i=1:length(testCase.sysCell) sys=testCase.sysCell{i}; if ~sys.isDae h=bodeplot(sys,1:100,'r--'); setoptions(h,'PhaseVisible','off'); verifyInstanceOf(testCase, h, 'handle','Instances not matching'); bodeplot(sys,{10,100}); end end end function plotFunctionalitySISO(testCase) % verify the correct plot compared to built-in when omega is % not passed sys1 = sss('building'); sys2 = sss('beam'); sys3 = sss('eady'); sys4 = sss('fom'); sys5 = sss('iss'); sys5 = sys5(1,1); figure; bodeplot(sys1,sys2,'r-',sys3,'k--',sys4,sys5); figure; bodeplot(ss(sys1),ss(sys2),'r-',ss(sys3),'k--',ss(sys4),ss(sys5)); figure; bodeplot(sys1,sys2,'r-',sys3,'k--',sys4,sys5,{1e-3,1e6}); % frequency range is passed end function plotFunctionalityMIMO(testCase) % verify the correct plot compared to built-in when omega is % not passed sys1 = sss('CDPlayer'); sys2 = sss('iss'); sys2 = sys2(1:2,1:2); figure; bodeplot(sys1,sys2,'r-'); figure; bodeplot(ss(sys1),ss(sys2),'r-'); figure; bodeplot(sys1,sys2,'r-',{1e-3,1e6}); % frequency range is passed end end end function [] = verification(testCase, actSolution, expSolution) verifyEqual(testCase, actSolution, expSolution,'RelTol',1e-2,'AbsTol',0.005,... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testPzmap.m
.m
sss-master/test/testScripts/testPzmap.m
827
utf_8
b8c7314055e253e2702a5ce9bbcd95fa
classdef testPzmap < sssTest % testPzmap - testing of pzmap.m methods(Test) function test1(testCase) for i=1:length(testCase.sysCell) sys=testCase.sysCell{i}; if ~sys.isDae % verification of results is done in testZeros and % testPoles, only test if call works [p,z]=pzmap(sys); pzmap(sys); verifyInstanceOf(testCase, p, 'double'); verifyInstanceOf(testCase, z, 'double'); end end end end end function [] = verification(testCase, actSolution, expSolution) verifyEqual(testCase, actSolution, expSolution,'RelTol',0.1e-6,... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testAppend.m
.m
sss-master/test/testScripts/testAppend.m
2,266
utf_8
90baeeae43448385dc1e08cc7d182fc2
classdef testAppend < sssTest methods (Test) function testAppend1(testCase) for i=1:2:length(testCase.sysCell)-1 sys1_sss=testCase.sysCell{i}; if sys1_sss.isDescriptor sys1_ss=ss(full(sys1_sss.E\sys1_sss.A),full(sys1_sss.E\sys1_sss.B),full(sys1_sss.C),0); else sys1_ss=ss(sys1_sss); end sys2_sss=testCase.sysCell{i+1}; if sys2_sss.isDescriptor sys2_ss=ss(full(sys2_sss.E\sys2_sss.A),full(sys2_sss.E\sys2_sss.B),full(sys2_sss.C),0); else sys2_ss=ss(sys2_sss); end expSys = append(sys1_ss, sys2_ss); actSys = append(sys1_sss, sys2_sss); expSolution={expSys.A, expSys.B, expSys.C, expSys.D}; actSolution={full(actSys.E\actSys.A), full(actSys.E\actSys.B), full(actSys.C), full(actSys.D)}; verification (testCase, actSolution, expSolution); verifyInstanceOf(testCase, actSys.A , 'double', 'Instances not matching'); verifyInstanceOf(testCase, actSys.B , 'double', 'Instances not matching'); verifyInstanceOf(testCase, actSys.C , 'double', 'Instances not matching'); verifyInstanceOf(testCase, actSys.D , 'double', 'Instances not matching'); verifyInstanceOf(testCase, actSys.E , 'double', 'Instances not matching'); verifySize(testCase, full(actSys.A), size(expSys.A), 'Size not matching'); verifySize(testCase, full(actSys.B), size(expSys.B), 'Size not matching'); verifySize(testCase, full(actSys.C), size(expSys.C), 'Size not matching'); verifySize(testCase, full(actSys.D), size(expSys.D), 'Size not matching'); verifySize(testCase, full(actSys.E), size(actSys.A), 'Size not matching'); end end end end function [] = verification (testCase, actSolution, expSolution) verifyEqual(testCase, actSolution, expSolution, 'RelTol', 0.1,'AbsTol',0.000001, ... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testNorm.m
.m
sss-master/test/testScripts/testNorm.m
3,990
utf_8
8f29c13ec37859d61d8c0bac3955bb6b
classdef testNorm < sssTest % testNorm - testing of norm.m % % Description: % The function norm.m is tested (3 tests) on: % + Norm of a SISO benchmark system. % + Norm of a SISO random system. % + Norm of a MISO random system. % + Norm of a SIMO random system. % + Norm of MIMO benchmark system. % + Norm of a MIMO random system. % + Verifies for every case the following inputs/outputs (norm(sys), % norm(sys,inf), [n,fpeak]=norm(sys,inf), norm(sys,2) % % ------------------------------------------------------------------ % This file is part of sssMOR, a Sparse State Space, Model Order % Reduction and System Analysis Toolbox developed at the Institute % of Automatic Control, Technische Universitaet Muenchen. % For updates and further information please visit www.rt.mw.tum.de % For any suggestions, submission and/or bug reports, mail us at % -> [email protected] <- % ------------------------------------------------------------------ % Authors: Alessandro Castagnotto % Jorge Luiz Moreira Silva % Last Change: 26 Out 2015 % Copyright (c) 2015 Chair of Automatic Control, TU Muenchen % ------------------------------------------------------------------ methods(Test) function testNorm1(testCase) warning('off','sss:isstable:EigsFailed'); for i=1:length(testCase.sysCell) sys_sss=testCase.sysCell{i}; if ~sys_sss.isDae sys_ss=ss(sys_sss); actNorm1=norm(sys_sss); [actNorm2,actFreq]=norm(sys_sss,inf); actNorm = [actNorm1,actNorm2,actFreq]; expNorm1=norm(sys_ss); [expNorm2,expFreq]=norm(sys_ss,inf); expNorm = [expNorm1,expNorm2,expFreq]; verification(testCase, actNorm, expNorm); end end end function testLyapchol(testCase) for i=1:length(testCase.sysCell) sys=testCase.sysCell{i}; if ~sys.isDae && sys.n>300 % options for mess % eqn struct: system data eqn=struct('A_',sys.A,'E_',sys.E,'B',sys.B,'C',sys.C,'type','N','haveE',sys.isDescriptor); % opts struct: mess options messOpts.adi=struct('shifts',struct('l0',20,'kp',50,'km',25,'b0',ones(sys.n,1),... 'info',0),'maxiter',300,'restol',0,'rctol',1e-12,... 'info',0,'norm','fro'); oper = operatormanager('default'); % get adi shifts [messOpts.adi.shifts.p,~,~,~,~,~,~,eqn]=mess_para(eqn,messOpts,oper); % low rank adi [R,~,eqn]=mess_lradi(eqn,messOpts,oper); actNrmAdi1=norm(R'*eqn.C','fro'); Opts.lyapchol='adi'; actNrmAdi2=norm(sys,Opts); Opts.lyapchol='builtIn'; actNrmBuiltIn=norm(sys,Opts); expNrm=norm(ss(sys)); actSolution={actNrmAdi1, actNrmAdi2, actNrmBuiltIn}; expSolution={expNrm, expNrm, expNrm}; verifyEqual(testCase, actSolution, expSolution,'RelTol',1e-3,... 'Difference between actual and expected solution.'); end end end end end function [] = verification(testCase, actSolution, expSolution) verifyEqual(testCase, actSolution, expSolution,'RelTol',1e-3,... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testSigma.m
.m
sss-master/test/testScripts/testSigma.m
3,538
utf_8
3b736754b58aed0411f1dda477d50a7e
classdef testSigma < sssTest % testSigma - testing of sigma.m % % Description: % The function sigma.m is tested (3 tests) on: % + Norm of a SISO benchmark system. % + Norm of a SISO random system. % + Norm of a MISO random system. % + Norm of a SIMO random system. % + Norm of MIMO benchmark system. % + Norm of a MIMO random system. % + Verifies for every case just if it runs for the syntax % [mag,omega]=sigma(sys) and sigma(sys) % % ------------------------------------------------------------------ % This file is part of sssMOR, a Sparse State Space, Model Order % Reduction and System Analysis Toolbox developed at the Institute % of Automatic Control, Technische Universitaet Muenchen. % For updates and further information please visit www.rt.mw.tum.de % For any suggestions, submission and/or bug reports, mail us at % -> [email protected] <- % ------------------------------------------------------------------ % Authors: Alessandro Castagnotto % Jorge Luiz Moreira Silva % Last Change: 26 Out 2015 % Copyright (c) 2015 Chair of Automatic Control, TU Muenchen % ------------------------------------------------------------------ methods(Test) function testBench(testCase) for i=1:length(testCase.sysCell) sysSparse=testCase.sysCell{i}; if ~sysSparse.isDae [expMag,omega]=sigma(ss(sysSparse)); actMag=sigma(sysSparse, omega'); verification(testCase, actMag, expMag); end end end function inputFunctionality(testCase) % input of frequnecy range for i=1:length(testCase.sysCell) sys = testCase.sysCell{i}; if ~sys.isDae w = {10,100}; [~,omega] = sigma(sys,w); verifyEqual(testCase,omega(1),w{1}, 'Wrong frequency returned'); verifyEqual(testCase,omega(end),w{2},'Wrong frequency returned'); end end end function plotFunctionalitySISO(testCase) % verify the correct plot compared to built-in when omega is % not passed sys1 = sss('building'); sys2 = sss('beam'); sys3 = sss('eady'); sys4 = sss('fom'); sys5 = sss('iss'); sys5 = sys5(1,1); figure; sigma(sys1,sys2,'r-',sys3,'k--',sys4,sys5); figure; sigma(ss(sys1),ss(sys2),'r-',ss(sys3),'k--',ss(sys4),ss(sys5)); figure; sigma(sys1,sys2,'r-',sys3,'k--',sys4,sys5,{1e-3,1e6}); % frequency range is passed end function plotFunctionalityMIMO(testCase) % verify the correct plot compared to built-in when omega is % not passed sys1 = sss('CDPlayer'); sys2 = sss('iss'); sys2 = sys2(1:2,1:2); figure; sigma(sys1,sys2,'r-'); figure; sigma(ss(sys1),ss(sys2),'r-'); figure; sigma(sys1,sys2,'r-',{1e-3,1e6}); % frequency range is passed end end end function [] = verification(testCase, actSolution, expSolution) verifyEqual(testCase, actSolution, expSolution,'RelTol',1e-2,'AbsTol',0.005,... 'Difference between actual and expected exceeds relative tolerance'); end
github
MORLab/sss-master
testEigs.m
.m
sss-master/test/testScripts/testEigs.m
1,608
utf_8
89f288cefc342f93db99e56534cd75b3
classdef testEigs < sssTest methods (Test) function testEigs1(testCase) for i=1:length(testCase.sysCell) sys_sss=testCase.sysCell{i}; if ~sys_sss.isDae [actD]=eigs(sys_sss,12); [expD]=eigs(full(sys_sss.A), full(sys_sss.E),12); %sort eigenvalues on real part actD_real=real(actD); actD_imag=imag(actD); tbl=table(actD_real, actD_imag); tbl=sortrows(tbl); actD_real=tbl.actD_real; actD_imag=tbl.actD_imag; expD_real=real(expD); expD_imag=imag(expD); tbl=table(expD_real, expD_imag); tbl=sortrows(tbl); expD_real=tbl.expD_real; expD_imag=tbl.expD_imag; actSolution={full(actD_real), sort(full(actD_imag))}; expSolution={expD_real, sort(expD_imag)}; verification (testCase, actSolution, expSolution); verifyInstanceOf(testCase, actD , 'double', 'Instances not matching'); verifySize(testCase, actD, size(expD), 'Size not matching'); end end end end end function [] = verification (testCase, actSolution, expSolution) verifyEqual(testCase, actSolution, expSolution, 'RelTol', 0.2,'AbsTol',0.00001, ... 'Difference between actual and expected exceeds relative tolerance'); end
github
iamitpatil/MATLAB_advanced_solid_mechanics_codes-master
shapeFunctionL2.m
.m
MATLAB_advanced_solid_mechanics_codes-master/Timoshenko Beam analysis code/shapeFunctionL2.m
364
utf_8
68db6d0144cdfc27459d4e97fd61ec61
% ............................................................. function [shape,naturalDerivatives]=shapeFunctionL2(xi) % shape function and derivatives for L2 elements % shape : Shape functions % naturalDerivatives: derivatives w.r.t. xi % xi: natural coordinates (-1 ... +1) shape=([1-xi,1+xi]/2)'; naturalDerivatives=[-1;1]/2; end % end function shapeFunctionL2
github
iamitpatil/MATLAB_advanced_solid_mechanics_codes-master
solution.m
.m
MATLAB_advanced_solid_mechanics_codes-master/Timoshenko Beam analysis code/solution.m
348
utf_8
c2f5f2b3cc647c6d3530c0999dc2aa80
%................................................................ function displacements=solution(GDof,prescribedDof,stiffness,force) % function to find solution in terms of global displacements activeDof=setdiff([1:GDof]',[prescribedDof]); U=stiffness(activeDof,activeDof)\force(activeDof); displacements=zeros(GDof,1); displacements(activeDof)=U;
github
iamitpatil/MATLAB_advanced_solid_mechanics_codes-master
outputDisplacementsReactions.m
.m
MATLAB_advanced_solid_mechanics_codes-master/Timoshenko Beam analysis code/outputDisplacementsReactions.m
485
utf_8
f05619a01bac16f599f321c484553214
%.............................................................. function outputDisplacementsReactions... (displacements,stiffness,GDof,prescribedDof) % output of displacements and reactions in % tabular form % GDof: total number of degrees of freedom of % the problem % displacements disp('Displacements') %displacements=displacements1; jj=1:GDof; format [jj' displacements] % reactions F=stiffness*displacements; reactions=F(prescribedDof); disp('reactions') [prescribedDof reactions]
github
panji530/Low-rank-kernel-subspace-clustering-master
BuildAdjacency.m
.m
Low-rank-kernel-subspace-clustering-master/BuildAdjacency.m
969
utf_8
e6246b92c3306608cee7c6769448d13e
%-------------------------------------------------------------------------- % This function takes a NxN coefficient matrix and returns a NxN adjacency % matrix by choosing the K strongest connections in the similarity graph % CMat: NxN coefficient matrix % K: number of strongest edges to keep; if K=0 use all the exiting edges % CKSym: NxN symmetric adjacency matrix %-------------------------------------------------------------------------- % Copyright @ Ehsan Elhamifar, 2012 %-------------------------------------------------------------------------- function [CKSym,CAbs] = BuildAdjacency(CMat,K) if (nargin < 2) K = 0; end N = size(CMat,1); CAbs = abs(CMat); [Srt,Ind] = sort( CAbs,1,'descend' ); if (K == 0) for i = 1:N CAbs(:,i) = CAbs(:,i) ./ (CAbs(Ind(1,i),i)+eps); end else for i = 1:N for j = 1:K CAbs(Ind(j,i),i) = CAbs(Ind(j,i),i) ./ (CAbs(Ind(1,i),i)+eps); end end end CKSym = CAbs + CAbs';
github
panji530/Low-rank-kernel-subspace-clustering-master
thrC.m
.m
Low-rank-kernel-subspace-clustering-master/thrC.m
680
utf_8
1d57203ca466d32bcd882ce949a6fea8
%-------------------------------------------------------------------------- % Copyright @ Ehsan Elhamifar, 2012 %-------------------------------------------------------------------------- function Cp = thrC(C,ro) if (nargin < 2) ro = 1; end if (ro < 1) N = size(C,2); Cp = zeros(N,N); [S,Ind] = sort(abs(C),1,'descend'); for i = 1:N cL1 = sum(S(:,i)); stop = false; cSum = 0; t = 0; while (~stop) t = t + 1; cSum = cSum + S(t,i); if ( cSum >= ro*cL1 ) stop = true; Cp(Ind(1:t,i),i) = C(Ind(1:t,i),i); end end end else Cp = C; end
github
panji530/Low-rank-kernel-subspace-clustering-master
lowRankKernelSubspaceClustering.m
.m
Low-rank-kernel-subspace-clustering-master/lowRankKernelSubspaceClustering.m
8,276
utf_8
7718fe67c530030db871f07f0cf79b28
function [missrate, A, grps, obj, resid] = lowRankKernelSubspaceClustering(X, s, lambda1, lambda2, lambda3, kType, affine, outlier, param) % Author: Pan Ji, University of Adelaide % All rights reserved! if(nargin<8) outlier = false; end if(nargin<7) affine = false; end if(nargin<6) kType = 'pol'; end if(nargin<5) lambda3 = 1; end if(nargin<4) lambda2 = 1; end if(nargin<3) lambda1 = 1; end % normalize data to lie in [-1 1] if(max(X(:)) <= 1 && min(X(:)) >= -1) else X = X - min(X(:)); X = X/(max(X(:))+1); X = 2*(X - 0.5); end [~, N] = size(X); alpha = param.alpha; if(strcmpi(kType,'pol')) a = param.a; b = param.b; KG = polynKernelMatrix(X,a,b); % hopkins 2.2 3 %two frames 3.4 2 % yale face 12 2 elseif(strcmpi(kType,'lin')) KG = polynKernelMatrix(X,0,1); elseif(strcmpi(kType,'rbf')) sig = std(sqrt(sum(X.^2))); KG = rbfKernelMatrix(X, 1*sig); else disp(['Select the kernel types: pol, lin, or rbf! Pol is used by default.']); KG = polynKernelMatrix(X,1.4,3); end % ADMM parameters epsilon = 1e-6; rho = 1e-8; maxIter = 1e3; eta = param.eta; max_rho = 1e10; % Initializations [U,S,V] = svd(KG); B = U*sqrt(S)*V'; K = KG; obj = []; resid = []; if(~outlier) if(~affine) Y2 = zeros(N, N); A = zeros(N,N); iter= 0; while(iter<maxIter) iter = iter+1; % Update C tmp = A + Y2/rho; C = max(0, abs(tmp)-lambda1/rho) .* sign(tmp); C = C - diag(diag(C)); % Update A K = B'*B; lhs = lambda2*K + rho*eye(N); rhs = lambda2*K - Y2 + rho*(C-diag(diag(C))); A = lhs\rhs; % Update B tmp = KG-lambda2*(eye(N)-2*A'+A*A')/(2*lambda3); B = solveB(tmp, lambda3); leq2 = A - (C - diag(diag(C))); stpC = max(abs(leq2(:))); if(iter == 1 || mod(iter,50)==0 || stpC<epsilon) disp(['iter ' num2str(iter) ',rho=' num2str(rho,'%2.1e') ',stopALM=' num2str(stpC,'%2.3e')]); end if(stpC<epsilon) break; else Y2 = Y2 + rho*leq2; rho = min(max_rho,rho*eta); end end else %affine Y2 = zeros(N, N); y3 = zeros(1,N); A = zeros(N,N); iter= 0; while(iter<maxIter) iter = iter+1; % Update C tmp = A + Y2/rho; C = max(0, abs(tmp)-lambda1/rho) .* sign(tmp); C = C - diag(diag(C)); % Update A K = B'*B; lhs = lambda2*K + rho*eye(N) + rho*ones(N,N); rhs = lambda2*K - Y2 - ones(N,1)*y3 + rho*(C-diag(diag(C))+ones(N,N)); A = lhs\rhs; % Update B tmp = KG-lambda2*(eye(N)-2*A'+A*A')/(2*lambda3); B = solveB(tmp, lambda3); leq2 = A - (C - diag(diag(C))); leq3 = sum(A) - ones(1,N); obj(iter) = sum(svd(B)) + lambda1*sum(abs(C(:))) + ... 0.5*lambda2*trace((eye(N)-2*A+A*A')*(B'*B)) + ... 0.5*lambda3*norm(KG-B'*B,'fro')^2; resid(iter) = max(norm(leq2,'fro'),norm(leq3)); stpC = max(abs(leq2(:))); stpC2 = max(abs(leq3)); stpC = max(stpC, stpC2); if(iter == 1 || mod(iter,50)==0 || stpC<epsilon) disp(['iter ' num2str(iter) ',rho=' num2str(rho,'%2.1e') ',stopALM=' num2str(stpC,'%2.3e')]); end if(stpC<epsilon) break; else Y2 = Y2 + rho*leq2; y3 = y3 + rho*leq3; rho = min(max_rho,rho*eta); end end end else% outliers if(~affine) %Y1 = zeros(N, N); Y2 = zeros(N, N); Y4 = zeros(N, N); A = zeros(N,N); E = zeros(N,N); iter= 0; while(iter<maxIter) iter = iter+1; % Update C tmp = A + Y2/rho; C = max(0, abs(tmp)-lambda1/rho) .* sign(tmp); C = C - diag(diag(C)); % Update A K = B'*B; lhs = lambda2*K + rho*eye(N); rhs = lambda2*K - Y2 + rho*(C-diag(diag(C))); A = lhs\rhs; % Update B tmp = KG - E - (0.5*lambda2*(eye(N)-2*A'+A*A')-Y4)/rho; B = solveB(tmp, rho); % Update E tmp = KG - B'*B + Y4/rho; E = max(0,tmp - lambda3/rho)+min(0,tmp + lambda3/rho); %E = solve_l1l2(tmp,lambda3/rho); leq2 = A - (C - diag(diag(C))); leq4 = KG - B'*B - E; stpC = max(abs(leq2(:))); stpC2 = max(abs(leq4(:))); stpC = max(stpC, stpC2); if(iter == 1 || mod(iter,50)==0 || stpC<epsilon) disp(['iter ' num2str(iter) ',rho=' num2str(rho,'%2.1e') ',stopALM=' num2str(stpC,'%2.3e')]); end if(stpC<epsilon) break; else Y2 = Y2 + rho*leq2; Y4 = Y4 + rho*leq4; rho = min(max_rho,rho*eta); end end else %Y1 = zeros(N, N); Y2 = zeros(N, N); y3 = zeros(1, N); Y4 = zeros(N, N); A = zeros(N, N); E = zeros(N, N); iter= 0; while(iter<maxIter) iter = iter+1; % Update C tmp = A + Y2/rho; C = max(0, abs(tmp)-lambda1/rho) .* sign(tmp); C = C - diag(diag(C)); % Update A K = B'*B; lhs = lambda2*K + rho*eye(N) + rho*ones(N,N); rhs = lambda2*K - Y2 - ones(N,1)*y3 + rho*(C-diag(diag(C))+ones(N,N)); A = lhs\rhs; % Update B %tmp = 0.5*(K - E + KG + (Y1+Y4)/rho); tmp = KG - E - (0.5*lambda2*(eye(N)-2*A'+A*A')-Y4)/rho; B = solveB(tmp, rho); % Update E tmp = KG - B'*B + Y4/rho; E = max(0,tmp - lambda3/rho)+min(0,tmp + lambda3/rho); %E = solve_l1l2(tmp,lambda3/rho); leq2 = A - (C - diag(diag(C))); leq3 = sum(A) - ones(1,N); leq4 = KG - B'*B - E; obj(iter) = sum(svd(B)) + lambda1*sum(abs(C(:))) + ... 0.5*lambda2*trace((eye(N)-2*A+A*A')*(B'*B)) + ... lambda3*sum(abs(E(:))); resid(iter) = max(max(norm(leq2,'fro'),norm(leq3)), norm(leq4,'fro')); stpC = max(abs(leq2(:))); stpC2 = max(max(abs(leq3)), max(abs(leq4(:)))); stpC = max(stpC, stpC2); if(iter == 1 || mod(iter,50)==0 || stpC<epsilon) disp(['iter ' num2str(iter) ',rho=' num2str(rho,'%2.1e') ',stopALM=' num2str(stpC,'%2.3e')]); end if(stpC<epsilon) break; else %Y1 = Y1 + rho*leq1; Y2 = Y2 + rho*leq2; y3 = y3 + rho*leq3; Y4 = Y4 + rho*leq4; rho = min(max_rho,rho*eta); end end end end A = BuildAdjacency(thrC(C,alpha)); grp = SpectralClustering(A, max(s)); grps = bestMap(s,grp); missrate = sum(s(:) ~= grps(:)) / length(s); end function [E] = solve_l1l2(W,lambda) n = size(W,2); E = W; for i=1:n E(:,i) = solve_l2(W(:,i),lambda); end end function [x] = solve_l2(w,lambda) % min lambda |x|_2 + |x-w|_2^2 nw = norm(w); if nw>lambda x = (nw-lambda)*w/nw; else x = zeros(length(w),1); end end
github
panji530/Low-rank-kernel-subspace-clustering-master
hungarian.m
.m
Low-rank-kernel-subspace-clustering-master/hungarian.m
11,781
utf_8
294996aeeca4dadfc427da4f81f8b99d
function [C,T]=hungarian(A) %HUNGARIAN Solve the Assignment problem using the Hungarian method. % %[C,T]=hungarian(A) %A - a square cost matrix. %C - the optimal assignment. %T - the cost of the optimal assignment. %s.t. T = trace(A(C,:)) is minimized over all possible assignments. % Adapted from the FORTRAN IV code in Carpaneto and Toth, "Algorithm 548: % Solution of the assignment problem [H]", ACM Transactions on % Mathematical Software, 6(1):104-111, 1980. % v1.0 96-06-14. Niclas Borlin, [email protected]. % Department of Computing Science, Ume? University, % Sweden. % All standard disclaimers apply. % A substantial effort was put into this code. If you use it for a % publication or otherwise, please include an acknowledgement or at least % notify me by email. /Niclas [m,n]=size(A); if (m~=n) error('HUNGARIAN: Cost matrix must be square!'); end % Save original cost matrix. orig=A; % Reduce matrix. A=hminired(A); % Do an initial assignment. [A,C,U]=hminiass(A); % Repeat while we have unassigned rows. while (U(n+1)) % Start with no path, no unchecked zeros, and no unexplored rows. LR=zeros(1,n); LC=zeros(1,n); CH=zeros(1,n); RH=[zeros(1,n) -1]; % No labelled columns. SLC=[]; % Start path in first unassigned row. r=U(n+1); % Mark row with end-of-path label. LR(r)=-1; % Insert row first in labelled row set. SLR=r; % Repeat until we manage to find an assignable zero. while (1) % If there are free zeros in row r if (A(r,n+1)~=0) % ...get column of first free zero. l=-A(r,n+1); % If there are more free zeros in row r and row r in not % yet marked as unexplored.. if (A(r,l)~=0 & RH(r)==0) % Insert row r first in unexplored list. RH(r)=RH(n+1); RH(n+1)=r; % Mark in which column the next unexplored zero in this row % is. CH(r)=-A(r,l); end else % If all rows are explored.. if (RH(n+1)<=0) % Reduce matrix. [A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR); end % Re-start with first unexplored row. r=RH(n+1); % Get column of next free zero in row r. l=CH(r); % Advance "column of next free zero". CH(r)=-A(r,l); % If this zero is last in the list.. if (A(r,l)==0) % ...remove row r from unexplored list. RH(n+1)=RH(r); RH(r)=0; end end % While the column l is labelled, i.e. in path. while (LC(l)~=0) % If row r is explored.. if (RH(r)==0) % If all rows are explored.. if (RH(n+1)<=0) % Reduce cost matrix. [A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR); end % Re-start with first unexplored row. r=RH(n+1); end % Get column of next free zero in row r. l=CH(r); % Advance "column of next free zero". CH(r)=-A(r,l); % If this zero is last in list.. if(A(r,l)==0) % ...remove row r from unexplored list. RH(n+1)=RH(r); RH(r)=0; end end % If the column found is unassigned.. if (C(l)==0) % Flip all zeros along the path in LR,LC. [A,C,U]=hmflip(A,C,LC,LR,U,l,r); % ...and exit to continue with next unassigned row. break; else % ...else add zero to path. % Label column l with row r. LC(l)=r; % Add l to the set of labelled columns. SLC=[SLC l]; % Continue with the row assigned to column l. r=C(l); % Label row r with column l. LR(r)=l; % Add r to the set of labelled rows. SLR=[SLR r]; end end end % Calculate the total cost. T=sum(orig(logical(sparse(C,1:size(orig,2),1)))); function A=hminired(A) %HMINIRED Initial reduction of cost matrix for the Hungarian method. % %B=assredin(A) %A - the unreduced cost matris. %B - the reduced cost matrix with linked zeros in each row. % v1.0 96-06-13. Niclas Borlin, [email protected]. [m,n]=size(A); % Subtract column-minimum values from each column. colMin=min(A); A=A-colMin(ones(n,1),:); % Subtract row-minimum values from each row. rowMin=min(A')'; A=A-rowMin(:,ones(1,n)); % Get positions of all zeros. [i,j]=find(A==0); % Extend A to give room for row zero list header column. A(1,n+1)=0; for k=1:n % Get all column in this row. cols=j(k==i)'; % Insert pointers in matrix. A(k,[n+1 cols])=[-cols 0]; end function [A,C,U]=hminiass(A) %HMINIASS Initial assignment of the Hungarian method. % %[B,C,U]=hminiass(A) %A - the reduced cost matrix. %B - the reduced cost matrix, with assigned zeros removed from lists. %C - a vector. C(J)=I means row I is assigned to column J, % i.e. there is an assigned zero in position I,J. %U - a vector with a linked list of unassigned rows. % v1.0 96-06-14. Niclas Borlin, [email protected]. [n,np1]=size(A); % Initalize return vectors. C=zeros(1,n); U=zeros(1,n+1); % Initialize last/next zero "pointers". LZ=zeros(1,n); NZ=zeros(1,n); for i=1:n % Set j to first unassigned zero in row i. lj=n+1; j=-A(i,lj); % Repeat until we have no more zeros (j==0) or we find a zero % in an unassigned column (c(j)==0). while (C(j)~=0) % Advance lj and j in zero list. lj=j; j=-A(i,lj); % Stop if we hit end of list. if (j==0) break; end end if (j~=0) % We found a zero in an unassigned column. % Assign row i to column j. C(j)=i; % Remove A(i,j) from unassigned zero list. A(i,lj)=A(i,j); % Update next/last unassigned zero pointers. NZ(i)=-A(i,j); LZ(i)=lj; % Indicate A(i,j) is an assigned zero. A(i,j)=0; else % We found no zero in an unassigned column. % Check all zeros in this row. lj=n+1; j=-A(i,lj); % Check all zeros in this row for a suitable zero in another row. while (j~=0) % Check the in the row assigned to this column. r=C(j); % Pick up last/next pointers. lm=LZ(r); m=NZ(r); % Check all unchecked zeros in free list of this row. while (m~=0) % Stop if we find an unassigned column. if (C(m)==0) break; end % Advance one step in list. lm=m; m=-A(r,lm); end if (m==0) % We failed on row r. Continue with next zero on row i. lj=j; j=-A(i,lj); else % We found a zero in an unassigned column. % Replace zero at (r,m) in unassigned list with zero at (r,j) A(r,lm)=-j; A(r,j)=A(r,m); % Update last/next pointers in row r. NZ(r)=-A(r,m); LZ(r)=j; % Mark A(r,m) as an assigned zero in the matrix . . . A(r,m)=0; % ...and in the assignment vector. C(m)=r; % Remove A(i,j) from unassigned list. A(i,lj)=A(i,j); % Update last/next pointers in row r. NZ(i)=-A(i,j); LZ(i)=lj; % Mark A(r,m) as an assigned zero in the matrix . . . A(i,j)=0; % ...and in the assignment vector. C(j)=i; % Stop search. break; end end end end % Create vector with list of unassigned rows. % Mark all rows have assignment. r=zeros(1,n); rows=C(C~=0); r(rows)=rows; empty=find(r==0); % Create vector with linked list of unassigned rows. U=zeros(1,n+1); U([n+1 empty])=[empty 0]; function [A,C,U]=hmflip(A,C,LC,LR,U,l,r) %HMFLIP Flip assignment state of all zeros along a path. % %[A,C,U]=hmflip(A,C,LC,LR,U,l,r) %Input: %A - the cost matrix. %C - the assignment vector. %LC - the column label vector. %LR - the row label vector. %U - the %r,l - position of last zero in path. %Output: %A - updated cost matrix. %C - updated assignment vector. %U - updated unassigned row list vector. % v1.0 96-06-14. Niclas Borlin, [email protected]. n=size(A,1); while (1) % Move assignment in column l to row r. C(l)=r; % Find zero to be removed from zero list.. % Find zero before this. m=find(A(r,:)==-l); % Link past this zero. A(r,m)=A(r,l); A(r,l)=0; % If this was the first zero of the path.. if (LR(r)<0) ...remove row from unassigned row list and return. U(n+1)=U(r); U(r)=0; return; else % Move back in this row along the path and get column of next zero. l=LR(r); % Insert zero at (r,l) first in zero list. A(r,l)=A(r,n+1); A(r,n+1)=-l; % Continue back along the column to get row of next zero in path. r=LC(l); end end function [A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR) %HMREDUCE Reduce parts of cost matrix in the Hungerian method. % %[A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR) %Input: %A - Cost matrix. %CH - vector of column of 'next zeros' in each row. %RH - vector with list of unexplored rows. %LC - column labels. %RC - row labels. %SLC - set of column labels. %SLR - set of row labels. % %Output: %A - Reduced cost matrix. %CH - Updated vector of 'next zeros' in each row. %RH - Updated vector of unexplored rows. % v1.0 96-06-14. Niclas Borlin, [email protected]. n=size(A,1); % Find which rows are covered, i.e. unlabelled. coveredRows=LR==0; % Find which columns are covered, i.e. labelled. coveredCols=LC~=0; r=find(~coveredRows); c=find(~coveredCols); % Get minimum of uncovered elements. m=min(min(A(r,c))); % Subtract minimum from all uncovered elements. A(r,c)=A(r,c)-m; % Check all uncovered columns.. for j=c % ...and uncovered rows in path order.. for i=SLR % If this is a (new) zero.. if (A(i,j)==0) % If the row is not in unexplored list.. if (RH(i)==0) % ...insert it first in unexplored list. RH(i)=RH(n+1); RH(n+1)=i; % Mark this zero as "next free" in this row. CH(i)=j; end % Find last unassigned zero on row I. row=A(i,:); colsInList=-row(row<0); if (length(colsInList)==0) % No zeros in the list. l=n+1; else l=colsInList(row(colsInList)==0); end % Append this zero to end of list. A(i,l)=-j; end end end % Add minimum to all doubly covered elements. r=find(coveredRows); c=find(coveredCols); % Take care of the zeros we will remove. [i,j]=find(A(r,c)<=0); i=r(i); j=c(j); for k=1:length(i) % Find zero before this in this row. lj=find(A(i(k),:)==-j(k)); % Link past it. A(i(k),lj)=A(i(k),j(k)); % Mark it as assigned. A(i(k),j(k))=0; end A(r,c)=A(r,c)+m;
github
panji530/Low-rank-kernel-subspace-clustering-master
SpectralClustering.m
.m
Low-rank-kernel-subspace-clustering-master/SpectralClustering.m
1,263
utf_8
07b220096869dca68257bc4d65642455
%-------------------------------------------------------------------------- % This function takes an adjacency matrix of a graph and computes the % clustering of the nodes using the spectral clustering algorithm of % Ng, Jordan and Weiss. % CMat: NxN adjacency matrix % n: number of groups for clustering % groups: N-dimensional vector containing the memberships of the N points % to the n groups obtained by spectral clustering %-------------------------------------------------------------------------- % Copyright @ Ehsan Elhamifar, 2012 % Modified @ Chong You, 2015 %-------------------------------------------------------------------------- function [groups, kerNS] = SpectralClustering(CKSym,n) warning off; N = size(CKSym,1); MAXiter = 1000; % Maximum number of iterations for KMeans REPlic = 20; % Number of replications for KMeans % Normalized spectral clustering according to Ng & Jordan & Weiss % using Normalized Symmetric Laplacian L = I - D^{-1/2} W D^{-1/2} DN = diag( 1./sqrt(sum(CKSym)+eps) ); LapN = speye(N) - DN * CKSym * DN; [~,~,vN] = svd(LapN); kerN = vN(:,N-n+1:N); normN = sum(kerN .^2, 2) .^.5; kerNS = bsxfun(@rdivide, kerN, normN + eps); groups = kmeans(kerNS,n,'maxiter',MAXiter,'replicates',REPlic,'EmptyAction','singleton');
github
zengjianping/mobile-id-master
d2p.m
.m
mobile-id-master/utils/tSNE_matlab/d2p.m
3,155
utf_8
dc48b1dd0688d11671d81af50a0970de
function [P, beta] = d2p(D, u, tol) %D2P Identifies appropriate sigma's to get kk NNs up to some tolerance % % [P, beta] = d2p(D, kk, tol) % % Identifies the required precision (= 1 / variance^2) to obtain a Gaussian % kernel with a certain uncertainty for every datapoint. The desired % uncertainty can be specified through the perplexity u (default = 15). The % desired perplexity is obtained up to some tolerance that can be specified % by tol (default = 1e-4). % The function returns the final Gaussian kernel in P, as well as the % employed precisions per instance in beta. % % % (C) Laurens van der Maaten, 2008 % Maastricht University if ~exist('u', 'var') || isempty(u) u = 15; end if ~exist('tol', 'var') || isempty(tol) tol = 1e-4; end % Initialize some variables n = size(D, 1); % number of instances P = zeros(n, n); % empty probability matrix beta = ones(n, 1); % empty precision vector logU = log(u); % log of perplexity (= entropy) % Run over all datapoints for i=1:n if ~rem(i, 500) disp(['Computed P-values ' num2str(i) ' of ' num2str(n) ' datapoints...']); end % Set minimum and maximum values for precision betamin = -Inf; betamax = Inf; % Compute the Gaussian kernel and entropy for the current precision [H, thisP] = Hbeta(D(i, [1:i - 1, i + 1:end]), beta(i)); % Evaluate whether the perplexity is within tolerance Hdiff = H - logU; tries = 0; while abs(Hdiff) > tol && tries < 50 % If not, increase or decrease precision if Hdiff > 0 betamin = beta(i); if isinf(betamax) beta(i) = beta(i) * 2; else beta(i) = (beta(i) + betamax) / 2; end else betamax = beta(i); if isinf(betamin) beta(i) = beta(i) / 2; else beta(i) = (beta(i) + betamin) / 2; end end % Recompute the values [H, thisP] = Hbeta(D(i, [1:i - 1, i + 1:end]), beta(i)); Hdiff = H - logU; tries = tries + 1; end % Set the final row of P P(i, [1:i - 1, i + 1:end]) = thisP; end disp(['Mean value of sigma: ' num2str(mean(sqrt(1 ./ beta)))]); disp(['Minimum value of sigma: ' num2str(min(sqrt(1 ./ beta)))]); disp(['Maximum value of sigma: ' num2str(max(sqrt(1 ./ beta)))]); end % Function that computes the Gaussian kernel values given a vector of % squared Euclidean distances, and the precision of the Gaussian kernel. % The function also computes the perplexity of the distribution. function [H, P] = Hbeta(D, beta) P = exp(-D * beta); sumP = sum(P); H = log(sumP) + beta * sum(D .* P) / sumP; % why not: H = exp(-sum(P(P > 1e-5) .* log(P(P > 1e-5)))); ??? P = P / sumP; end
github
zengjianping/mobile-id-master
x2p.m
.m
mobile-id-master/utils/tSNE_matlab/x2p.m
3,297
utf_8
e0d6a8b9bcdd6ebd97037e46252fe200
function [P, beta] = x2p(X, u, tol) %X2P Identifies appropriate sigma's to get kk NNs up to some tolerance % % [P, beta] = x2p(xx, kk, tol) % % Identifies the required precision (= 1 / variance^2) to obtain a Gaussian % kernel with a certain uncertainty for every datapoint. The desired % uncertainty can be specified through the perplexity u (default = 15). The % desired perplexity is obtained up to some tolerance that can be specified % by tol (default = 1e-4). % The function returns the final Gaussian kernel in P, as well as the % employed precisions per instance in beta. % % % (C) Laurens van der Maaten, 2008 % Maastricht University if ~exist('u', 'var') || isempty(u) u = 15; end if ~exist('tol', 'var') || isempty(tol) tol = 1e-4; end % Initialize some variables n = size(X, 1); % number of instances P = zeros(n, n); % empty probability matrix beta = ones(n, 1); % empty precision vector logU = log(u); % log of perplexity (= entropy) % Compute pairwise distances disp('Computing pairwise distances...'); sum_X = sum(X .^ 2, 2); D = bsxfun(@plus, sum_X, bsxfun(@plus, sum_X', -2 * X * X')); % Run over all datapoints disp('Computing P-values...'); for i=1:n if ~rem(i, 500) disp(['Computed P-values ' num2str(i) ' of ' num2str(n) ' datapoints...']); end % Set minimum and maximum values for precision betamin = -Inf; betamax = Inf; % Compute the Gaussian kernel and entropy for the current precision Di = D(i, [1:i-1 i+1:end]); [H, thisP] = Hbeta(Di, beta(i)); % Evaluate whether the perplexity is within tolerance Hdiff = H - logU; tries = 0; while abs(Hdiff) > tol && tries < 50 % If not, increase or decrease precision if Hdiff > 0 betamin = beta(i); if isinf(betamax) beta(i) = beta(i) * 2; else beta(i) = (beta(i) + betamax) / 2; end else betamax = beta(i); if isinf(betamin) beta(i) = beta(i) / 2; else beta(i) = (beta(i) + betamin) / 2; end end % Recompute the values [H, thisP] = Hbeta(Di, beta(i)); Hdiff = H - logU; tries = tries + 1; end % Set the final row of P P(i, [1:i - 1, i + 1:end]) = thisP; end disp(['Mean value of sigma: ' num2str(mean(sqrt(1 ./ beta)))]); disp(['Minimum value of sigma: ' num2str(min(sqrt(1 ./ beta)))]); disp(['Maximum value of sigma: ' num2str(max(sqrt(1 ./ beta)))]); end % Function that computes the Gaussian kernel values given a vector of % squared Euclidean distances, and the precision of the Gaussian kernel. % The function also computes the perplexity of the distribution. function [H, P] = Hbeta(D, beta) P = exp(-D * beta); sumP = sum(P); H = log(sumP) + beta * sum(D .* P) / sumP; P = P / sumP; end
github
jantomec/Matlab-master
EditorMacro.m
.m
Matlab-master/.matlab/utils/EditorMacro.m
44,535
utf_8
f122d01b23833c7a6f52969105d5e749
function [bindingsList, actionsList] = EditorMacro(keystroke, macro, macroType) % EditorMacro assigns a macro to a keyboard key-stroke in the Matlab-editor % % Syntax: % [bindingsList, actionsList] = EditorMacro(keystroke, macro, macroType) % [bindingsList, actionsList] = EditorMacro(bindingsList) % % Description: % EditorMacro assigns the specified MACRO to the requested keyboard % KEYSTROKE, within the context of the Matlab Editor and Command Window. % % KEYSTROKE is a string representation of the keyboard combination. % Special modifiers (Alt, Ctrl or Control, Shift, Meta, AltGraph) are % recognized and should be separated with a space, dash (-), plus (+) or % comma (,). At least one of the modifiers should be specified, otherwise % very weird things will happen... % For a full list of supported keystrokes, see: % <a href="http://tinyurl.com/2s63e9">http://java.sun.com/javase/6/docs/api/java/awt/event/KeyEvent.html</a> % If KEYSTROKE was already defined, then it will be updated (overridden). % % MACRO should be in one of Matlab's standard callback formats: 'string', % @FunctionHandle or {@FunctionHandle,arg1,...}, or any of several hundred % built-in editor action-names - read MACROTYPE below for a full % description. To remove a KEYSTROKE-MACRO definition, simply enter an % empty MACRO ([], {} or ''). % % MACROTYPE is an optional input argument specifying the type of action % that MACRO is expected to do: % % - 'text' (=default value) indicates that if the MACRO is a: % 1. 'string': this string will be inserted as-is into the current % editor caret position (or replace the selected editor text). % Multi-line strings can be set using embedded \n's (example: % 'Multi-line\nStrings'). This can be used to insert generic % comments or code templates (example: 'try \n catch \n end'). % 2. @FunctionHandle - the specified function will be invoked with % two input arguments: the editorPane object and the eventData % object (the KEYSTROKE event details). FunctionHandle is % expected to return a string which will then be inserted into % the editor document as expained above. % 3. {@FunctionHandle,arg1,...} - like #2, but the function will be % called with the specified arg1+ as input args #3+, following % the editorPane and eventData args. % % - 'run' indicates that MACRO should be invoked as a Matlab command, % just like any regular Matlab callback. The accepted MACRO % formats and function input args are exactly like for 'text' % above, except that no output string is expected and no text % insertion/replacement will be done (unless specifically done % within the invoked MACRO command/function). This MACROTYPE is % useful for closing/opening files, moving to another document % position and any other non-textual action. % % In addition, this MACROTYPE accepts all available (built-in) % editor action names. Valid action names can be listed by % requesting the ACTIONSLIST output argument. % % BINDINGSLIST = EditorMacro returns the list of currently-defined % KEYSTROKE bindings as a 4-columned cell array: {keystroke, macro, type, % class}. The class information indicates a built-in action ('editor menu % action', 'editor native action', 'cmdwin native action' or 'cmdwin menu % action') or a user-defined action ('text' or 'user-defined macro'). % % BINDINGSLIST = EditorMacro(KEYSTROKE) returns the bindings list for % the specified KEYSTROKE as a 4-columned cell array: {keystroke, macro, % type, class}. % % BINDINGSLIST = EditorMacro(KEYSTROKE,MACRO) returns the bindings list % after defining a specific KEYSTROKE-MACRO binding. % % EditorMacro(BINDINGSLIST) can be used to set a bunch of key bindings % using a single command. BINDINGSLIST is the cell array returned from % a previous invocation of EditorMacro, or by manual construction (just % be careful to set the keystroke strings correctly!). Only non-native % bindings are updated in this bulk mode of operation. % % [BINDINGSLIST, ACTIONSLIST] = EditorMacro(...) returns in ACTIONSLIST a % 3-columned cell array of all available built-in actions and currently- % associated key-biding(s): {actionName, keyBinding(s), class}. % % Examples: % bindingsList = EditorMacro; % get list of current key-bindings % bindingsList = EditorMacro('ctrl r'); % get list of bindings for <Ctrl>-R % [bindings,actions] = EditorMacro; % get list of available built-in action-names % EditorMacro('Ctrl Shift C', '%%% Main comment %%%\n% \n% \n% \n'); % EditorMacro('Alt-x', 'try\n % Main code here\ncatch\n % Exception handling here\nend'); % EditorMacro('Ctrl-Alt C', @myCallbackFunction); % myCallbackFunction returns a string to insert % EditorMacro('Alt control t', @(a,b)datestr(now), 'text'); % insert current timestamp % EditorMacro('Shift-Control d', {@computeDiameter,3.14159}, 'run'); % EditorMacro('Alt L', 'to-lower-case', 'run') % Built-in action: convert text to lowercase % EditorMacro('ctrl D','open-selection','run') % Override default Command-Window action (=delete) % % to behave as in the Editor (=open selected file) % % Known limitations (=TODO for future versions): % 1. Multi-keystroke bindings (e.g., 'alt-U,L') are not supported % 2. In Matlab 6, macro insertions are un-undo-able (ok in Matlab 7) % 3. Key bindings are sometimes lost when switching between a one-document % editor and a two-document one (i.e., adding/closing the second doc) % 4. Key bindings are not saved between editor sessions % 5. In split-pane mode, when inserting a macro on the secondary (right/ % bottom) pane, then both panes (and the actual document) are updated % but the secondary pane does not display the inserted macro (the % primary pane looks ok). % 6. Native menu/editor/command-window actions cannot be updated in bulk % mode (EditorMacro(BINDINGSLIST)) - only one at a time. % 7. Key-bindings may be fogotten when switching between docked/undocked % editor or between the Command-Window and other docked desktop panes % (such as Command History, Profiler etc.) % 8. In Matlab 6, actions are not supported: only user-defined text/macro % % Bugs and suggestions: % Please send to Yair Altman (altmany at gmail dot com) % % Warning: % This code heavily relies on undocumented and unsupported Matlab % functionality. It works on Matlab 6 & 7+, but use at your own risk! % % A technical description of the implementation can be found at: % <a href="http://undocumentedmatlab.com/blog/EditorMacro/">http://UndocumentedMatlab.com/blog/EditorMacro/</a> % % Change log: % 2011-01-31: Fixes for R2011a % 2009-10-26: Fixes for Matlab 6 % 2009-08-19: Support for command-window actions; use EDT for text replacement % 2009-08-11: Several fixes; support for native/menu actions (idea by Perttu Ranta-aho) % 2009-07-03: Fixed Matlab 6 edge-case; Automatically detect macro functions that do not accept the expected two input args % 2009-07-01: First version posted on <a href="http://www.mathworks.com/matlabcentral/fileexchange/authors/27420">MathWorks File Exchange</a> % Programmed by Yair M. Altman: altmany(at)gmail.com % $Revision: 1.6 $ $Date: 2011/01/31 20:47:25 $ persistent appdata try % Check input args if nargin == 2 macroType = 'text'; elseif nargin == 3 & ~ischar(macroType) %#ok Matlab 6 compatibility myError('YMA:EditorMacro:badMacroType','MacroType must be ''text'', ''run'' or ''native'''); elseif nargin > 3 myError('YMA:EditorMacro:tooManyArgs','too many input argument'); end % Try to get the editor's Java handle jEditor = getJEditor; % ...and the editor's main documents container handle jMainPane = getJMainPane(jEditor); hEditorPane = getEditorPane(jMainPane.getComponent(0)); % first document % ...and the desktop's Command Window handle try jCmdWin = []; %mde = jMainPane.getRootPane.getParent.getDesktop; mde = com.mathworks.mde.desk.MLDesktop.getInstance; % different in ML6!!! hCmdWin = mde.getClient('Command Window'); jCmdWin = hCmdWin.getComponent(0).getComponent(0).getComponent(0); % com.mathworks.mde.cmdwin.XCmdWndView jCmdWin = handle(jCmdWin, 'CallbackProperties'); catch % Maybe ML6 or... - never mind... end % Now try to get the persistent list of macros try appdata = getappdata(jEditor,'EditorMacro'); catch % never mind - we will use the persistent object instead... end % If no EditorMacro has been set yet if isempty(appdata) % Set the initial binding hashtable appdata = {}; %java.util.Hashtable is better but can't extract {@function}... % Add editor native action bindings to the bindingsList edActionsMap = getAccelerators(hEditorPane); % =getAccelerators(hEditorPane.getActiveTextComponent); appdata.bindings = getBindings({},edActionsMap,'editor native action'); % Add CW native action bindings to the bindingsList cwActionsMap = getAccelerators(jCmdWin); appdata.bindings = getBindings(appdata.bindings,cwActionsMap,'cmdwin native action'); % Add editor menu action bindings to the bindingsList appdata.edMenusMap = getMenuShortcuts(jMainPane); appdata.bindings = getBindings(appdata.bindings,appdata.edMenusMap,'editor menu action'); % Add CW menu action bindings to the bindingsList appdata.cwMenusMap = getMenuShortcuts(jCmdWin); appdata.bindings = getBindings(appdata.bindings,appdata.cwMenusMap,'cmdwin menu action'); % Loop over all the editor's currently-open documents for docIdx = 1 : jMainPane.getComponentCount % Instrument these documents to catch user keystrokes instrumentDocument([],[],jMainPane.getComponent(docIdx-1),jEditor,appdata); end % Update the editor's ComponentAdded callback to also instrument new documents set(jMainPane,'ComponentAddedCallback',{@instrumentDocument,[],jEditor,appdata}) if isempty(get(jMainPane,'ComponentAddedCallback')) pause(0.1); set(jMainPane,'ComponentAddedCallback',{@instrumentDocument,[],jEditor,appdata}) end % Also instrument the CW to catch user keystrokes set(jCmdWin, 'KeyPressedCallback', {@keyPressedCallback,jEditor,appdata,jCmdWin}); end % If any macro setting is requested if nargin % Update the bindings list with the new key binding if nargin > 1 appdata = updateBindings(appdata,keystroke,macro,macroType,jMainPane,jCmdWin); setappdata(jEditor,'EditorMacro',appdata); elseif iscell(keystroke) & (isempty(keystroke) | size(keystroke,2)==4) %#ok Matlab 6 compatibility appdata = keystroke; % passed updated bindingsList as input arg setappdata(jEditor,'EditorMacro',appdata); elseif ischar(keystroke) | isa(keystroke,'javax.swing.KeyStroke') %#ok Matlab 6 compatibility setappdata(jEditor,'EditorMacro',appdata); keystroke = normalizeKeyStroke(keystroke); bindingIdx = strmatch(keystroke,appdata.bindings(:,1),'exact'); appdata.bindings = appdata.bindings(bindingIdx,:); % only return matching bindings else myError('YMA:EditorMacro:invalidBindingsList','invalid BINDINGSLIST input argument'); end end % Check if output is requested if nargout if ~iscell(appdata.bindings) appdata.bindings = {}; end bindingsList = appdata.bindings; % Return the available actionsList if nargout > 1 % Start with the native editor actions actionsList = listActionsMap(hEditorPane); try [actionsList{:,3}] = deal('editor native action'); catch, end % ...add the desktop's CW native actions... cwActionsList = listActionsMap(jCmdWin); try [cwActionsList{:,3}] = deal('cmdwin native action'); catch, end actionsList = [actionsList; cwActionsList]; % ...and finally add the menu actions try menusList = appdata.edMenusMap(:,[2,1]); % {action,keystroke} try [menusList{:,3}] = deal('editor menu action'); catch, end actionsList = [actionsList; menusList]; catch % never mind... end try menusList = appdata.cwMenusMap(:,[2,1]); try [menusList{:,3}] = deal('cmdwin menu action'); catch, end actionsList = [actionsList; menusList]; catch % never mind... end end end % Error handling catch handleError; end %% Get the current list of key-bindings function bindings = getBindings(bindings,actionsMap,groupName) try for bindingIdx = 1 : size(actionsMap,1) ks = actionsMap{bindingIdx,1}; if ~isempty(ks) actionName = actionsMap{bindingIdx,2}; [bindings(end+1,:)] = {ks,actionName,'run',groupName}; %#ok grow end end catch % never mind... end %% Modify native shortcuts function bindingsList = nativeShortcuts(keystroke, macro, jMainPane) % Note: this function is unused hEditorPane = getEditorPane(jMainPane.getComponent(0)); % first document switch lower(keystroke(1:5)) case 'listn' % List all active accelerators bindingsList = getAccelerators(hEditorPane.getActiveTextComponent); if ~nargout for ii = 1 : size(bindingsList,1) disp(sprintf('%-35s %s',bindingsList{ii,:})) end end case 'lista' % List all available actions bindingsList = listActionsMap(hEditorPane,nargout); otherwise % Bind native action bindingsList = getNativeActions(hEditorPane); if ~ismember(macro,bindingsList) & ~isempty(macro) %#ok Matlab 6 compatibility myError('YMA:EditorMacro:invalidNativeAction','invalid Native Action'); end [keystroke,jKeystroke] = normalizeKeyStroke(keystroke); %jkeystroke = javax.swing.KeyStroke.getKeyStroke(keystroke); for docIdx = 1 : jMainPane.getComponentCount % Instrument these documents to catch user keystrokes hEditorPane = getEditorPane(jMainPane.getComponent(docIdx-1)); inputMap = hEditorPane.getInputMap; removeShortcut(inputMap,jKeystroke); if ~isempty(macro) action = hEditorPane.getActionMap.get(macro); inputMap.put(jKeystroke,action); end end removeMenuShortcut(jMainPane,keystroke); end %% Get/list all available key-bindings for all the possible actions function bindingsList = listActionsMap(hEditorPane,nargoutFlag) try bindingsList = getNativeActions(hEditorPane); try % Editor accelerators are stored in the activeTextComponent accellerators = getAccelerators(hEditorPane.getActiveTextComponent); catch % The CW doesn't have an activeTextComponent... accellerators = getAccelerators(hEditorPane); end for ii = 1 : size(bindingsList,1) actionKeys = accellerators(strcmpi(accellerators(:,2),bindingsList{ii}),1); if numel(actionKeys)==1 actionKeys = actionKeys{1}; keysStr = actionKeys; elseif isempty(actionKeys) actionKeys = []; keysStr = ' [not assigned]'; else % multiple keys assigned keysStr = strcat(char(actionKeys),',')'; keysStr = keysStr(:)'; % =reshape(keysStr,1,numel(keysStr)); keysStr = strtrim(strrep(keysStr,',',', ')); keysStr = regexprep(keysStr,'\s+',' '); keysStr = keysStr(1:end-1); % remove trailing ',' end bindingsList{ii,2} = actionKeys; if nargin > 1 & ~nargoutFlag %#ok Matlab 6 compatibility %disp(bindingsList) disp(sprintf('%-35s %s',bindingsList{ii,1},keysStr)) end end catch % never mind... end %% Get all available actions (even those without any key-binding) function actionNames = getNativeActions(hEditorPane) try actionNames = {}; actionKeys = hEditorPane.getActionMap.allKeys; actionNames = cellfun(@char,cell(actionKeys),'UniformOutput',false); actionNames = sort(actionNames); catch % never mind... end %% Get all active native shortcuts function accelerators = getAccelerators(hEditorPane) try accelerators = cell(0,2); inputMap = hEditorPane.getInputMap; inputKeys = inputMap.allKeys; accelerators = cell(numel(inputKeys),2); for ii = 1 : numel(inputKeys) accelerators(ii,:) = {char(inputKeys(ii)), char(inputMap.get(inputKeys(ii)))}; end accelerators = sortrows(accelerators,1); catch % never mind... end %% Remove shortcut from inputMap function removeShortcut(inputMap,keystroke) if ~isa(keystroke,'javax.swing.KeyStroke') keystroke = javax.swing.KeyStroke.getKeyStroke(keystroke); end inputMap.remove(keystroke); %keys = inputMap.allKeys; %for ii = 1:length(keys) % if keys(ii) == keystroke % % inputMap.remove(keystroke); % inputMap.put(keystroke,[]); %,null(1)); % return % end %end try % keystroke not found - try to find it in the parent inputMap... removeShortcut(inputMap.getParent,keystroke) catch % Never mind end %% Get the list of all menu actions function menusMap = getMenuShortcuts(jMainPane) try menusMap = {}; jRootPane = jMainPane.getRootPane; jMenubar = jRootPane.getMenuBar; %=jRootPane.getComponent(1).getComponent(1); for menuIdx = 1 : jMenubar.getMenuCount % top-level menus should be treated differently than sub-menus jMenu = jMenubar.getMenu(menuIdx-1); menusMap = getMenuShortcuts_recursive(jMenu,menusMap); end catch % Never mind end %% Recursively get the list of all menu actions function menusMap = getMenuShortcuts_recursive(jMenu,menusMap) try numMenuComponents = getNumMenuComponents(jMenu); for child = 1 : numMenuComponents menusMap = getMenuShortcuts_recursive(jMenu.getMenuComponent(child-1),menusMap); end catch % Probably a simple menu item, not a sub-menu - add it to the menusMap try accelerator = char(jMenu.getAccelerator); if isempty(accelerator) accelerator = []; % ''=>[] end [menusMap(end+1,:)] = {accelerator, char(jMenu.getActionCommand), jMenu}; catch % maybe a separator or something strange... - ignore end end %% Remove shortcut from Menu items inputMap function menusMap = removeMenuShortcut(menusMap,keystroke) try keystroke = normalizeKeyStroke(keystroke); map = cellfun(@char,menusMap(:,1),'un',0); oldBindingIdx = strmatch(keystroke,map,'exact'); if ~isempty(oldBindingIdx) menusMap{oldBindingIdx,1} = ''; menusMap{oldBindingIdx,3}.setAccelerator([]); end catch % never mind... end %% Remove shortcut from Menu items inputMap function removeMenuShortcut_old(jMainPane,keystroke) % Note: this function was replaced by removeMenuShortcut() try % Try to remove any corresponding menu-item accelerator jRootPane = jMainPane.getRootPane; jMenubar = jRootPane.getMenuBar; %=jRootPane.getComponent(1).getComponent(1); if ~isa(keystroke,'javax.swing.KeyStroke') keystroke = javax.swing.KeyStroke.getKeyStroke(keystroke); end for menuIdx = 1 : jMenubar.getMenuCount % top-level menus should be treated differently than sub-menus jMenu = jMenubar.getMenu(menuIdx-1); if removeMenuShortcut_recursive(jMenu,keystroke) return; end end catch % never mind... end %% Recursively remove shortcut from Menu items inputMap function found = removeMenuShortcut_recursive(jMenu,keystroke) try % Try to remove any corresponding menu-item accelerator found = 0; if ~isempty(jMenu.getActionForKeyStroke(keystroke)) jMenu.setAccelerator([]); found = 1; return; end % Not found - try to dig further try numMenuComponents = getNumMenuComponents(jMenu); for child = 1 : numMenuComponents found = removeMenuShortcut_recursive(jMenu.getMenuComponent(child-1),keystroke); if found return; end end catch % probably a simple menu item, not a sub-menu - ignore %a=1; % debuggable breakpoint... end catch % never mind... end %% Get the number of menu sub-elements function numMenuComponents = getNumMenuComponents(jcontainer) % The following line will raise an Exception for anything except menus numMenuComponents = jcontainer.getMenuComponentCount; % No error so far, so this must be a menu container... % Note: Menu subitems are not visible until the top-level (root) menu gets initial focus... % Try several alternatives, until we get a non-empty menu (or not...) % TODO: Improve performance - this takes WAY too long... if jcontainer.isTopLevelMenu & (numMenuComponents==0) jcontainer.requestFocus; numMenuComponents = jcontainer.getMenuComponentCount; if (numMenuComponents == 0) drawnow; pause(0.001); numMenuComponents = jcontainer.getMenuComponentCount; if (numMenuComponents == 0) jcontainer.setSelected(true); numMenuComponents = jcontainer.getMenuComponentCount; if (numMenuComponents == 0) drawnow; pause(0.001); numMenuComponents = jcontainer.getMenuComponentCount; if (numMenuComponents == 0) jcontainer.doClick; % needed in order to populate the sub-menu components numMenuComponents = jcontainer.getMenuComponentCount; if (numMenuComponents == 0) drawnow; %pause(0.001); numMenuComponents = jcontainer.getMenuComponentCount; jcontainer.doClick; % close menu by re-clicking... if (numMenuComponents == 0) drawnow; %pause(0.001); numMenuComponents = jcontainer.getMenuComponentCount; end else % ok - found sub-items % Note: no need to close menu since this will be done when focus moves to another window %jcontainer.doClick; % close menu by re-clicking... end end end jcontainer.setSelected(false); % de-select the menu end end end %% Get the Java editor component handle function jEditor = getJEditor jEditor = []; try % Matlab 7 jEditor = com.mathworks.mde.desk.MLDesktop.getInstance.getGroupContainer('Editor'); catch % Matlab 6 try %desktop = com.mathworks.ide.desktop.MLDesktop.getMLDesktop; % no use - can't get to the editor from here... openDocs = com.mathworks.ide.editor.EditorApplication.getOpenDocuments; % a java.util.Vector firstDoc = openDocs.elementAt(0); % a com.mathworks.ide.editor.EditorViewContainer object jEditor = firstDoc.getParent.getParent.getParent; % a com.mathworks.mwt.MWTabPanel or com.mathworks.ide.desktop.DTContainer object catch myError('YMA:EditorMacro:noEditor','Cannot retrieve the Matlab editor handle - possibly no open editor'); end end if isempty(jEditor) myError('YMA:EditorMacro:noEditor','Cannot retrieve the Matlab editor handle - possibly no open editor'); end try jEditor = handle(jEditor,'CallbackProperties'); catch % never mind - might be Matlab 6... end %% Get the Java editor's main documents container handle function jMainPane = getJMainPane(jEditor) jMainPane = []; try v = version; if (v(1) >= '7') for childIdx = 1 : jEditor.getComponentCount componentClassName = regexprep(jEditor.getComponent(childIdx-1).class,'.*\.',''); if any(strcmp(componentClassName,{'DTMaximizedPane','DTFloatingPane','DTTiledPane'})) jMainPane = jEditor.getComponent(childIdx-1); break; end end if isa(jMainPane,'com.mathworks.mwswing.desk.DTFloatingPane') jMainPane = jMainPane.getComponent(0); % a com.mathworks.mwswing.desk.DTFloatingPane$2 object end else for childIdx = 1 : jEditor.getComponentCount if isa(jEditor.getComponent(childIdx-1),'com.mathworks.mwt.MWGroupbox') | ... isa(jEditor.getComponent(childIdx-1),'com.mathworks.ide.desktop.DTClientFrame') %#ok Matlab 6 compatibility jMainPane = jEditor.getComponent(childIdx-1); break; end end end catch % Matlab 6 - ignore for now... end if isempty(jMainPane) myError('YMA:EditorMacro:noMainPane','Cannot find the Matlab editor''s main document pane'); end try jMainPane = handle(jMainPane,'CallbackProperties'); catch % never mind - might be Matlab 6... end %% Get EditorPane function hEditorPane = getEditorPane(jDocPane) try % Matlab 7 TODO: good for ML 7.1-7.7: need to check other versions jSyntaxTextPaneView = getDescendent(jDocPane,[0,0,1,0,0,0,0]); if isa(jSyntaxTextPaneView,'com.mathworks.widgets.SyntaxTextPaneMultiView$1') hEditorPane(1) = handle(getDescendent(jSyntaxTextPaneView.getComponent(1),[1,0,0]),'CallbackProperties'); hEditorPane(2) = handle(getDescendent(jSyntaxTextPaneView.getComponent(2),[1,0,0]),'CallbackProperties'); else jEditorPane = getDescendent(jSyntaxTextPaneView,[1,0,0]); hEditorPane = handle(jEditorPane,'CallbackProperties'); end catch % Matlab 6 hEditorPane = getDescendent(jDocPane,[0,0,0,0]); if isa(hEditorPane,'com.mathworks.mwt.MWButton') % edge case hEditorPane = getDescendent(jDocPane,[0,1,0,0]); end end %% Internal error processing function myError(id,msg) v = version; if (v(1) >= '7') error(id,msg); else % Old Matlab versions do not have the error(id,msg) syntax... error(msg); end %% Error handling routine function handleError v = version; if v(1)<='6' err.message = lasterr; %#ok no lasterror function... else err = lasterror; %#ok end try err.message = regexprep(err.message,'Error .* ==> [^\n]+\n',''); catch try % Another approach, used in Matlab 6 (where regexprep is unavailable) startIdx = findstr(err.message,'Error using ==> '); stopIdx = findstr(err.message,char(10)); for idx = length(startIdx) : -1 : 1 idx2 = min(find(stopIdx > startIdx(idx))); %#ok ML6 err.message(startIdx(idx):stopIdx(idx2)) = []; end catch % never mind... end end if isempty(findstr(mfilename,err.message)) % Indicate error origin, if not already stated within the error message err.message = [mfilename ': ' err.message]; end if v(1)<='6' while err.message(end)==char(10) err.message(end) = []; % strip excessive Matlab 6 newlines end error(err.message); else rethrow(err); end %% Main keystroke callback function function instrumentDocument(jObject,jEventData,jDocPane,jEditor,appdata) %#ok jObject is unused try if isempty(jDocPane) % This happens when we get here via the jEditor's ComponentAddedCallback % (when adding a new document pane) try % Matlab 7 jDocPane = jEventData.getChild; catch % Matlab 6 eventData = get(jObject,'ComponentAddedCallbackData'); jDocPane = eventData.child; end end hEditorPane = getEditorPane(jDocPane); % Note: KeyTypedCallback is called less frequently (i.e. better), % ^^^^ but unfortunately it does not catch alt/ctrl combinations... %set(hEditorPane, 'KeyTypedCallback', {@keyPressedCallback,jEditor,appdata,hEditorPane}); set(hEditorPane, 'KeyPressedCallback', {@keyPressedCallback,jEditor,appdata,hEditorPane}); pause(0.01); % needed in Matlab 6... catch % never mind - might be Matlab 6... end %% Recursively get the specified children function child = getDescendent(child,listOfChildrenIdx) if ~isempty(listOfChildrenIdx) child = getDescendent(child.getComponent(listOfChildrenIdx(1)),listOfChildrenIdx(2:end)); end %% Update the bindings list function appdata = updateBindings(appdata,keystroke,macro,macroType,jMainPane,jCmdWin) [keystroke,jKeystroke] = normalizeKeyStroke(keystroke); %jKeystroke = javax.swing.KeyStroke.getKeyStroke(keystroke); %appdata.put(keystroke,macro); %using java.util.Hashtable is better but can't extract {@function}... try oldBindingIdx = strmatch(keystroke,appdata.bindings(:,1),'exact'); appdata.bindings(oldBindingIdx,:) = []; % clear any possible old binding catch % ignore - possibly empty appdata a=1; % debug point end % Remove native key-bindings from all editor documents / menu-items try for docIdx = 1 : jMainPane.getComponentCount hEditorPane = getEditorPane(jMainPane.getComponent(docIdx-1)); inputMap = hEditorPane.getInputMap; removeShortcut(inputMap,keystroke); end appdata.edMenusMap = removeMenuShortcut(appdata.edMenusMap,keystroke); appdata.cwMenusMap = removeMenuShortcut(appdata.cwMenusMap,keystroke); catch % never mind... end try if ~isempty(macro) % Normalize the requested macro (if it's a string): '\n', ... if ischar(macro) macro = sprintf(strrep(macro,'%','%%')); end % Check & normalize the requested macroType if ~ischar(macroType) myError('YMA:EditorMacro:badMacroType','bad MACROTYPE input argument - must be a ''string'''); elseif isempty(macroType) | ~any(lower(macroType(1))=='rt') %#ok for Matlab6 compatibility myError('YMA:EditorMacro:badMacroType','bad MACROTYPE input argument - must be ''text'' or ''run'''); elseif lower(macroType(1)) == 'r' macroType = 'run'; macroClass = 'user-defined macro'; else macroType = 'text'; macroClass = 'text'; end % Check if specified macro is a native and/or menu action name if ischar(macro) & macroType(1)=='r' %#ok Matlab 6 compatibility % Check for editor native action name actionFound = 0; hEditorPane = getEditorPane(jMainPane.getComponent(0)); % first document actionNames = getNativeActions(hEditorPane); if any(strcmpi(macro,actionNames)) %#ok Matlab 6 compatibility % Specified macro appears to be a valid native action name for docIdx = 1 : jMainPane.getComponentCount % Add requested action binding to all editor documents' inputMaps hEditorPane = getEditorPane(jMainPane.getComponent(docIdx-1)); inputMap = hEditorPane.getInputMap; %removeShortcut(inputMap,jKeystroke); action = hEditorPane.getActionMap.get(macro); inputMap.put(jKeystroke,action); end [appdata.bindings(end+1,:)] = {keystroke,macro,macroType,'editor native action'}; actionFound = 1; end % Check for CW native action name actionNames = getNativeActions(jCmdWin); if any(strcmpi(macro,actionNames)) %#ok Matlab 6 compatibility % Specified macro appears to be a valid native action name % Add requested action binding to the CW inputMap inputMap = jCmdWin.getInputMap; %removeShortcut(inputMap,jKeystroke); action = jCmdWin.getActionMap.get(macro); inputMap.put(jKeystroke,action); [appdata.bindings(end+1,:)] = {keystroke,macro,macroType,'cmdwin native action'}; actionFound = 1; end % Check for editor menu action name oldBindingIdx = find(strcmpi(macro, appdata.bindings(:,2)) & ... strcmpi('editor menu action', appdata.bindings(:,4))); appdata.bindings(oldBindingIdx,:) = []; %#ok clear any possible old binding menuItemIdx = find(strcmpi(macro,appdata.edMenusMap(:,2))); for menuIdx = 1 : length(menuItemIdx) appdata.edMenusMap{menuItemIdx(menuIdx),1} = keystroke; appdata.edMenusMap{menuItemIdx(menuIdx),3}.setAccelerator(jKeystroke); [appdata.bindings(end+1,:)] = {keystroke,macro,macroType,'editor menu action'}; actionFound = 1; end % Check for CW menu action name oldBindingIdx = find(strcmpi(macro, appdata.bindings(:,2)) & ... strcmpi('cmdwin menu action', appdata.bindings(:,4))); appdata.bindings(oldBindingIdx,:) = []; %#ok clear any possible old binding menuItemIdx = find(strcmpi(macro,appdata.cwMenusMap(:,2))); for menuIdx = 1 : length(menuItemIdx) appdata.cwMenusMap{menuItemIdx(menuIdx),1} = keystroke; appdata.cwMenusMap{menuItemIdx(menuIdx),3}.setAccelerator(jKeystroke); [appdata.bindings(end+1,:)] = {keystroke,macro,macroType,'cmdwin menu action'}; actionFound = 1; end % Bail out if native and/or menu action was handled if actionFound return; end end % A non-native macro - Store the new/updated key-binding in the bindings list [appdata.bindings(end+1,:)] = {keystroke,macro,macroType,macroClass}; end catch myError('YMA:EditorMacro:badMacro','bad MACRO or MACROTYPE input argument - read the help section'); end %% Normalize the keystroke string to a standard format function [keystroke,jKeystroke] = normalizeKeyStroke(keystroke) try if ~ischar(keystroke) myError('YMA:EditorMacro:badKeystroke','bad KEYSTROKE input argument - must be a ''string'''); end keystroke = strrep(keystroke,',',' '); % ',' => space (extra spaces are allowed) keystroke = strrep(keystroke,'-',' '); % '-' => space (extra spaces are allowed) keystroke = strrep(keystroke,'+',' '); % '+' => space (extra spaces are allowed) [flippedKeyChar,flippedMods] = strtok(fliplr(keystroke)); keyChar = upper(fliplr(flippedKeyChar)); modifiers = lower(fliplr(flippedMods)); keystroke = sprintf('%s %s', modifiers, keyChar); % PRESSED: the character needs to be UPPERCASE, all modifiers lowercase %keystroke = sprintf('%s typed %s', modifiers, keyChar); % TYPED: in runtime, the callback is for Typed, not Pressed jKeystroke = javax.swing.KeyStroke.getKeyStroke(keystroke); % normalize & check format validity keystroke = char(jKeystroke.toString); % javax.swing.KeyStroke => Matlab string %keystroke = strrep(keystroke, 'pressed', 'released'); % in runtime, the callback is for Typed, not Pressed %keystroke = strrep(keystroke, '-P', '-R'); % a different format in Matlab 6 (=Java 1.1.8)... keystroke = strrep(keystroke,'keyCode ',''); % Fix for JVM 1.1.8 (Matlab 6) if isempty(keystroke) myError('YMA:EditorMacro:badKeystroke','bad KEYSTROKE input argument'); end catch myError('YMA:EditorMacro:badKeystroke','bad KEYSTROKE input argument - see help section'); end %% Main keystroke callback function function keyPressedCallback(jEditorPane,jEventData,jEditor,appdata,hEditorPane,varargin) try try appdata = getappdata(jEditor,'EditorMacro'); catch % gettappdata() might fail on Matlab 6 so it will fallback to the supplied appdata input arg end % Normalize keystroke string try keystroke = javax.swing.KeyStroke.getKeyStrokeForEvent(jEventData); %get(jEventData) catch % Matlab 6 - for some reason, all Fn keys don't work with KeyReleasedCallback, but some of them work ok with KeyPressedCallback... jEventData = get(jEditorPane,'KeyPressedCallbackData'); keystroke = javax.swing.KeyStroke.getKeyStroke(jEventData.keyCode, jEventData.modifiers); keystroke = char(keystroke.toString); % no automatic type-casting in Matlab 6... keystroke = strrep(keystroke,'keyCode ',''); % Fix for JVM 1.1.8 (Matlab 6) jEditorPane = hEditorPane; % bypass Matlab 6 quirk... end % If this keystroke was bound to a macro macroIdx = strmatch(keystroke,appdata.bindings(:,1),'exact'); if ~isempty(macroIdx) % Disregard built-in actions - they are dispatched via a separate mechanism userTextIdx = strcmp(appdata.bindings(macroIdx,4),'text'); userMacroIdx = strcmp(appdata.bindings(macroIdx,4),'user-defined macro'); if ~any(userTextIdx) & ~any(userMacroIdx) %#ok Matlab 6 compatibility return; end % Dispatch the defined macro macro = appdata.bindings{macroIdx,2}; macroType = appdata.bindings{macroIdx,3}; switch lower(macroType(1)) case 't' % Text if ischar(macro) % Simple string - insert as-is elseif iscell(macro) % Cell or cell array - feval this cell macro = myFeval(macro{1}, jEditorPane, jEventData, macro{2:end}); else % assume @FunctionHandle % feval this @FunctionHandle macro = myFeval(macro, jEditorPane, jEventData); end % Now insert the resulting string into the jEditorPane caret position or replace selection %caretPosition = jEditorPane.getCaretPosition; try % Matlab 7 %jEditorPane.insert(caretPosition, macro); % better to use replaceSelection() than insert() try % Try to dispatch on EDT awtinvoke(jEditorPane, 'replaceSelection', macro); catch try awtinvoke(java(jEditorPane), 'replaceSelection', macro); catch % no good - try direct invocation jEditorPane.replaceSelection(macro); end end catch % Matlab 6 %jEditorPane.insert(macro, caretPosition); % note the reverse order of input args vs. Matlab 7... try % Try to dispatch on EDT awtinvoke(jEditorPane, 'replaceRange', macro, jEditorPane.getSelStart, jEditorPane.getSelEnd); catch try awtinvoke(java(jEditorPane), 'replaceRange', macro, jEditorPane.getSelStart, jEditorPane.getSelEnd); catch % no good - try direct invocation jEditorPane.replaceRange(macro, jEditorPane.getSelStart, jEditorPane.getSelEnd); end end end case 'r' % Run if ischar(macro) % Simple string - evaluate in the base evalin('base', macro); elseif iscell(macro) % Cell or cell array - feval this cell myFeval(macro{1}, jEditorPane, jEventData, macro{2:end}); else % assume @FunctionHandle % feval this @FunctionHandle myFeval(macro, jEditorPane, jEventData); end end end catch % never mind... - ignore error %lasterr try err = lasterror; catch, end %#ok for debugging, will fail on ML6 dummy=1; %#ok debugging point end %% Evaluate a function with exception handling to automatically fix too-many-inputs problems function result = myFeval(func,varargin) try result = []; if nargout result = feval(func,varargin{:}); else feval(func,varargin{:}); end catch % Try rerunning the function without the two default args %v = version; %if v(1)<='6' % err.identifier = 'MATLAB:TooManyInputs'; %#ok no lasterror function so assume... %else % err = lasterror; %#ok %end %if strcmpi(err.identifier,'MATLAB:TooManyInputs') if nargout result = feval(func,varargin{3:end}); else feval(func,varargin{3:end}); end %end end %{ % TODO: % ===== % - Handle Multi-KeyStroke bindings as in Alt-U U (Text / Uppercase) % - Support native actions in EditorMacro(BINDINGSLIST) bulk mode of operation % - Fix docking/menu limitations % - GUI interface (list of actions, list of keybindings %}
github
jantomec/Matlab-master
timelabel.m
.m
Matlab-master/.matlab/libs/quant/charts/timelabel.m
1,003
utf_8
7feed49660baef5fc7b318dbfefe2f52
function timelabel(scaleFix, fmt) %TIMELABEL Summary of this function goes here % Detailed explanation goes here if nargin == 0, scaleFix = true; end if nargin == 1, fmt = 'HH:MM:SS.FFF'; end set(datacursormode(get(gca, 'Parent')), 'UpdateFcn', @dateTip); set(gca, 'UserData', fmt); ticklabelformat(gca, 'x', {@tick2datestr, 'x', fmt}) if scaleFix, set(gca, 'Position', [0.05, 0.05, 0.91, 0.91]) end end function tick2datestr(hProp,eventData,axName,dateformat) %#ok<INUSL> hAxes = eventData.AffectedObject; tickValues = get(hAxes,[axName 'Tick']); tickLabels = arrayfun(@(x)datestr(x, dateformat), tickValues, 'UniformOutput', false); set(hAxes,[axName 'TickLabel'],tickLabels); end function output_txt = dateTip(gar, ev) %#ok<INUSL> pos = ev.Position; fmt = get(gca,'UserData'); if isempty(fmt), fmt = 'HH:MM:SS.FFF'; end output_txt = sprintf('X: %s\nY: %0.4g', datestr(pos(1), fmt), pos(2)); end
github
jantomec/Matlab-master
ticklabelformat.m
.m
Matlab-master/.matlab/libs/quant/charts/ticklabelformat.m
4,208
utf_8
41bb83c32eae2294b1be28cf6dd26bc1
function ticklabelformat(hAxes,axName,format) %TICKLABELFORMAT Sets axis tick labels format % % TICKLABELFORMAT enables setting the format of the tick labels % % Syntax: % ticklabelformat(hAxes,axName,format) % % Input Parameters: % hAxes - handle to the modified axes, such as returned by the gca function % axName - name(s) of axles to modify: 'x','y','z' or combination (e.g. 'xy') % format - format of the tick labels in sprintf format (e.g. '%.1f V') or a % function handle that will be called whenever labels need to be updated % % Note: Calling TICKLABELFORMAT again with an empty ([] or '') format will revert % ^^^^ to Matlab's normal tick labels display behavior % % Examples: % ticklabelformat(gca,'y','%.6g V') - sets y axis on current axes to display 6 significant digits % ticklabelformat(gca,'xy','%.2f') - sets x & y axes on current axes to display 2 decimal digits % ticklabelformat(gca,'z',@myCbFcn) - sets a function to update the Z tick labels on current axes % ticklabelformat(gca,'z',{@myCbFcn,extraData}) - sets an update function as above, with extra data % % Warning: % This code heavily relies on undocumented and unsupported Matlab functionality. % It works on Matlab 7+, but use at your own risk! % % Technical description and more details: % http://UndocumentedMatlab.com/blog/setting-axes-tick-labels-format/ % % Bugs and suggestions: % Please send to Yair Altman (altmany at gmail dot com) % % Change log: % 2012-04-18: first version % % See also: sprintf, gca % Check # of args (we now have narginchk but this is not available on older Matlab releases) if nargin < 1 help(mfilename) return; elseif nargin < 3 error('YMA:TICKLABELFORMAT:ARGS','Not enough input arguments'); end % Check input args if ~ishandle(hAxes) || ~isa(handle(hAxes),'axes') error('YMA:TICKLABELFORMAT:hAxes','hAxes input argument must be a valid axes handle'); elseif ~ischar(axName) error('YMA:TICKLABELFORMAT:axName','axName input argument must be a string'); elseif ~isempty(format) && ~ischar(format) && ~isa(format,'function_handle') && ~iscell(format) error('YMA:TICKLABELFORMAT:format','format input argument must be a string or function handle'); end % normalize axes name(s) to lowercase axName = lower(axName); if strfind(axName,'x') install_adjust_ticklbl(hAxes,'X',format) end if strfind(axName,'y') install_adjust_ticklbl(hAxes,'Y',format) end if strfind(axName,'z') install_adjust_ticklbl(hAxes,'Z',format) end % Install the new tick labels for the specified axes function install_adjust_ticklbl(hAxes,axName,format) % If empty format was specified if isempty(format) % Remove the current format (revert to default Matlab format) set(hAxes,[axName 'TickLabelMode'],'auto') setappdata(hAxes,[axName 'TickListener'],[]) return end % Determine whether to use the specified format as a % sprintf format or a user-specified callback function if ischar(format) cb = {@adjust_ticklbl axName format}; else cb = format; end % Now install axis tick listeners to adjust tick labels % (use undocumented feature for adjustments) ha = handle(hAxes); hp = findprop(ha,[axName 'Tick']); hl = handle.listener(ha,hp,'PropertyPostSet',cb); setappdata(hAxes,[axName 'TickListener'],hl) % Adjust tick labels now %eventData.AffectedObject = hAxes; %adjust_ticklbl([],eventData,axName,format) set(hAxes,[axName 'TickLabelMode'],'manual') set(hAxes,[axName 'TickLabelMode'],'auto') % Default tick labels update callback function (used if user did not specify their own function) function adjust_ticklbl(hProp,eventData,axName,format) %#ok<INUSL> hAxes = eventData.AffectedObject; tickValues = get(hAxes,[axName 'Tick']); tickLabels = arrayfun(@(x)(sprintf(format,x)),tickValues,'UniformOutput',false); set(hAxes,[axName 'TickLabel'],tickLabels)
github
jantomec/Matlab-master
genhurst.m
.m
Matlab-master/.matlab/libs/quant/utils/genhurst.m
3,027
utf_8
17cff2d310725d04f4d832fd039c938a
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Calculates the generalized Hurst exponent H(q) from the scaling % of the renormalized q-moments of the distribution % % <|x(t+r)-x(t)|^q>/<x(t)^q> ~ r^[qH(q)] % % In a nutshell, this nifty little number H tells us if a time series is a % mean reverting (H < 0.5) % random walk (H ~ 0.5) % trending (H > 0.5) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % H = genhurst(S) % S is 1xT data series (T>50 recommended) % calculates H(q=1) % % H = GenHurst(S,q) % specifies the exponent q which can be a vector (default value q=1) % % H = genhurst(S,q,maxT) % specifies value maxT of the scaling window, default value maxT=19 % % [H,sH]=GenHurst(S,...) % estimates the standard deviation sH(q) % % example: % generalized Hurst exponent for a random gaussian process % H=genhurst(cumsum(randn(10000,1))) % or % H=genhurst(cumsum(randn(10000,1)),q) to calculate H(q) with arbitrary q % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % for the generalized Hurst exponent method please refer to: % % T. Di Matteo et al. Physica A 324 (2003) 183-188 % T. Di Matteo et al. Journal of Banking & Finance 29 (2005) 827-851 % T. Di Matteo Quantitative Finance, 7 (2007) 21-36 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Tomaso Aste 30/01/2013 %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [mH,sH] = genhurst(S,q,maxT) if nargin < 2, q = 1; maxT = 19; end if nargin < 3, maxT = 19; end if size(S,1)==1 & size(S,2)>1 S = S'; elseif size(S,1)>1 & size(S,2)>1 fprintf('S must be 1xT \n') return end if size(S,1) < (maxT*4 | 60) warning('Data serie very short!') end L=length(S); lq = length(q); H = []; k = 0; for Tmax=5:maxT k = k+1; x = 1:Tmax; mcord = zeros(Tmax,lq); for tt = 1:Tmax dV = S((tt+1):tt:L) - S(((tt+1):tt:L)-tt); VV = S(((tt+1):tt:(L+tt))-tt)'; N = length(dV)+1; X = 1:N; Y = VV; mx = sum(X)/N; SSxx = sum(X.^2) - N*mx^2; my = sum(Y)/N; SSxy = sum(X.*Y) - N*mx*my; cc(1) = SSxy/SSxx; cc(2) = my - cc(1)*mx; ddVd = dV - cc(1); VVVd = VV - cc(1).*(1:N) - cc(2); %figure %plot(X,Y,'o') %hold on %plot(X,cc(1)*X+cc(2),'-r') %figure %plot(1:N-1,dV,'ob') %hold on %plot([1 N-1],mean(dV)*[1 1],'-b') %plot(1:N-1,ddVd,'xr') %plot([1 N-1],mean(ddVd)*[1 1],'-r') for qq=1:lq mcord(tt,qq)=mean(abs(ddVd).^q(qq))/mean(abs(VVVd).^q(qq)); end end mx = mean(log10(x)); SSxx = sum(log10(x).^2) - Tmax*mx^2; for qq=1:lq my = mean(log10(mcord(:,qq))); SSxy = sum(log10(x).*log10(mcord(:,qq))') - Tmax*mx*my; H(k,qq) = SSxy/SSxx; end end %figure %loglog(x,mcord,'x-') mH = mean(H)'./q(:); if nargout == 2 sH = std(H)'./q(:); elseif nargout == 1 sH = []; end
github
jantomec/Matlab-master
join2matrix.m
.m
Matlab-master/.matlab/libs/quant/utils/join2matrix.m
792
utf_8
ee9919587adeb68c77828e7cf6c70d63
function z = join2matrix(x,y) %JOIN2MATRIX Join 2 matrix using 1sts rows as a key % % x = [1 2 3 4 6; 11 12 13 14 16; ]; % y = [3 6 7; 23 26 27; ]; % z = join2matrix(x, y) % z = % % 1 2 3 4 6 7 % 11 12 13 14 16 16 % NaN NaN 23 23 26 27 z(1,:) = union(x(1,:), y(1,:)); z(2:3,:) = nan(2, size(z,2)); [~, ~, ib] = intersect(x(1,:), z(1,:)); z(2, ib) = x(2,:); [~, ~, ib] = intersect(y(1,:), z(1,:)); z(3, ib) = y(2,:); z(2,:) = propagateNans(z(2,:)); z(3,:) = propagateNans(z(3,:)); end function v = propagateNans(vi) vo = vi; in = find(isnan(vi)); for i = in, if i > 1, vo(i) = vo(i-1); end end v = vo; end
github
jantomec/Matlab-master
supsmu.m
.m
Matlab-master/.matlab/libs/quant/utils/supsmu.m
13,562
utf_8
a4d533ecfb1116a980895e3666898ef2
function smo = supsmu(x,y,varargin) %supsmu: Smoothing of scatterplots using Friedman's supersmoother algorithm. % % Syntax: % Y_SMOOTH = supsmu(X,Y,'PropertyName',PropertyValue,...) % % Inputs: % X, Y are same-length vectors. % % Output % Y_SMOOTH is a smoothed version of Y. % % Example, % x = linspace(0,1,201); % y = sin(2.5*x) + 0.05*randn(1,201); % smo = supsmu(x,y); % plot(x,y,'o',x,smo) % % The supersmoother algorithm computes three separate smooth curves from % the input data with symmetric spans of 0.05*n, 0.2*n and 0.5*n, where n % is the number of data points. The best of the three smooth curves is % chosen for each predicted point using leave-one-out cross validation. The % best spans are then smoothed by a fixed-span smoother (span = 0.2*n) and % the prediction is computed by linearly interpolating between the three % smooth curves. This final smooth curve is then smmothed again with a % fixed-span smoother (span = 0.05*n). % % According to comments by Friedman, "For small samples (n < 40) or if % there are substantial serial correlations between observations close in % x-value, then a prespecified fixed span smoother (span > 0) should be % used. Reasonable span values are 0.2 to 0.4." % % % The following optional property/value pairs can be specified as arguments % to control the indicated behavior: % % Property Value % ---------- ---------------------------------------------------------- % Weights Vector of relative weights of each data point. Default is % for all points to be weighted equally. % % Span Sets the width of a fixed-width smoothing operation % relative to the number of data points, 0 < SPAN < 1. % Setting this to be non-zero disables the supersmoother % algorithm. Default is 0 (use supersmoother). % % Period Sets the period of periodic data. Default is Inf % (infinity) which implies that the data is not periodic. % Can also be set to zero for the same effect. % % Alpha Sets a small-span penalty to produce a greater smoothing % effect. 0 < Alpha < 10, where 0 does nothing and 10 % produces the maximum effect. Default = 0. % % Unsorted If the data points are not already sorted in order of the X % values then setting this to true will sort them for you. % Default = false. % % All properties names are case-insensitive and need only be unambiguous. % For example, % % Y_SMOOTH = supsmu(X,Y,'weights',ones(n,1),'per',2*pi) % % is valid usage. % Friedman, J. H. (1984). A Variable Span Smoother. Tech. Rep. No. 5, % Laboratory for Computational Statistics, Dept. of Statistics, Stanford % Univ., California. % Version: 1.0, 12 December 2007 % Author: Douglas M. Schwarz % Email: dmschwarz=ieee*org, dmschwarz=urgrad*rochester*edu % Real_email = regexprep(Email,{'=','*'},{'@','.'}) % Input checks. error(nargchk(2,Inf,nargin)) % x and y must be vectors with same number of points (at least 5). sy = size(y); n = length(y); if ~isvector(x) || ~isvector(y) || length(x) ~= n || n < 5 error('X and Y must be equal-length vectors of at least 5 points.') end % Define properties and set default values. prop.weights = []; prop.span = 0; prop.period = Inf; prop.alpha = 0; prop.unsorted = false; % Process inputs and set prop fields. properties = fieldnames(prop); arg_index = 1; while arg_index <= length(varargin) arg = varargin{arg_index}; if ischar(arg) prop_index = find(strncmpi(arg,properties,length(arg))); if length(prop_index) == 1 prop.(properties{prop_index}) = varargin{arg_index + 1}; else error('Property ''%s'' does not exist or is ambiguous.',arg) end arg_index = arg_index + 2; elseif isstruct(arg) arg_fn = fieldnames(arg); for i = 1:length(arg_fn) prop_index = find(strncmpi(arg_fn{i},properties,... length(arg_fn{i}))); if length(prop_index) == 1 prop.(properties{prop_index}) = arg.(arg_fn{i}); else error('Property ''%s'' does not exist or is ambiguous.',... arg_fn{i}) end end arg_index = arg_index + 1; else error(['Properties must be specified by property/value pairs',... ' or structures.']) end end % Validate Weights property. if isempty(prop.weights) elseif length(prop.weights) == 1 prop.weights = []; elseif isvector(prop.weights) && length(prop.weights) == n prop.weights = prop.weights(:); else error('Weights property must be a vector of the same length as X and Y.') end % Validate Span property. if ~isscalar(prop.span) || prop.span < 0 || prop.span >= 1 error('Span property must be a scalar, 0 <= span < 1.') end % Validate Periodic property. if ~isscalar(prop.period) || prop.period < 0 error('Periodic property must be a scalar >= 0.') end if isinf(prop.period) prop.period = 0; end % Validate Alpha property. if isscalar(prop.alpha) prop.alpha = min(max(prop.alpha,0),10); else error('Alpha property must be a scalar.') end % Validate Unsorted property. if ~isscalar(prop.unsorted) error('Unsorted property must be a scalar.') end % Select one of four smooth functions. Each smooth function has been % speed optimized for the specific conditions. smooth_fcn_selector = 2*isempty(prop.weights) + (prop.period == 0); switch smooth_fcn_selector case 0 % use weights, periodic smooth = @smooth_wt_per; case 1 % use weights, aperiodic smooth = @smooth_wt_aper; case 2 % no weights, periodic smooth = @smooth_per; case 3 % no weights, aperiodic smooth = @smooth_aper; end % Make x and y into column vectors and sort if necessary. x = x(:); y = y(:); if prop.unsorted [x,order] = sort(x); y = y(order); if ~isempty(prop.weights) prop.weights = prop.weights(order); end end % If prop.span > 0 then we have a fixed span smooth. if prop.span > 0 smo = smooth(x,y,prop.weights,prop.span,prop.period); smo = reshape(smo,sy); if prop.unsorted smo(order) = smo; end return end spans = [0.05;0.2;0.5]; nspans = length(spans); % Compute three smooth curves. smo_n = zeros(n,nspans); acvr_smo = zeros(n,nspans); for i = 1:nspans [smo_n(:,i),abs_cv_res] = smooth(x,y,prop.weights,spans(i),prop.period); acvr_smo(:,i) = smooth(x,abs_cv_res,prop.weights,spans(2),prop.period); end % Select which smooth curve has smallest error using cross validation. [resmin,index] = min(acvr_smo,[],2); span_cv = spans(index); % Apply alpha. if prop.alpha ~= 0 small = 1e-7; tf = resmin < acvr_smo(:,3) & resmin > 0; span_cv(tf) = span_cv(tf) + (spans(3) - span_cv(tf)).* ... max(small,resmin(tf)./acvr_smo(tf,3)).^(10 - prop.alpha); end % Smooth span_cv and clip at spans(1) and spans(end). smo_span = smooth(x,span_cv,prop.weights,spans(2),prop.period); smo_span = max(min(smo_span,spans(end)),spans(1)); % Interpolate each point. % The block of code below does the same thing as this, but much faster: % smo_raw = zeros(n,1); % for i = 1:n % smo_raw(i) = interp1(spans,smo_n(i,:),smo_span(i)); % end try bin = sum(bsxfun(@ge,smo_span,spans(1:end-1)'),2); catch % if bsxfun does not exist. bin = sum(repmat(smo_span,1,nspans-1) >= repmat(spans(1:end-1)',n,1),2); end dspans = diff(spans); t = (smo_span - spans(bin))./dspans(bin); index = (1:n)' + n*bin; smo_raw = (1-t).*smo_n(index - n) + t.*smo_n(index); % Apply final smooth. smo = smooth(x,smo_raw,prop.weights,spans(1),prop.period); smo = reshape(smo,sy); if prop.unsorted smo(order) = smo; end %------------------------------------------------------------------------- % Subfunctions %------------------------------------------------------------------------- function [smo,acvr] = smooth_wt_aper(x,y,w,span,period) % smoothing function for aperiodic data, uses weights. % Get the dimensions of the input. n = length(y); m = max(round(0.5*span*n),2); k = 2*m + 1; wy = w.*y; wxy = wy.*x; data = [cumprod([w,x,x],2),wy,wxy]; % Compute sum(w), sum(w*x), sum(w*x^2), sum(w*y), sum(w*x*y) over k points. sums = zeros(n,5); % ---------------------------------------------- % Slower, more accurate code: % temp = filter(ones(it,1),1,data); % sums(m+1:n-m,:) = temp(k:end,:); % ---------------------------------------------- % Faster, slightly less accurate code: cs = [0 0 0 0 0;cumsum(data)]; sums(m+1:n-m,:) = cs(k+1:end,:) - cs(1:end-k,:); % ---------------------------------------------- sums(1:m,:) = sums((m+1)*ones(1,m),:); sums(n-m+1:end,:) = sums((n-m)*ones(1,m),:); denom = sums(:,1).*sums(:,3) - sums(:,2).^2; a = (sums(:,4).*sums(:,3) - sums(:,2).*sums(:,5))./denom; b = (sums(:,1).*sums(:,5) - sums(:,2).*sums(:,4))./denom; smo = a + b.*x; if nargout > 1 sums_cv = sums - data; denom_cv = sums_cv(:,1).*sums_cv(:,3) - sums_cv(:,2).^2; a_cv = (sums_cv(:,4).*sums_cv(:,3) - sums_cv(:,2).*sums_cv(:,5))./denom_cv; b_cv = (sums_cv(:,1).*sums_cv(:,5) - sums_cv(:,2).*sums_cv(:,4))./denom_cv; smo_cv = a_cv + b_cv.*x; acvr = abs(smo_cv - y); end %------------------------------------------------------------------------- function [smo,acvr] = smooth_wt_per(x,y,w,span,period) % smoothing function for periodic data, uses weights. % Get the dimensions of the input. n = length(y); m = max(round(0.5*span*n),2); k = 2*m + 1; x = [x;x(1:k-1)+period]; y = [y;y(1:k-1)]; w = [w;w(1:k-1)]; wy = w.*y; wxy = wy.*x; data = [cumprod([w,x,x],2),wy,wxy]; % Compute sum(w), sum(w*x), sum(w*x^2), sum(w*y), sum(w*x*y) over k points. % ---------------------------------------------- % Slower, more accurate code: % temp = filter(ones(k,1),1,data); % sums = temp(k:end,:); % ---------------------------------------------- % Faster, slightly less accurate code: cs = [0 0 0 0 0;cumsum(data)]; sums = cs(k+1:n+k,:) - cs(1:n,:); % ---------------------------------------------- denom = sums(:,1).*sums(:,3) - sums(:,2).^2; a = (sums(:,4).*sums(:,3) - sums(:,2).*sums(:,5))./denom; b = (sums(:,1).*sums(:,5) - sums(:,2).*sums(:,4))./denom; % smo = circshift(a + b.*x(m+1:n+m),m); % slow smo([m+1:n,1:m],:) = a + b.*x(m+1:n+m); % fast if nargout > 1 sums_cv = sums - data(m+1:n+m,:); denom_cv = sums_cv(:,1).*sums_cv(:,3) - sums_cv(:,2).^2; a_cv = (sums_cv(:,4).*sums_cv(:,3) - sums_cv(:,2).*sums_cv(:,5))./denom_cv; b_cv = (sums_cv(:,1).*sums_cv(:,5) - sums_cv(:,2).*sums_cv(:,4))./denom_cv; % smo_cv = circshift(a_cv + b_cv.*x(m+1:n+m),m); % slow smo_cv([m+1:n,1:m],:) = a_cv + b_cv.*x(m+1:n+m); % fast acvr = abs(smo_cv - y(1:n)); end %------------------------------------------------------------------------- function [smo,acvr] = smooth_aper(x,y,w,span,period) % smoothing function for aperiodic data, does not use weights. % Get the dimensions of the input. n = length(y); m = max(round(0.5*span*n),2); k = 2*m + 1; xy = y.*x; data = [cumprod([x,x],2),y,xy]; % Compute sum(x), sum(x^2), sum(y), sum(x*y) over k points. sums = zeros(n,4); % ---------------------------------------------- % Slower, more accurate code: % temp = filter(ones(k,1),1,data); % sums(m+1:n-m,:) = temp(k:end,:); % ---------------------------------------------- % Faster, slightly less accurate code: cs = [0 0 0 0;cumsum(data)]; sums(m+1:n-m,:) = cs(k+1:end,:) - cs(1:end-k,:); % ---------------------------------------------- sums(1:m,:) = sums((m+1)*ones(1,m),:); sums(n-m+1:end,:) = sums((n-m)*ones(1,m),:); denom = k.*sums(:,2) - sums(:,1).^2; a = (sums(:,3).*sums(:,2) - sums(:,1).*sums(:,4))./denom; b = (k.*sums(:,4) - sums(:,1).*sums(:,3))./denom; smo = a + b.*x; if nargout > 1 sums_cv = sums - data; denom_cv = (k-1).*sums_cv(:,2) - sums_cv(:,1).^2; a_cv = (sums_cv(:,3).*sums_cv(:,2) - sums_cv(:,1).*sums_cv(:,4))./denom_cv; b_cv = ((k-1).*sums_cv(:,4) - sums_cv(:,1).*sums_cv(:,3))./denom_cv; smo_cv = a_cv + b_cv.*x; acvr = abs(smo_cv - y); end %------------------------------------------------------------------------- function [smo,acvr] = smooth_per(x,y,w,span,period) % smoothing function for periodic data, does not use weights. % Get the dimensions of the input. n = length(y); m = max(round(0.5*span*n),2); k = 2*m + 1; x = [x;x(1:k-1)+period]; y = [y;y(1:k-1)]; xy = y.*x; data = [cumprod([x,x],2),y,xy]; % Compute sum(x), sum(x^2), sum(y), sum(x*y) over k points. % ---------------------------------------------- % Slower, more accurate code: % temp = filter(ones(k,1),1,data); % sums = temp(k:end,:); % ---------------------------------------------- % Faster, slightly less accurate code: cs = [0 0 0 0;cumsum(data)]; sums = cs(k+1:n+k,:) - cs(1:n,:); % ---------------------------------------------- denom = k.*sums(:,2) - sums(:,1).^2; a = (sums(:,3).*sums(:,2) - sums(:,1).*sums(:,4))./denom; b = (k.*sums(:,4) - sums(:,1).*sums(:,3))./denom; % smo = circshift(a + b.*x(m+1:n+m),m); % slow smo([m+1:n,1:m],:) = a + b.*x(m+1:n+m); % fast if nargout > 1 sums_cv = sums - data(m+1:n+m,:); denom_cv = (k-1).*sums_cv(:,2) - sums_cv(:,1).^2; a_cv = (sums_cv(:,3).*sums_cv(:,2) - sums_cv(:,1).*sums_cv(:,4))./denom_cv; b_cv = ((k-1).*sums_cv(:,4) - sums_cv(:,1).*sums_cv(:,3))./denom_cv; % smo_cv = circshift(a_cv + b_cv.*x(m+1:n+m),m); % slow smo_cv([m+1:n,1:m],:) = a_cv + b_cv.*x(m+1:n+m); % fast acvr = abs(smo_cv - y(1:n)); end
github
jantomec/Matlab-master
retrieveData.m
.m
Matlab-master/.matlab/libs/quant/tester/retrieveData.m
887
utf_8
705e12178320376fabe4448c2e0dad90
function S = retrieveData(symbs, from, to, datasource, frame) if ~iscell(symbs), symbs = {symbs}; end if nargin < 4, datasource = 'yahoo.a'; end if nargin < 5, frame = Helper.D; end % Collect series data S = struct('Name',[], 'Tm', [], 'Op', [], 'Hi', [], 'Lo', [], 'Cl', [], 'Vo', []); k = 1; for i = {symbs{:}} d = getData(char(i), datasource, frame, from, to); if ~isempty(d) S(k).Name = char(i); S(k).Tm = d(:,1); S(k).Op = d(:,2); S(k).Hi = d(:,3); S(k).Lo = d(:,4); S(k).Cl = d(:,5); S(k).Vo = d(:,6); k = k + 1; end end end function s = getData(symb, datasource, frame, from, to) try s = Helper.fetch(datasource, symb, frame, from, to); s = s.toMat(1); catch s = []; end end
github
sunspec/prodromos-master
rtwmakecfg.m
.m
prodromos-master/feeder-models/Simulink/Feeder_2/Feeder2_RT_Lab_Model/models/Feeder_2/rtwmakecfg.m
2,815
utf_8
16b58d91a07c158f3016ba8d1adbf057
function makeInfo=rtwmakecfg() %RTWMAKECFG.m adds include and source directories to rtw make files. % makeInfo=RTWMAKECFG returns a structured array containing % following field: % makeInfo.includePath - cell array containing additional include % directories. Those directories will be % expanded into include instructions of Simulink % Coder generated make files. % % makeInfo.sourcePath - cell array containing additional source % directories. Those directories will be % expanded into rules of Simulink Coder generated % make files. makeInfo.includePath = {}; makeInfo.sourcePath = {}; makeInfo.linkLibsObjs = {}; %<Generated by S-Function Builder 3.0. DO NOT REMOVE> sfBuilderBlocksByMaskType = find_system(bdroot,'FollowLinks','on','LookUnderMasks','on','MaskType','S-Function Builder'); sfBuilderBlocksByCallback = find_system(bdroot,'OpenFcn','sfunctionwizard(gcbh)'); sfBuilderBlocksDeployed = find_system(bdroot,'BlockType','S-Function','SFunctionDeploymentMode','on'); sfBuilderBlocks = {sfBuilderBlocksByMaskType{:} sfBuilderBlocksByCallback{:} sfBuilderBlocksDeployed{:}}; sfBuilderBlocks = unique(sfBuilderBlocks); if isempty(sfBuilderBlocks) return; end for idx = 1:length(sfBuilderBlocks) sfBuilderBlockNameMATFile{idx} = get_param(sfBuilderBlocks{idx},'FunctionName'); sfBuilderBlockNameMATFile{idx} = ['.' filesep 'SFB__' char(sfBuilderBlockNameMATFile{idx}) '__SFB.mat']; end sfBuilderBlockNameMATFile = unique(sfBuilderBlockNameMATFile); for idx = 1:length(sfBuilderBlockNameMATFile) if exist(sfBuilderBlockNameMATFile{idx}) loadedData = load(sfBuilderBlockNameMATFile{idx}); if isfield(loadedData,'SFBInfoStruct') makeInfo = UpdateMakeInfo(makeInfo,loadedData.SFBInfoStruct); clear loadedData; end end end function updatedMakeInfo = UpdateMakeInfo(makeInfo,SFBInfoStruct) updatedMakeInfo = {}; if isfield(makeInfo,'includePath') if isfield(SFBInfoStruct,'includePath') updatedMakeInfo.includePath = {makeInfo.includePath{:} SFBInfoStruct.includePath{:}}; else updatedMakeInfo.includePath = {makeInfo.includePath{:}}; end end if isfield(makeInfo,'sourcePath') if isfield(SFBInfoStruct,'sourcePath') updatedMakeInfo.sourcePath = {makeInfo.sourcePath{:} SFBInfoStruct.sourcePath{:}}; else updatedMakeInfo.sourcePath = {makeInfo.sourcePath{:}}; end end if isfield(makeInfo,'linkLibsObjs') if isfield(SFBInfoStruct,'additionalLibraries') updatedMakeInfo.linkLibsObjs = {makeInfo.linkLibsObjs{:} SFBInfoStruct.additionalLibraries{:}}; else updatedMakeInfo.linkLibsObjs = {makeInfo.linkLibsObjs{:}}; end end
github
Sundrops/caffe-rgh-master
classification_demo.m
.m
caffe-rgh-master/matlab/demo/classification_demo.m
5,412
utf_8
8f46deabe6cde287c4759f3bc8b7f819
function [scores, maxlabel] = classification_demo(im, use_gpu) % [scores, maxlabel] = classification_demo(im, use_gpu) % % Image classification demo using BVLC CaffeNet. % % IMPORTANT: before you run this demo, you should download BVLC CaffeNet % from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html) % % **************************************************************************** % For detailed documentation and usage on Caffe's Matlab interface, please % refer to Caffe Interface Tutorial at % http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab % **************************************************************************** % % input % im color image as uint8 HxWx3 % use_gpu 1 to use the GPU, 0 to use the CPU % % output % scores 1000-dimensional ILSVRC score vector % maxlabel the label of the highest score % % You may need to do the following before you start matlab: % $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64 % $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 % Or the equivalent based on where things are installed on your system % % Usage: % im = imread('../../examples/images/cat.jpg'); % scores = classification_demo(im, 1); % [score, class] = max(scores); % Five things to be aware of: % caffe uses row-major order % matlab uses column-major order % caffe uses BGR color channel order % matlab uses RGB color channel order % images need to have the data mean subtracted % Data coming in from matlab needs to be in the order % [width, height, channels, images] % where width is the fastest dimension. % Here is the rough matlab for putting image data into the correct % format in W x H x C with BGR channels: % % permute channels from RGB to BGR % im_data = im(:, :, [3, 2, 1]); % % flip width and height to make width the fastest dimension % im_data = permute(im_data, [2, 1, 3]); % % convert from uint8 to single % im_data = single(im_data); % % reshape to a fixed size (e.g., 227x227). % im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % % subtract mean_data (already in W x H x C with BGR channels) % im_data = im_data - mean_data; % If you have multiple images, cat them with cat(4, ...) % Add caffe/matlab to you Matlab search PATH to use matcaffe if exist('../+caffe', 'dir') addpath('..'); else error('Please run this demo from caffe/matlab/demo'); end % Set caffe mode if exist('use_gpu', 'var') && use_gpu caffe.set_mode_gpu(); gpu_id = 0; % we will use the first gpu in this demo caffe.set_device(gpu_id); else caffe.set_mode_cpu(); end % Initialize the network using BVLC CaffeNet for image classification % Weights (parameter) file needs to be downloaded from Model Zoo. model_dir = '../../models/bvlc_reference_caffenet/'; net_model = [model_dir 'deploy.prototxt']; net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel']; phase = 'test'; % run with phase test (so that dropout isn't applied) if ~exist(net_weights, 'file') error('Please download CaffeNet from Model Zoo before you run this demo'); end % Initialize a network net = caffe.Net(net_model, net_weights, phase); if nargin < 1 % For demo purposes we will use the cat image fprintf('using caffe/examples/images/cat.jpg as input image\n'); im = imread('../../examples/images/cat.jpg'); end % prepare oversampled input % input_data is Height x Width x Channel x Num tic; input_data = {prepare_image(im)}; toc; % do forward pass to get scores % scores are now Channels x Num, where Channels == 1000 tic; % The net forward function. It takes in a cell array of N-D arrays % (where N == 4 here) containing data of input blob(s) and outputs a cell % array containing data from output blob(s) scores = net.forward(input_data); toc; scores = scores{1}; scores = mean(scores, 2); % take average scores over 10 crops [~, maxlabel] = max(scores); % call caffe.reset_all() to reset caffe caffe.reset_all(); % ------------------------------------------------------------------------ function crops_data = prepare_image(im) % ------------------------------------------------------------------------ % caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that % is already in W x H x C with BGR channels d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat'); mean_data = d.mean_data; IMAGE_DIM = 256; CROPPED_DIM = 227; % Convert an image returned by Matlab's imread to im_data in caffe's data % format: W x H x C with BGR channels im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR im_data = permute(im_data, [2, 1, 3]); % flip width and height im_data = single(im_data); % convert from uint8 to single im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR) % oversample (4 corners, center, and their x-axis flips) crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices = [0 IMAGE_DIM-CROPPED_DIM] + 1; n = 1; for i = indices for j = indices crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :); crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n); n = n + 1; end end center = floor(indices(2) / 2) + 1; crops_data(:,:,:,5) = ... im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:); crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
github
Sinan81/PSAT-master
fm_spf.m
.m
PSAT-master/psat-mat/psat/fm_spf.m
12,837
utf_8
1773dd0bb33b536ad45b435eb52d1f03
function fm_spf % FM_SPF solve standard power flow by means of the NR method % and fast decoupled power flow (XB and BX variations) % with either a single or distributed slack bus model. % % FM_SPF % %see the properties of the Settings structure for options. % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 09-Jul-2003 %Version: 1.0.1 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global DAE Pl Mn Lines Line SW PV PQ Bus global History Theme Fig Settings LIB Snapshot Path File fm_disp fm_disp('Newton-Raphson Method for Power Flow Computation') if Settings.show fm_disp(['Data file "',Path.data,File.data,'"']) end nodyn = 0; % these computations are needed only the first time the power flow is run if ~Settings.init % bus type initialization fm_ncomp if ~Settings.ok, return, end % report components parameters to system bases if Settings.conv, fm_base, end % create the admittance matrix Line = build_y(Line); % create the FM_CALL FUNCTION if Settings.show, fm_disp('Writing file "fm_call" ...',1), end fm_wcall; fm_dynlf; % indicization of components used in power flow computations end % memory allocation for equations and Jacobians DAE.g = ones(DAE.m,1); DAE.Gy = sparse(DAE.m,DAE.m); if (DAE.n~=0) DAE.f = ones(DAE.n,1); % differential equations DAE.x = ones(DAE.n,1); % state variables fm_xfirst; DAE.Fx = sparse(DAE.n,DAE.n); % df/dx DAE.Fy = sparse(DAE.n,DAE.m); % df/dy DAE.Gx = sparse(DAE.m,DAE.n); % dg/dx else % no dynamic elements nodyn = 1; DAE.n = 1; DAE.f = 0; DAE.x = 0; DAE.Fx = 1; DAE.Fy = sparse(1,DAE.m); DAE.Gx = sparse(DAE.m,1); end % check PF solver method PFmethod = Settings.pfsolver; ncload = getnum(Mn) + getnum(Pl) + getnum(Lines) + (~nodyn); if (ncload || Settings.distrsw) && (PFmethod == 2 || PFmethod == 3) if ncload fm_disp('Fast Decoupled PF cannot be used with dynamic components') end if Settings.distrsw fm_disp('Fast Decoupled PF cannot be used with distributed slack bus model') end PFmethod = 1; % force using standard NR method end switch PFmethod case 1, fm_disp('PF solver: Newton-Raphson method') case 2, fm_disp('PF solver: XB fast decoupled method') case 3, fm_disp('PF solver: BX fast decoupled method') case 4, fm_disp('PF solver: Runge-Kutta method') case 5, fm_disp('PF solver: Iwamoto method') case 6, fm_disp('PF solver: Robust power flow method') case 7, fm_disp('PF solver: DC power flow') end DAE.lambda = 1; Jrow = 0; if Settings.distrsw DAE.Fk = sparse(DAE.n,1); DAE.Gk = sparse(DAE.m,1); Jrow = sparse(1,DAE.n+SW.refbus,1,1,DAE.n+DAE.m+1); DAE.kg = 0; if ~swgamma(SW,'sum') fm_disp('Slack buses have zero power loss participation factor.') fm_disp('Single slack bus model will be used') Setting.distrsw = 0; end if totp(SW) == 0 SW = setpg(totp(PQ)-totp(PV),1); fm_disp('Slack buses have zero generated power.') fm_disp('P_slack = sum(P_load)-sum(P_gen) will be used.') fm_disp('Only PQ loads and PV generators are used.') fm_disp('If there are convergence problems, use the single slack bus model.') end Gkcall(SW); Gkcall(PV); end switch Settings.distrsw case 1 fm_disp('Distributed slack bus model') case 0 fm_disp('Single slack bus model') end iter_max = Settings.lfmit; convergence = 1; if iter_max < 2, iter_max = 2; end iteration = 0; tol = Settings.lftol; Settings.error = tol+1; Settings.iter = 0; err_max_old = 1e6; err_vec = []; alfatry = 1; alfa = 1; %0.85; safety = 0.9; pgrow = -0.2; pshrnk = -0.25; robust = 1; try errcon = (5/safety)^(1/pgrow); catch errcon = 1.89e-4; end % Graphical settings fm_status('pf','init',iter_max,{'r'},{'-'},{Theme.color11}) islands(Line) % Newton-Raphson routine t0 = clock; while (Settings.error > tol) && (iteration <= iter_max) && (alfa > 1e-5) if ishandle(Fig.main) if ~get(Fig.main,'UserData'), break, end end switch PFmethod case 1 % Standard Newton-Raphson method inc = calcInc(nodyn,Jrow); DAE.x = DAE.x + inc(1:DAE.n); DAE.y = DAE.y + inc(1+DAE.n:DAE.m+DAE.n); if Settings.distrsw, DAE.kg = DAE.kg + inc(end); end case {2,3} % Fast Decoupled Power Flow if ~iteration % initialize variables Line = build_b(Line); no_sw = Bus.a; no_sw(getbus(SW)) = []; no_swv = no_sw + Bus.n; no_g = Bus.a; no_g([getbus(SW); getbus(PV)]) = []; Bp = Line.Bp(no_sw,no_sw); Bpp = Line.Bpp(no_g,no_g); [Lp, Up, Pp] = lu(Bp); [Lpp, Upp, Ppp] = lu(Bpp); no_g = no_g + Bus.n; fm_call('fdpf') end % P-theta da = -(Up\(Lp\(Pp*(DAE.g(no_sw)./DAE.y(no_swv))))); DAE.y(no_sw) = DAE.y(no_sw) + da; fm_call('fdpf') normP = norm(DAE.g,inf); % Q-V dV = -(Upp\(Lpp\(Ppp*(DAE.g(no_g)./DAE.y(no_g))))); DAE.y(no_g) = DAE.y(no_g)+dV; fm_call('fdpf') normQ = norm(DAE.g,inf); inc = [normP; normQ]; % recompute Bpp if some PV bus has been switched to PQ bus if Settings.pv2pq && strmatch('Switch',History.text{end}) fm_disp('Recomputing Bpp matrix for Fast Decoupled PF') no_g = Bus.a; no_g([getbus(SW); getbus(PV)]) = []; Bpp = Line.Bpp(no_g,no_g); [Lpp, Upp, Ppp] = lu(Bpp); no_g = no_g + Bus.n; end case 4 % Runge-Kutta method xold = DAE.x; yold = DAE.y; kold = DAE.kg; k1 = alfa*calcInc(nodyn,Jrow); Jac = -[DAE.Fx, DAE.Fy; DAE.Gx, DAE.Gy]; DAE.x = xold + 0.5*k1(1:DAE.n); DAE.y = yold + 0.5*k1(1+DAE.n:DAE.m+DAE.n); if Settings.distrsw, DAE.kg = kold + 0.5*k1(end); end k2 = alfa*calcInc(nodyn,Jrow); DAE.x = xold + 0.5*k2(1:DAE.n); DAE.y = yold + 0.5*k2(1+DAE.n:DAE.m+DAE.n); if Settings.distrsw, DAE.kg = kold + 0.5*k2(end); end k3 = alfa*calcInc(nodyn,Jrow); DAE.x = xold + k3(1:DAE.n); DAE.y = yold + k3(1+DAE.n:DAE.m+DAE.n); if Settings.distrsw, DAE.kg = kold + k3(end); end k4 = alfa*calcInc(nodyn,Jrow); % compute RK4 increment of variables inc = (k1+2*(k2+k3)+k4)/6; % to estimate RK error, use the RK2:Dy and RK4:Dy. yerr = max(abs(abs(k2)-abs(inc))); if yerr > 0.01 alfa = max(0.985*alfa,0.75); else alfa = min(1.015*alfa,0.75); end DAE.x = xold + inc(1:DAE.n); DAE.y = yold + inc(1+DAE.n:DAE.m+DAE.n); if Settings.distrsw, DAE.kg = kold + inc(end); end case 5 % Iwamoto method xold = DAE.x; yold = DAE.y; kold = DAE.kg; inc = calcInc(nodyn,Jrow); vec_a = -[DAE.Fx, DAE.Fy; DAE.Gx, DAE.Gy]*inc; vec_b = -vec_a; DAE.x = inc(1:DAE.n); DAE.y = inc(1+DAE.n:DAE.m+DAE.n); if Settings.distrsw DAE.kg = inc(end); fm_call('kgpf'); if nodyn, DAE.Fx = 1; end vec_c = -[DAE.f; DAE.g; DAE.y(SW.refbus)]; else refreshJac; fm_call('l'); refreshGen(nodyn); vec_c = -[DAE.f; DAE.g]; end g0 = (vec_a')*vec_b; g1 = sum(vec_b.*vec_b + 2*vec_a.*vec_c); g2 = 3*(vec_b')*vec_c; g3 = 2*(vec_c')*vec_c; % mu = fsolve(@(x) g0 + x*(g1 + x*(g2 + x*g3)), 1.0); % Cardan's formula pp = -g2/3/g3; qq = pp^3 + (g2*g1-3*g3*g0)/6/g3/g3; rr = g1/3/g3; mu = (qq+sqrt(qq*qq+(rr-pp*pp)^3))^(1/3) + ... (qq-sqrt(qq*qq+(rr-pp*pp)^3))^(1/3) + pp; mu = min(abs(mu),0.75); DAE.x = xold + mu*inc(1:DAE.n); DAE.y = yold + mu*inc(1+DAE.n:DAE.n+DAE.m); if Settings.distrsw, DAE.kg = kold + mu*inc(end); end case 6 % simple robust power flow method inc = robust*calcInc(nodyn,Jrow); Settings.error = max(abs(inc)); if Settings.error > 1.5*err_max_old && iteration robust = 0.25*robust; if robust < tol fm_disp('The otpimal multiplier is too small.') iteration = iter_max+1; break end else DAE.x = DAE.x + inc(1:DAE.n); DAE.y = DAE.y + inc(1+DAE.n:DAE.m+DAE.n); if Settings.distrsw, DAE.kg = DAE.kg + inc(end); end err_max_old = Settings.error; robust = 1; end end iteration = iteration + 1; Settings.error = max(abs(inc)); Settings.iter = iteration; err_vec(iteration) = Settings.error; if Settings.error < 1e-2 && PFmethod > 3 && Settings.switch2nr fm_disp('Switch to standard Newton-Raphson method.') PFmethod = 1; end fm_status('pf','update',[iteration, Settings.error],iteration) if Settings.show if Settings.error == Inf, Settings.error = 1e3; end fm_disp(['Iteration = ', num2str(iteration), ... ' Maximum Convergency Error = ', ... num2str(Settings.error)],1) end % stop if the error increases too much if iteration > 4 if err_vec(iteration) > 1000*err_vec(1) fm_disp('The error is increasing too much.') fm_disp('Convergence is likely not reachable.') convergence = 0; break end end end Settings.lftime = etime(clock,t0); if iteration > iter_max fm_disp(['Reached maximum number of iteration of NR routine without ' ... 'convergence'],2) convergence = 0; end % Total power injections and consumptions at network buses % Pl and Ql computation (shunts only) DAE.g = zeros(DAE.m,1); fm_call('load0'); Bus.Pl = DAE.g(Bus.a); Bus.Ql = DAE.g(Bus.v); %Pg and Qg computation fm_call('gen0'); Bus.Pg = DAE.g(Bus.a); Bus.Qg = DAE.g(Bus.v); if ~Settings.distrsw SW = setpg(SW,'all',Bus.Pg(SW.bus)); end % adjust powers in case of PQ generators adjgen(PQ) % memory allocation for dynamic variables & state variables indicization if nodyn == 1; DAE.x = []; DAE.f = []; DAE.n = 0; end DAE.npf = DAE.n; m_old = DAE.m; fm_dynidx; % rebuild algebraic variables and vectors m_diff = DAE.m-m_old; if m_diff DAE.y = [DAE.y;zeros(m_diff,1)]; DAE.g = [DAE.g;zeros(m_diff,1)]; DAE.Gy = sparse(DAE.m,DAE.m); end % rebuild state variables and vectors if DAE.n ~= 0 DAE.f = [DAE.f; ones(DAE.n-DAE.npf,1)]; % differential equations DAE.x = [DAE.x; ones(DAE.n-DAE.npf,1)]; % state variables DAE.Fx = sparse(DAE.n,DAE.n); % state Jacobian df/dx DAE.Fy = sparse(DAE.n,DAE.m); % state Jacobian df/dy DAE.Gx = sparse(DAE.m,DAE.n); % algebraic Jacobian dg/dx end % build cell arrays of variable names fm_idx(1) if (Settings.vs == 1), fm_idx(2), end % initializations of state variables and components if Settings.static fm_disp('* * * Dynamic components are not initialized * * *') end if convergence Settings.init = 1; else Settings.init = -1; end fm_rmgen(-1); % initialize function for removing static generators fm_call('0'); % compute initial state variables % power flow result visualization fm_disp(['Power Flow completed in ',num2str(Settings.lftime),' s']) if Settings.showlf == 1 || ishandle(Fig.stat) fm_stat; else if Settings.beep, beep, end end if ishandle(Fig.threed), fm_threed('update'), end % initialization of all equations & Jacobians refreshJac fm_call('i'); % build structure "Snapshot" if isempty(Settings.t0) && ishandle(Fig.main) hdl = findobj(Fig.main,'Tag','EditText3'); Settings.t0 = str2num(get(hdl,'String')); end if ~Settings.locksnap && Bus.n <= 5000 && DAE.n < 5000 Snapshot = struct( ... 'name','Power Flow Results', ... 'time',Settings.t0, ... 'y',DAE.y, ... 'x',DAE.x,... 'Ybus',Line.Y, ... 'Pg',Bus.Pg, ... 'Qg',Bus.Qg, ... 'Pl',Bus.Pl, ... 'Ql',Bus.Ql, ... 'Gy',DAE.Gy, ... 'Fx',DAE.Fx, ... 'Fy',DAE.Fy, ... 'Gx',DAE.Gx, ... 'Ploss',sum(Bus.Pg)-sum(Bus.Pl), ... 'Qloss',sum(Bus.Qg)-sum(Bus.Ql), ... 'it',1); else if Bus.n > 5000 fm_disp(['Snapshots are disabled for networks with more than 5000 ' ... 'buses.']) end if DAE.n > 5000 fm_disp(['Snapshots are disabled for networks with more than 5000 ' ... 'state variables.']) end end fm_status('pf','close') LIB.selbus = min(LIB.selbus,Bus.n); if ishandle(Fig.lib), set(findobj(Fig.lib,'Tag','Listbox1'), ... 'String',Bus.names, ... 'Value',LIB.selbus); end % ----------------------------------------------- function refreshJac global DAE DAE.g = zeros(DAE.m,1); % ----------------------------------------------- function refreshGen(nodyn) global DAE SW PV if nodyn, DAE.Fx = 1; end Fxcall(SW,'full') Fxcall(PV) % ----------------------------------------------- function inc = calcInc(nodyn,Jrow) global DAE Settings SW PV DAE.g = zeros(DAE.m,1); if Settings.distrsw % distributed slack bus fm_call('kgpf'); if nodyn, DAE.Fx = 1; end inc = -[DAE.Fx,DAE.Fy,DAE.Fk;DAE.Gx,DAE.Gy,DAE.Gk;Jrow]\ ... [DAE.f; DAE.g; DAE.y(SW.refbus)]; else % single slack bus fm_call('l'); if nodyn, DAE.Fx = 1; end Fxcall(SW,'full') Fxcall(PV) inc = -[DAE.Fx, DAE.Fy; DAE.Gx, DAE.Gy]\[DAE.f; DAE.g]; end
github
Sinan81/PSAT-master
zbuild.m
.m
PSAT-master/psat-mat/psat/zbuild.m
2,232
utf_8
19b01a90de020a329cd2a597231ecf5a
% This program forms the complex bus impedance matrix by the method % of building algorithm. Bus zero is taken as reference. % Copyright (c) 1998 by H. Saadat % % Update By s.m. Shariatzadeh For Psat Data Format function [Zbus] = zbuild(linedata) nl = linedata(:,1); nr = linedata(:,2); R = linedata(:,8); X = linedata(:,9); nbr = length(linedata(:,1)); nbus = max(max(nl), max(nr)); for k=1:nbr if R(k) == inf || X(k) == inf R(k) = 99999999; X(k) = 99999999; end end ZB = R + j*X; Zbus = zeros(nbus, nbus); tree = 0; %%%%new % Adding a branch from a new bus to reference bus 0 for I = 1:nbr ntree(I) = 1; if nl(I) == 0 || nr(I) == 0 if nl(I) == 0 n = nr(I); elseif nr(I) == 0 n = nl(I); end if abs(Zbus(n, n)) == 0 Zbus(n,n) = ZB(I); tree = tree + 1; %%new else Zbus(n,n) = Zbus(n,n)*ZB(I)/(Zbus(n,n) + ZB(I)); end ntree(I) = 2; end end Zbus % Adding a branch from new bus to an existing bus while tree < nbus %%% new for n = 1:nbus nadd = 1; if abs(Zbus(n,n)) == 0 for I = 1:nbr if nadd == 1; if nl(I) == n || nr(I) == n if nl(I) == n k = nr(I); elseif nr(I) == n k = nl(I); end %if abs(Zbus(k,k)) ~= 0 for m = 1:nbus if m ~= n Zbus(m,n) = Zbus(m,k); Zbus(n,m) = Zbus(m,k); end end Zbus(n,n) = Zbus(k,k) + ZB(I); tree=tree+1; %%new nadd = 2; ntree(I) = 2; %else, end end end end end end end %%%%%%new % Adding a link between two old buses for n = 1:nbus for I = 1:nbr if ntree(I) == 1 if nl(I) == n || nr(I) == n if nl(I) == n k = nr(I); elseif nr(I) == n k = nl(I); end DM = Zbus(n,n) + Zbus(k,k) + ZB(I) - 2*Zbus(n,k); for jj = 1:nbus AP = Zbus(jj,n) - Zbus(jj,k); for kk = 1:nbus AT = Zbus(n,kk) - Zbus(k, kk); DELZ(jj,kk) = AP*AT/DM; end end Zbus = Zbus - DELZ; ntree(I) = 2; end end end end
github
Sinan81/PSAT-master
fm_cpf.m
.m
PSAT-master/psat-mat/psat/fm_cpf.m
20,934
utf_8
67a099a64227616d14b66c993400bf73
function lambda_crit = fm_cpf(fun) % FM_CPF continuation power flow routines for computing nose curves % and determining critical points (saddle-node bifurcations) % % [LAMBDAC] = FM_CPF % % LAMBDAC: loading paramter at critical or limit point % %see also CPF structure and FM_CPFFIG % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 16-Sep-2003 %Version: 1.0.1 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano fm_var global Settings if ~autorun('Continuation Power Flow',0), return, end lambda_crit = []; lastwarn('') % Settings if CPF.ilim ilim = CPF.flow; else ilim = 0; end type = double(~CPF.sbus); if type && SW.n == 1 && Supply.n == 1 if Supply.bus ~= SW.bus fm_disp(' * * ') fm_disp('Only one Supply found. Single slack bus model will be used.') type = 0; end end stop = CPF.type - 1; vlim = CPF.vlim; qlim = CPF.qlim; perp = ~(CPF.method - 1); hopf = 1; if strcmp(fun,'atc') || strcmp(fun,'gams') one = 1; else one = 0; end %if PV.n+SW.n == 1, type = 0; end if CPF.show fm_disp if type fm_disp('Continuation Power Flow - Distribuited Slack Bus') else fm_disp('Continuation Power Flow - Single Slack Bus') end fm_disp(['Data file "',Path.data,File.data,'"']) fm_disp if perp fm_disp('Corrector Method: Perpendicular Intersection') else fm_disp('Corrector Method: Local Parametrization') end if vlim fm_disp('Check Voltage Limits: Yes') else fm_disp('Check Voltage Limits: No') end if qlim fm_disp('Check Generator Q Limits: Yes') else fm_disp('Check Generator Q Limits: No') end if ilim fm_disp('Check Flow Limits: Yes') else fm_disp('Check Flow Limits: No') end fm_disp end % Initializations of vectors and matrices % ---------------------------------------------------------------------- % disable conversion to impedance for PQ loads forcepq = Settings.forcepq; Settings.forcepq = 1; nodyn = 0; % initialization of the state vector and Jacobian matices if DAE.n > 0 DAE.f = ones(DAE.n,1); % state variable time derivatives fm_xfirst; DAE.Fx = sparse(DAE.n,DAE.n); % Dx(f) DAE.Fy = sparse(DAE.n,DAE.m); % Dy(f) DAE.Gx = sparse(DAE.m,DAE.n); % Dx(g) DAE.Fl = sparse(DAE.n,1); DAE.Fk = sparse(DAE.n,1); else % no dynamic components nodyn = 1; DAE.n = 1; DAE.f = 0; DAE.x = 0; DAE.Fx = 1; DAE.Fy = sparse(1,DAE.m); DAE.Gx = sparse(DAE.m,1); DAE.Fl = 0; DAE.Fk = 0; end PV2PQ = Settings.pv2pq; noDem = 0; noSup = 0; sp = ' * '; Settings.pv2pq = 0; Imax = getflowmax(Line,ilim); switch ilim case 1, fw = 'I '; case 2, fw = 'P '; case 3, fw = 'S '; end if CPF.areaannualgrowth, growth(Areas,'area'), end if CPF.regionannualgrowth, growth(Regions,'region'), end % if no Demand.con is found, the load direction % is assumed to be the one of the PQ load if Demand.n no_dpq = findzero(Demand); if ~isempty(no_dpq), fm_disp for i = 1:length(no_dpq) fm_disp(['No power direction found in "Demand.con" for Bus ', ... Bus.names{Demand.bus(no_dpq(i))}]) end fm_disp('Continuation load flow routine may have convergence problems.',2) fm_disp end else noDem = 1; idx = findpos(PQ); Demand = add(Demand,dmdata(PQ,idx)); PQ = pqzero(PQ,idx); end PQgen = pqzero(PQgen,'all'); % if no Supply.con is found, the load direction % is assumed to be the one of the PV or the SW generator if Supply.n && ~Syn.n no_sp = findzero(Supply); if ~isempty(no_sp), fm_disp if length(no_sp) == Supply.n fm_disp(['No power directions found in "Supply.con" for all buses.']) if noDem fm_disp('Supply data will be ignored.') noSup = 1; Supply = remove(Supply,[1:Supply.n]); if qlim && type, SW = move2sup(SW); end %SW = move2sup(SW); %PV = move2sup(PV); else fm_disp('Remove "Supply" components or set power directions.') fm_disp('Continuation power flow interrupted',2) if CPF.show set(Fig.main,'Pointer','arrow'); end return end else for i = 1:length(no_sp) fm_disp(['No power direction found in "Supply.con" for Bus ', ... Bus.names{Supply.bus(no_sp(i))}]) end fm_disp('Continuation power flow routine may have convergence problems.',2) fm_disp end end else noSup = 1; Supply = remove(Supply,[1:Supply.n]); if qlim && type, SW = move2sup(SW); end end % Newton-Raphson routine settings iter_max = Settings.lfmit; iterazione = 0; tol = CPF.tolc; tolf = CPF.tolf; tolv = CPF.tolv; proceed = 1; sigma_corr = 1; if DAE.n == 0, DAE.n = 1; end Kjac = sparse(1,DAE.m+DAE.n+2); Ljac = sparse(1,DAE.m+DAE.n+2); kjac = sparse(1,DAE.m+DAE.n+1); Kjac(1,DAE.n+SW.refbus) = 1; kjac(1,DAE.n+SW.refbus) = 1; % chose a PQ to display the CPF progress in the main window PQidx = pqdisplay(PQ); fm_snap('cleansnap') if ~PQidx % absence of PQ buses PQidx = pqdisplay(Demand); if ~PQidx if ~perp perp = 1; fm_disp('* * * Switch to perpendicular intersection * * * ') end PQidx = 1; end end PQvdx = PQidx + Bus.n; % --------------------------------------------------------------------- % Continuation Power Flow Routine % --------------------------------------------------------------------- tic fm_status('cpf','init',12,{'m'},{'-'},{Theme.color11},[0 1.2]) l_vect = []; lambda = CPF.linit; DAE.lambda = lambda; lambda_crit = CPF.linit; kg = 0; lambda_old = -1; Jsign = 0; Jsign_old = 0; Sflag = 1; ksign = 1; Qmax_idx = []; Qmin_idx = []; Vmax_idx = []; Vmin_idx = []; Iij_idx = []; Iji_idx = []; Iij = ones(Line.n,1); Iji = ones(Line.n,1); Qswmax_idx = []; Qswmin_idx = []; pqlim(PQ,vlim,0,0,0); fm_out(0,0,0) if nodyn DAE.Fx = 1; Varout.idx = Varout.idx+1; end fm_out(1,0,0) % initial Jacobian Gk DAE.Gk = sparse(DAE.m,1); if type, Gkcall(Supply), end if type, Gkcall(PV), end Gkcall(SW) DAE.kg = 0; Gycall(Line) if noSup Gyreactive(PV) else Gycall(PV) end Gyreactive(SW) % First predictor step % --------------------------------------------------------------- Jsign = 1; count_qmin = 0; kqmin = 1; d_lambda = 0; lambda_old = CPF.linit; inc = zeros(DAE.n+DAE.m+2,1); Ljac(end) = 1; % critical point y_crit = DAE.y; x_crit = DAE.x; k_crit = kg; l_crit = lambda; while 1 cpfmsg = []; % corrector step % --------------------------------------------------------------- lim_hb = 0; lim_lib = 0; y_old = DAE.y; x_old = DAE.x; kg_old = kg; lambda_old = lambda; corrector = 1; if PV.n, inc(DAE.n+getbus(PV,'v')) = 0; end if SW.n, inc(DAE.n+getbus(SW,'v')) = 0; end while corrector if ishandle(Fig.main) if ~get(Fig.main,'UserData'), break, end end iter_corr = 0; Settings.error = tol+1; while Settings.error > tol if (iter_corr > iter_max), break, end if ishandle(Fig.main) if ~get(Fig.main,'UserData'), break, end end DAE.lambda = lambda; DAE.Fl = sparse(DAE.n,1); DAE.Gl = sparse(DAE.m,1); DAE.Gk = sparse(DAE.m,1); % call component functions fm_call('kg') if nodyn, DAE.Fx = 1; end gcall(PQgen) glambda(Demand,lambda) glambda(Supply,lambda,type*kg) glambda(Syn,lambda,kg) glambda(Tg,lambda,kg) Glcall(Pl) Glcall(Mn) Glcall(Demand) Glcall(Supply) Glcall(Syn) Glcall(Tg) Glcall(Wind) Flcall(Ind) if type, Gkcall(Supply), end if noSup glambda(PV,lambda,type*kg) glambda(SW,lambda,kg) greactive(PV) if type, Gkcall(PV), end Glcall(PV) Gyreactive(PV) Glcall(SW) else gcall(PV); Gycall(PV) glambda(SW,1,kg) end Glreac(PV) Fxcall(PV) Gkcall(SW) greactive(SW) Gyreactive(SW) Glreac(SW) Fxcall(SW,'onlyq') if perp*iterazione Cinc = sigma_corr*inc; %cont_eq = Cinc'*([DAE.x;DAE.y;kg;lambda]- ... % [x_old; y_old; kg_old; lambda_old]-Cinc); Cinc(end-1) = 0; cont_eq = Cinc'*([DAE.x;DAE.y;0;lambda]- ... [x_old; y_old; 0; lambda_old]-Cinc); inc_corr = -[DAE.Fx, DAE.Fy, DAE.Fk, DAE.Fl; DAE.Gx, DAE.Gy, ... DAE.Gk, DAE.Gl; Cinc'; Kjac]\[DAE.f; DAE.g; ... cont_eq; DAE.y(SW.refbus)]; if strcmp(lastwarn,['Matrix is singular to working ' ... 'precision.']) Cinc(end) = 0; cont_eq = Cinc'*([DAE.x;DAE.y;0;0]- ... [x_old; y_old; 0; 0]-Cinc); inc_corr = -[DAE.Fx, DAE.Fy, DAE.Fk, DAE.Fl; DAE.Gx, DAE.Gy, ... DAE.Gk, DAE.Gl; Cinc'; Kjac]\[DAE.f; DAE.g; ... cont_eq; DAE.y(SW.refbus)]; end else if iterazione cont_eq = DAE.y(PQvdx)-sigma_corr*inc(PQvdx+DAE.n)-y_old(PQvdx); else cont_eq = lambda - sigma_corr*d_lambda - lambda_old; end inc_corr = -[DAE.Fx, DAE.Fy, DAE.Fk, DAE.Fl; DAE.Gx, DAE.Gy, ... DAE.Gk, DAE.Gl; Ljac; Kjac]\[DAE.f; DAE.g; ... cont_eq; DAE.y(SW.refbus)]; end DAE.x = DAE.x + inc_corr(1:DAE.n); DAE.y = DAE.y + inc_corr(1+DAE.n:DAE.m+DAE.n); kg = kg + inc_corr(end-1); %[xxx,iii] = max(abs(inc_corr)); %disp([xxx,iii]) lambda = lambda + inc_corr(end); iter_corr = iter_corr + 1; Settings.error = max(abs(inc_corr)); end % Generator reactive power computations if qlim DAE.g = zeros(DAE.m,1); fm_call('load'); glambda(Demand,lambda) Bus.Ql = DAE.g(Bus.v); fm_call('gen'); glambda(Demand,lambda) Bus.Qg = DAE.g(Bus.v); DAE.g = zeros(DAE.m,1); [Qmax_idx,Qmin_idx] = pvlim(PV); [Qswmax_idx,Qswmin_idx] = swlim(SW); if ~kqmin Qmin_idx = []; Qswmin_idx = []; end end [PQ,lim_v] = pqlim(PQ,vlim,sp,lambda,one); if lim_v sigma_corr = 1; proceed = 1; if stop > 1 sigma_corr = -1; break end end if ilim [Fij,Fji] = flows(Line,ilim); Iij_idx = find(Fij > Imax & Iij); Iji_idx = find(Fji > Imax & Iji); end % determination of the initial loading factor in case % of infeasible underexcitation of generator at zero % load condition if ~iterazione && qlim && ~isempty(Qmin_idx) && count_qmin <= 5 count_qmin = count_qmin+1; if count_qmin > 5 fm_disp([sp,'There are generator Qmin limit violations at ' ... 'the initial point.']) fm_disp([sp,'Generator Qmin limits will be disabled.']) kqmin = 0; lambda_old = CPF.linit; lambda = CPF.linit; sigma_corr = 1; else lambda_old = lambda_old + d_lambda; fm_disp([sp,'Initial loading parameter changed to ', ... fvar(lambda_old-one,4)]) end proceed = 0; break end % Check for Hopf Bifurcations if DAE.n >= 2 && CPF.hopf && hopf As = DAE.Fx-DAE.Fy*(DAE.Gy\DAE.Gx); if DAE.n > 100 opt.disp = 0; auto = eigs(As,20,'SR',opt); else auto = eig(full(As)); end auto = round(auto/Settings.lftol)*Settings.lftol; hopf_idx = find(real(auto) > 0); if ~isempty(hopf_idx) hopf = 0; hopf_idx = find(abs(imag(auto(hopf_idx))) > 1e-5); if ~isempty(hopf_idx) lim_hb = 1; fm_disp([sp,'Hopf bifurcation encountered.']) end if stop sigma_corr = -1; break end end end if ~isempty(Iij_idx) && ilim Iij_idx = Iij_idx(1); Iij(Iij_idx) = 0; fm_disp([sp,fw,'from bus #',fvar(Line.fr(Iij_idx),4), ... ' to bus #',fvar(Line.to(Iij_idx),4), ... ' reached I_max at lambda = ',fvar(lambda-one,9)],1) sigma_corr = 1; proceed = 1; if stop > 1 proceed = 1; sigma_corr = -1; break end end if ~isempty(Iji_idx) && ilim Iji_idx = Iji_idx(1); Iji(Iji_idx) = 0; fm_disp([sp,fw,'from bus #',fvar(Line.to(Iji_idx),4), ... ' to bus #',fvar(Line.fr(Iji_idx),4), ... ' reached I_max at lambda = ',fvar(lambda-one,9)],1) sigma_corr = 1; proceed = 1; if stop > 1 proceed = 1; sigma_corr = -1; break end end if lambda < CPF.linit cpfmsg = [sp,'lambda is lower than initial value']; if iterazione > 5 proceed = 0; break end end if abs(lambda-lambda_old) > 5*abs(d_lambda) && perp && iterazione ... && ~Hvdc.n fm_disp([sp,'corrector solution is too far from predictor value']) proceed = 0; break end if lambda > lambda_old && lambda < max(l_vect) && ~Hvdc.n fm_disp([sp,'corrector goes back increasing lambda']) proceed = 0; break end lim_q = (~isempty(Qmax_idx) || ~isempty(Qmin_idx) || ... (~isempty(Qswmax_idx) || ~isempty(Qswmin_idx))*type) && qlim; lim_i = (~isempty(Iij_idx) || ~isempty(Iji_idx)) && ilim; anylimit = (lim_q || lim_v || lim_i) && CPF.stepcut; if iter_corr > iter_max % no convergence if lambda_old < 0.5*max(l_vect) fm_disp([sp,'Convergence problems in the unstable curve']) lambda = -1; proceed = 1; break end if sigma_corr < 1e-3 proceed = 1; break end if CPF.show fm_disp([sp,'Max # of iters. at corrector step.']) fm_disp([sp,'Reduced Variable Increments in ', ... 'Corrector Step ', num2str(0.5*sigma_corr)]) end cpfmsg = [sp,'Reached maximum number of iterations ', ... 'for corrector step.']; proceed = 0; break elseif anylimit && sigma_corr > 0.11 proceed = 0; break elseif lim_q if ~isempty(Qmax_idx) PQgen = add(PQgen,pqdata(PV,Qmax_idx(1),'qmax',sp,lambda,one,noSup)); if noSup, PV = move2sup(PV,Qmax_idx(1)); else PV = remove(PV,Qmax_idx(1)); end elseif ~isempty(Qmin_idx) PQgen = add(PQgen,pqdata(PV,Qmin_idx(1),'qmin',sp,lambda,one,noSup)); if noSup PV = move2sup(PV,Qmin_idx(1)); else PV = remove(PV,Qmin_idx(1)); end elseif ~isempty(Qswmax_idx) PQgen = add(PQgen,pqdata(SW,Qswmax_idx(1),'qmax',sp,lambda,one)); SW = remove(SW,Qswmax_idx(1)); elseif ~isempty(Qswmin_idx) PQgen = add(PQgen,pqdata(SW,Qswmin_idx(1),'qmin',sp,lambda,one)); SW = remove(SW,Qswmin_idx(1)); end lim_lib = 1; Qmax_idx = []; Qmin_idx = []; Qswmax_idx = []; Qswmin_idx = []; if ~iterazione d_lambda = 0; lambda_old = CPF.linit; lambda = CPF.linit; if perp inc(end) = 1e-5; else Ljac(end) = 1; end else lambda = lambda_old; sigma_corr = 1; proceed = 0; break end else proceed = 1; sigma_corr = 1; if stop && ksign < 0, if lim_lib fm_disp([sp,'Saddle-Node Bifurcation encountered.']) else fm_disp([sp,'Limit-Induced Bifurcation encountered.']) end sigma_corr = -1; end break end end switch proceed case 1 if lambda < 0 && iterazione > 1 % needed to make consistent the last snapshot fm_call('kg') gcall(PQgen) fm_disp([sp,'lambda < 0 at iteration ',num2str(iterazione)]) break end l_vect = [l_vect; lambda]; if CPF.show fm_disp(['Point = ',fvar(iterazione+1,5),'lambda =', ... fvar(lambda-one,9), ' kg =',fvar(kg,9)],1) end iterazione = iterazione + 1; fm_out(2,lambda,iterazione) fm_status('cpf','update',[lambda, DAE.y(PQvdx)],iterazione) if sigma_corr < tol, break, end sigma_corr = 1; if lambda > lambda_old y_crit = DAE.y; x_crit = DAE.x; k_crit = kg; l_crit = lambda; end case 0 DAE.y = y_old; DAE.x = x_old; if abs(lambda-CPF.linit) < 0.001 && ... abs(lambda-lambda_old) <= 10*abs(d_lambda) && ... iterazione > 1 fm_disp([sp,'Reached initial lambda.']) % needed to make consistent the last snapshot fm_call('kg') gcall(PQgen) break end kg = kg_old; lambda = lambda_old; sigma_corr = 0.1*sigma_corr; if sigma_corr < tol, if ~isempty(cpfmsg) fm_disp(cpfmsg) end if iterazione == 0 fm_disp([sp,'Infeasible initial loading condition.']) else fm_disp([sp,'Convergence problem encountered.']) end break end end % stop routine % -------------------------------------------------------------- if iterazione >= CPF.nump && ~strcmp(fun,'gams') fm_disp([sp,'Reached maximum number of points.']) break end if ishandle(Fig.main) if ~get(Fig.main,'UserData'), break, end end % predictor step % -------------------------------------------------------------- DAE.lambda = lambda; % update Jacobians fm_call('kg') if nodyn, DAE.Fx = 1; end if noSup Gyreactive(PV) else Gycall(PV); end Gyreactive(SW) if (DAE.m+DAE.n) > 500 [L,U,P] = luinc([DAE.Fx,DAE.Fy,DAE.Fk;DAE.Gx,DAE.Gy,DAE.Gk;kjac],1e-6); else [L,U,P] = lu([DAE.Fx,DAE.Fy,DAE.Fk;DAE.Gx,DAE.Gy,DAE.Gk;kjac]); end dz_dl = -U\(L\(P*[DAE.Fl;DAE.Gl;0])); Jsign_old = Jsign; Jsign = signperm(P)*sign(prod(diag(U))); if lim_lib fm_snap('assignsnap','new','LIB',lambda) elseif lim_hb fm_snap('assignsnap','new','HB',lambda) end if iterazione == 1 if noDem && lambda == 1 fm_snap('assignsnap','start','OP',lambda) elseif ~noDem && lambda == 0 fm_snap('assignsnap','start','OP',lambda) else fm_snap('assignsnap','start','Init',lambda) end end if Jsign ~= Jsign_old && Sflag && iterazione > 1 ksign = -1; Sflag = 0; if ~lim_lib, fm_snap('assignsnap','new','SNB',lambda), end end Norm = norm(dz_dl,2); if Norm == 0, Norm = 1; end d_lambda = ksign*CPF.step/Norm; d_lambda = min(d_lambda,0.35); d_lambda = max(d_lambda,-0.35); if ksign > 0, d_lambda = max(d_lambda,0); end if ksign < 0, d_lambda = min(d_lambda,0); end d_z = d_lambda*dz_dl; inc = [d_z; d_lambda]; if ~perp && iterazione a = inc(DAE.n+PQvdx); a = min(a,0.025); a = max(a,-0.025); inc(DAE.n+PQvdx) = a; Ljac(end) = 0; Ljac(DAE.n+PQvdx) = 1; end end fm_out(3,0,iterazione) fm_snap('assignsnap','new','End',Varout.t(end)) [lambda_crit, idx_crit] = max(Varout.t); if isnan(lambda_crit), lambda_crit = lambda; end if isempty(lambda_crit), lambda_crit = lambda; end if CPF.show fm_disp([sp,'Maximum Loading Parameter lambda_max = ', ... fvar(lambda_crit-one,9)],1) end % Visualization of results % -------------------------------------------------------------- if nodyn DAE.n = 0; Varout.idx = Varout.idx-1; end Settings.lftime = toc; Settings.iter = iterazione; DAE.y = y_crit; DAE.x = x_crit; kg = k_crit; lambda = l_crit; if ~isempty(DAE.y) if CPF.show fm_disp(['Continuation Power Flow completed in ', ... num2str(toc),' s'],1); end DAE.g = zeros(DAE.m,1); fm_call('load'); glambda(Demand,lambda) % load powers Bus.Pl = DAE.g(Bus.a); Bus.Ql = DAE.g(Bus.v); % gen powers fm_call('gen') Bus.Qg = DAE.g(Bus.a); Bus.Pg = DAE.g(Bus.v); DAE.g = Settings.error*ones(DAE.m,1); if (Settings.showlf == 1 && CPF.show) || ishandle(Fig.stat) SDbus = [Supply.bus;Demand.bus]; report = cell(1,1); report{1,1} = ['Lambda_max = ', fvar(lambda_crit,9)]; %for i = 1:length(dl_dp) % report{2+i,1} = ['d lambda / d P ', ... % Bus.names{SDbus(i)},' = ', ... % fvar(dl_dp(i),9)]; %end fm_stat(report); end if CPF.show && ishandle(Fig.plot) fm_plotfig end end % Reset of SW, PV and PQ structures Settings.forcepq = forcepq; %PQgen = restore(PQgen,0); %PQ = restore(PQ); %PV = restore(PV); %SW = restore(SW); Demand = restore(Demand); Supply = restore(Supply); if CPF.show && ishandle(Fig.main) set(Fig.main,'Pointer','arrow'); Settings.xlabel = ['Loading Parameter ',char(92),'lambda (p.u.)']; Settings.tf = 1.2*lambda_crit; end fm_status('cpf','close') Settings.pv2pq = PV2PQ; CPF.lambda = lambda_crit; CPF.kg = kg; fm_snap('viewsnap',0) SNB.init = 0; LIB.init = 0; CPF.init = 1; OPF.init = 0; % -------------------------------- function s = signperm(P) % -------------------------------- [i,j,p] = find(sparse(P)); idx = find(i ~= j); q = P(idx,idx); s = det(q);
github
Sinan81/PSAT-master
fm_equiv.m
.m
PSAT-master/psat-mat/psat/fm_equiv.m
9,133
utf_8
a08056932461730a6e5193ea2c7daa9e
function check = fm_equiv % FM_EQUIV computes simple static and dynamic network equivalents % %see also the function FM_EQUIVFIG % %Author: Federico Milano %Update: 02-Apr-2008 %Version: 0.1 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global EQUIV Settings Path File DAE Bus global Line PQ Shunt PV SW Syn Exc Pl Mn check = 0; if ~autorun('Network Equivalent',1) return end fm_disp(' ') switch EQUIV.equivalent_method case 1 fm_disp('Equivalencing procedure. Thevenin equivalents.') case 2 fm_disp('Equivalencing procedure. Dynamic equivalents.') otherwise fm_disp('Error: Unknown equivalencing procedure.',2) return end % define the bus list write_buslist if isempty(EQUIV.buslist) fm_disp('Error: There were problems in writing the bus list selection.',2) return end if EQUIV.island && EQUIV.stop_island fm_disp('Error: The equivalent procedure cannot continue',2) return end % check equivalent method consistency %if ~DAE.n && EQUIV.equivalent_method == 2 % fm_disp('The network does not contain dynamic data.') % fm_disp('Thevenin equivalent method will be used.') % EQUIV.equivalent_method = 1; %end % open data file for the equivalent network cd(Path.data) jobname = strrep(File.data,'(mdl)',''); fid = fopen([jobname,'_equiv.m'],'wt'); % headers fprintf(fid,['%% ',jobname,' (Equivalent network created by EQUIV)\n']); fprintf(fid,'%%\n\n'); % restore static data that can have been modified during power flow. SW = restore(SW); PV = restore(PV); PQ = restore(PQ); Pl = restore(Pl); Mn = restore(Mn); Settings.init = 0; % write data write(Bus,fid,EQUIV.buslist) write(Line,fid,EQUIV.buslist) write(PQ,fid,EQUIV.buslist,'PQ') write(Pl,fid,EQUIV.buslist) write(Mn,fid,EQUIV.buslist) write(Shunt,fid,EQUIV.buslist) slack = write(SW,fid,EQUIV.buslist); slack = write(PV,fid,EQUIV.buslist,slack); [borderbus,gengroups,yi,y0,zth] = equiv(Line,fid); synidx = write(Syn,fid,EQUIV.buslist); write(Exc,fid,synidx,0); xbus = borderbus + Bus.n; nborder = length(borderbus); % write external buses Buseq = BUclass; Buseq.con = Bus.con(borderbus,:); Buseq.con(:,1) = xbus; Buseq.names = fm_strjoin('X',Bus.names(borderbus)); write(Buseq,fid,1:length(Buseq.names)) [idx1,idx2,busidx1,busidx2] = filter(Line,EQUIV.buslist); beq = zeros(length(EQUIV.buslist),1); peq = beq; qeq = beq; for i = 1:length(busidx1) [Pij,Qij,Pji,Qji] = flows(Line,'pq',idx1{i}); h = busidx1(i); beq(h) = EQUIV.buslist(h); peq(h) = -sum(Pij); qeq(h) = -sum(Qij); end for i = 1:length(busidx2) [Pij,Qij,Pji,Qji] = flows(Line,'pq',idx2{i}); h = busidx2(i); beq(h) = EQUIV.buslist(h); peq(h) = peq(h)-sum(Pji); qeq(h) = qeq(h)-sum(Qji); end ieq = find(beq); beq = beq(ieq); peq = peq(ieq); qeq = qeq(ieq); zth = zth(ieq); % take into account that the REI equivalent add a shunt load at the border if EQUIV.equivalent_method == 2 vbd = DAE.y(borderbus + Bus.n); vb2 = vbd.*vbd; peq = peq-real(y0).*vb2; % qeq = qeq-imag(y0).*vb2; end % compute and write synchronous machine equivalents if EQUIV.equivalent_method == 2 && Syn.n Syneq = SYclass; [Syneq.con,pf] = equiv(Syn,borderbus,gengroups,yi); % discard generators that are producing negative active power gdx = find(peq > 1e-3); if ~isempty(gdx) % synchronous machines bdx = find(ismember(Syneq.con(:,1),beq(gdx)+Bus.n)); Syneq.con = Syneq.con(bdx,:); Syneq.bus = Syneq.con(:,1); nsyn = length(Syneq.bus); Syneq.u = ones(nsyn,1); Syneq.n = nsyn; write(Syneq,fid,xbus); % automatic voltage regulators AVReq = AVclass; AVReq.con = equiv(Exc,gengroups(gdx),pf(bdx),length(synidx)); AVReq.syn = AVReq.con(:,1); AVReq.n = length(AVReq.syn); AVReq.u = ones(AVReq.n,1); write(AVReq,fid,AVReq.syn,length(synidx)); end end % write slack bus data if needed if ~slack [pmax,h] = max(abs(peq)); [v,a,p] = veq(zth(h),peq(h),qeq(h),beq(h)); data = [beq(h)+Bus.n,Settings.mva,getkv(Bus,beq(h),1),v,a,0,0,1.1,0.9,p,1,1,1]; SWeq = SWclass; SWeq.con = data; SWeq.bus = beq(h)+Bus.n; SWeq.n = 1; SWeq.u = 1; slack = write(SWeq,fid,beq(h)+Bus.n); beq(h) = []; peq(h) = []; qeq(h) = []; end % write equivalent PV or PQ generators at external buses xbeq = beq+Bus.n; switch EQUIV.gentype case 1 data = zeros(length(beq),11); for h = 1:length(beq) [v,a,p,q] = veq(zth(h),peq(h),qeq(h),beq(h)); data(h,:) = [xbeq(h),Settings.mva,getkv(Bus,beq(h),1),p,v,0,0,1.1,0.9,1,1]; end PVeq = PVclass; PVeq.con = data; PVeq.bus = xbeq; PVeq.n = length(beq); PVeq.u = ones(length(beq),1); write(PVeq,fid,xbeq,slack); case 2 data = zeros(length(beq),9); pdx = []; for h = 1:length(beq) [v,a,p,q] = veq(zth(h),peq(h),qeq(h),beq(h)); data(h,:) = [xbeq(h),Settings.mva,getkv(Bus,beq(h),1),p,q,1.1,0.9,1,1]; if abs(p) < 1e-3 && abs(q) < 1e-3 pdx = [pdx; h]; end end PQeq = PQclass; if ~isempty(pdx) data(pdx,:) = []; xbeq(pdx) = []; end PQeq.con = data; PQeq.bus = xbeq; PQeq.n = length(xbeq); PQeq.u = ones(length(xbeq),1); write(PQeq,fid,xbeq,'PQgen'); end % close file fclose(fid); cd(Path.local) % everything ok check = 1; % ------------------------------------------------------------------------- % This function returns the indexes of the current bus list % ------------------------------------------------------------------------- function write_buslist global EQUIV Line Bus Path File EQUIV.buslist = []; switch EQUIV.bus_selection case 1 % voltage level buslist = find(getkv(Bus,0,0) == EQUIV.bus_voltage); if isempty(buslist) disp(['There is no bus whose nominal voltage is ', ... num2str(EQUIV.bus_voltage)]) return end case 2 % area buslist = find(getarea(Bus,0,0) == EQUIV.area_num); if isempty(buslist) disp(['There is no bus whose nominal voltage is >= ', ... num2str(EQUIV.bus_voltage)]) return end case 3 % region buslist = find(getregion(Bus,0,0) == EQUIV.region_num); if isempty(buslist) disp(['There is no bus whose nominal voltage is >= ', ... num2str(EQUIV.bus_voltage)]) return end case 4 % voltage threshold buslist = find(getkv(Bus,0,0) >= EQUIV.bus_voltage); if isempty(buslist) disp(['There is no bus whose nominal voltage is >= ', ... num2str(EQUIV.bus_voltage)]) return end case 5 % custom bus list if isempty(EQUIV.custom_file) disp('Warning: No bus list file selected!') end [fid,msg] = fopen([EQUIV.custom_path,EQUIV.custom_file],'rt'); if fid == -1 disp(msg) disp('An empty bus list is returned.') return end % scanning bus list file buslist = []; while ~feof(fid) busname = deblank(fgetl(fid)); buslist = [buslist; strmatch(busname,Bus.names,'exact')]; end if isempty(buslist) disp('There is no bus whose name matches the given bus list.') return end otherwise disp('Unkonwn bus selection type. Empty bus list is returned.') end % removing repetitions buslist = unique(buslist); % bus depth nd = EQUIV.bus_depth; % line indexes busfr = Line.fr; busto = Line.to; idxLd = [busfr; busto]; idxLq = [busto; busfr]; % bus search newbus = []; for i = 1:length(buslist) busi = buslist(i); newbus = [newbus; searchbus(nd,busi,idxLd,idxLq)]; end % removing repetions again if ~isempty(newbus) buslist = unique([buslist; newbus]); end % check equivalent network connectivity Bn = length(buslist); Busint(buslist,1) = [1:Bn]; busmax = length(Busint); idxL = find(ismember(busfr,buslist).*ismember(busto,buslist)); Lfr = Busint(busfr(idxL)); Lto = Busint(busto(idxL)); u = Line.u(idxL); % connectivity matrix connect_mat = ... sparse(Lfr,Lfr,1,Bn,Bn) + ... sparse(Lfr,Lto,u,Bn,Bn) + ... sparse(Lto,Lto,u,Bn,Bn) + ... sparse(Lto,Lfr,1,Bn,Bn); % find network islands using QR factorization [Q,R] = qr(connect_mat); idx = find(abs(sum(R,2)-diag(R)) < 1e-5); nisland = length(idx); if nisland > 1 disp(['There are ',num2str(nisland),' islanded networks.']) EQUIV.island = nisland; else disp(['The equivalent network is interconnected.']) end EQUIV.buslist = buslist; % ------------------------------------------------------------------------- % recursive bus search up to the desired depth % ------------------------------------------------------------------------- function newbus = searchbus(nd,busi,idxLd,idxLq) newbus = []; if ~nd, return, end idx = find(idxLd == busi); if ~isempty(idx) newbus = idxLq(idx); for i = 1:length(newbus) newbus = [newbus; searchbus(nd-1,newbus(i),idxLd,idxLq)]; end end % ------------------------------------------------------------------------- % compute the voltage and power at the recieving end of external lines % ------------------------------------------------------------------------- function [v,a,p,q] = veq(zth,peq,qeq,idx) global DAE Bus if isempty(zth), return, end v1 = DAE.y(Bus.n+idx)*exp(i*DAE.y(idx)); i21 = (peq-i*qeq)/conj(v1); v2 = v1 + zth*i21; s = v2*conj(i21); p = real(s); q = imag(s); v = abs(v2); a = angle(v2);
github
Sinan81/PSAT-master
fm_omib.m
.m
PSAT-master/psat-mat/psat/fm_omib.m
4,162
utf_8
a81e5e2bc6cd41fce6a83f298b64f4b2
function fm_omib %FM_OMIB computes the equivalent OMIB for a multimachine network and its % transient stability margin. % % see also FM_INT and FM_CONNECTIVITY % %Author: Sergio Mora & Federico Milano %Date: July 2006 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2006 Segio Mora & Federico Milano global OMIB Line Bus Syn DAE jay % ------------------------------------------------------------------------- % initial conditions % ------------------------------------------------------------------------- [gen,ib] = setdiff(getbus(Syn),Bus.island); Pm = getvar(Syn,ib,'pm'); ang = getvar(Syn,ib,'delta'); omega = getvar(Syn,ib,'omega'); M = getvar(Syn,ib,'M'); to = 0; do = sum(M.*ang)/sum(M); wo = sum(M.*omega)/sum(M)-1; E = getvar(Syn,ib,'e1q'); dt = 0.005; ngen = length(ib); ygen = -jay./getvar(Syn,ib,'xd1'); bgen = getbus(Syn,ib); bus0 = [1:ngen]'; nbus = Bus.n + ngen; Y11 = sparse(bus0, bus0, ygen, ngen, ngen); Y21 = sparse(bgen, bus0, -ygen, Bus.n, ngen); Y12 = sparse(bus0, bgen, -ygen, ngen, Bus.n); Yint = Y11 - Y12*[Line.Y\Y21]; % ------------------------------------------------------------------------- % sorting of rotor angles % ------------------------------------------------------------------------- [delta,pos] = sort(ang); difangle = delta(2:ngen) - delta(1:ngen-1); [difmax,idxmax] = sort(difangle,1,'descend'); m = 1; i = 1; while (m <= 5) && (m <= fix(ngen/2)) % select the m-th critical machine candidate cm = pos((idxmax(m)+1):ngen); ncm = pos(1:idxmax(m)); if ~isempty(cm) % compute the m-th equivalent OMIB data = equiv_omib(M,Pm,cm,ncm,Yint,E); % compute the critical clearing time [du,tu,margen] = critical_time(data,dt,to,do,wo); CMvec{i} = cm; NCMvec{i} = ncm; MT(i) = data(1); Pmax(i) = data(2); sig(i) = data(3); PM(i) = data(4); Pc(i) = data(5); dif(i) = difmax(m); DU(:,i) = du; TU(:,i) = tu; MAR(:,i) = margen; i = i + 1; end m = m + 1; end [mcri,i] = min(MAR); OMIB.cm = CMvec{i}; OMIB.ncm = NCMvec{i}; OMIB.mt = MT(i); OMIB.pmax = Pmax(i); OMIB.pc = Pc(i); OMIB.sig = sig(i); OMIB.du = DU(i); OMIB.tu = TU(i); OMIB.margin = MAR(i); % ------------------------------------------------------------------------- function data = equiv_omib(M,Pm,cm,ncm,Y,E) Mc = sum(M(cm)); Mn = sum(M(ncm)); Pc = (Mn*([E(cm)]'*[real(Y(cm,cm))*E(cm)]) - ... Mc*([E(ncm)]'*[real(Y(ncm,ncm))*E(ncm)]))/(Mc+Mn); PM = (Mn*sum(Pm(cm))-Mc*sum(Pm(ncm)))/(Mc+Mn); M = (Mc*Mn)/(Mc+Mn); EE = [E(cm)]'*[Y(cm,ncm)*E(ncm)]; V = ((Mc-Mn)*real(EE))/(Mc+Mn)+j*imag(EE); sig = -angle(V); Pmax = abs(V); data = [M,Pmax,sig,PM,Pc]; disp(data) % ------------------------------------------------------------------------- function [deltau,omegau,margin] = critical_time(data,dt,to,delta0,omega0) global Settings Wb = 2*pi*Settings.freq; iter_max = Settings.dynmit; tol = Settings.dyntol; %Pgen = inline('d(5)+d(2)*sin(delta-d(3))','d','delta'); t = 0; tu = inf; deltau = inf; omegau = inf; Mt = data(1); Pmax = data(2); d0 = data(3); Pm = data(4); Pc = data(5); Pe_old = Pc + Pmax*sin(delta0-d0); Pa_old = Pm - Pe_old; f = zeros(2,1); f(1) = Wb*omega0; f(2) = Pa_old/Mt; fn = f; x = [delta0; omega0]; xa = x; inc = ones(2,1); k = 0; while k < 200 inc(1) = 1; h = 0; while max(abs(inc)) > tol if (h > iter_max), break, end f(1) = Wb*x(2); f(2) = (Pm - Pc - Pmax*sin(x(1)-d0))/Mt; tn = x - xa - 0.5*dt*(f+fn); inc(1) = tn(2)/(Pmax*cos(x(1)-d0)); inc(2) = -tn(1)/Wb; x = x + inc; h = h + 1; disp([h, x(1), x(2), inc(1), inc(2), f(1), f(2)]) pause end Pe = Pc + Pmax*sin(x(1)-d0); Pa = Pm - Pe; if (Pe_old > Pm) && (Pe < Pm) && ((Pa-Pa_old) > 0) deltau = 0.5*(x(1) + xa(1)); % instability condition omegau = 0.5*(x(2) + xa(2)); tu = t - dt/2; break end if (Pa < 0) && (xa(2) > 0) && (x(2) < 0) deltau = 0.5*(x(1) + xa(1)); % stability condition omegau = 0.5*(x(2) + xa(2)); tu = t - dt/2; break end xa = x; fn = f; k = k + 1; t = t + dt; end margin = -0.5*Mt*omegau*omegau;
github
Sinan81/PSAT-master
psed.m
.m
PSAT-master/psat-mat/psat/psed.m
5,198
utf_8
28f1dea3f0f86d9d7bc4f5e2e3f96903
function psed(expression,string1,string2,type) %PSED change strings within files % %PSED(EXPRESSION,STRING1,STRING2,TYPE) % EXPRESSION: regular expression % STRING1: the string to be changed. % STRING2: the new string % TYPE: 1 - change all the occurrence % 2 - change only Matlab variable type % 3 - as 2 but no file modifications % 4 - as 1 but span all subdirectories % %see also PGREP % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 18-Feb-2003 %Update: 30-Mar-2004 %Version: 1.0.2 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano if nargin < 4, disp('Check synthax ...') disp(' ') help psed, return, end if ~ischar(expression) disp('First argument (EXPRESSION) has to be a string.') return end if ~ischar(string1) || isempty(string1), disp('Second argument (STRING1) has to be a string.') return end if ~ischar(string2) disp('Third argument (STRING2) has to be a string.') return end if isempty(string2) string2 = ''; end if ~isnumeric(type) || length(type) > 1 || rem(type,1) || type > 4 || ... type <= 0 disp('Fourth argument has to be a scalar integer [1-4]') return end a = dir(expression); if isempty(a) disp('No file name matches the given expression.') return end file = {a.name}'; a = dir(pwd); names = {a.name}'; isdir = [a.isdir]'; if type == 4, disp(' ') disp('Spanning directories ...') disp(' ') disp(pwd) file = deepdir(expression,names,file,isdir,pwd); type = 1; else disp(' ') disp(pwd) end n_file = length(file); if ~n_file, disp('No matches.'), return, end tipo = type; if tipo == 3, tipo = 2; end trova = 0; try, if exist('strfind'); trova = 1; end catch % nothing to do % this is for Octave compatibility end disp(' ') disp('Scanning files ...') disp(' ') for i = 1:n_file fid = fopen(file{i}, 'rt'); n_row = 0; match = 0; while 1 && fid > 0 sline = fgetl(fid); if ~isempty(sline), if sline == -1, break; end end n_row = n_row + 1; if trova vec = strfind(sline,string1); else vec = findstr(sline,string1); end slinenew = sline; if ~isempty(vec) switch tipo case 1 match = 1; slinenew = strrep(sline,string1,string2); disp([fvar(file{i},14),' row ',fvar(int2str(n_row),5), ... ' >> ',slinenew(1:end)]) disp([' ',sline]) case 2 ok = 0; okdisp = 0; okdispl = 0; okdispr = 0; count = 0; for j = 1:length(vec) if vec(j) > 1, ch_l = double(sline(vec(j)-1)); if ch_l ~= 34 && ch_l ~= 39 && ch_l ~= 95 && ... ch_l ~= 46 && (ch_l < 48 || (ch_l > 57 && ch_l < 65) || ... (ch_l > 90 && ch_l < 97) || ch_l > 122) okdispl = 1; end else okdispl = 1; end if vec(j) + length(string1) < length(sline), ch_r = double(sline(vec(j)+length(string1))); if ch_r ~= 34 && ch_r ~= 95 && ... (ch_r < 48 || (ch_r > 57 && ch_r < 65) || ... (ch_r > 90 && ch_r < 97) || ch_r > 122) okdispr = 1; end else okdispr = 1; end if okdispl && okdispr, okdisp = 1; end okdispl = 0; okdispr = 0; if okdisp count = count + 1; iniz = vec(j)-1+(count-1)*(length(string2)-length(string1)); slinenew = [slinenew(1:iniz),string2, ... sline(vec(j)+length(string1):end)]; ok = 1; end okdisp = 0; end if ok, disp([fvar(file{i},14),' row ',fvar(int2str(n_row),5), ... ' >> ',slinenew(1:end)]) disp([' ',sline]) match = 1; end end end newfile{n_row,1} = slinenew; end if fid > 0, count = fclose(fid); end if match && type ~= 3 fid = fopen(file{i}, 'wt'); if fid > 0 for i = 1:n_row-1, count = fprintf(fid,'%s\n',deblank(newfile{i})); end count = fprintf(fid,'%s',deblank(newfile{n_row})); count = fclose(fid); end end end % --------------------------------------------------------------------- % find subdirectories % --------------------------------------------------------------------- function file = deepdir(expression,names,file,isdir,folder) idx = find(isdir); for i = 3:length(idx) disp([folder,filesep,names{idx(i)}]) newfolder = [folder,filesep,names{idx(i)}]; b = dir([newfolder,filesep,expression]); if ~isempty({b.name}), bnames = {b.name}; n = length(bnames); newfiles = cell(n,1); for k = 1:n newfiles{k} = [folder,filesep,names{idx(i)},filesep,bnames{k}]; end file = [file; newfiles]; end b = dir([newfolder]); newdir = [b.isdir]'; newnames = {b.name}'; file = deepdir(expression,newnames,file,newdir,newfolder); end
github
Sinan81/PSAT-master
pgrep.m
.m
PSAT-master/psat-mat/psat/pgrep.m
4,302
utf_8
103545a4c4eba39f7a95a16bdbdf9512
function pgrep(expression,string,options) %PGREP change strings within files % %PGREP(EXPRESSION,STRING,TYPE) % EXPRESSION: regular expression % STRING: the string to be searched. % TYPE: 1 - list file names, row number and line text % 2 - list file names and line text % 3 - list file names % 4 - as 1, but look for Matlab variables only % 5 - as 1, but span all subdirectories % %see also PSED % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 18-Feb-2003 %Update: 30-Mar-2004 %Version: 1.0.2 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano if nargin < 3, disp('Check synthax ...') disp(' ') help pgrep, return, end if ~ischar(expression) disp('First argument has to be a not empty string.') return end if ~ischar(string) || isempty(string) disp('Second argument has to be a not empty string.') return end if ~isnumeric(options) || length(options) > 1 || rem(options,1) || ... options > 5 || options <= 0 disp('Third argument has to be a scalar integer within [1-5]') return end a = dir(expression); if isempty(a) disp('No file name matches the given expression.') return end file = {a.name}'; a = dir(pwd); names = {a.name}'; isdir = [a.isdir]'; if options == 5, disp(' ') disp('Spanning directories ...') disp(' ') disp(pwd) file = deepdir(expression,names,file,isdir,pwd); options = 1; else disp(' ') disp(pwd) end n_file = length(file); if ~n_file, disp('No matches.'), return, end check = 0; try, if exist('strfind'); check = 1; end catch % nothing to do % this for Octave compatibility end disp(' ') disp('Scanning files ...') disp(' ') for i = 1:n_file fid = fopen(file{i}, 'rt'); n_row = 0; while 1 && fid > 0 sline = fgets(fid); if ~isempty(sline), if sline == -1, break; end end n_row = n_row + 1; if check vec = strfind(sline,string); else vec = findstr(sline,string); end if ~isempty(vec) switch options case 1 disp([fvar(file{i},14),' row ',fvar(int2str(n_row),5), ... ' >> ',sline(1:end-1)]) case 3 disp(file{i}) break case 2 disp([fvar(file{i},14),' >> ',sline(1:end-1)]) case 4 okdisp = 0; okdispl = 0; okdispr = 0; for j = 1:length(vec) if vec(j) > 1, ch_l = double(sline(vec(j)-1)); if ch_l ~= 34 && ch_l ~= 39 && ch_l ~= 95 && ch_l ~= 46 && ... (ch_l < 48 || (ch_l > 57 && ch_l < 65) || ... (ch_l > 90 && ch_l < 97) || ch_l > 122) okdispl = 1; end end if vec(j) + length(string) < length(sline), ch_r = double(sline(vec(j)+length(string))); if ch_r ~= 34 && ch_r ~= 95 && ... (ch_r < 48 || (ch_r > 57 && ch_r < 65) || ... (ch_r > 90 && ch_r < 97) || ch_r > 122) okdispr = 1; end else okdispr = 1; end if okdispl && okdispr, okdisp = 1; break end okdispl = 0; okdispr = 0; end if okdisp, disp([fvar(file{i},14),' row ',fvar(int2str(n_row),5), ... ' >> ',sline(1:end-1)]), end end end end if fid > 0, count = fclose(fid); end end % ---------------------------------------------------------------------- % find subdirectories % ---------------------------------------------------------------------- function file = deepdir(expression,names,file,isdir,folder) idx = find(isdir); for i = 3:length(idx) disp([folder,filesep,names{idx(i)}]) newfolder = [folder,filesep,names{idx(i)}]; b = dir([newfolder,filesep,expression]); if ~isempty({b.name}) bnames = {b.name}; n = length(bnames); newfiles = cell(n,1); for k = 1:n newfiles{k} = [folder,filesep,names{idx(i)},filesep,bnames{k}]; end file = [file; newfiles]; end b = dir([newfolder]); newdir = [b.isdir]'; newnames = {b.name}'; file = deepdir(expression,newnames,file,newdir,newfolder); end
github
Sinan81/PSAT-master
fm_wcall.m
.m
PSAT-master/psat-mat/psat/fm_wcall.m
11,669
utf_8
24d7c39d37c7d12104faa20b152b1d96
function fm_wcall %FM_WCALL writes the function FM_CALL for the component calls. % and uses the information in Comp.prop for setting % the right calls. Comp.prop is organized as follows: % comp(i,:) = [x1 x2 x3 x4 x5 xi x0 xt] % % if x1 -> call for algebraic equations % if x2 -> call for algebraic Jacobians % if x3 -> call for state equations % if x4 -> call for state Jacobians % if x5 -> call for non-windup limits % if xi -> component used in power flow computations % if x0 -> call for initializations % if xt -> call for current simulation time % (-1 is used for static analysis) % % Comp.prop is stored in the "comp.ini" file. % %FM_WCALL % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 22-Aug-2003 %Update: 03-Nov-2005 %Version: 1.2.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Settings fm_var % ------------------------------------------------------------------------- % Opening file "fm_call.m" for writing % ------------------------------------------------------------------------- if Settings.local fid = fopen([Path.local,'fm_call.m'], 'wt'); else [fid,msg] = fopen([Path.psat,'fm_call.m'], 'wt'); if fid == -1 fm_disp(msg) fid = fopen([Path.local,'fm_call.m'], 'wt'); end end count = fprintf(fid,'function fm_call(flag)\n\n'); count = fprintf(fid,'\n%%FM_CALL calls component equations'); count = fprintf(fid,'\n%%'); count = fprintf(fid,'\n%%FM_CALL(CASE)'); count = fprintf(fid,'\n%% CASE ''1'' algebraic equations'); count = fprintf(fid,'\n%% CASE ''pq'' load algebraic equations'); count = fprintf(fid,'\n%% CASE ''3'' differential equations'); count = fprintf(fid,'\n%% CASE ''1r'' algebraic equations for Rosenbrock method'); count = fprintf(fid,'\n%% CASE ''4'' state Jacobians'); count = fprintf(fid,'\n%% CASE ''0'' initialization'); count = fprintf(fid,'\n%% CASE ''l'' full set of equations and Jacobians'); count = fprintf(fid,'\n%% CASE ''kg'' as "L" option but for distributed slack bus'); count = fprintf(fid,'\n%% CASE ''n'' algebraic equations and Jacobians'); count = fprintf(fid,'\n%% CASE ''i'' set initial point'); count = fprintf(fid,'\n%% CASE ''5'' non-windup limits'); count = fprintf(fid,'\n%%'); count = fprintf(fid,'\n%%see also FM_WCALL\n\n'); count = fprintf(fid,'fm_var\n\n'); count = fprintf(fid,'switch flag\n\n'); % ------------------------------------------------------------------------- % look for loaded components % ------------------------------------------------------------------------- Comp.prop(:,10) = 0; for i = 1:Comp.n ncompi = eval([Comp.names{i},'.n']); if ncompi, Comp.prop(i,10) = 1; end end cidx1 = find(Comp.prop(:,10)); prop1 = Comp.prop(cidx1,1:9); s11 = buildcell(cidx1,prop1(:,1),'gcall'); s12 = buildcell(cidx1,prop1(:,2),'Gycall'); s13 = buildcell(cidx1,prop1(:,3),'fcall'); s14 = buildcell(cidx1,prop1(:,4),'Fxcall'); s15 = buildcell(cidx1,prop1(:,5),'windup'); cidx2 = find(Comp.prop(1:end-2,10)); prop2 = Comp.prop(cidx2,1:9); s20 = buildcell(cidx2,prop2(:,7),'setx0'); s21 = buildcell(cidx2,prop2(:,1),'gcall'); s22 = buildcell(cidx2,prop2(:,2),'Gycall'); s23 = buildcell(cidx2,prop2(:,3),'fcall'); s24 = buildcell(cidx2,prop2(:,4),'Fxcall'); gisland = ' gisland(Bus)\n'; gyisland = ' Gyisland(Bus)\n'; % ------------------------------------------------------------------------- % call algebraic equations % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''gen''\n\n'); idx = find(sum(prop2(:,[8 9]),2)); count = fprintf(fid,' %s\n',s21{idx}); % ------------------------------------------------------------------------- % call algebraic equations of shunt components % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''load''\n\n'); idx = find(prod(prop2(:,[1 8]),2)); count = fprintf(fid,' %s\n',s21{idx}); count = fprintf(fid,gisland); % ------------------------------------------------------------------------- % call algebraic equations % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''gen0''\n\n'); idx = find(sum(prop2(:,[8 9]),2) & prop2(:,6)); count = fprintf(fid,' %s\n',s21{idx}); % ------------------------------------------------------------------------- % call algebraic equations of shunt components % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''load0''\n\n'); idx = find(prod(prop2(:,[1 6 8]),2)); count = fprintf(fid,' %s\n',s21{idx}); count = fprintf(fid,gisland); % ------------------------------------------------------------------------- % call differential equations % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''3''\n\n'); idx = find(prop2(:,3)); count = fprintf(fid,' %s\n',s23{idx}); % ------------------------------------------------------------------------- % call algebraic equations for Rosenbrock method % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''1r''\n\n'); idx = find(prop1(:,1)); count = fprintf(fid,' %s\n',s11{idx}); count = fprintf(fid,gisland); % ------------------------------------------------------------------------- % call algebraic equations of series component % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''series''\n\n'); idx = find(prop1(:,9)); count = fprintf(fid,' %s\n',s11{idx}); count = fprintf(fid,gisland); % ------------------------------------------------------------------------- % call DAE Jacobians % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''4''\n'); writejacs(fid) idx = find(prop2(:,4)); count = fprintf(fid,' %s\n',s24{idx}); % ------------------------------------------------------------------------- % call initialization functions % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''0''\n\n'); idx = find(prop2(:,7)); count = fprintf(fid,' %s\n',s20{idx}); % ------------------------------------------------------------------------- % call the complete set of algebraic equations % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''fdpf''\n\n'); idx = find(prod(prop1(:,[1 6]),2)); count = fprintf(fid,' %s\n',s11{idx}); count = fprintf(fid,gisland); % ------------------------------------------------------------------------- % call the complete set of equations and Jacobians % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''l''\n\n'); idx = find(prod(prop1(:,[1 6]),2)); count = fprintf(fid,' %s\n',s11{idx}); count = fprintf(fid,gisland); idx = find(prod(prop1(:,[2 6]),2)); count = fprintf(fid,' %s\n',s12{idx}); count = fprintf(fid,gyisland); count = fprintf(fid,'\n\n'); idx = find(prod(prop1(:,[3 6]),2)); count = fprintf(fid,' %s\n',s13{idx}); writejacs(fid) idx = find(prod(prop1(:,[4 6]),2)); count = fprintf(fid,' %s\n',s14{idx}); % ------------------------------------------------------------------------- % call the complete set of eqns and Jacs for distributed slack bus % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''kg''\n\n'); idx = find(prop2(:,1)); count = fprintf(fid,' %s\n',s21{idx}); count = fprintf(fid,gisland); idx = find(prop2(:,2)); count = fprintf(fid,' %s\n',s22{idx}); count = fprintf(fid,gyisland); count = fprintf(fid,'\n\n'); idx = find(prop2(:,3)); count = fprintf(fid,' %s\n',s23{idx}); writejacs(fid) idx = find(prop2(:,4)); count = fprintf(fid,' %s\n',s24{idx}); % ------------------------------------------------------------------------- % call the complete set of eqns and Jacs for distributed slack bus % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''kgpf''\n\n'); count = fprintf(fid,' global PV SW\n'); idx = find(prod(prop2(:,[1 6]),2)); count = fprintf(fid,' %s\n',s21{idx}); count = fprintf(fid,' PV = gcall(PV);\n'); count = fprintf(fid,' greactive(SW)\n'); count = fprintf(fid,' glambda(SW,1,DAE.kg)\n'); count = fprintf(fid,gisland); idx = find(prod(prop2(:,[2 6]),2)); count = fprintf(fid,' %s\n',s22{idx}); count = fprintf(fid,' Gycall(PV)\n'); count = fprintf(fid,' Gyreactive(SW)\n'); count = fprintf(fid,gyisland); count = fprintf(fid,'\n\n'); idx = find(prod(prop2(:,[3 6]),2)); count = fprintf(fid,' %s\n',s23{idx}); writejacs(fid) idx = find(prod(prop2(:,[4 6]),2)); count = fprintf(fid,' %s\n',s24{idx}); % ------------------------------------------------------------------------- % calling algebraic equations and Jacobians % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''n''\n\n'); idx = find(prop1(:,1)); count = fprintf(fid,' %s\n',s11{idx}); count = fprintf(fid,gisland); idx = find(prop1(:,2)); count = fprintf(fid,' %s\n',s12{idx}); count = fprintf(fid,gyisland); count = fprintf(fid,'\n'); % ------------------------------------------------------------------------- % call all the functions for setting initial point % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''i''\n\n'); idx = find(prop1(:,1)); count = fprintf(fid,' %s\n',s11{idx}); count = fprintf(fid,gisland); idx = find(prop1(:,2)); count = fprintf(fid,' %s\n',s12{idx}); count = fprintf(fid,gyisland); count = fprintf(fid,'\n\n'); idx = find(prop1(:,3)); count = fprintf(fid,' %s\n',s13{idx}); count = fprintf(fid,'\n if DAE.n > 0'); writejacs(fid) count = fprintf(fid,' end \n\n'); idx = find(prop1(:,4)); count = fprintf(fid,' %s\n',s14{idx}); % ------------------------------------------------------------------------- % call saturation functions % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''5''\n\n'); idx = find(prop1(:,5)); count = fprintf(fid,' %s\n',s15{idx}); % ------------------------------------------------------------------------- % close "fm_call.m" % ------------------------------------------------------------------------- count = fprintf(fid,'\nend\n'); count = fclose(fid); cd(Path.local); % ------------------------------------------------------------------------- % function for writing Jacobian initialization % ------------------------------------------------------------------------- function writejacs(fid) count = fprintf(fid,'\n DAE.Fx = sparse(DAE.n,DAE.n);'); count = fprintf(fid,'\n DAE.Fy = sparse(DAE.n,DAE.m);'); count = fprintf(fid,'\n DAE.Gx = sparse(DAE.m,DAE.n);\n'); % ------------------------------------------------------------------------- % function for building component call function cells % ------------------------------------------------------------------------- function out = buildcell(j,idx,type) global Comp Settings out = cell(length(idx),1); h = find(idx <= 1); k = j(h); if Settings.octave c = Comp.names(k); out(h) = fm_strjoin(type,'_',lower(c),'(',c,')'); else out(h) = fm_strjoin(type,'(',{Comp.names{k}}',')'); end h = find(idx == 2); k = j(h); if Settings.octave c = Comp.names(k); out(h) = fm_strjoin(c,' = ',type,'_',lower(c),'(',c,');'); else str = [' = ',type,'(']; out(h) = fm_strjoin({Comp.names{k}}',str,{Comp.names{k}}',');'); end
github
Sinan81/PSAT-master
fm_linedlg.m
.m
PSAT-master/psat-mat/psat/fm_linedlg.m
18,525
utf_8
bc5ff2655dcc848e320ac75686ab208f
function fm_linedlg(varargin) %SCRIBELINEDLG Line property dialog helper function for Plot Editor % % Copyright 1984-2001 The MathWorks, Inc. % $Revision: 1.19 $ $Date: 2001/04/15 12:00:41 $ % %Modified by: Federico Milano %Date: 11-Nov-2002 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano persistent localData; global Theme switch nargin case 1 arg1 = varargin{1}; if isempty(arg1) || ishandle(arg1(1)) || isa(arg1(1), 'scribehandle') localData = LInitFig(arg1,localData); return elseif ischar(arg1(1)) action = arg1; parameter = []; end case 2 action = varargin{1}; parameter = varargin{2}; end if strcmp(parameter,'me') parameter = gcbo; end localData = feval(action,parameter,localData); %%%%%% function localData = LInitFig(objectV,localData) global Theme if isempty(objectV) LNoLineError; return end try if ishandle(objectV) fig = get(get(objectV(1),'Parent'),'Parent'); else % might be any selected object fig = get(objectV(1),'Figure'); end catch fm_disp(['Unable to edit line properties: invalid line handles']); return end oldPointer = get(fig,'Pointer'); set(fig,'Pointer','watch'); try if ishandle(objectV) LineVector = []; ArrowVector = []; for aHG = objectV if strcmp(get(aHG,'Type'),'line') LineVector(end+1) = aHG; end end else % pick out the line objects from the list LineVector = scribehandle([]); ArrowVector = scribehandle([]); for aObj = objectV if isa(aObj,'editline'), LineVector = [LineVector aObj]; % LineVector(end+1) = aObj; elseif isa(aObj,'arrowline') ArrowVector = [ArrowVector aObj]; % ArrowVector(end+1) = aObj; end end end if isempty(LineVector) IndLine = []; else IndLine = [1:length(LineVector)]; end HG = [LineVector ArrowVector]; catch set(fig,'Pointer',oldPointer); fm_disp(['Unable to open line properties dialog. ' ... 'Selection list is invalid:' ... 10 lasterr],2); return end if isempty(HG) LNoLineError; set(fig,'Pointer',oldPointer); return end %--temporary: redirect to Property Editor %propedit(get(HG,'MyHGHandle')); %set(fig,'Pointer',oldPointer); %return %---Set enable flag for marker boxes if isequal(length(ArrowVector),length(HG)), MarkerEnable='off'; else MarkerEnable='on'; end %---Get all object data for ctHG = 1:length(HG) GetData(ctHG) = struct('Selected',get(HG(ctHG),'Selected'), ... 'Parent',get(HG(ctHG),'Parent'), ... 'LineStyle',get(HG(ctHG),'LineStyle'), ... 'LineWidth',get(HG(ctHG),'LineWidth'), ... 'Marker',get(HG(ctHG),'Marker'), ... 'MarkerSize',get(HG(ctHG),'MarkerSize'), ... 'Color',get(HG(ctHG),'Color')); % turn off selection so we can see changes in marker style set(HG(ctHG),'Selected','off'); end % for ctHG localData = struct('CommonWidth',1,'CommonStyle',1,'CommonSize',1, ... 'CommonMarker',1,'CommonColor',1); localData.Selected = {GetData(:).Selected}; try % adjustment factors for character units % work in character units. fx = 5; fy = 13; figWidth = 360/fx; figHeight = 220/fy; callerPosition = get(fig,'Position'); callerUnits = get(fig,'Units'); bgcolor = get(0,'DefaultUIControlBackgroundColor'); if bgcolor==[0 0 0] fgcolor = [1 1 1]; else fgcolor = get(0,'DefaultUIControlForegroundColor'); end fProps = struct(... 'Units', callerUnits,... 'Color', Theme.color01,... 'NumberTitle', 'off',... 'IntegerHandle', 'off',... 'Pointer','watch', ... 'Resize', 'on',... 'Visible', 'off',... 'KeyPressFcn', 'fm_linedlg keypress',... 'HandleVisibility', 'callback',... 'WindowStyle', 'modal',... 'CloseRequestFcn', 'fm_linedlg button close',... 'Name', 'Edit Line Properties',... 'Position', callerPosition); f = figure(fProps); set(f,'Units','character'); figPos = get(f,'Position'); figPos(1:2) = figPos(1:2) + (figPos(3:4)-[figWidth, figHeight])/2; figPos(3:4) = [figWidth, figHeight]; set(f,'Position',figPos); ut = uicontrol('Style' , 'text',... 'Units' , 'character',... 'Parent' , f,... 'Visible' , 'off',... 'String' , 'Title'); charSize = get(ut,'Extent'); charH = charSize(4); delete(ut); % geometry LMarginW = 25/fx; RMarginW = 25/fx; ColPadW = 10/fx; RowLabelW = 65/fx; ColW = (figPos(3)-2*RowLabelW-LMarginW-RMarginW-3*ColPadW)/2; TopMarginH = 20/fy; BotMarginH = 20/fy; RowH = 30/fy; RowPadH = 8/fy; uiH = RowH-RowPadH; buttonW = 72/fx; buttonH = RowH-RowPadH; buttonPad = 7/fx; charOffset = uiH-charH; % property defaults editProps = struct(... 'Style', 'edit',... 'Parent' , f,... 'Units', 'character',... 'BackgroundColor', Theme.color04,... 'ForegroundColor', Theme.color05,... 'FontName',Theme.font01, ... 'HorizontalAlignment', 'left'); tProps = struct(... 'Style','text',... 'Parent' , f,... 'Units', 'character',... 'HorizontalAlignment', 'right',... 'BackgroundColor', Theme.color01,... 'ForegroundColor', fgcolor); prompt = {... 'Line Width:' 'Line Style:' '' 'Color:' 'Marker Size:' 'Marker:' }; properties = {... 'edit' 'fm_linedlg verifyposnumber me' 'LineWidth' 'popupmenu' '' 'LineStyle' '' '' '' 'frame' '' '' 'edit' 'fm_linedlg verifyposnumber me' 'MarkerSize' 'popupmenu' '' 'Marker' }; linestyles = {'-' '--' ':' '-.' 'none'}; markers = {'none' '+' 'o' '*' '.' 'x' 'square' 'diamond' ... 'v' '^' '>' '<' 'pentagram' 'hexagram'}; % Find common LineWidth and MarkerSize CommonWidth = unique([GetData(:).LineWidth]); if length(CommonWidth)>1, widthStr = ''; localData.CommonWidth = 0; else, widthStr = num2str(CommonWidth); end CommonSize = unique([GetData(IndLine).MarkerSize]); if length(CommonSize)>1, sizeStr = ''; localData.CommonSize = 0; else, sizeStr = num2str(CommonSize); end % Find Common LineStyle CommonStyle = unique({GetData(:).LineStyle}); if length(CommonStyle)==1, styleVal = find(strcmp(CommonStyle{1},linestyles)); linestr = {'solid (-)' 'dash (--)' 'dot (:)' 'dash-dot (-.)' 'none'}; else styleVal = 1; localData.CommonStyle = 0; linestyles = [{'Current'},linestyles]; linestr = {'Current' 'solid (-)' 'dash (--)' 'dot (:)' 'dash-dot (-.)' 'none'}; end % Find Common Marker markerVal = 1; if ~isempty(IndLine), CommonMarker = unique({GetData(IndLine).Marker}); if length(CommonMarker)==1, markerVal = find(strcmp(CommonMarker{1},markers)); else localData.CommonMarker = 0; markers = [{'Current'},markers]; end end strings = {... widthStr linestr '' '' sizeStr markers }; values = {... 0 styleVal 0 0 0 markerVal }; enables = {... 'on' 'on' 'on' 'on' MarkerEnable MarkerEnable }; data = {... '' linestyles '' '' '' markers }; nRows = length(prompt); % lay down prompts Y = figPos(4)-TopMarginH-charOffset; headingPosition = [LMarginW Y RowLabelW uiH]; for iRow=1:nRows if iRow==5 % start new column Y = figPos(4)-TopMarginH-charOffset; headingPosition = [LMarginW+RowLabelW+ColW+2*ColPadW Y RowLabelW uiH]; end Y = Y-RowH; if ~isempty(prompt{iRow}) headingPosition(2) = Y; uicontrol(tProps,... 'String', prompt{iRow,1},... 'Tag', prompt{iRow,1},... 'Enable',enables{iRow}, ... 'Position', headingPosition); end end iGroup = 1; Y = figPos(4)-TopMarginH; headingPosition = [LMarginW+RowLabelW+ColPadW Y ColW uiH]; for iRow=1:nRows if iRow ==5 % start new column Y = figPos(4)-TopMarginH; headingPosition = [LMarginW+2*RowLabelW+ColW+3*ColPadW Y ColW uiH]; end Y = Y-RowH; if ~isempty(prompt{iRow}) headingPosition(2) = Y; uic = uicontrol(editProps,... 'Style', properties{iRow,1},... 'Callback', properties{iRow,2},... 'Tag', properties{iRow,3},... 'ToolTip', properties{iRow,3},... 'String', strings{iRow},... 'Value', values{iRow},... 'UserData', data{iRow},... 'Enable',enables{iRow}, ... 'Position', headingPosition); localData.LimCheck(iGroup) = uic; localData.Prop{iGroup} = properties{iRow,3}; if strcmp(properties{iRow,1},'edit') % edit text box localData.OldVal{iGroup} = str2double(strings{iRow}); end iGroup = iGroup + 1; end end % set color on color button % Check for common color, otherwise use white col = cat(1,GetData(:).Color); col = unique(col,'rows'); if size(col,1)>1, BGC = [1 1 1]; localData.CommonColor = 0; ColVis='off'; else, BGC = col; ColVis='on'; end Y = figPos(4)-TopMarginH-4*RowH; headingPosition = [LMarginW+RowLabelW+ColPadW+(.1067*ColW) Y+(.164*uiH) ... ColW-(.205*ColW) uiH-(.3*uiH)]; colorSwatch = uicontrol(editProps,... 'BackgroundColor',BGC, ... 'Style','frame', ... 'Tag','Color', ... 'ToolTip', 'Color', ... 'Visible',ColVis, ... 'Position', headingPosition); headingPosition = [LMarginW+RowLabelW+ColW+2*ColPadW Y RowLabelW uiH]; uicontrol(editProps,... 'Style', 'pushbutton',... 'Callback', 'fm_linedlg getcolor me',... 'Tag', '',... 'BackgroundColor',Theme.color01,... 'ForegroundColor',fgcolor,... 'FontName',Theme.font01, ... 'Horiz','center', ... 'String', 'Select...',... 'UserData', colorSwatch,... 'Position', headingPosition); % OK, Apply, Cancel, Help buttonX(1) = (figPos(3)-3*1.5*buttonW-2*buttonPad)/2; for ib = 2:3 buttonX(ib) = buttonX(ib-1) + 1.5*buttonW + buttonPad; end buttonProps = struct(... 'Parent', f,... 'Units','character',... 'BackgroundColor', Theme.color01,... 'ForegroundColor', fgcolor,... 'Position', [0 BotMarginH 1.5*buttonW 1.5*buttonH],... 'Style', 'pushbutton'); buttonProps.Position(1) = buttonX(1); uicontrol(buttonProps,... 'Interruptible', 'off',... 'String', 'OK',... 'Callback', 'fm_linedlg button ok', ... 'ForegroundColor',Theme.color04, ... 'FontWeight','bold', ... 'BackgroundColor',Theme.color03); buttonProps.Position(1) = buttonX(2); uicontrol(buttonProps,... 'Interruptible', 'off',... 'String', 'Cancel',... 'Callback', 'fm_linedlg button cancel'); buttonProps.Position(1) = buttonX(3); uicontrol(buttonProps,... 'Interruptible', 'on',... 'String', 'Apply',... 'Callback', 'fm_linedlg button apply'); set(fig,'Pointer',oldPointer); set(f,'Visible','on','Pointer','arrow'); localData.HG = HG; catch if exist('f') delete(f); end set(fig,'Pointer',oldPointer); for ct=1:length(HG), set(HG,'Selected',localData.Selected{ct}); end lasterr end function localData = keypress(selection, localData) key = double(get(gcbf,'CurrentCharacter')); switch key case 13, localData = button('ok',localData); case 27, localData = button('cancel',localData); end function localData = showhelp(selection, localData) try helpview([docroot '/mapfiles/plotedit.map'], ... 'pe_line_change_props', 'PlotEditPlain'); catch fm_disp(['Unable to display help for Line Properties:' ... sprintf('\n') lasterr ],2); end function localData = button(selection, localData); switch selection case 'close' for ct=1:length(localData.HG) set(localData.HG(ct),'Selected',localData.Selected{ct}); end delete(gcbf); localData = []; case 'cancel' close(gcbf); case 'ok' set(gcbf,'Pointer','watch'); localData = LApplySettings(gcbf,localData); close(gcbf); case 'apply' set(gcbf,'Pointer','watch'); localData = LApplySettings(gcbf,localData); set(gcbf,'Pointer','arrow'); end function val = getval(f,tag) uic = findobj(f,'Tag',tag); switch get(uic,'Style') case 'edit' val = get(uic, 'String'); case {'checkbox' 'radiobutton'} val = get(uic, 'Value'); case 'popupmenu' choices = get(uic, 'UserData'); val = choices{get(uic,'Value')}; case 'frame' val = get(uic, 'BackgroundColor'); end function val = setval(f,tag,val) uic = findobj(f,'Tag',tag); switch get(uic,'Style') case 'edit' set(uic, 'String',val); case {'checkbox' 'radiobutton' 'popupmenu'} set(uic, 'Value',val); end function localData = verifyposnumber(uic, localData) iGroup = find(uic==localData.LimCheck); val = str2double(get(uic,'String')); if ~isnan(val) if length(val)==1 && val>0 % if it's a single number greater than zero, then it's fine localData.OldVal{iGroup} = val; return end end % trap errors set(uic,'String',num2str(localData.OldVal{iGroup})); fieldName = get(uic,'ToolTip'); fm_disp([fieldName ' field requires a single positive numeric input'],2) function localData = getcolor(uic, localData) colorSwatch = get(uic,'UserData'); currentColor = get(colorSwatch,'BackgroundColor'); c = uisetcolor(currentColor); %---Trap when cancel is pressed. if ~isequal(c,currentColor) set(colorSwatch,'BackgroundColor',c,'Visible','on'); end function localData = LApplySettings(f, localData) global Fig hdl_line = get(Fig.line,'UserData'); hdl_line = hdl_line(end:-1:1); Hdl_legend = findobj(Fig.plot,'Tag','Checkbox2'); Hdl_listplot = findobj(Fig.plot,'Tag','Listbox2'); Hdl_tipoplot = findobj(Fig.plot,'Tag','PopupMenu1'); allbaby = get(Fig.plot,'Children'); hdlfig = allbaby(end-1); HG = localData.HG; try %---Only change LineWidth if not set to Current LW = str2double(getval(f,'LineWidth')); if ~isnan(LW), lineSettings.LineWidth = LW; localData.CommonWidth = 1; end % if strcmp(Marker...'Current') %---Only change Linestyle if not set to Current if ~strcmp(getval(f,'LineStyle'),'Current'), lineSettings.LineStyle = getval(f,'LineStyle'); if ~localData.CommonStyle, StylePopup = findobj(f,'Tag','LineStyle'); StyleVal = get(StylePopup,'Value'); ud=get(StylePopup,'UserData'); str = get(StylePopup,'String'); set(StylePopup,'UserData',ud(2:end),'String',str(2:end), ... 'Value',StyleVal-1); localData.CommonStyle= 1; end end % if strcmp(Linestyle...'Current') %---Only change the color if the colorswatch is visible colorSwatch = findobj(f,'Tag','Color'); if strcmp(get(colorSwatch,'Visible'),'on'); lineSettings.Color = getval(f,'Color'); end % if colorswatch is visible %---Store subset for arrows arrowSettings = lineSettings; %---Only change the MarkerSize if on is actually entered MS = str2double(getval(f,'MarkerSize')); if ~isnan(MS), lineSettings.MarkerSize = MS; end % if strcmp(Marker...'Current') %---Only change Marker if not set to Current if ~strcmp(getval(f,'Marker'),'Current'), lineSettings.Marker= getval(f,'Marker'); if ~localData.CommonMarker, StylePopup = findobj(f,'Tag','Marker'); StyleVal = get(StylePopup,'Value'); ud=get(StylePopup,'UserData'); str = get(StylePopup,'String'); set(StylePopup,'UserData',ud(2:end),'String',str(2:end), ... 'Value',StyleVal-1); localData.CommonMarker = 1; end end % if strcmp(Marker...'Current') for ctHG=1:length(HG) if ishandle(HG(ctHG)) set(HG(ctHG), lineSettings); else if isa(HG(ctHG),'editline'), settings = lineSettings; elseif isa(HG(ctHG),'arrowline'), settings = arrowSettings; end % if/else isa(HG... props = fieldnames(settings)'; for i = props i=i{1}; set(HG(ctHG),i,getfield(settings,i)); end % for i end hdl = legend(get(HG(ctHG),'Parent')); end if get(Hdl_legend,'Value') n_var = length(get(Hdl_listplot,'String')); tipoplot = get(Hdl_tipoplot,'Value'); if tipoplot == 4 || tipoplot == 5 h = findobj(hdl,'Type','line'); for i = 0:n_var-1 marker = get(hdl_line(n_var+i+1),'Marker'); markersize = get(hdl_line(n_var+i+1),'MarkerSize'); markercolor = get(hdl_line(n_var+i+1),'MarkerEdgeColor'); %xdata = get(h(-i*2+3*n_var),'XData'); %ydata = get(h(-i*2+3*n_var),'YData'); %hmarker = plot((xdata(2)-xdata(1))/1.2,ydata(1)); set(h(i+1),'Marker',marker,'MarkerEdgeColor',markercolor,'MarkerSize',markersize); end end end catch fm_disp(lasterr,2) fm_disp('Unable to set line properties.',2); end function LNoLineError fm_disp(['No lines are selected. Click on an line to select it.'],2);
github
Sinan81/PSAT-master
autorun.m
.m
PSAT-master/psat-mat/psat/autorun.m
4,902
utf_8
20741ef2a2583acd393c076a1e0dc065
function check = autorun(msg,type) % AUTORUN properly launch PSAT routine checking for data % files and previous power flow solutions % % CHECK = AUTORUN(MSG) % MSG message to be displayed % TYPE 0 for static analysis, 1 for dynamic analysis % CHECK 1 if everything goes fine, 0 otherwise % %Author: Federico Milano %Date: 29-Oct-2003 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Settings File Bus global DAE LIB SNB OPF CPF clpsat Comp check = 0; % check for data file if isempty(File.data), fm_disp(['Set a data file before running ',msg,'.'],2) return end % check for initial power flow solution if ~Settings.init solvepf if ~Settings.init, return, end end % check for dynamic components if running a static analysis if ~type && DAE.n && ~clpsat.init dynlf = sum(prod(Comp.prop(:,[3 6 9]),2)); iscpf = strcmp(msg,'Continuation Power Flow'); if ~Settings.static && ~dynlf Settings.ok = 0; uiwait(fm_choice('Dynamic components will be discarded. Continue?')) if Settings.ok Settings.static = 1; solvepf Settings.static = 0; % reset initial condition else return end elseif ~Settings.static && ~dynlf && iscpf Settings.ok = 0; uiwait(fm_choice(['Dynamic components can lead to numerical ' ... 'problems, discard?'])) if Settings.ok Settings.static = 1; solvepf Settings.static = 0; % reset initial condition end elseif iscpf Settings.ok = 1; %uiwait(fm_choice(['Dynamic components can lead to numerical ' ... % 'problems, continue?'])) %if ~Settings.ok, return, end else uiwait(fm_choice(['Dynamic components are not supported for ' ... 'static analysis'],2)) return end end % check for previous CPF & ATC solutions if strcmp(msg,'SNB Direct Method') one = 1; else one = 0; end if CPF.init && ~(one && CPF.init == 1) switch CPF.init case 1, met = 'CPF'; case 2, met = 'ATC'; case 3, met = 'N-1 Cont. An.'; case 4, met = 'Continuation OPF (PSAT-GAMS)'; end Settings.ok = 0; if clpsat.init Settings.ok = clpsat.refresh; else uiwait(fm_choice([met,' has been run last. Do you want to' ... ' restore initial PF solution?'])) end if Settings.ok solvepf fm_disp(['Initial PF solution will be used as ', ... 'base case solution.']) else fm_disp(['Last ',met,' solution will be used as ', ... 'base case solution.']) end CPF.init = 0; end % check for previous time domain simulations if Settings.init == 2 Settings.ok = 0; if clpsat.init Settings.ok = clpsat.refresh; else uiwait(fm_choice(['TD has been run last. Do you want to' ... ' restore initial PF solution?'])) end if Settings.ok solvepf fm_disp(['Initial PF solution will be used as ', ... 'base case solution.']) else fm_disp('Last TD point will be used as base case solution.') end Settings.init = 1; end % check for SNB direct method if SNB.init Settings.ok = 0; if clpsat.init Settings.ok = clpsat.refresh; else uiwait(fm_choice(['SNB direct method has been run last. Do you want to' ... ' restore initial PF solution?'])) end if Settings.ok solvepf fm_disp(['Initial PF solution will be used as ', ... 'base case solution.']) else fm_disp('SNB solution will be used as base case solution.') end SNB.init = 0; end % check for LIB direct method if LIB.init Settings.ok = 0; if clpsat.init Settings.ok = clpsat.refresh; else uiwait(fm_choice(['LIB direct method has been run last. Do you want to' ... ' restore initial PF solution?'])) end if Settings.ok solvepf fm_disp('Initial PF solution will be used as base case solution.') else fm_disp('LIB solution will be used as base case solution.') end LIB.init = 0; end % check for OPF solution if strcmp(msg,'Optimal Power Flow') one = 0; else one = 1; end if OPF.init && one Settings.ok = 0; if clpsat.init Settings.ok = clpsat.refresh; else uiwait(fm_choice(['OPF has been run last. Do you want to' ... ' restore initial PF solution?'])) end if Settings.ok solvepf fm_disp(['Initial PF solution will be used as ', ... 'base case solution.']) else fm_disp('OPF solution will be used as base case solution.') end OPF.init = 0; end check = 1; % --------------------------------------------------- function solvepf global Settings Varname fm_disp('Solve base case power flow...') varname_old = Varname.idx; Settings.show = 0; fm_set('lf') Settings.show = 1; if ~isempty(varname_old) Varname.idx = varname_old; end
github
Sinan81/PSAT-master
fm_plotsel.m
.m
PSAT-master/psat-mat/psat/fm_plotsel.m
16,948
utf_8
052ac8e599b640ff0ff06593ef5181f5
function fig = fm_plotsel(varargin) % FM_PLOTSEL create GUI to select plotting variables % % HDL = FM_PLOTSEL() % %Author: Federico Milano %Date: 21-Dec-2005 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Fig Theme Varname Settings File Path % check for data file if isempty(File.data) fm_disp('Set a data file before selecting plot variables.',2) return end % check for initial power flow solution if ~Settings.init fm_disp('Solve base case power flow...') Settings.show = 0; fm_set lf Settings.show = 1; if ~Settings.init, return, end end if nargin switch varargin{1} case 'area' values = get(gcbo,'Value')-1; if ~values(1) values = 0; set(gcbo,'Value',1) end Varname.areas = values; setidx case 'region' values = get(gcbo,'Value')-1; if ~values(1) values = 0; set(gcbo,'Value',1) end Varname.regions = values; setidx case 'selvars' values = get(gcbo,'Value'); hdl = findobj(gcf,'Tag','listbox2'); Varname.idx = values; setidx case 'selection' if isempty(Varname.idx) set(gcbo,'String','<Empty>','Value',1) elseif Varname.idx(end) > Varname.nvars set(gcbo,'String','<Empty>','Value',1) Varname.idx = []; else set(gcbo,'String',Varname.uvars(Varname.idx),'Value',1) end case 'remove' hdl = findobj(gcf,'Tag','listbox2'); values = get(hdl,'Value'); Varname.idx(values) = []; if isempty(Varname.idx) set(hdl,'String','<Empty>') else nidx = length(Varname.idx); toplist = max(1,nidx-8); set(hdl,'String',Varname.uvars(Varname.idx), ... 'Value',min(max(values),nidx), ... 'ListboxTop',toplist) end case 'create_custom' setarea(0,1,'on','off') case 'creates_fixed' setarea(1,0,'off','on') case 'custom' setarea(0,1,'on','off') setidx case 'fixed' setarea(1,0,'off','on') setidx case 'setx' Varname.x = get(gcbo,'Value'); setidx case 'sety' Varname.y = get(gcbo,'Value'); setidx case 'setP' Varname.P = get(gcbo,'Value'); setidx case 'setQ' Varname.Q = get(gcbo,'Value'); setidx case 'setPij' Varname.Pij = get(gcbo,'Value'); setidx case 'setQij' Varname.Qij = get(gcbo,'Value'); setidx case 'setIij' Varname.Iij = get(gcbo,'Value'); setidx case 'setSij' Varname.Sij = get(gcbo,'Value'); setidx case 'appendidx' if isempty(File.data), fm_disp('No data file loaded.',2), return, end filedata = strrep(File.data,'@ ',''); if Settings.init == 0, fm_disp('Run power flow before saving plot variable indexes.',2), return, end if isempty(strfind(filedata,'(mdl)')) fid = fopen([Path.data,filedata,'.m'],'r+'); count = fseek(fid,0,1); count = fprintf(fid, '\n\nVarname.idx = [...\n'); nidx = length(Varname.idx); count = fprintf(fid,'%5d; %5d; %5d; %5d; %5d; %5d; %5d;\n',Varname.idx); if rem(nidx,7) ~= 0, count = fprintf(fid,'\n'); end count = fprintf(fid,' ];\n'); count = fprintf(fid, '\nVarname.areas = [...\n'); nidx = length(Varname.areas); count = fprintf(fid,'%5d; %5d; %5d; %5d; %5d; %5d; %5d;\n',Varname.areas); if rem(nidx,7) ~= 0, count = fprintf(fid,'\n'); end count = fprintf(fid,' ];\n'); count = fprintf(fid, '\nVarname.regions = [...\n'); nidx = length(Varname.regions); count = fprintf(fid,'%5d; %5d; %5d; %5d; %5d; %5d; %5d;\n',Varname.regions); if rem(nidx,7) ~= 0, count = fprintf(fid,'\n'); end count = fprintf(fid,' ];\n'); fclose(fid); fm_disp(['Plot variable indexes appended to file "',Path.data,File.data,'"']) else % load Simulink Library and add Varname block load_system('fm_lib'); cd(Path.data); filedata = filedata(1:end-5); open_sys = find_system('type','block_diagram'); if ~sum(strcmp(open_sys,filedata)) open_system(filedata); end cur_sys = get_param(filedata,'Handle'); blocks = find_system(cur_sys,'MaskType','Varname'); if ~isempty(blocks) if iscell(blocks) varblock = blocks{1}; % remove duplicate 'Varname' blocks for i = 2:length(blocks) delete_block(blocks{i}); end else varblock = blocks; end vec = Varname.idx; if size(vec,1) > 1, vec = vec'; end set_param( ... varblock, 'pxq', ... ['[',regexprep(num2str(vec),'\s*',' '),']']) else vec = Varname.idx; if size(vec,1) > 1, vec = vec'; end add_block( ... 'fm_lib/Connections/Varname',[filedata,'/Varname'], 'pxq', ... ['[',regexprep(num2str(vec),'\s*',' '),']'], ... 'Position',[20,20,105,57]) end cd(Path.local); end end return end if ishandle(Fig.plotsel), figure(Fig.plotsel), return, end h0 = figure(... 'Units','normalized',... 'Color',Theme.color01,... 'Colormap',[], ... 'MenuBar','none',... 'Name','Select Plot Variables',... 'NumberTitle','off',... 'Position',sizefig(0.75,0.69), ... 'FileName','fm_plotsel', ... 'HandleVisibility','callback',... 'Tag','figure1',... 'CreateFcn','Fig.plotsel = gcf;', ... 'DeleteFcn','Fig.plotsel = -1;', ... 'UserData',[],... 'Visible','on'); % Menu File h1 = uimenu('Parent',h0, ... 'Label','File', ... 'Tag','MenuFile'); h2 = uimenu('Parent',h1, ... 'Callback','close(gcf)', ... 'Label','Exit', ... 'Tag','PlotSelExit', ... 'Accelerator','x'); h1 = uipanel(... 'Parent',h0, ... 'Title','Variables', ... 'BackgroundColor',Theme.color02, ... 'Units','normalized',... 'Tag','uipanel1',... 'Clipping','on',... 'Position',[0.0611 0.2717 0.2506 0.6359]); idx = Varname.idx; if isempty(idx), idx = 1; end h1 = uicontrol(... 'Parent',h1, ... 'BackgroundColor',Theme.color03, ... 'Callback','fm_plotsel selvars', ... 'FontName',Theme.font01, ... 'Max',20, ... 'ForegroundColor',Theme.color06, ... 'Units','normalized',... 'Position',[0.1015 0.0597 0.8071 0.8985],... 'String',Varname.uvars,... 'Style','listbox',... 'Value',idx,... 'Tag','listbox1'); h1 = uipanel(... 'Parent',h0, ... 'Title','Selection', ... 'BackgroundColor',Theme.color02, ... 'Units','normalized',... 'Tag','uipanel2',... 'Clipping','on',... 'Position',[0.6833 0.2717 0.2506 0.6359]); h5 = uicontrol(... 'Parent',h1, ... 'Units','normalized',... 'BackgroundColor',Theme.color03, ... 'CreateFcn','fm_plotsel selection', ... 'Max',20, ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color06, ... 'Position',[0.1015 0.0597 0.8071 0.9015],... 'String',{ '<Empty>' },... 'Style','listbox',... 'Value',1,... 'Tag','listbox2'); set(h5,'Value',max(1,length(Varname.idx)-8)) h4 = uipanel(... 'Parent',h0,... 'Title','Region',... 'BackgroundColor',Theme.color02, ... 'Tag','uipanel2',... 'Clipping','on',... 'Position',[0.3728 0.6341 0.2506 0.2736]); h5 = uicontrol(... 'Parent',h4,... 'BackgroundColor',Theme.color03, ... 'ForegroundColor',Theme.color06, ... 'CreateFcn','set(gcbo,''String'',[{''<all>''};Regions.names])', ... 'Callback','fm_plotsel region', ... 'Max',20, ... 'FontName',Theme.font01, ... 'Units','normalized',... 'Position',[0.1015 0.1333 0.8020 0.7630],... 'String',{ '<empty>' },... 'Style','listbox',... 'Value',1,... 'Tag','listbox3'); if ~Varname.regions(1) Varname.regions = 0; set(h5,'Value',1) else set(h5,'Value',Varname.regions+1); end h6 = uipanel(... 'Parent',h0,... 'Title','Area',... 'BackgroundColor',Theme.color02, ... 'Tag','uipanel3',... 'Clipping','on',... 'Position',[0.3716 0.2736 0.2506 0.2736]); h7 = uicontrol(... 'Parent',h6,... 'BackgroundColor',Theme.color03, ... 'ForegroundColor',Theme.color06, ... 'CreateFcn','set(gcbo,''String'',[{''<all>''};Areas.names])', ... 'Callback','fm_plotsel area', ... 'Max',20, ... 'FontName',Theme.font01, ... 'Units','normalized',... 'Position',[0.1066 0.1185 0.8020 0.7852],... 'String',{ '<Empty>' },... 'Style','listbox',... 'Value',1,... 'Tag','listbox4'); if ~Varname.areas(1) Varname.areas = 0; set(h7,'Value',1) else set(h7,'Value',Varname.areas+1); end h8 = uicontrol(... 'Parent',h0, ... 'Units','normalized',... 'BackgroundColor',Theme.color03, ... 'FontWeight','bold', ... 'ForegroundColor',Theme.color09, ... 'Callback','close(gcf);', ... 'Position',[0.8092 0.1087 0.1259 0.0580],... 'String','Close',... 'Tag','Pushbutton1'); h8 = uicontrol(... 'Parent',h0, ... 'Callback','fm_plotsel appendidx', ... 'Units','normalized',... 'BackgroundColor',Theme.color02, ... 'Position',[0.6222 0.1087 0.1259 0.0598],... 'String','Save',... 'Tag','Pushbutton2'); h10 = uicontrol(... 'CData',fm_mat('plotsel_pij'), ... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel setPij', ... 'HorizontalAlignment','center', ... 'Position',[0.0611 0.0453 0.0623 0.0924],... 'String','',... 'Value',Varname.Pij,... 'Style','togglebutton',... 'Tag','radiobutton1'); h11 = uicontrol(... 'CData',fm_mat('plotsel_qij'), ... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel setQij', ... 'HorizontalAlignment','center', ... 'Position',[0.1297 0.0453 0.0623 0.0924],... 'String','',... 'Value',Varname.Qij,... 'Style','togglebutton',... 'Tag','radiobutton2'); h12 = uicontrol(... 'CData',fm_mat('plotsel_iij'), ... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel setIij', ... 'Position',[0.1983 0.0453 0.0623 0.0924],... 'HorizontalAlignment','center', ... 'String','',... 'Value',Varname.Iij,... 'Style','togglebutton',... 'Tag','radiobutton3'); h13 = uicontrol(... 'CData',fm_mat('plotsel_sij'), ... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel setSij', ... 'Position',[0.2668 0.0453 0.0623 0.0924],... 'HorizontalAlignment','center', ... 'String','',... 'Style','togglebutton',... 'Value',Varname.Sij,... 'Tag','radiobutton4'); h10 = uicontrol(... 'CData',fm_mat('plotsel_x'), ... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel setx', ... 'HorizontalAlignment','center', ... 'Position',[0.0611 0.1467 0.0623 0.0924],... 'String','',... 'Value',Varname.x,... 'Style','togglebutton',... 'Tag','radiobutton5'); h11 = uicontrol(... 'CData',fm_mat('plotsel_y'), ... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel sety', ... 'HorizontalAlignment','center', ... 'Position',[0.1297 0.1467 0.0623 0.0924],... 'String','',... 'Value',Varname.y,... 'Style','togglebutton',... 'Tag','radiobutton6'); h12 = uicontrol(... 'CData',fm_mat('plotsel_p'), ... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel setP', ... 'Position',[0.1983 0.1467 0.0623 0.0924],... 'HorizontalAlignment','center', ... 'String','',... 'Value',Varname.P,... 'Style','togglebutton',... 'Tag','radiobutton7'); h13 = uicontrol(... 'CData',fm_mat('plotsel_q'), ... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel setQ', ... 'Position',[0.2668 0.1467 0.0623 0.0924],... 'HorizontalAlignment','center', ... 'String','',... 'Style','togglebutton',... 'Value',Varname.Q,... 'Tag','radiobutton8'); h6 = uicontrol(... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel fixed', ... 'CreateFcn','fm_plotsel create_fixed', ... 'Position',[0.3728 0.1594 0.1870 0.0453],... 'HorizontalAlignment','left', ... 'String','Fixed Selection',... 'Value',Varname.fixed,... 'Style','checkbox',... 'Tag','checkbox_fixed'); h7 = uicontrol(... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel custom', ... 'CreateFcn','fm_plotsel create_custom', ... 'Position',[0.3728 0.0688 0.1870 0.0453],... 'HorizontalAlignment','left', ... 'String','Manual Selection',... 'Value',Varname.custom,... 'Style','checkbox',... 'Tag','checkbox_custom'); h1 = uicontrol( ... 'Parent',h0, ... 'CData',fm_mat('main_exit'), ... 'Units','normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_plotsel remove', ... 'Position',[0.885 0.9 0.05 0.05], ... 'Tag','PushRemove'); if nargout > 0, fig = h0; end % =============================================== function setarea(s1,s2,s3,s4) % =============================================== global Varname value = get(gcbo,'Value'); hdl_fix = findobj(gcf,'Tag','checkbox_fixed'); hdl_cus = findobj(gcf,'Tag','checkbox_custom'); hdl_list1 = findobj(gcf,'Tag','listbox1'); hdl_list2 = findobj(gcf,'Tag','listbox2'); hdl_tog = findobj(gcf,'Style','togglebutton'); hdl_text1 = findobj(gcf,'Tag','StaticText1'); hdl_text2 = findobj(gcf,'Tag','StaticText2'); hdl_text3 = findobj(gcf,'Tag','StaticText3'); if value set(hdl_fix,'Value',s1); set(hdl_cus,'Value',s2); set(hdl_list1,'Enable',s3) set(hdl_tog,'Enable',s4) set(hdl_text1,'Enable',s3) set(hdl_text3,'Enable',s4) Varname.custom = s2; Varname.fixed = s1; else set(hdl_fix,'Value',s2); set(hdl_cus,'Value',s1); set(hdl_list1,'Enable',s4) set(hdl_tog,'Enable',s3) set(hdl_text1,'Enable',s4) set(hdl_text3,'Enable',s3) Varname.custom = s1; Varname.fixed = s2; end % =============================================== function setidx % =============================================== global Varname Bus DAE Settings Fig Areas Regions if Varname.fixed Varname.idx = []; n1 = DAE.n+DAE.m; n2 = n1 + 2*Bus.n; n3 = 2*Settings.nseries; jdx = [1:(2*Settings.nseries)]'; if Varname.x Varname.idx = [1:DAE.n]'; end if Varname.y idx0 = DAE.n; Varname.idx = [Varname.idx; idx0+[1:DAE.m]']; end if Varname.P idx0 = n1; Varname.idx = [Varname.idx; idx0+Bus.a]; end if Varname.Q idx0 = n1; Varname.idx = [Varname.idx; idx0+Bus.v]; end if Varname.Pij idx0 = n2; Varname.idx = [Varname.idx; idx0+jdx]; end if Varname.Qij idx0 = n2 + n3; Varname.idx = [Varname.idx; idx0+jdx]; end if Varname.Iij idx0 = n2 + 2*n3; Varname.idx = [Varname.idx; idx0+jdx]; end if Varname.Sij idx0 = n2 + 3*n3; Varname.idx = [Varname.idx; idx0+jdx]; end elseif Varname.custom Varname.idx = get(findobj(gcf,'Tag','listbox1'),'Value'); end % take into account area selection if Varname.areas(1), setzone('area'), end % take into account region selection if Varname.regions(1), setzone('region'), end hdl_list2 = findobj(gcf,'Tag','listbox2'); if isempty(Varname.idx) set(hdl_list2,'String','<Empty>','Value',1) else set(hdl_list2,'String',Varname.uvars(Varname.idx), ... 'Value',1, ... 'ListboxTop',1) end % =============================================== function setzone(type) % =============================================== global DAE Areas Bus Regions Settings Varname n1 = DAE.n+DAE.m; n2 = n1 + 2*Bus.n; n3 = Settings.nseries; n4 = 2*n3; switch type case 'area' zdx = getidx(Areas,Varname.areas); buses = getarea(Bus,0,0); case 'region' zdx = getidx(Regions,Varname.regions); buses = getregion(Bus,0,0); end % find buses within selected zones bdx = find(ismember(buses,zdx)); idx = getint(Bus,getidx(Bus,bdx)); % find series components within selected zones [fr,to] = fm_flows('onlyidx'); series1 = ismember(fr,idx); series2 = ismember(to,idx); ldx = find(series1+series2); % find state and algebraic variables within selected zones [x,y] = fm_getxy(idx); values = []; if Varname.x || (Varname.y && ~isempty(y)) values = [x; DAE.n+y]; end if Varname.y values = [values; DAE.n+[bdx; Bus.n+bdx]]; end if Varname.P values = [values; n1+bdx]; end if Varname.Q values = [values; n1+Bus.n+bdx]; end if Varname.Pij values = [values; n2+ldx]; values = [values; n2+n3+ldx]; end if Varname.Qij values = [values; n2+n4+ldx]; values = [values; n2+n3+n4+ldx]; end if Varname.Iij values = [values; n2+2*n4+ldx]; values = [values; n2+2*n4+n3+ldx]; end if Varname.Sij values = [values; n2+3*n4+ldx]; values = [values; n2+3*n4+n3+ldx]; end values = sort(values); Varname.idx = intersect(Varname.idx,values);
github
Sinan81/PSAT-master
fm_axesdlg.m
.m
PSAT-master/psat-mat/psat/fm_axesdlg.m
39,209
utf_8
86e49074fe6ba75e24c2cc7863f15124
function fm_axesdlg(varargin) %SCRIBEAXESDLG Axes property dialog helper function for Plot Editor % SCRIBEAXESDLG(A) opens axes property dialog for axes A % % If the plot editor is active, the SCRIBEAXESDLG edits all % currently selected axes. Alternatively, SCRIBEAXESDLG(S) % explicitly passes a selection list S, a row vector % of scribehandle objects, to SCRIBEAXESDLG for editing. % % Copyright 1984-2001 The MathWorks, Inc. % $Revision: 1.27 $ $Date: 2001/04/15 12:01:20 $ % j. H. Roh % %Modified by: Federico Milano %Date: 11-Nov-2002 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html persistent localData; switch nargin case 1 arg1 = varargin{1}; if isempty(arg1) || ishandle(arg1) || isa(arg1(1),'scribehandle') localData = LInitFig(arg1,localData); return elseif ischar(arg1) action = arg1; parameter = []; end case 2 action = varargin{1}; parameter = varargin{2}; end if strcmp(parameter,'me') parameter = gcbo; end localData = feval(action,parameter,localData); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function localData = showhelp(selection, localData) try helpview([docroot '/mapfiles/plotedit.map'], ... 'pe_ax_props', 'PlotEditPlain'); catch errordlg(['Unable to display help for Axes Properties:' ... sprintf('\n') lasterr ]); end function localData = button(selection, localData); switch selection case 'cancel' close(gcbf); case 'ok' set(gcbf,'Pointer','watch'); localData = LApplySettings(gcbf,localData); close(gcbf); case 'apply' set(gcbf,'Pointer','watch'); localData = LApplySettings(gcbf,localData); set(gcbf,'Pointer','arrow'); end function localData = verifynumber(uic, localData) iGroup = find(uic==localData.LimCheck); val = str2double(get(uic,'String')); if ~isnan(val) if length(val)==1 localData.OldVal{iGroup} = val; return end end % trap errors set(uic,'String',num2str(localData.OldVal{iGroup})); fieldName = get(uic,'ToolTip'); errordlg([fieldName ' field requires a single numeric input'],'Error','modal'); function localData = key(fig,localData); theKey = get(fig,'CurrentCharacter'); if isempty(theKey), return, end switch theKey case 13 % return fm_axesdlg button ok; case 27 % escape fm_axesdlg button cancel; case 9 % tab % next field end % manage state of controls function localData = toggle(uic,localData); iGroup = find(uic==localData.LimCheck); Sibling = get(uic,'UserData'); enable = {'off' 'on'}; if isempty(Sibling), % Perform as before value = get(uic,'Value'); if ~isempty(iGroup), set(localData.LimGroup{iGroup},'Enable',enable{value+1}); end else % See if the extra checkbox was pressed if isempty(get(uic,'String')), Sibling=uic; % Reset the Sibling as the current UIcontrol end SibUd = get(Sibling,'UserData'); % Toggle the extra check box state if strcmp(get(Sibling,'enable'),'off'); set(Sibling,'enable','inactive'); value = get(Sibling,'Value'); elseif isequal(SibUd.Value,get(Sibling,'Value')), set(Sibling,'value',~get(Sibling,'Value')) value = get(Sibling,'Value'); else set(Sibling,'enable','off','Value',SibUd.Value); value = 0; end if ~isempty(iGroup), set(localData.LimGroup{iGroup},'Enable',enable{value+1}); end end % if/else isempty(Sibling) function localData = radio(uic,localData); iGroup = find(uic==localData.LimCheck); Sibling = get(uic,'UserData'); enableflag = 1; if isempty(Sibling), % Perform as before set(uic,'Value',1); set(localData.LimGroup{iGroup},'Value',0); else if ~isempty(get(uic,'String')), iGroup = iGroup+2; ActiveButton = localData.LimCheck(iGroup); value = ~get(ActiveButton,'Value'); else ActiveButton = uic; value = get(ActiveButton,'Value'); end udAB = get(ActiveButton,'UserData'); udLimGroup = get(localData.LimGroup{iGroup},'UserData'); udLimGroup.Value = 0; % Toggle the active radio button's state if strcmp(get(ActiveButton,'enable'),'off'); udAB.Value = 1; set(ActiveButton,'enable','on','Value',1,'UserData',udAB); set(localData.LimGroup{iGroup},'Enable','on'); elseif udAB.Value, udAB.Value = 0; set(ActiveButton,'Value',0, ... 'Enable','off','UserData',udAB) set(localData.LimGroup{iGroup},'Value',0, ... 'Enable','off','UserData',udLimGroup) % Store the checkbox state, if ~isempty(localData.Enable{iGroup}), localData.Disable{iGroup-1}.CheckValue = get(localData.Enable{iGroup}(1),'Value'); end enableflag = 0; else udAB.Value = 1; set(ActiveButton,'Value',1,'UserData',udAB); set(localData.LimGroup{iGroup},'Value',0,'UserData',udLimGroup) end % if/else strcmp(Sibling,'enable'...) end % if/else length(localData.axes... % for the linear/log switches disableGroup = localData.Disable{iGroup}; if ~isempty(disableGroup) && enableflag, if any(strcmp(get(disableGroup.Controls,'Enable'),'on')) , set(disableGroup.Controls,'Enable','off'); % Save the checkbox value localData.Disable{iGroup}.CheckValue = get(disableGroup.Controls(1),'Value'); end set(disableGroup.Controls(1),'Value',0); % uncheck Sibling = get(disableGroup.Controls(1),'UserData'); if ~isempty(Sibling), set(Sibling,'Value',0,'Enable','off','HitTest','off'); end end enableGroup = localData.Enable{iGroup}; if ~isempty(enableGroup) && enableflag, Sibling = get(enableGroup(1),'UserData'); if ~isempty(Sibling), value = get(Sibling,'Value'); else value = get(enableGroup(1),'Value'); end if ~value set(enableGroup(1),'Enable','on',... 'Value',localData.Disable{iGroup-1}.CheckValue); % enable checkbox else set(enableGroup,'Enable','on'); % enable both set(enableGroup(1),'Value',localData.Disable{iGroup-1}.CheckValue); end % if/else value if ~isempty(Sibling), set(Sibling,'HitTest','on','Value',localData.Disable{iGroup-1}.CheckValue); end else set(enableGroup,'Enable','off'); % disable both end function localData = LInitFig(ax,localData) if isempty(ax) LNoAxesError; return end try if ishandle(ax) fig = get(ax(1),'Parent'); else % might be any selected object fig = get(ax(1),'Figure'); end catch errordlg(['Unable to edit axes properties: invalid axes' ... ' handles.']); return end oldPointer = get(fig,'Pointer'); set(fig,'Pointer','watch'); try % look for a list of selected objects HG = []; if ~plotedit(fig,'isactive') % plotedit has not been activated and we have a list of HG handles HG = ax; % take the original handle list else % call from the Figure Tools menu or from context menu % ax is a selection list for aObj = ax aHG = get(aObj,'MyHGHandle'); if strcmp('axes',get(aHG,'Type')) HG(end+1) = aHG; end end end catch set(fig,'Pointer',oldPointer); errordlg(['Unable to open Axes Properties dialog. ' ... 'Selection list is invalid:' ... 10 lasterr]); return end if isempty(HG) LNoAxesError; set(fig,'Pointer',oldPointer); return end %--temporary: redirect to Property Editor %propedit(HG); %set(fig,'Pointer',oldPointer); %return ax = HG; try % Property constants White = [1 1 1]; Black = [0 0 0]; % Check each axes, if one is 3D allViews = get(ax,{'view'}); f2D = isequal(allViews{:},[0 90]); bgcolor = get(0,'DefaultUIControlBackgroundColor'); if bgcolor==Black fgcolor = White; else fgcolor = get(0,'DefaultUIControlForegroundColor'); end % adjustment factors for character units % work in character units. fx = 5; fy = 13; fProps = struct(... 'Units', get(fig,'Units'),... 'NumberTitle', 'off',... 'IntegerHandle', 'off',... 'Pointer','watch', ... 'Resize', 'on',... 'Color', bgcolor,... 'Visible', 'off',... 'KeyPressFcn', 'fm_axesdlg key me',... 'WindowStyle', 'modal',... 'Name', 'Edit Axes Properties', ... 'Position', get(fig,'Position')); f = figure(fProps); set(f,'Units','character'); figPos = get(f,'Position'); figWidth = 550/fx; figHeight = 325/fy; % center dialog over the calling window figPos(1:2) = figPos(1:2) + (figPos(3:4)-[figWidth, figHeight])/2; figPos(3:4) = [figWidth, figHeight]; set(f,'Position',figPos); enable = {'off' 'on'}; % geometry LMarginW = 15/fx; RMarginW = 25/fx; ColPadW = 20/fx; RowPadH = 9/fy; RowLabelW = 70/fx; if f2D nCols = 2; else nCols = 3; end data.nCols = nCols; setappdata(f,'ScribeAxesDialogData',data); ColW = (figPos(3)-RowLabelW-LMarginW-RMarginW-nCols*ColPadW)/nCols; TopMarginH = 20/fy; BotMarginH = 20/fy; TitleH = 25/fy; HeaderH = 30/fy; RowH = 30/fy; buttonW = 72/fx; buttonH = RowH-RowPadH; buttonPad = 7/fx; XCol(1) = LMarginW; XCol(2) = XCol(1) + RowLabelW + ColPadW; XCol(3) = XCol(2) + ColW + ColPadW; XCol(4) = XCol(3) + ColW + ColPadW; % defaults for each style editProps = struct(... 'Parent', f,... 'Style', 'edit',... 'Units', 'character',... 'BackgroundColor', White,... 'ForegroundColor', Black,... 'HorizontalAlignment', 'left',... 'Callback', 'fm_axesdlg verifynumber me'); checkProps = struct(... 'Parent', f,... 'Style', 'checkbox',... 'Units', 'character',... 'HorizontalAlignment', 'left',... 'BackgroundColor', bgcolor,... 'ForegroundColor', fgcolor,... 'Callback', 'fm_axesdlg toggle me'); radioProps = struct(... 'Parent', f,... 'Style', 'radio',... 'Units', 'character',... 'HorizontalAlignment', 'left',... 'BackgroundColor', bgcolor,... 'ForegroundColor', fgcolor,... 'Callback', 'fm_axesdlg radio me'); tProps = struct(... 'Parent', f,... 'Style', 'text',... 'Units', 'character',... 'HorizontalAlignment', 'right',... 'BackgroundColor', bgcolor,... 'ForegroundColor', fgcolor); % get text size ut = uicontrol(tProps,... 'Visible','off',... 'String','Title'); charSize = get(ut,'Extent'); charH = charSize(4); delete(ut); % charOffset = (RowH-charH)/2; editH = charH + 4/fy; uiH = RowH-RowPadH; YTitleRow = figPos(4)-TitleH-TopMarginH-uiH; % Title row charOffset = uiH-charH; uicontrol(tProps,... 'FontWeight','bold',... 'String', 'Title:',... 'Position', ... [ LMarginW YTitleRow + uiH + uiH - charH ... RowLabelW charH]); % Check for similar titles titleHandle = get(ax,{'Title'}); titleString = get([titleHandle{:}],{'String'}); if isempty(titleString{1}) || ... (length(titleString) > 1 && ~isequal(titleString{:})), % use a cell array, so spaces aren't padded out. CommonFlag = 0; titleString = {}; else CommonFlag = 1; titleString=titleString{1}; end titleU = uicontrol(editProps,... 'Tag', 'Title',... 'UserData',CommonFlag, ... 'Callback', '',... 'HorizontalAlignment','center',... 'Max', 2, ... % allow multi line titles 'String', titleString,... 'Position', ... [ XCol(2) YTitleRow ... nCols*ColW+(nCols-1)*ColPadW uiH + uiH]); iGroup=1; localData.LimCheck(iGroup)=titleU; localData.Prop{iGroup} = 'Title'; % put down the row headings rowLabelStrings = {... '','left', 'Label:','right', 'Limits:','right', 'Tick Step:','right', 'Scale:','right', '','right', 'Grid:','right', '','right', }; nRows = size(rowLabelStrings,1); Y = YTitleRow - HeaderH + RowPadH; headingPosition = [LMarginW Y RowLabelW charH]; for iRow = 1:nRows, if ~isempty(rowLabelStrings{iRow,1}) headingPosition(2) = Y; uicontrol(tProps,... 'FontWeight', 'bold',... 'String', rowLabelStrings{iRow,1},... 'HorizontalAlignment', rowLabelStrings{iRow,2},... 'Position', headingPosition); end Y = Y-RowH; end % fill each column cCol = ' XYZ'; for iCol = 2:nCols+1, X = XCol(iCol); col = cCol(iCol); % heading Y = YTitleRow - HeaderH + RowPadH; uicontrol(tProps,... 'Style', 'text',... 'FontWeight', 'bold',... 'HorizontalAlignment', 'center',... 'Position', [X Y-charOffset ColW charH],... 'String', col); % label Y = Y-RowH; % Check for similar labels labelHandle = get(ax,{[col 'Label']}); labelString = get([labelHandle{:}],{'String'}); if isempty(labelString{1}) || ... (length(labelString)>1 && ~isequal(labelString{:})), % use a cell array, so spaces aren't padded out. CommonFlag = 0; labelString = {}; else labelString=labelString{1}; CommonFlag = 1; end if size(labelString,1)>1 % multiline label multiline = 2; else multiline = 1; end labelU = uicontrol(editProps,... 'Enable', 'on',... 'Tag', [col 'Label'],... 'ToolTip', [col 'Label'],... 'UserData',CommonFlag, ... 'Position', [X Y ColW uiH ],... 'String', labelString,... 'Max', multiline,... 'Callback', ''); iGroup = iGroup+1; localData.LimCheck(iGroup) = labelU; localData.Prop{iGroup} = 'Title'; % range Y = Y-RowH; % Check if all axes are manual or auto AllMods = strcmp(get(ax, [col 'LimMode']),'manual'); MultMods = 0; if all(~AllMods) checkProps.Value = 0; elseif all(AllMods) checkProps.Value = 1; else MultMods = 1; checkProps.Value = length(find(AllMods))>=length(find(~AllMods)); end CheckVal = checkProps.Value; clim = uicontrol(checkProps,... 'String', 'Manual',... 'Tag', [col 'LimMode'],... 'ToolTip', [col 'LimMode'],... 'Position', [X Y ColW/2 uiH]); % Add a second checkbox when editing multiple axes if MultMods, % Overwrite the other checkbox, since it's callback will never % be invoked clim2 = uicontrol(checkProps,... 'ButtonDownFcn','fm_axesdlg toggle me', ... 'Enable','off', ... 'Tag', [col 'LimMode'],... 'ToolTip', [col 'LimMode'],... 'UserData',struct('Value',checkProps.Value,'Sibling',clim), ... 'Position', [X Y 3 uiH]); checkProps.Value = 0; set(clim,'UserData',clim2,'Tag','') end % Check for common limits lim = get(ax,{[col 'Lim']}); lim = cat(1,lim{:}); Umin = unique(lim(:,1)); Umax = unique(lim(:,2)); if length(Umin)>1, uminStr = ''; else, uminStr = num2str(Umin); end if length(Umax)>1, umaxStr = ''; else, umaxStr = num2str(Umax); end umin = uicontrol(editProps,... 'Tag', [col 'LimMin'],... 'ToolTip', [col ' Min'],... 'Enable', enable{checkProps.Value+1},... 'String', uminStr,... 'Position', [X+ColW/2 Y ColW/4 uiH]); iGroup=iGroup+1; localData.LimCheck(iGroup) = umin; localData.OldVal{iGroup} = min(lim); umax = uicontrol(editProps,... 'Tag', [col 'LimMax'],... 'Enable', enable{checkProps.Value+1},... 'String', umaxStr,... 'Position', [X+ColW*3/4 Y ColW/4 uiH],... 'ToolTip', [col ' Max']); iGroup = iGroup+1; localData.LimCheck(iGroup) = umax; localData.OldVal{iGroup} = max(lim); iGroup = iGroup+1; localData.LimGroup{iGroup} = [umin umax]; localData.LimCheck(iGroup) = clim; localData.Prop{iGroup} = [col 'LimMode']; if MultMods iGroup = iGroup+1; localData.LimGroup{iGroup} = [umin umax]; localData.LimCheck(iGroup) = clim2; localData.Prop{iGroup} = [col 'LimMode']; end % Check if all axes use a linear scale AllScales = strcmp(get(ax,[col 'Scale']),'linear'); MultScales = 0; if all(~AllScales) linearScale = 0; elseif all(AllScales) linearScale = 1; else MultScales = 1; linearScale=0; end % tickstep Y = Y-RowH; % Check if all TickModes are manual or auto AllMods = strcmp(get(ax, [col 'TickMode']),'manual'); MultMods = 0; if all(~AllMods) checkProps.Value = 0; elseif all(AllMods) checkProps.Value = 1; else MultMods = 1; checkProps.Value = length(find(AllMods))>=length(find(~AllMods)); end CheckVal = checkProps.Value; clim = uicontrol(checkProps,... 'String', 'Manual',... 'Tag', [col 'TickMode'],... 'Enable', enable{linearScale+1},... 'ToolTip', [col 'TickMode'],... 'Position', [X Y ColW/2 uiH]); % Add a second checkbox when editing multiple axes if MultMods, % Overwrite the other checkbox, since it's callback will never % be invoked clim2 = uicontrol(checkProps,... 'ButtonDownFcn','fm_axesdlg toggle me', ... 'Enable','off', ... 'Tag', [col 'TickMode'],... 'ToolTip', [col 'TickMode'],... 'UserData',struct('Value',checkProps.Value,'Sibling',clim), ... 'Position', [X Y 3 uiH]); checkProps.Value = 0; set(clim,'UserData',clim2,'Tag','') end if linearScale editProps.Enable = enable{checkProps.Value+1}; % Check for common tick marks tick = get(ax,{[col 'Tick']}); if (length(tick)>1 && ~isequal(tick{:})) || isempty(tick{1}) || length(tick{1})<2 tickstep = []; else tickstep = tick{1}(2)-tick{1}(1); end else editProps.Enable = enable{0+1}; tickstep = []; end utick = uicontrol(editProps,... 'Tag', [col 'TickStep'],... 'ToolTip', [col ' Tick step size'],... 'HorizontalAlignment','center',... 'String', num2str(min(tickstep)),... 'Position', [X+ColW/2 Y ColW/2 uiH]); iGroup = iGroup+1; localData.LimCheck(iGroup) = utick; localData.OldVal{iGroup} = tickstep; iGroup = iGroup+1; localData.LimGroup{iGroup} = utick; localData.LimCheck(iGroup) = clim; if MultMods, iGroup = iGroup+1; localData.LimGroup{iGroup} = utick; localData.LimCheck(iGroup) = clim2; end % Scale Y = Y-RowH; radioProps.Value = linearScale; rlin = uicontrol(radioProps,... 'Position', [X Y ColW/2 uiH],... 'String', 'Linear',... 'Tag', [col 'ScaleLinear'],... 'ToolTip',[col 'Scale=''linear''']); % Add a second set of radio buttons when editing multiple axes if MultScales, rlin2 = uicontrol(radioProps,... 'ButtonDownFcn','fm_axesdlg radio me', ... 'Enable','off', ... 'Position', [X Y 3 uiH],... 'String', '',... 'Tag', [col 'ScaleLinear'],... 'ToolTip',[col 'Scale=''linear'''], ... 'Value',0); set(rlin,'UserData',rlin2,'Tag',''); end Y = Y-RowH*2/3; rlog = uicontrol(radioProps,... 'Position', [X Y ColW/2 uiH],... 'String', 'Log',... 'Value', ~radioProps.Value,... 'Tag', [col 'ScaleLog'],... 'ToolTip',[col 'Scale=''log''']); % Add a second set of radio buttons when editing multiple axes if MultScales, rlog2 = uicontrol(radioProps,... 'Enable','off', ... 'Position', [X Y 3 uiH],... 'String', '',... 'Value', ~radioProps.Value,... 'Tag', [col 'ScaleLog'],... 'ToolTip',[col 'Scale=''log'''], ... 'Value',0); set(rlog,'UserData',rlog2,'Tag',''); set(rlin2,'UserData',... struct('Value',0,'Sibling',rlin,'OtherRadio',rlog2)); set(rlog2,'UserData',... struct('Value',0,'Sibling',rlog,'OtherRadio',rlin2)); end Y = Y-RowH*1/3; iGroup = iGroup+1; localData.LimGroup{iGroup} = [rlin]; localData.LimCheck(iGroup) = rlog; localData.Enable{iGroup} = []; localData.Disable{iGroup} = struct('Controls',[clim utick], ... 'CheckValue',CheckVal); iGroup = iGroup+1; localData.LimGroup{iGroup} = [rlog]; localData.LimCheck(iGroup) = rlin; localData.Enable{iGroup} = [clim utick]; % checkbox then % other control localData.Disable{iGroup} = []; if MultScales iGroup = iGroup+1; localData.LimGroup{iGroup} = [rlin2]; localData.LimCheck(iGroup) = rlog2; localData.Enable{iGroup} = []; localData.Disable{iGroup} = struct('Controls',[clim utick], ... 'CheckValue',CheckVal); iGroup = iGroup+1; localData.LimGroup{iGroup} = [rlog2]; localData.LimCheck(iGroup) = rlin2; localData.Enable{iGroup} = [clim utick]; % checkbox then % other control localData.Disable{iGroup} = []; end % Direction Y = Y+RowH; % Check if all axes use a normal dirction AllDirs = strcmp(get(ax, [col 'Dir']),'normal'); MultDirs = 0; if all(~AllDirs) radioProps.Value = 0; elseif all(AllDirs) radioProps.Value = 1; else MultDirs= 1; radioProps.Value = 0; end rnormal = uicontrol(radioProps,... 'Position', [X+ColW/2 Y ColW/2 uiH],... 'String', 'Normal',... 'Tag', [col 'DirNormal'],... 'ToolTip',[col 'Dir=''normal''']); if MultDirs rnormal2 = uicontrol(radioProps,... 'ButtonDownFcn','fm_axesdlg radio me', ... 'Enable','off', ... 'Position', [X+ColW/2 Y 3 uiH],... 'String', '',... 'Tag', [col 'DirNormal'],... 'ToolTip',[col 'Dir=''normal''']); set(rnormal,'UserData',rnormal2,'Tag',''); end Y = Y-RowH*2/3; rreverse = uicontrol(radioProps,... 'Position', [X+ColW/2 Y ColW/2 uiH],... 'String', 'Reverse',... 'Value', ~radioProps.Value,... 'Tag', [col 'DirReverse'],... 'ToolTip',[col 'Dir=''reverse''']); if MultDirs rreverse2 = uicontrol(radioProps,... 'ButtonDownFcn','fm_axesdlg radio me', ... 'Enable','off', ... 'Position', [X+ColW/2 Y 3 uiH],... 'String', '',... 'Tag', [col 'DirReverse'],... 'ToolTip',[col 'Dir=''reverse''']); set(rreverse,'UserData',rreverse2,'Tag',''); set(rreverse2,'UserData',... struct('Value',0,'Sibling',rreverse,'OtherRadio',rnormal2)); set(rnormal2,'UserData',... struct('Value',0,'Sibling',rnormal,'OtherRadio',rreverse2)); end Y = Y-RowH*1/3; iGroup = iGroup+1; localData.LimGroup{iGroup} = [rnormal]; localData.LimCheck(iGroup) = rreverse; localData.Enable{iGroup} = []; localData.Disable{iGroup} = []; iGroup = iGroup+1; localData.LimGroup{iGroup} = [rreverse]; localData.LimCheck(iGroup) = rnormal; localData.Enable{iGroup} = []; localData.Disable{iGroup} = []; if MultDirs iGroup = iGroup+1; localData.LimGroup{iGroup} = [rnormal2]; localData.LimCheck(iGroup) = rreverse2; localData.Enable{iGroup} = []; localData.Disable{iGroup} = []; iGroup = iGroup+1; localData.LimGroup{iGroup} = [rreverse2]; localData.LimCheck(iGroup) = rnormal2; localData.Enable{iGroup} = []; localData.Disable{iGroup} = []; end % grid % Check if all axes grids are on AllGrids = strcmpi(get(ax,[col 'Grid']),'on'); MultGrids = 0; if all(~AllGrids) checkProps.Value = 0; elseif all(AllGrids) checkProps.Value = 1; else MultGrids = 1; checkProps.Value = length(find(AllGrids))>=length(find(~AllGrids)); end Y = Y-RowH; g = uicontrol(checkProps,... 'String', 'On',... 'Tag', [col 'Grid'],... 'ToolTip', [col 'Grid'],... 'Position', [X Y ColW/3 uiH],... 'Callback', 'fm_axesdlg toggle me'); iGroup = iGroup+1; localData.LimGroup{iGroup} = []; localData.LimCheck(iGroup) = g; localData.Enable{iGroup} = []; localData.Disable{iGroup} = []; if MultGrids g2 = uicontrol(checkProps,... 'ButtonDownFcn','fm_axesdlg toggle me', ... 'Enable','off', ... 'String', '',... 'Tag', [col 'Grid'],... 'ToolTip', [col 'Grid'],... 'UserData',struct('Value',checkProps.Value,'Sibling',g), ... 'Position', [X Y 3 uiH],... 'Callback', 'fm_axesdlg toggle me'); set(g,'UserData',g2,'Tag',''); iGroup = iGroup+1; localData.LimGroup{iGroup} = []; localData.LimCheck(iGroup) = g2; localData.Enable{iGroup} = []; localData.Disable{iGroup} = []; end iGroup = iGroup+1; end buttonX(1) = (figPos(3)-4*buttonW-3*buttonPad)/2; for ib = 2:4 buttonX(ib) = buttonX(ib-1) + buttonW + buttonPad; end buttonProps = struct(... 'Parent',f,... 'Units','character',... 'BackgroundColor', bgcolor,... 'ForegroundColor', fgcolor,... 'Position', [0 BotMarginH buttonW buttonH],... 'Style', 'pushbutton'); buttonProps.Position(1) = buttonX(1); u = uicontrol(buttonProps,... 'Interruptible', 'off',... 'String', 'OK',... 'Callback', 'fm_axesdlg button ok'); buttonProps.Position(1) = buttonX(2); uicontrol(buttonProps,... 'Interruptible', 'off',... 'String', 'Cancel',... 'Callback', 'fm_axesdlg button cancel'); buttonProps.Position(1) = buttonX(3); uicontrol(buttonProps,... 'Interruptible', 'off',... 'String', 'Help',... 'Callback', 'fm_axesdlg showhelp me'); buttonProps.Position(1) = buttonX(4); uicontrol(buttonProps,... 'Interruptible', 'on',... 'String', 'Apply',... 'Callback', 'fm_axesdlg button apply'); % finish opening axes dialog box set(fig,'Pointer',oldPointer); set(f,'Visible','on','Pointer','arrow'); localData.axes = ax; catch set(fig,'Pointer',oldPointer); if exist('f') delete(f); end errordlg({'Couldn''t open axes properties dialog:' ... lasterr},... 'Error',... 'modal'); end function [val,setflag] = getval(f,tag) uic = findobj(f,'Tag',tag); setflag = 1; % Flag for setting properties on multiple axes switch get(uic,'Style') case 'edit' val = get(uic, 'String'); if isempty(val) setflag = 0; end case {'checkbox' 'radiobutton'} val = get(uic, 'Value'); setflag = ~strcmp(get(uic,'Enable'),'off'); if setflag && isstruct(get(uic,'UserData')); %---Making a previously non-common property, common LdeleteControl(uic) end end function val = setval(f,tag,val) uic = findobj(f,'Tag',tag); switch get(uic,'Style') case 'edit' set(uic, 'String',val); case {'checkbox' 'radiobutton'} set(uic, 'Value',val); end function localData = LApplySettings(f, localData) % get the values and set props: ax = localData.axes; iProp = 0; try % title val = getval(f,'Title'); switch class(val) case 'char' if ~isempty(val) && size(val,1)>1 % title returns as a string matrix % check for blank line at end of multiline title nTitleLines = size(val,1); if val(nTitleLines,:)==32 % true if all spaces val(nTitleLines,:) = []; setval(f,'Title',val); end end case 'cell' if length(val)>1 nTitleLines = length(val); if isempty(val{nTitleLines}) || val{nTitleLines}==32 val(nTitleLines) = []; end end end CommonTitle = get(findobj(f,'Tag','Title'),'UserData'); if ~(isempty(val) && length(ax)>1) || CommonTitle || length(ax)==1, t = get(ax,{'Title'}); set([t{:}],'String',val); if ~CommonTitle, % They are common, now set(findobj(f,'Tag','Title'),'UserData',1) end end data = getappdata(f,'ScribeAxesDialogData'); cols = 'XYZ'; for i = 1:data.nCols col = cols(i); %label CommonLabel = get(findobj(f,'Tag',[col 'Label']),'UserData'); val = getval(f,[col 'Label']); if ~(isempty(val) && length(ax)>1) || CommonLabel || length(ax)==1, t = get(ax,{[col 'Label']}); set([t{:}],'String',val) if ~CommonLabel, % They are common, now set(findobj(f,'Tag',[col 'Label']),'UserData',1) end end % scale [mode,setflag] = getval(f,[col 'ScaleLinear']); if setflag, iProp = iProp+1; axProps{iProp} = [col 'Scale']; modeswitch = {'log' 'linear'}; axVals{iProp} = modeswitch{mode+1}; % update immediately so that we get updated limits and ticks set(ax,axProps(iProp),axVals(iProp)); end % if setflag linearScale = mode; %limitmode [manual,setflag] = getval(f,[col 'LimMode']); valMax=[]; valMin=[]; limits=[]; if setflag iProp = iProp+1; axProps{iProp} = [col 'LimMode']; modeswitch = {'auto' 'manual'}; axVals{iProp} = modeswitch{manual+1}; if manual %limits valMin = str2double(getval(f,[col 'LimMin'])); valMax = str2double(getval(f,[col 'LimMax'])); % ranges checked on callbacks if ~(isnan(valMax) || isnan(valMin)), iProp = iProp+1; axProps{iProp} = [col 'Lim']; limits = [valMin valMax]; axVals{iProp} = limits; end else % auto set(ax,[col 'LimMode'],'auto'); % Check for common limits lim = get(ax,{[col 'Lim']}); lim = cat(1,lim{:}); Umin = unique(lim(:,1)); Umax = unique(lim(:,2)); if length(Umin)>1, uminStr = ''; else, uminStr = num2str(Umin); end if length(Umax)>1, umaxStr = ''; else, umaxStr = num2str(Umax); end setval(f, [col 'LimMin'], uminStr); setval(f, [col 'LimMax'], umaxStr); end % if manual end % if setflag %tickmode TickInd=[]; [manual,setflag] = getval(f,[col 'TickMode']); if setflag, iProp = iProp+1; axProps{iProp} = [col 'TickMode']; modeswitch = {'auto' 'manual'}; axVals{iProp} = modeswitch{manual+1}; if linearScale if manual tickstep = str2double(getval(f,[col 'TickStep'])); if ~isempty(tickstep), % Make sure something is there if ~isempty(limits), % Only preset ticks when everything is the same iProp = iProp+1; axProps{iProp} = [col 'Tick']; ticks = limits(1):tickstep:limits(2); % ranges checked on callbacks axVals{iProp} = ticks; else TickInd = iProp; end end else % auto set(ax,[col 'TickMode'],'auto'); if length(ax)==1 ticks = get(ax,[col 'Tick']); setval(f, [col 'TickStep'], ticks(2)-ticks(1)); end end % if manual else % log scale % manual mode disabled for log scale set(ax,[col 'TickMode'],'auto'); setval(f, [col 'TickStep'], ''); end end % if setflag % scale direction [mode,setflag] = getval(f,[col 'DirNormal']); if setflag, iProp = iProp+1; axProps{iProp} = [col 'Dir']; modeswitch = {'reverse' 'normal'}; axVals{iProp} = modeswitch{mode+1}; end % grid [mode,setflag] = getval(f,[col 'Grid']); if setflag, iProp = iProp+1; axProps{iProp} = [col 'Grid']; modeswitch = {'off' 'on'}; axVals{iProp} = modeswitch{mode+1}; end % if setflag if ~isempty(TickInd) || isnan(valMax) || isnan(valMin) % Going to have to loop thru to set limits/ticks individually for ct = 1:length(ax) limits = get(ax(ct),[col 'Lim']); axPropsCustom{1} = [col 'Lim']; if ~isnan(valMax), limits(2) = valMax; end if ~isnan(valMin), limits(1) = valMin; end axValsCustom{1} = limits; if ~isempty(TickInd); axPropsCustom{2} = [col 'Tick']; ticks = limits(1):tickstep:limits(2); % ranges checked on callbacks axValsCustom{2} = ticks; end % if ~isempty(TickInd) set(ax(ct),axPropsCustom,axValsCustom); end % for ct end end % for col set(ax,axProps,axVals) catch % error somewhere in there... end % try/catch function LdeleteControl(OldControl) ud = get(OldControl,'UserData'); set(ud.Sibling,'Value',get(OldControl,'Value'), ... 'Tag',get(OldControl,'Tag'),'UserData',[]) if isfield(ud,'OtherRadio'), ud2 = get(ud.OtherRadio,'UserData'); set(ud2.Sibling,'Value',get(ud.OtherRadio,'Value'), ... 'Tag',get(ud.OtherRadio,'Tag'),'UserData',[]) delete(ud.OtherRadio) end delete(OldControl) function LNoAxesError errordlg(['No axes are selected. Click on an axis to select it.']);
github
Sinan81/PSAT-master
runpsat.m
.m
PSAT-master/psat-mat/psat/runpsat.m
10,540
utf_8
9b670f8311e146f66ea289eefb24aa19
function runpsat(varargin) % RUNPSAT run PSAT routine for power system analysis % % RUNPSAT([FILE,[PATH]],[PERTFILE,[PERTPATH]],ROUTINE) % % FILE: string containing the PSAT data file (can be a % simulink model) % PATH: string containing the absolute path of the data % file (default path is "pwd") % PERTFILE: string containing the PSAT perturbation file % (default is the empty string) % PERTPATH: string containing the absolute path of the % perturbation file (default is the empty string) % ROUTINE: name of the routine to be launched: % % General options: % % 'data' => set data file % 'pert' => set perturbation file % 'opensys' => open saved system % 'savsys' => save currenst system % 'pfrep' => write power flow solution % 'eigrep' => write eigenvalue report file % 'pmurep' => write PMU placement report file % 'plot' => plot TD results (Octave only) % % Routines: % % 'pf' => power flow % 'cpf' => continuation power flow % 'snb' => SNB computation (direct method) % 'limit' => LIB computation % 'n1cont' => N-1 contingency analysis % 'opf' => optimal power flow % 'cpfatc' => ATC computation through CPF analysis % 'sensatc' => ATC computation through sensitivity % analysis % 'td' => time domain simulation % 'sssa' => small signal stability analysis % 'pmu' => PMU placement % 'gams' => OPF through PSAT-GAMS interface % 'uw' => CPF through PSAT-UWPFLOW interface % %Author: Federico Milano %Date: 23-Feb-2004 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Settings fm_var % last input is the routine type if nargin == 0 disp('Error: runpsat needs at least one argument.') return end routine = varargin{nargin}; if isnumeric(routine) fm_disp('Routine specifier must be a string.') return end % Simulink models are not supported on GNU/Octave if Settings.octave && strcmp(routine,'data') && ... ~isempty(findstr(varargin{1},'.mdl')) fm_disp('Simulink models are not supported on GNU/Octave') return end % check if the data file has been changed changedata = strcmp(routine,'data'); if nargin > 1 changedata = changedata || ~strcmp(varargin{1},File.data); end if changedata, Settings.init = 0; end % check inputs switch nargin case 5 File.data = varargin{1}; Path.data = checksep(varargin{2}); File.pert = varargin{3}; Path.pert = checksep(varargin{4}); case 4 File.data = varargin{1}; Path.data = checksep(varargin{2}); File.pert = varargin{3}; Path.pert = [pwd,filesep]; case 3 switch routine case 'data' File.data = varargin{1}; Path.data = checksep(varargin{2}); case 'pert' File.pert = varargin{1}; Path.pert = checksep(varargin{2}); case 'opensys' datafile = varargin{1}; datapath = checksep(varargin{2}); otherwise File.data = varargin{1}; Path.data = checksep(varargin{2}); File.pert = ''; Path.pert = ''; end case 2 switch routine case 'data' File.data = varargin{1}; Path.data = [pwd,filesep]; case 'pert' File.pert = varargin{1}; Path.pert = [pwd,filesep]; case 'opensys' datafile = varargin{1}; datapath = [pwd,filesep]; case 'plot' % nothing to do... otherwise File.data = varargin{1}; Path.data = [pwd,filesep]; File.pert = ''; Path.pert = ''; end case 1 % nothing to do... otherwise fm_disp('Invalid number of arguments: check synthax...') return end % remove extension from data file (only Matlab files) if length(File.data) >= 2 && strcmp(routine,'data') if strcmp(File.data(end-1:end),'.m') File.data = File.data(1:end-2); end end % remove extension from perturbation file (only Matlab files) if length(File.pert) >= 2 && strcmp(routine,'pert') if strcmp(File.pert(end-1:end),'.m') File.pert = File.pert(1:end-2); end end % set local path as data path to prevent undesired change % of path within user defined functions Path.local = Path.data; % check if the data file is a Simulink model File.data = strrep(File.data,'.mdl','(mdl)'); if ~isempty(findstr(File.data,'(mdl)')) filedata = deblank(strrep(File.data,'(mdl)','_mdl')); if exist(filedata) ~= 2 || clpsat.refreshsim || strcmp(routine,'data') check = sim2psat; if ~check, return, end File.data = filedata; end end % launch PSAT computations switch routine case 'data' % set data file % checking the consistency of the data file localpath = pwd; cd(Path.data) check = exist(File.data); cd(localpath) if check ~= 2 && check ~= 4 fm_disp(['Warning: The selected file is not valid or not in the ' ... 'current folder!']) else Settings.init = 0; end case 'pert' % set perturbation file localpath = pwd; cd(Path.pert) check = exist(File.pert); cd(localpath) % checking the consistency of the pert file if check ~= 2 fm_disp(['Warning: The selected file is not valid or not in the ' ... 'current folder!']) else localpath = pwd; cd(Path.pert) if Settings.hostver >= 6 Hdl.pert = str2func(File.pert); else Hdl.pert = File.pert; end cd(localpath) end case 'opensys' fm_set('opensys',datafile,datapath) Settings.init = 0; case 'savesys' fm_set('savesys') case 'log' fm_text(1) case 'pfrep' fm_report case 'eigrep' fm_eigen('report') case 'pf' % solve power flow if isempty(File.data) fm_disp('Set a data file before running Power Flow.',2) return end if clpsat.readfile || Settings.init == 0 fm_inilf filedata = [File.data,' ']; filedata = strrep(filedata,'@ ',''); if ~isempty(findstr(filedata,'(mdl)')) && clpsat.refreshsim filedata1 = File.data(1:end-5); open_sys = find_system('type','block_diagram'); OpenModel = sum(strcmp(open_sys,filedata1)); if OpenModel if strcmp(get_param(filedata1,'Dirty'),'on') || ... str2num(get_param(filedata1,'ModelVersion')) > Settings.mv check = sim2psat; if ~check, return, end end end end cd(Path.data) filedata = deblank(strrep(filedata,'(mdl)','_mdl')); a = exist(filedata); clear(filedata) if a == 2, b = dir([filedata,'.m']); lasterr(''); %if ~strcmp(File.modify,b.date) try fm_disp('Load data from file...') eval(filedata); File.modify = b.date; catch fm_disp(lasterr), fm_disp(['Something wrong with the data file "',filedata,'"']), return end %end else fm_disp(['File "',filedata,'" not found or not an m-file'],2) end cd(Path.local) Settings.init = 0; end if Settings.init fm_restore if Settings.conv, fm_base, end Line = build_y(Line); fm_wcall; fm_dynlf; end filedata = deblank(strrep(File.data,'(mdl)','_mdl')); if Settings.static % do not use dynamic components for i = 1:Comp.n comp_name = [Comp.names{i},'.con']; comp_con = eval(['~isempty(',comp_name,')']); if comp_con && ~Comp.prop(i,6) eval([comp_name,' = [];']); end end end % the following code is needed for compatibility with older PSAT versions if isfield(Varname,'bus') if ~isempty(Varname.bus) Bus.names = Varname.bus; Varname = rmfield(Varname,'bus'); end end if exist('Mot') if isfield(Mot,'con') Ind.con = Mot.con; clear Mot end end fm_spf SNB.init = 0; LIB.init = 0; CPF.init = 0; OPF.init = 0; case 'opf' % solve optimal power flow fm_set('opf') case 'cpf' % solve continuation power flow fm_cpf('main'); case 'cpfatc' % find ATC of the current system opftype = OPF.type; OPF.type = 4; fm_atc OPF.type = opftype; case 'sensatc' opftype = OPF.type; OPF.type = 5; fm_atc OPF.type = opftype; case 'n1cont' fm_n1cont; case 'td' % solve time domain simulation fm_int case 'sssa' % solve small signal stability analyisis fm_eigen('runsssa') case 'snb' fm_snb case 'lib' fm_limit case 'pmu' fm_pmuloc; case 'pmurep' fm_pmurep; case 'gams' % solve OPF using the PSAT-GAMS interface fm_gams case 'uw' % solve CPF using the PSAT-UWPFLOW interface fm_uwpflow('init') fm_uwpflow('uwrun') case 'plot' if ~Settings.octave fm_disp('This option is supported only on GNU/Octave') return end if isempty(Varout.t) fm_disp('No data is available for plotting') return end if nargin == 2 value = varargin{1}; else value = menu('Plot variables:','States','Voltage Magnitudes', ... 'Voltage Angles','Active Powers','Reactive Powers', ... 'Generator Speeds','Generator Angles'); end switch value case 1 if ~DAE.n fm_disp('No dynamic component is loaded') return end case {2,3,4,5} if ~Bus.n fm_disp('No bus is present in the current network') return end case {6,7} if ~Syn.n fm_disp('No synchronous generator is loaded') return end end switch value case 1 idx = intersect([1:DAE.n],Varname.idx); case 2 idx0 = DAE.n+Bus.n; idx = intersect([idx0+1:idx0+Bus.n],Varname.idx); case 3 idx0 = DAE.n; idx = intersect([idx0+1:idx0+Bus.n],Varname.idx); case 4 idx0 = DAE.n+DAE.m; idx = intersect([idx0+1:idx0+Bus.n],Varname.idx); case 5 idx0 = DAE.n+DAE.m+Bus.n; idx = intersect([idx0+1:idx0+Bus.n],Varname.idx); case 6 idx = intersect(Syn.omega,Varname.idx); case 7 idx = intersect(Syn.delta,Varname.idx); end if isempty(idx) fm_disp('The selected data have not been stored.') return end n = length(idx); y = Varout.vars(:,idx); s = Varname.uvars(idx); plot(Varout.t,y(:,1),['1;',strrep(s{1},'_',' '),';']) hold on for i = 2:n FMT = [num2str(rem(i-1,6)+1),';',strrep(s{i},'_',' '),';']; plot(Varout.t,y(:,i),FMT) end xlabel(Settings.xlabel) hold off otherwise % give an error message and exit fm_disp(['"',routine,'" is an invalid routine identifier.']) return end % ---------------------------------------------------------------- function string = checksep(string) if ~strcmp(string(end),filesep) string = [string,filesep]; end
github
Sinan81/PSAT-master
fm_dump.m
.m
PSAT-master/psat-mat/psat/fm_dump.m
1,579
utf_8
e82f5e57ff859c7a2cc916e8f07ee9d9
function fm_dump % FM_DUMP dump the current data file to a file % %Author: Federico Milano %Date: 28-Nov-2008 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano fm_var filename = [fm_filenum('m'), '.m']; [fid,msg] = fopen([Path.data,filename], 'wt'); if fid == -1 fm_disp(msg) return end dump_data(fid, Bus, 'Bus') dump_data(fid, SW, 'SW') dump_data(fid, PV, 'PV') for i = 1:(length(Comp.names)-2) dump_data(fid, eval(Comp.names{i}), Comp.names{i}) end dump_data(fid, Areas, 'Areas') dump_data(fid, Regions, 'Regions') dump_name(fid, Bus.names, 'Bus') dump_name(fid, Areas.names, 'Areas') dump_name(fid, Regions.names, 'Regions') fclose(fid); fm_disp(['Data dumped to file <', filename ,'>']) function dump_data(fid, var, name) if ~var.n, return, end fprintf(fid, '%s.con = [ ...\n', name); fprintf(fid, [var.format, ';\n'], var.store.'); fprintf(fid, ' ];\n\n'); function dump_name(fid, var, name) if isempty(var), return, end n = length(var); count = fprintf(fid, [name,'.names = {... \n ']); for i = 1:n-1 names = strrep(var{i,1},char(10),' '); names = strrep(var{i,1},'''',''''''); count = fprintf(fid, ['''',names,'''; ']); if rem(i,5) == 0; count = fprintf(fid,'\n '); end end if iscell(var) names = strrep(var{n,1},char(10),' '); names = strrep(var{n,1},'''',''''''); count = fprintf(fid, ['''',names,'''};\n\n']); else names = strrep(var,char(10),' '); names = strrep(var,'''',''''''); count = fprintf(fid, ['''',names,'''};\n\n']); end
github
Sinan81/PSAT-master
fm_laprint.m
.m
PSAT-master/psat-mat/psat/fm_laprint.m
67,335
utf_8
9f22107ad64af26a59a85b5285887c81
function fm_laprint(figno,filename,varargin) %FM_LAPRINT prints a figure for inclusion in LaTeX documents. % It creates an eps-file and a tex-file. The tex-file contains the % annotation of the figure such as titles, labels and texts. The % eps-file contains the non-text part of the figure as well as the % position of the text-objects. The packages 'epsfig' and 'psfrag' are % required for the LaTeX run. A postscript driver like 'dvips' is % required for printing. % % Usage: fm_laprint % % This opens a graphical user interface window, to control the % various options. It is self-explainatory. Just try it. % % Example: Suppose you have created a MATLAB Figure. Saving the figure % with LaPrint (using default values everywhere), creates the two % files unnamed.eps and unnamed.tex. The tex-file calls the % eps-file and can be included into a LaTeX document as follows: % .. \usepackage{epsfig,psfrag} .. % .. \input{unnamed} .. % This will create a figure of width 12cm in the LaTeX document. % Its texts (labels,title, etc) are set in LaTeX and have 80% of the % font size of the surrounding text. Figure widths, text font % sizes, file names and various other issues can be freely % adjusted using the interface window. % % Alternatively, you can control the behaviour of LaPrint using various % extra input arguments. This is recommended for advanced users only. % Help on advanced usage is obtained by typing fm_laprint({'AdvancedHelp'}). % % The document 'MATLAB graphics in LaTeX documents: Some tips and % a tool' contains more help on LaPrint and various examples. % It can be obtained along with the most recent version of LaPrint % from http://www.uni-kassel.de/~linne/matlab/. % known problems and limitations, things to do, ... % -- The matlab functions copyobj and plotedit have bugs. % If this is a problem, use option 'nofigcopy'. % -- multi-line text is not supported % -- cm is the only unit used (inches not supported) % -- a small preview would be nice % (c) Arno Linnemann. All rights reserved. % The author of this program assumes no responsibility for any errors % or omissions. In no event shall he be liable for damages arising out of % any use of the software. Redistribution of the unchanged file is allowed. % Distribution of changed versions is allowed provided the file is renamed % and the source and authorship of the original version is acknowledged in % the modified file. % Please report bugs, suggestions and comments to: % Arno Linnemann % Control and Systems Theory % Department of Electrical Engineering % University of Kassel % 34109 Kassel % Germany % mailto:[email protected] % http://www.uni-kassel.de/~linne/ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% Initialize %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% global LAPRINTOPT global LAPRINTHAN global Theme Fig laprintident = '2.03 (19.1.2000)'; vers=version; vers=eval(vers(1:3)); if vers < 5.0 fm_disp('LaPrint Error: Matlab 5.0 or above is required.',2) return end % no output if nargout fm_disp('La Print Error: No output argument is required.',2) return end if nargin==0 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% GUI %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ishandle(Fig.laprint), return, end %--------------------------------- % default values %--------------------------------- LAPRINTOPT.figno=gcf; LAPRINTOPT.filename='unnamed'; LAPRINTOPT.verbose=0; LAPRINTOPT.asonscreen=0; LAPRINTOPT.keepticklabels=0; LAPRINTOPT.mathticklabels=0; LAPRINTOPT.keepfontprops=0; LAPRINTOPT.extrapicture=1; LAPRINTOPT.loose=0; LAPRINTOPT.nofigcopy=0; LAPRINTOPT.nohead=0; LAPRINTOPT.noscalefonts=0; LAPRINTOPT.caption=0; LAPRINTOPT.commenttext=['Figure No. ' int2str(LAPRINTOPT.figno)]; LAPRINTOPT.width=12; LAPRINTOPT.factor=0.8; LAPRINTOPT.viewfile=0; LAPRINTOPT.viewfilename='unnamed_'; LAPRINTOPT.HELP=1; %--------------------------------- % open window %--------------------------------- hf = figure; Fig.laprint = hf; clf reset; set(hf,'NumberTitle','off') %set(hf,'CreateFcn','Fig.laprint = hf;') set(hf,'FileName','fm_laprint') set(hf,'DeleteFcn','fm_laprint({''quit''})') set(hf,'MenuBar','none') set(hf,'Color',Theme.color01) set(hf,'Name','LaPrint (LaTeX Print)') set(hf,'Units','points') set(hf,'Resize','off') h=uicontrol(hf); set(h,'Units','points') fsize=get(h,'Fontsize'); delete(h) posf=get(hf,'Position'); figheight=30*fsize; posf= [ posf(1) posf(2)+posf(4)-figheight ... 31*fsize figheight]; set(hf,'Position',posf) curh=figheight-0*fsize; %--------------------------------- % LaTeX logo %--------------------------------- h1 = axes('Parent',hf, ... 'Units','points', ... 'Box','on', ... 'CameraUpVector',[0 1 0], ... 'CameraUpVectorMode','manual', ... 'Color',Theme.color04, ... 'HandleVisibility','on', ... 'HitTest','off', ... 'Layer','top', ... 'Position',[23*fsize 20.5*fsize 7*fsize 7*fsize], ... 'Tag','Axes1', ... 'XColor',Theme.color03, ... 'XLim',[0.5 128.5], ... 'XLimMode','manual', ... 'XTickLabelMode','manual', ... 'XTickMode','manual', ... 'YColor',Theme.color03, ... 'YDir','reverse', ... 'YLim',[0.5 128.5], ... 'YLimMode','manual', ... 'YTickLabelMode','manual', ... 'YTickMode','manual', ... 'ZColor',[0 0 0]); h2 = image('Parent',h1, ... 'CData',fm_mat('misc_laprint'), ... 'Tag','Axes1Image1', ... 'XData',[1 128], ... 'YData',[1 128]); %--------------------------------- % figure no. %--------------------------------- loch=1.7*fsize; curh=curh-loch-1*fsize; h = uicontrol; set(h,'Parent',hf) set(h,'BackgroundColor',Theme.color01) set(h,'style','text') set(h,'Units','points') set(h,'Position',[1*fsize curh 8*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'string','Figure No.:') h = uicontrol; set(h,'Parent',hf) set(h,'Parent',hf) set(h,'style','edit') set(h,'FontName',Theme.font01) set(h,'BackgroundColor',Theme.color04) set(h,'ForegroundColor',Theme.color05) set(h,'Units','points') set(h,'Position',[10*fsize curh 3*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'String',int2str(LAPRINTOPT.figno)) set(h,'Callback','fm_laprint({''figno''});') LAPRINTHAN.figno=h; %--------------------------------- % filename %--------------------------------- loch=1.7*fsize; curh=curh-loch; h = uicontrol; set(h,'Parent',hf) set(h,'style','text') set(h,'BackgroundColor',Theme.color01) set(h,'Units','points') set(h,'Position',[1*fsize curh 8*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'string','filename (base):') h = uicontrol; set(h,'Parent',hf) set(h,'Parent',hf) set(h,'style','edit') set(h,'FontName',Theme.font01) set(h,'BackgroundColor',Theme.color04) set(h,'ForegroundColor',Theme.color05) set(h,'Units','points') set(h,'Position',[10*fsize curh 12*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'String',LAPRINTOPT.filename) set(h,'Callback','fm_laprint({''filename''});') LAPRINTHAN.filename=h; %--------------------------------- % width %--------------------------------- loch=1.7*fsize; curh=curh-loch-1*fsize; h = uicontrol; set(h,'Parent',hf) set(h,'style','text') set(h,'BackgroundColor',Theme.color01) set(h,'Units','points') set(h,'Position',[1*fsize curh 17*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'string','Width in LaTeX document [cm]:') h = uicontrol; set(h,'Parent',hf) set(h,'Parent',hf) set(h,'style','edit') set(h,'FontName',Theme.font01) set(h,'BackgroundColor',Theme.color04) set(h,'ForegroundColor',Theme.color05) set(h,'Units','points') set(h,'Position',[19*fsize curh 3*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'String',num2str(LAPRINTOPT.width)) set(h,'Callback','fm_laprint({''width''});') LAPRINTHAN.width=h; %--------------------------------- % factor %--------------------------------- loch=1.7*fsize; curh=curh-loch; h = uicontrol; set(h,'Parent',hf) set(h,'style','text') set(h,'BackgroundColor',Theme.color01) set(h,'Units','points') set(h,'Position',[1*fsize curh 17*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'string','Factor to scale fonts and eps figure:') h = uicontrol; set(h,'Parent',hf) set(h,'Parent',hf) set(h,'style','edit') set(h,'FontName',Theme.font01) set(h,'BackgroundColor',Theme.color04) set(h,'ForegroundColor',Theme.color05) set(h,'Units','points') set(h,'Position',[19*fsize curh 3*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'String',num2str(LAPRINTOPT.factor)) set(h,'Callback','fm_laprint({''factor''});') LAPRINTHAN.factor=h; %--------------------------------- % show sizes %--------------------------------- loch=1.7*fsize; curh=curh-loch; h = uicontrol; set(h,'Parent',hf) set(h,'style','text') set(h,'BackgroundColor',Theme.color01) set(h,'Units','points') set(h,'Position',[1*fsize curh 22*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'string',[ 'latex figure size: ' ]) LAPRINTHAN.texsize=h; loch=1.7*fsize; curh=curh-loch; h = uicontrol; set(h,'Parent',hf) set(h,'style','text') set(h,'BackgroundColor',Theme.color01) set(h,'Units','points') set(h,'Position',[1*fsize curh 22*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'string',[ 'postscript figure size: ' ]) LAPRINTHAN.epssize=h; %--------------------------------- % comment/caption text %--------------------------------- loch=1.7*fsize; curh=curh-loch-fsize; h = uicontrol; set(h,'Parent',hf) set(h,'style','text') set(h,'BackgroundColor',Theme.color01) set(h,'Units','points') set(h,'Position',[1*fsize curh 12*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'string','Comment/Caption text:') h = uicontrol; set(h,'Parent',hf) set(h,'style','edit') set(h,'FontName',Theme.font01) set(h,'BackgroundColor',Theme.color04) set(h,'ForegroundColor',Theme.color05) set(h,'Units','points') set(h,'Position',[14*fsize curh 16*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'String',LAPRINTOPT.commenttext) set(h,'Callback','fm_laprint({''commenttext''});') LAPRINTHAN.commenttext=h; %--------------------------------- % text %--------------------------------- loch=10*fsize; curh=curh-loch-fsize; h = uicontrol; set(h,'Parent',hf) set(h,'style','text') set(h,'FontName',Theme.font01) set(h,'BackgroundColor',Theme.color04) set(h,'ForegroundColor',Theme.color05) set(h,'Units','points') set(h,'Position',[1*fsize curh 29*fsize loch]) set(h,'HorizontalAlignment','left') %set(h,'BackgroundColor',[1 1 1]) LAPRINTHAN.helptext=h; if (isempty(get(LAPRINTOPT.figno,'children'))) txt=['Warning: Figure ' int2str(LAPRINTOPT.figno) ... ' is empty. There is nothing to do yet.' ]; else txt=''; end showtext({['This is LaPrint, Version ', laprintident, ... ', by Arno Linnemann. ', ... 'The present version was slightly modified by ', ... 'Federico Milano (17.12.2003) and can be used only from within ', ... 'PSAT. To get started, press ''Help'' below.', txt]}) showsizes; %--------------------------------- % save, quit, help %--------------------------------- loch=2*fsize; curh=curh-loch-fsize; h=uicontrol; set(h,'Parent',hf) set(h,'Style','pushbutton') set(h,'BackgroundColor',Theme.color01) set(h,'Units','Points') set(h,'Position',[23*fsize curh 5*fsize loch]) set(h,'HorizontalAlignment','center') set(h,'String','Quit') set(h,'Callback','fm_laprint({''quit''});') h=uicontrol; set(h,'Parent',hf) set(h,'Style','pushbutton') set(h,'BackgroundColor',Theme.color01) set(h,'Units','Points') set(h,'Position',[13*fsize curh 5*fsize loch]) set(h,'HorizontalAlignment','center') set(h,'String','Help') set(h,'Callback','fm_laprint({''help''});') h=uicontrol; set(h,'Parent',hf) set(h,'BackgroundColor',Theme.color03) set(h,'FontWeight','bold') set(h,'ForegroundColor',Theme.color09) set(h,'Style','pushbutton') set(h,'Units','Points') set(h,'Position',[3*fsize curh 5*fsize loch]) set(h,'HorizontalAlignment','center') set(h,'String','Export') set(h,'Callback','fm_laprint({''save''});') %--------------------------------- % options uimenue %--------------------------------- % Menu File h1 = uimenu('Parent',hf, ... 'Label','File', ... 'Tag','MenuFile'); h2 = uimenu('Parent',h1, ... 'Label', 'Export figure', ... 'Callback','fm_laprint({''save''});', ... 'Accelerator','s', ... 'Tag','file_save'); h2 = uimenu('Parent',h1, ... 'Label', 'Quit LaPrint', ... 'Callback','fm_laprint({''quit''});', ... 'Accelerator','x', ... 'Separator','on', ... 'Tag','file_quit'); hm=uimenu('label','Options'); LAPRINTHAN.asonscreen=uimenu(hm,... 'label','as on screen',... 'callback','fm_laprint({''asonscreen''})',... 'checked','off'); LAPRINTHAN.keepticklabels=uimenu(hm,... 'label','keep tick labels',... 'callback','fm_laprint({''keepticklabels''})',... 'checked','off'); LAPRINTHAN.mathticklabels=uimenu(hm,... 'label','math tick labels',... 'callback','fm_laprint({''mathticklabels''})',... 'checked','off'); LAPRINTHAN.keepfontprops=uimenu(hm,... 'label','keep font props',... 'callback','fm_laprint({''keepfontprops''})',... 'checked','off'); LAPRINTHAN.extrapicture=uimenu(hm,... 'label','extra picture',... 'callback','fm_laprint({''extrapicture''})',... 'checked','on'); LAPRINTHAN.loose=uimenu(hm,... 'label','print loose',... 'callback','fm_laprint({''loose''})',... 'checked','off'); LAPRINTHAN.nofigcopy=uimenu(hm,... 'label','figure copy',... 'callback','fm_laprint({''nofigcopy''})',... 'checked','on'); LAPRINTHAN.nohead=uimenu(hm,... 'label','file head',... 'callback','fm_laprint({''nohead''})',... 'checked','on'); LAPRINTHAN.noscalefonts=uimenu(hm,... 'label','scale fonts',... 'callback','fm_laprint({''noscalefonts''})',... 'checked','on'); LAPRINTHAN.caption=uimenu(hm,... 'label','caption',... 'callback','fm_laprint({''caption''})',... 'checked','off'); LAPRINTHAN.viewfile=uimenu(hm,... 'label','viewfile',... 'callback','fm_laprint({''viewfile''})',... 'checked','off'); uimenu(hm,... 'label','Defaults',... 'callback','laprint({''defaults''})',... 'separator','on'); % Menu Help h1 = uimenu('Parent',hf, ... 'Label','Help', ... 'Tag','MenuFile'); h2 = uimenu('Parent',h1, ... 'Label', 'LaPrint help', ... 'Callback','fm_laprint({''help''});', ... 'Accelerator','h', ... 'Tag','file_help'); h2 = uimenu('Parent',h1, ... 'label','About',... 'callback','fm_laprint({''whois''})'); %--------------------------------- % make hf invisible %--------------------------------- set(hf,'HandleVisibility','callback') return end % if nargin==0 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% callback calls %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isa(figno,'cell') switch lower(figno{1}) %%% figno %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'figno' global LAPRINTOPT global LAPRINTHAN LAPRINTOPT.figno=eval(get(LAPRINTHAN.figno,'string')); figure(LAPRINTOPT.figno) figure(Fig.laprint) txt=[ 'Pushing ''Export'' will save the contents of Figure No. '... int2str(LAPRINTOPT.figno) '.' ]; showtext({txt}); %%% filename %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'filename' global LAPRINTOPT global LAPRINTHAN LAPRINTOPT.filename=get(LAPRINTHAN.filename,'string'); LAPRINTOPT.viewfilename=[ LAPRINTOPT.filename '_']; [texfullnameext,texbasenameext,texbasename,texdirname] = ... getfilenames(LAPRINTOPT.filename,'tex',0); [epsfullnameext,epsbasenameext,epsbasename,epsdirname] = ... getfilenames(LAPRINTOPT.filename,'eps',0); txt0=[ 'Pushing ''save'' will create the following files:' ]; txt1=[ texfullnameext ' (LaTeX file)' ]; txt2=[ epsfullnameext ' (Postscript file)']; if exist(texfullnameext,'file') txt5=[ 'Warning: LaTeX file exists an will be overwritten.']; else txt5=''; end if exist(epsfullnameext,'file') txt6=[ 'Warning: Postscript file exists an will be overwritten.']; else txt6=''; end if LAPRINTOPT.viewfile [viewfullnameext,viewbasenameext,viewbasename,viewdirname] = ... getfilenames(LAPRINTOPT.viewfilename,'tex',0); txt3=[ viewfullnameext ' (View file)']; if exist(viewfullnameext,'file') txt7=[ 'Warning: View file exists an will be overwritten.']; else txt7=''; end else txt3=''; txt7=''; end showtext({txt0,txt1,txt2,txt3,txt5,txt6,txt7}); %%% width %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'width' global LAPRINTOPT global LAPRINTHAN LAPRINTOPT.width=eval(get(LAPRINTHAN.width,'string')); txt1=[ 'The width of the figure in the LaTeX document is set to '... int2str(LAPRINTOPT.width) ' cm. Its height is determined '... 'by the aspect ratio of the figure on screen '... '(i.e. the figure ''position'' property).']; showtext({txt1}); showsizes; %%% factor %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'factor' global LAPRINTOPT global LAPRINTHAN LAPRINTOPT.factor=eval(get(LAPRINTHAN.factor,'string')); txt1=[ 'The factor to scale the fonts and the eps figure is set to '... num2str(LAPRINTOPT.factor) '.']; if LAPRINTOPT.factor < 1 txt2=[ 'Thus the (bounding box of the) eps figure is ' ... 'larger than the figure in the LaTeX document ' ... 'and the text fonts of the figure are ' ... 'by the factor ' num2str(LAPRINTOPT.factor) ' smaller ' ... 'than the fonts of the surrounding text.']; elseif LAPRINTOPT.factor > 1 txt2=[ 'Thus the (bounding box of the) eps figure ' ... 'is smaller than the figure in the LaTeX document. ' ... 'Especially, the text fonts of the figure are ' ... 'by the factor ' num2str(LAPRINTOPT.factor) ' larger ' ... 'than the fonts of the surrounding text.']; else txt2=[ 'Thus the eps figure is displayed 1:1.'... 'Especially, the text fonts of the figure are of ' ... 'the same size as the fonts of the surrounding text.']; end showtext({txt1,txt2}); showsizes; case 'commenttext' global LAPRINTOPT global LAPRINTHAN LAPRINTOPT.commenttext=get(LAPRINTHAN.commenttext,'string'); txt=[ 'The comment text is displayed in the commenting header '... 'of the tex file. This is for bookkeeping only.' ... 'If the option ''caption'' is set to ''on'', then '... 'this text is also displayed in the caption of the figure.']; showtext({txt}); %%% options %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'asonscreen' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', the ticks, ticklabels '... 'and lims are printed ''as on screen''. Note that the '... 'aspect ratio of the printed figure is always equal '... 'to the aspect ratio on screen.']; if LAPRINTOPT.asonscreen==1 LAPRINTOPT.asonscreen=0; set(LAPRINTHAN.asonscreen,'check','off') txt2= 'Current setting is: off'; else LAPRINTOPT.asonscreen=1; set(LAPRINTHAN.asonscreen,'check','on') txt2='Current setting is: on'; end showtext({txt1, txt2}); case 'keepticklabels' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', the tick labels '... 'are kept within the eps-file and are therefore not set '... 'in LaTeX. This option is useful for some rotated 3D plots.']; if LAPRINTOPT.keepticklabels==1 LAPRINTOPT.keepticklabels=0; set(LAPRINTHAN.keepticklabels,'check','off') txt2= 'Current setting is: off'; else LAPRINTOPT.keepticklabels=1; set(LAPRINTHAN.keepticklabels,'check','on') txt2='Current setting is: on'; end showtext({txt1, txt2}); case 'mathticklabels' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', the tick labels '... 'are set in LaTeX math mode.']; if LAPRINTOPT.mathticklabels==1 LAPRINTOPT.mathticklabels=0; set(LAPRINTHAN.mathticklabels,'check','off') txt2= 'Current setting is: off'; else LAPRINTOPT.mathticklabels=1; set(LAPRINTHAN.mathticklabels,'check','on') txt2='Current setting is: on'; end showtext({txt1, txt2}); case 'keepfontprops' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', LaPrint tries to ',... 'translate the MATLAB font properties (size, width, ',... 'angle) into similar LaTeX font properties. Set to ''off'', ',... 'LaPrint does not introduce any LaTeX font selection commands.']; if LAPRINTOPT.keepfontprops==1 LAPRINTOPT.keepfontprops=0; set(LAPRINTHAN.keepfontprops,'check','off') txt2= 'Current setting is: off'; else LAPRINTOPT.keepfontprops=1; set(LAPRINTHAN.keepfontprops,'check','on') txt2='Current setting is: on'; end showtext({txt1, txt2}); case 'loose' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', LaPrint uses the ',... '''-loose'' option in the Matlab print command. ']; if LAPRINTOPT.loose==1 LAPRINTOPT.loose=0; set(LAPRINTHAN.loose,'check','off') txt2= 'Current setting is: off'; else LAPRINTOPT.loose=1; set(LAPRINTHAN.loose,'check','on') txt2='Current setting is: on'; end showtext({txt1, txt2}); case 'extrapicture' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', LaPrint adds an ',... 'extra picture environment to each axis correponding to a '... '2D plot. The picture ',... 'is empty, but alows to place LaTeX objects in arbitrary ',... 'positions by editing the tex file. ']; if LAPRINTOPT.extrapicture==1 LAPRINTOPT.extrapicture=0; set(LAPRINTHAN.extrapicture,'check','off') txt2= 'Current setting is: off'; else LAPRINTOPT.extrapicture=1; set(LAPRINTHAN.extrapicture,'check','on') txt2='Current setting is: on'; end showtext({txt1, txt2}); case 'nofigcopy' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', LaPrint creates a temporary ',... 'figure to introduce the tags. If set to ''off'', it directly ',... 'modifies the original figure. ' ... 'There are some bugs in the Matlab copyobj '... 'command. If you encounter these cases, set this '... 'option to ''off''.']; if LAPRINTOPT.nofigcopy==1 LAPRINTOPT.nofigcopy=0; set(LAPRINTHAN.nofigcopy,'check','on') txt2= 'Current setting is: on'; else LAPRINTOPT.nofigcopy=1; set(LAPRINTHAN.nofigcopy,'check','off') txt2='Current setting is: off'; end showtext({txt1, txt2}); case 'nohead' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', LaPrint ',... 'adds a commenting head to the tex-file. To save disk '... 'space, out can turn this option ''off''.']; if LAPRINTOPT.nohead==1 LAPRINTOPT.nohead=0; set(LAPRINTHAN.nohead,'check','on') txt2= 'Current setting is: on'; else LAPRINTOPT.nohead=1; set(LAPRINTHAN.nohead,'check','off') txt2='Current setting is: off'; end showtext({txt1, txt2}); case 'noscalefonts' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', LaPrint scales the ',... 'fonts with the figure. With this option set to '... '''off'', the font size in the figure is equal to the '... 'size of the surrounding text.']; if LAPRINTOPT.noscalefonts==1 LAPRINTOPT.noscalefonts=0; set(LAPRINTHAN.noscalefonts,'check','on') txt2= 'Current setting is: on'; else LAPRINTOPT.noscalefonts=1; set(LAPRINTHAN.noscalefonts,'check','off') txt2='Current setting is: off'; end showtext({txt1, txt2}); case 'caption' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', LaPrint adds ',... '\caption{' LAPRINTOPT.commenttext ,... '} and \label{fig:' LAPRINTOPT.filename '} entries ',... 'to the tex-file.']; if LAPRINTOPT.caption==1 LAPRINTOPT.caption=0; set(LAPRINTHAN.caption,'check','off') txt2= 'Current setting is: off'; else LAPRINTOPT.caption=1; set(LAPRINTHAN.caption,'check','on') txt2='Current setting is: on'; end showtext({txt1, txt2}); case 'viewfile' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', LaPrint creates an ',... 'additional file ' LAPRINTOPT.viewfilename ... '.tex containing a LaTeX document ',... 'which calls the tex-file.']; if LAPRINTOPT.viewfile==1 LAPRINTOPT.viewfile=0; set(LAPRINTHAN.viewfile,'check','off') txt2= 'Current setting is: off'; else LAPRINTOPT.viewfile=1; set(LAPRINTHAN.viewfile,'check','on') txt2='Current setting is: on'; end showtext({txt1, txt2}); case 'defaults' global LAPRINTOPT global LAPRINTHAN LAPRINTOPT.asonscreen=0; LAPRINTOPT.keepticklabels=0; LAPRINTOPT.mathticklabels=0; LAPRINTOPT.keepfontprops=0; LAPRINTOPT.extrapicture=1; LAPRINTOPT.loose=0; LAPRINTOPT.nofigcopy=0; LAPRINTOPT.nohead=0; LAPRINTOPT.noscalefonts=0; LAPRINTOPT.caption=0; LAPRINTOPT.viewfile=0; set(LAPRINTHAN.asonscreen,'check','off') set(LAPRINTHAN.keepticklabels,'check','off') set(LAPRINTHAN.mathticklabels,'check','off') set(LAPRINTHAN.keepfontprops,'check','off') set(LAPRINTHAN.extrapicture,'check','off') set(LAPRINTHAN.loose,'check','off') set(LAPRINTHAN.nofigcopy,'check','on') set(LAPRINTHAN.nohead,'check','on') set(LAPRINTHAN.noscalefonts,'check','on') set(LAPRINTHAN.caption,'check','off') set(LAPRINTHAN.viewfile,'check','off') showtext({[ 'All options availabe through the menu bar '... 'are set to their default values.']}); case 'whois' showtext({'To blame for LaPrint:',... 'Arno Linnemann','Control and Systems Theory',... 'Department of Electrical Engineering',... 'University of Kassel',... '34109 Kassel | mailto:[email protected]'... 'Germany | http://www.uni-kassel.de/~linne/'}) %%% help %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'help' global LAPRINTOPT global LAPRINTHAN txt0='...Press ''Help'' again to continue....'; if LAPRINTOPT.HELP==1 txt=[ 'LAPRINT prints a figure for inclusion in LaTeX documents. ',... 'It creates an eps-file and a tex-file. The tex-file contains the ',... 'annotation of the figure such as titles, labels and texts. The ',... 'eps-file contains the non-text part of the figure as well as the ',... 'position of the text-objects.']; txt={txt,txt0}; elseif LAPRINTOPT.HELP==2 txt1= [ 'The packages epsfig and psfrag are ',... 'required for the LaTeX run. A postscript driver like dvips is ',... 'required for printing. ' ]; txt2=' '; txt3= ['It is recommended to switch off the Matlab TeX ' ... 'interpreter before using LaPrint:']; txt4= ' >> set(0,''DefaultTextInterpreter'',''none'')'; txt={txt1,txt2,txt3,txt4,txt0}; elseif LAPRINTOPT.HELP==3 txt1= [ 'EXAMPLE: Suppose you have created a MATLAB Figure.']; txt2= [ 'Saving the figure with LaPrint (using default '... 'values everywhere), creates the two files unnamed.eps '... 'and unnamed.tex. The tex-file calls the eps-file '... 'and can be included into a LaTeX document as follows:']; txt={txt1,txt2,txt0}; elseif LAPRINTOPT.HELP==4 txt1=' ..'; txt2=' \usepackage{epsfig,psfrag}'; txt3=' ..'; txt4=' \input{unnamed}'; txt5=' ..'; txt={txt1,txt2,txt3,txt4,txt5,txt0}; elseif LAPRINTOPT.HELP==5 txt1=[ 'This will create a figure of width 12cm in the LaTeX '... 'document. Its texts (labels,title, etc) are set in '... 'LaTeX and have 80% of the font size of the '... 'surrounding text.']; txt={txt1,txt0}; elseif LAPRINTOPT.HELP==6 txt1=[ 'The LaTeX figure width, the scaling factor and the '... 'file names can be adjusted using '... 'this interface window.']; txt2=[ 'More options are available through the menu bar above. '... 'Associated help is displayed as you change the options.']; txt={txt1,txt2,txt0}; elseif LAPRINTOPT.HELP==7 txt1=[ 'The document ''MATLAB graphics in LaTeX documents: '... 'Some tips and a tool'' contains more help on LaPrint '... 'and various examples. It can be obtained along '... 'with the most recent version of LaPrint from '... 'http://www.uni-kassel.de/~linne/matlab/.']; txt2=[ 'Please report bugs, suggestions '... 'and comments to [email protected].']; txt={txt1,txt2,txt0}; else txt={'Have fun!'}; LAPRINTOPT.HELP=0; end LAPRINTOPT.HELP=LAPRINTOPT.HELP+1; showtext(txt); %%% quit %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'quit' LAPRINTHAN=[]; LAPRINTOPT=[]; delete(Fig.laprint) Fig.laprint = -1; %%% Advanced Help %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'advancedhelp' disp(' ') disp('Advanced usage: fm_laprint(figno,filename,opt1,opt2,..)') disp('where ') disp(' figno : integer, figure to be printed') disp(' filename : string, basename of files to be created') disp(' opt1,.. : strings, describing optional inputs as follows') disp('') disp(' ''width=xx'' : xx is the width of the figure in the tex') disp(' file (in cm).') disp(' ''factor=xx'' : xx is the factor by which the figure in ') disp(' the LaTeX document is smaller than the figure') disp(' in the postscript file.') disp(' A non-positive number for xx lets the factor') disp(' be computed such that the figure in the') disp(' postscript file has the same size as the') disp(' figure on screen.') disp(' ''asonscreen'' : prints a graphics ''as on screen'',') disp(' retaining ticks, ticklabels and lims.') disp(' ''verbose'' : verbose mode; asks before overwriting') disp(' files and issues some more messages.') disp(' ''keepticklabels'': keeps the tick labels within the eps-file') disp(' ''mathticklabels'': tick labels are set in LaTeX math mode') disp(' ''keepfontprops'' : tries to translate the MATLAB font') disp(' properties (size, width, angle) into') disp(' similar LaTeX font properties.') disp(' ''noscalefonts'' : does not scale the fonts with the figure.') disp(' ''noextrapicture'': does not add extra picture environments.') disp(' ''loose'' : uses ''-loose'' in the Matlab print command.') disp(' ''nofigcopy'' : directly modifies the figure figno.') disp(' ''nohead'' : does not place a commenting head in ') disp(' the tex-file. ') disp(' ''caption=xx'' : adds \caption{xx} and \label{fig:filename}') disp(' entries to the tex-file.') disp(' ''comment=xx'' : places the comment xx into the header') disp(' of the tex-file') disp(' ''viewfile=xx'' : creates an additional file xx.tex') disp(' containing a LaTeX document which calls') disp(' the tex-file.') disp(' ') %%% save %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'save' global LAPRINTOPT global LAPRINTHAN global Fig psatfigs = fieldnames(Fig); for hhh = 1:length(psatfigs) psatfigno = getfield(Fig,psatfigs{hhh}); if psatfigno == LAPRINTOPT.figno fm_choice('Exporting PSAT GUIs using LaPrint is not allowed.',2) return end end lapcmd = [ 'fm_laprint(' int2str(LAPRINTOPT.figno) ... ', ''' LAPRINTOPT.filename ''''... ', ''width=' num2str(LAPRINTOPT.width) '''' ... ', ''factor=' num2str(LAPRINTOPT.factor) '''' ]; if LAPRINTOPT.verbose lapcmd = [ lapcmd ,', ''verbose''' ]; end if LAPRINTOPT.asonscreen lapcmd = [ lapcmd ,', ''asonscreen''' ]; end if LAPRINTOPT.keepticklabels lapcmd = [ lapcmd ,', ''keepticklabels''' ]; end if LAPRINTOPT.mathticklabels lapcmd = [ lapcmd ,', ''mathticklabels''' ]; end if LAPRINTOPT.keepfontprops lapcmd = [ lapcmd ,', ''keepfontprops''' ]; end if ~LAPRINTOPT.extrapicture lapcmd = [ lapcmd ,', ''noextrapicture''' ]; end if LAPRINTOPT.loose lapcmd = [ lapcmd ,', ''loose''' ]; end if LAPRINTOPT.nofigcopy lapcmd = [ lapcmd ,', ''nofigcopy''' ]; end if LAPRINTOPT.nohead lapcmd = [ lapcmd ,', ''nohead''' ]; end if LAPRINTOPT.noscalefonts lapcmd = [ lapcmd ,', ''noscalefonts''' ]; end if LAPRINTOPT.caption lapcmd = [ lapcmd ,', ''caption=' LAPRINTOPT.commenttext '''' ]; end if length(LAPRINTOPT.commenttext) lapcmd = [ lapcmd ,', ''comment=' LAPRINTOPT.commenttext '''' ]; end if LAPRINTOPT.viewfile lapcmd = [ lapcmd ,', ''viewfile=' LAPRINTOPT.viewfilename '''' ]; end lapcmd = [ lapcmd ')']; showtext({'Saving using:', lapcmd }); eval(lapcmd) otherwise fm_disp('LaPrint Error: unknown callback option!',2) end return end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% PART 1 of advanced usage: %%%% Check inputs and initialize %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % called directly or via gui? directcall=1; iswarning=0; if exist('LAPRINTHAN','var') if ~isempty(LAPRINTHAN) directcall=0; end end if nargin==1 if ~isa(figno,'char') filename='unnamed'; else filename=figno; figno=gcf; end end if ~isa(figno,'double') fm_disp(['LaPrint Error: "',num2str(figno),'" is not a figure handle.'],2) return end if ~any(get(0,'children')==figno) fm_disp(['LaPrint Error: "',num2str(figno),'" is not a figure handle.'],2) return end if ~isa(filename,'char') filename fm_disp(['La Print Error: file name is not valid.'],2) return end % default values furtheroptions=''; verbose=0; asonscreen=0; keepticklabels=0; mathticklabels=0; keepfontprops=0; extrapicture=1; loose=0; nofigcopy=0; nohead=0; noscalefonts=0; caption=0; commenttext=''; captiontext=''; width=12; factor=0.8; viewfile=0; % read and check options if nargin>2 for i=1:nargin-2 if ~isa(varargin{i},'char') fm_disp('LaPrint Error: Options must be character arrays.',2) return end oriopt=varargin{i}(:)'; opt=[ lower(strrep(oriopt,' ','')) ' ' ]; if strcmp(opt(1:7),'verbose') verbose=1; furtheroptions=[ furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:10),'asonscreen') asonscreen=1; furtheroptions=[furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:14),'keepticklabels') keepticklabels=1; furtheroptions=[furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:14),'mathticklabels') mathticklabels=1; furtheroptions=[furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:13),'keepfontprops') keepfontprops=1; furtheroptions=[furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:14),'noextrapicture') extrapicture=0; furtheroptions=[furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:5),'loose') loose=1; furtheroptions=[furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:9),'nofigcopy') nofigcopy=1; furtheroptions=[furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:12),'noscalefonts') noscalefonts=1; furtheroptions=[furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:6),'nohead') nohead=1; furtheroptions=[furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:7),'caption') caption=1; eqpos=findstr(oriopt,'='); if isempty(eqpos) furtheroptions=[furtheroptions ' / ' deblank(opt) ]; captiontext=[]; else furtheroptions=[furtheroptions ' / ' oriopt ]; captiontext=oriopt(eqpos+1:length(oriopt)); end elseif strcmp(opt(1:8),'comment=') eqpos=findstr(oriopt,'='); furtheroptions=[furtheroptions ' / ' oriopt ]; commenttext=oriopt(eqpos(1)+1:length(oriopt)); elseif strcmp(opt(1:9),'viewfile=') viewfile=1; eqpos=findstr(oriopt,'='); furtheroptions=[furtheroptions ' / ' oriopt ]; viewfilename=oriopt(eqpos(1)+1:length(oriopt)); elseif strcmp(opt(1:6),'width=') eval([ opt ';' ]); elseif strcmp(opt(1:7),'factor=') eval([ opt ';' ]); else fm_disp(['LaPrint Error: Option ' varargin{i} ' not recognized.'],2) return end end end furtheroptions=strrep(strrep(furtheroptions,'\','\\'),'%','%%'); captiontext=strrep(strrep(captiontext,'\','\\'),'%','%%'); commenttext=strrep(strrep(commenttext,'\','\\'),'%','%%'); if verbose, fm_disp(['This is LaPrint, version ',laprintident,'.']); end if mathticklabels Do='$'; else Do=''; end % eps- and tex- filenames [epsfullnameext,epsbasenameext,epsbasename,epsdirname]= ... getfilenames(filename,'eps',verbose); [texfullnameext,texbasenameext,texbasename,texdirname]= ... getfilenames(filename,'tex',verbose); if ~strcmp(texdirname,epsdirname) fm_disp(['LaPrint Warning: eps-file and tex-file are placed in ' ... 'different directories.']) iswarning=1; end if viewfile [viewfullnameext,viewbasenameext,viewbasename,viewdirname]= ... getfilenames(viewfilename,'tex',verbose); if strcmp(texfullnameext,viewfullnameext) fm_disp(['LaPrint Error: The tex- and view-file coincide. Use ' ... 'different names.'],2) return end if ~strcmp(texdirname,viewdirname) fm_disp(['LaPrint Warning: eps-file and view-file are placed '... 'in different directories.']) iswarning=1; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% PART 2 of advanced usage: %%%% Create new figure, insert tags, and bookkeep original text %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % open new figure (if required) and set properties if ~nofigcopy figno=copyobj(figno,0); set(figno,'Numbertitle','off') set(figno,'MenuBar','none') pause(0.5) end if asonscreen xlimmodeauto=findobj(figno,'xlimmode','auto'); xtickmodeauto=findobj(figno,'xtickmode','auto'); xticklabelmodeauto=findobj(figno,'xticklabelmode','auto'); ylimmodeauto=findobj(figno,'ylimmode','auto'); ytickmodeauto=findobj(figno,'ytickmode','auto'); yticklabelmodeauto=findobj(figno,'yticklabelmode','auto'); zlimmodeauto=findobj(figno,'zlimmode','auto'); ztickmodeauto=findobj(figno,'ztickmode','auto'); zticklabelmodeauto=findobj(figno,'zticklabelmode','auto'); set(xlimmodeauto,'xlimmode','manual') set(xtickmodeauto,'xtickmode','manual') set(xticklabelmodeauto,'xticklabelmode','manual') set(ylimmodeauto,'ylimmode','manual') set(ytickmodeauto,'ytickmode','manual') set(yticklabelmodeauto,'yticklabelmode','manual') set(zlimmodeauto,'ylimmode','manual') set(ztickmodeauto,'ytickmode','manual') set(zticklabelmodeauto,'yticklabelmode','manual') end set(figno,'paperunits','centimeters'); set(figno,'units','centimeters'); %oripp=get(figno,'PaperPosition'); orip=get(figno,'Position'); if factor <= 0 factor=width/orip(3); end latexwidth=width; epswidth=latexwidth/factor; epsheight = epswidth*orip(4)/orip(3); set(figno,'PaperPosition',[1 1 epswidth epsheight ]) set(figno,'Position',[orip(1)+0.5 orip(2)-0.5 epswidth epsheight ]) set(figno,'Name',[ 'To be printed; size: ' num2str(factor,3) ... ' x (' num2str(epswidth,3) 'cm x ' num2str(epsheight,3) 'cm)' ]) asonscreen_dummy=0; if asonscreen_dummy set(xlimmodeauto,'xlimmode','auto') set(xtickmodeauto,'xtickmode','auto') set(xticklabelmodeauto,'xticklabelmode','auto') set(ylimmodeauto,'ylimmode','auto') set(ytickmodeauto,'ytickmode','auto') set(yticklabelmodeauto,'yticklabelmode','auto') set(zlimmodeauto,'ylimmode','auto') set(ztickmodeauto,'ytickmode','auto') set(zticklabelmodeauto,'yticklabelmode','auto') end % some warnings if directcall if (epswidth<13) || (epsheight<13*0.75) disp('warning: The size of the eps-figure is quite small.') disp(' The text objects might not be properly set.') disp(' Reducing ''factor'' might help.') end if latexwidth/epswidth<0.5 disp([ 'warning: The size of the eps-figure is large compared ' ... 'to the latex figure.' ]) disp(' The text size might be too small.') disp(' Increasing ''factor'' might help.') end if (orip(3)-epswidth)/orip(3) > 0.1 disp(['warning: The size of the eps-figure is much smaller '... 'than the original']) disp(' figure on screen. Matlab might save different ticks and') disp([ ' ticklabels than in the original figure. See option ' ... '''asonsceen''. ' ]) end end if verbose disp('Strike any key to continue.'); pause end % % TEXT OBJECTS: modify new figure % % find all text objects hxl=get(findobj(figno,'type','axes'),'xlabel'); hyl=get(findobj(figno,'type','axes'),'ylabel'); hzl=get(findobj(figno,'type','axes'),'zlabel'); hti=get(findobj(figno,'type','axes'),'title'); hte=findobj(figno,'type','text'); % array of all text handles htext=unique([ celltoarray(hxl) celltoarray(hyl) celltoarray(hzl) ... celltoarray(hti) celltoarray(hte)]); nt=length(htext); % generate new strings and store old ones oldstr=get(htext,'string'); newstr=cell(nt,1); basestr='str00'; for i=1:nt if isa(oldstr{i},'cell') if length(oldstr{i})>1 disp('LaPrint warning: Annotation in form of a cell is currently') disp(' not supported. Ignoring all but first component.') iswarning=1; end % To do: place a parbox here. oldstr{i}=oldstr{i}{1}; end if size(oldstr{i},1)>1 disp([ 'LaPrint warning: Annotation in form of string matrices ' ... 'is currently not supported.' ]) disp(' Ignoring all but first row.') iswarning=1; % To do: place a parbox here. oldstr{i}=oldstr{i}(1,:); end if length(oldstr{i}) oldstr{i}=strrep(strrep(oldstr{i},'\','\\'),'%','%%'); newstr{i} = overwritetail(basestr,i); else newstr{i}=''; end end % replace strings in figure for i=1:nt set(htext(i),'string',newstr{i}); %set(htext(i),'visible','on'); end % get alignments hora=get(htext,'HorizontalAlignment'); vera=get(htext,'VerticalAlignment'); align=cell(nt,1); for i=1:nt align{i}=hora{i}(1); if strcmp(vera{i},'top') align{i}=[align{i} 't']; elseif strcmp(vera{i},'cap') align{i}=[align{i} 't']; elseif strcmp(vera{i},'middle') align{i}=[align{i} 'c']; elseif strcmp(vera{i},'baseline') align{i}=[align{i} 'B']; elseif strcmp(vera{i},'bottom') align{i}=[align{i} 'b']; end end % get font properties and create commands if nt > 0 [fontsizecmd{1:nt}] = deal(''); [fontanglecmd{1:nt}] = deal(''); [fontweightcmd{1:nt}] = deal(''); end selectfontcmd=''; if keepfontprops % fontsize set(htext,'fontunits','points'); fontsize=get(htext,'fontsize'); for i=1:nt fontsizecmd{i}=[ '\\fontsize{' num2str(fontsize{i}) '}{' ... num2str(fontsize{i}*1.5) '}' ]; end % fontweight fontweight=get(htext,'fontweight'); for i=1:nt if strcmp(fontweight{i},'light') fontweightcmd{i}=[ '\\fontseries{l}\\mathversion{normal}' ]; elseif strcmp(fontweight{i},'normal') fontweightcmd{i}=[ '\\fontseries{m}\\mathversion{normal}' ]; elseif strcmp(fontweight{i},'demi') fontweightcmd{i}=[ '\\fontseries{sb}\\mathversion{bold}' ]; elseif strcmp(fontweight{i},'bold') fontweightcmd{i}=[ '\\fontseries{bx}\\mathversion{bold}' ]; else disp([ ' LaPrint warning: unknown fontweight:' fontweight{i} ]) iswarning=1; fontweightcmd{i}=[ '\\fontseries{m}\\mathversion{normal}' ]; end end % fontangle fontangle=get(htext,'fontangle'); for i=1:nt if strcmp(fontangle{i},'normal') fontanglecmd{i}=[ '\\fontshape{n}' ]; elseif strcmp(fontangle{i},'italic') fontanglecmd{i}=[ '\\fontshape{it}' ]; elseif strcmp(fontangle{i},'oblique') fontangle{i}=[ '\\fontshape{it}' ]; else disp([ ' LaPrint warning: unknown fontangle:' fontangle{i} ]) iswarning=1; fontanglecmd{i}=[ '\\fontshape{n}' ]; end end selectfontcmd= '\\selectfont '; end % % LABELS: modify new figure % if ~keepticklabels % all axes hax=celltoarray(findobj(figno,'type','axes')); na=length(hax); if directcall % try to figure out if we have 3D axes an warn issuewarning=0; for i=1:na issuewarning=max(issuewarning,is3d(hax(i))); end if issuewarning disp('LaPrint warning: There seems to be a 3D plot. The LaTeX labels are') disp(' possibly incorrect. The option ''keepticklabels'' might') disp(' help. The option ''nofigcopy'' might be wise, too.') end end % try to figure out if we linear scale with extra factor % and determine powers of 10 powers=NaN*zeros(na,3); % matrix with powers of 10 for i=1:na % all axes allxyz={ 'x', 'y', 'z' }; for ixyz=1:3 % x,y,z xyz=allxyz{ixyz}; ticklabelmode=get(hax(i),[ xyz 'ticklabelmode']); if strcmp(ticklabelmode,'auto') tick=get(hax(i),[ xyz 'tick']); ticklabel=get(hax(i),[ xyz 'ticklabel']); nticks=size(ticklabel,1); if nticks==0, powers(i,ixyz)=0; end for k=1:nticks % all ticks label=str2num(ticklabel(k,:)); if length(label)==0, powers(i,ixyz)=0; break; end if ( label==0 ) && ( abs(tick(k))>1e-10 ) powers(i,ixyz)=0; break; end if label~=0 expon=log10(tick(k)/label); rexpon=round(expon); if abs(rexpon-expon)>1e-10 powers(i,ixyz)=0; break; end if isnan(powers(i,ixyz)) powers(i,ixyz)=rexpon; else if powers(i,ixyz)~=rexpon powers(i,ixyz)=0; break; end end end end % k else % if 'auto' powers(i,ixyz)=0; end % if 'auto' end % ixyz end % i % replace all ticklabels and bookkeep nxlabel=zeros(1,na); nylabel=zeros(1,na); nzlabel=zeros(1,na); allxyz={ 'x', 'y', 'z' }; for ixyz=1:3 xyz=allxyz{ixyz}; k=1; basestr=[ xyz '00' ]; if strcmp(xyz,'y') % 'y' is not horizontally centered! basestr='v00'; end oldtl=cell(na,1); newtl=cell(na,1); nlabel=zeros(1,na); for i=1:na % set(hax(i),[ xyz 'tickmode' ],'manual') % set(hax(i),[ xyz 'ticklabelmode' ],'manual') oldtl{i}=chartocell(get(hax(i),[ xyz 'ticklabel' ])); nlabel(i)=length(oldtl{i}); newtl{i}=cell(1,nlabel(i)); for j=1:nlabel(i) newtl{i}{j} = overwritetail(basestr,k); k=k+1; oldtl{i}{j}=deblank(strrep(strrep(oldtl{i}{j},'\','\\'),'%','%%')); end set(hax(i),[ xyz 'ticklabel' ],newtl{i}); end eval([ 'old' xyz 'tl=oldtl;' ]); eval([ 'new' xyz 'tl=newtl;' ]); eval([ 'n' xyz 'label=nlabel;' ]); end % determine latex commands for font properties if keepfontprops % font size afsize=zeros(na,1); for i=1:na afsize(i)=get(hax(i),'fontsize'); end if (any(afsize ~= afsize(1) )) disp('LaPrint warning: Different font sizes for axes not supported.') disp([ ' All axses will have font size ' ... num2str(afsize(1)) '.' ] ) iswarning=1; end afsizecmd = [ '\\fontsize{' num2str(afsize(1)) '}{' ... num2str(afsize(1)*1.5) '}' ]; % font weight afweight=cell(na,1); for i=1:na afweight{i}=get(hax(i),'fontweight'); end if strcmp(afweight{1},'light') afweightcmd=[ '\\fontseries{l}\\mathversion{normal}' ]; elseif strcmp(afweight{1},'normal') afweightcmd=[ '\\fontseries{m}\\mathversion{normal}' ]; elseif strcmp(afweight{1},'demi') afweightcmd=[ '\\fontseries{sb}\\mathversion{bold}' ]; elseif strcmp(afweight{1},'bold') afweightcmd=[ '\\fontseries{bx}\\mathversion{bold}' ]; else disp([ ' LaPrint warning: unknown fontweight:' afweight{1} ]) iswarning=1; afweightcmd=[ '\\fontseries{m}\\mathversion{normal}' ]; end for i=1:na if ~strcmp(afweight{i},afweight{1}) disp(' LaPrint warning: Different font weights for axes not') disp([ ' supported. All axes will have font weight ' afweightcmd]) iswarning=1; end end % font angle afangle=cell(na,1); for i=1:na afangle{i}=get(hax(i),'fontangle'); end if strcmp(afangle{1},'normal') afanglecmd=[ '\\fontshape{n}' ]; elseif strcmp(afangle{1},'italic') afanglecmd=[ '\\fontshape{it}' ]; elseif strcmp(afangle{1},'oblique') afanglecmd=[ '\\fontshape{it}' ]; else disp([ ' LaPrint warning: unknown fontangle:' afangle{1} ]) iswarning=1; afanglecmd=[ '\\fontshape{n}' ]; end for i=1:na if ~strcmp(afangle{i},afangle{1}) disp('LaPrint warning: Different font angles for axes not supported.') disp([ ' All axes will have font angle ' afanglecmd ] ) iswarning=1; end end end end % % extra picture environment % if extrapicture unitlength=zeros(na,1); ybound=zeros(na,1); for i=1:na if ~is3d(hax(i)) xlim=get(hax(i),'xlim'); ylim=get(hax(i),'ylim'); axes(hax(i)); hori=text(ylim(1),ylim(1),[ 'origin' int2str(i) ]); set(hori,'VerticalAlignment','bottom'); set(hori,'Fontsize',2); pos=get(hax(i),'Position'); unitlength(i)=pos(3)*epswidth; ybound(i)=(pos(4)*epsheight)/(pos(3)*epswidth); else if directcall disp('LaPrint warning: Option ''extrapicture'' for 3D axes not supported.') end end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% PART 3 of advanced usage: %%%% save eps and tex files %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % save eps file % if ~loose cmd=[ 'print(''-deps'',''-f' int2str(figno) ''',''' epsfullnameext ''')' ]; else cmd=[ 'print(''-deps'',''-loose'',''-f' int2str(figno) ... ''',''' epsfullnameext ''')' ]; end if verbose disp([ 'executing: '' ' cmd ' ''' ]); end eval(cmd); % % create latex file % if verbose disp([ 'writing to: '' ' texfullnameext ' ''' ]) end fid=fopen(texfullnameext,'w'); % head if ~nohead fprintf(fid,[ '%% This file is generated by the MATLAB m-file fm_laprint.m.' ... ' It can be included\n']); fprintf(fid,[ '%% into LaTeX documents using the packages epsfig and ' ... 'psfrag. It is accompanied\n' ]); fprintf(fid, '%% by a postscript file. A sample LaTeX file is:\n'); fprintf(fid, '%% \\documentclass{article} \\usepackage{epsfig,psfrag}\n'); fprintf(fid,[ '%% \\begin{document}\\begin{figure}\\input{' ... texbasename '}\\end{figure}\\end{document}\n' ]); fprintf(fid, [ '%% See http://www.uni-kassel.de/~linne/ for recent ' ... 'versions of fm_laprint.m.\n' ]); fprintf(fid, '%%\n'); fprintf(fid,[ '%% created by: ' 'LaPrint version ' ... laprintident '\n' ]); fprintf(fid,[ '%% created on: ' datestr(now) '\n' ]); fprintf(fid,[ '%% options used: ' furtheroptions '\n' ]); fprintf(fid,[ '%% latex width: ' num2str(latexwidth) ' cm\n' ]); fprintf(fid,[ '%% factor: ' num2str(factor) '\n' ]); fprintf(fid,[ '%% eps file name: ' epsbasenameext '\n' ]); fprintf(fid,[ '%% eps bounding box: ' num2str(epswidth) ... ' cm x ' num2str(epsheight) ' cm\n' ]); fprintf(fid,[ '%% comment: ' commenttext '\n' ]); fprintf(fid,'%%\n'); else fprintf(fid,[ '%% generated by fm_laprint.m\n' ]); fprintf(fid,'%%\n'); end % go on fprintf(fid,'\\begin{psfrags}%%\n'); %fprintf(fid,'\\fontsize{10}{12}\\selectfont%%\n'); fprintf(fid,'\\psfragscanon%%\n'); % text strings numbertext=0; for i=1:nt numbertext=numbertext+length(newstr{i}); end if numbertext>0, fprintf(fid,'%%\n'); fprintf(fid,'%% text strings:\n'); for i=1:nt if length(newstr{i}) alig=strrep(align{i},'c',''); fprintf(fid,[ '\\psfrag{' newstr{i} '}[' alig '][' alig ']{' ... fontsizecmd{i} fontweightcmd{i} fontanglecmd{i} selectfontcmd ... oldstr{i} '}%%\n' ]); end end end % labels if ~keepticklabels if keepfontprops fprintf(fid,'%%\n'); fprintf(fid,'%% axes font properties:\n'); fprintf(fid,[ afsizecmd afweightcmd '%%\n' ]); fprintf(fid,[ afanglecmd '\\selectfont%%\n' ]); end nxlabel=zeros(1,na); nylabel=zeros(1,na); nzlabel=zeros(1,na); for i=1:na nxlabel(i)=length(newxtl{i}); nylabel(i)=length(newytl{i}); nzlabel(i)=length(newztl{i}); end allxyz={ 'x', 'y', 'z' }; for ixyz=1:3 xyz=allxyz{ixyz}; eval([ 'oldtl=old' xyz 'tl;' ]); eval([ 'newtl=new' xyz 'tl;' ]); eval([ 'nlabel=n' xyz 'label;' ]); if sum(nlabel) > 0 fprintf(fid,'%%\n'); fprintf(fid,[ '%% ' xyz 'ticklabels:\n']); if xyz=='x' poss='[t][t]'; else poss='[r][r]'; end for i=1:na if nlabel(i) if strcmp(get(hax(i),[ xyz 'scale']),'linear') % lin scale % all but last for j=1:nlabel(i)-1 fprintf(fid,[ '\\psfrag{' newtl{i}{j} '}' poss '{' ... Do oldtl{i}{j} Do '}%%\n' ]); end % last rexpon=powers(i,ixyz); if rexpon if xyz=='x' fprintf(fid,[ '\\psfrag{' newtl{i}{nlabel(i)} ... '}' poss '{\\shortstack{' ... Do oldtl{i}{nlabel(i)} Do '\\\\$\\times 10^{'... int2str(rexpon) '}\\ $}}%%\n' ]); else fprintf(fid,[ '\\psfrag{' newtl{i}{nlabel(i)} ... '}' poss '{' Do oldtl{i}{nlabel(i)} Do ... '\\setlength{\\unitlength}{1ex}%%\n' ... '\\begin{picture}(0,0)\\put(0.5,1.5){$\\times 10^{' ... int2str(rexpon) '}$}\\end{picture}}%%\n' ]); end else fprintf(fid,[ '\\psfrag{' newtl{i}{nlabel(i)} '}' poss '{' ... Do oldtl{i}{nlabel(i)} Do '}%%\n' ]); end else % log scale for j=1:nlabel fprintf(fid,[ '\\psfrag{' newtl{i}{j} '}' poss '{$10^{' ... oldtl{i}{j} '}$}%%\n' ]); end end end end end end end % extra picture if extrapicture fprintf(fid,'%%\n'); fprintf(fid,'%% extra picture(s):\n'); for i=1:na fprintf(fid,[ '\\psfrag{origin' int2str(i) '}[lb][lb]{' ... '\\setlength{\\unitlength}{' ... num2str(unitlength(i),'%5.5f') 'cm}%%\n' ]); fprintf(fid,[ '\\begin{picture}(1,' ... num2str(ybound(i),'%5.5f') ')%%\n' ]); %fprintf(fid,'\\put(0,0){}%% lower left corner\n'); %fprintf(fid,[ '\\put(1,' num2str(ybound(i),'%5.5f') ... % '){}%% upper right corner\n' ]); fprintf(fid,'\\end{picture}%%\n'); fprintf(fid,'}%%\n'); end end % figure fprintf(fid,'%%\n'); fprintf(fid,'%% Figure:\n'); if caption fprintf(fid,[ '\\parbox{' num2str(latexwidth) 'cm}{\\centering%%\n' ]); end if noscalefonts fprintf(fid,[ '\\epsfig{file=' epsbasenameext ',width=' ... num2str(latexwidth) 'cm}}%%\n' ]); else fprintf(fid,[ '\\resizebox{' num2str(latexwidth) 'cm}{!}' ... '{\\epsfig{file=' epsbasenameext '}}%%\n' ]); end if caption if isempty(captiontext) captiontext=[ texbasenameext ', ' epsbasenameext ]; end fprintf(fid,[ '\\caption{' captiontext '}%%\n' ]); fprintf(fid,[ '\\label{fig:' texbasename '}%%\n' ]); fprintf(fid,[ '}%%\n' ]); end fprintf(fid,'\\end{psfrags}%%\n'); fprintf(fid,'%%\n'); fprintf(fid,[ '%% End ' texbasenameext '\n' ]); fclose(fid); set(figno,'Name','Printed by LaPrint') if ~nofigcopy if verbose disp('Strike any key to continue.'); pause end close(figno) end % % create view file % if viewfile if verbose disp([ 'writing to: '' ' viewfullnameext ' ''' ]) end fid=fopen(viewfullnameext,'w'); if ~nohead fprintf(fid,[ '%% This file is generated by fm_laprint.m.\n' ]); fprintf(fid,[ '%% It calls ' texbasenameext ... ', which in turn calls ' epsbasenameext '.\n' ]); fprintf(fid,[ '%% Process this file using\n' ]); fprintf(fid,[ '%% latex ' viewbasenameext '\n' ]); fprintf(fid,[ '%% dvips -o' viewbasename '.ps ' viewbasename '.dvi' ... '\n']); fprintf(fid,[ '%% ghostview ' viewbasename '.ps&\n' ]); else fprintf(fid,[ '%% generated by fm_laprint.m\n' ]); end fprintf(fid,[ '\\documentclass{article}\n' ]); fprintf(fid,[ '\\usepackage{epsfig,psfrag,a4}\n' ]); fprintf(fid,[ '\\usepackage[latin1]{inputenc}\n' ]); if ~strcmp(epsdirname,viewdirname) %disp([ 'warning: The view-file has to be supplemented by '... % 'path information.' ]) fprintf(fid,[ '\\graphicspath{{' epsdirname '}}\n' ]); end fprintf(fid,[ '\\begin{document}\n' ]); fprintf(fid,[ '\\pagestyle{empty}\n' ]); fprintf(fid,[ '\\begin{figure}[ht]\n' ]); fprintf(fid,[ ' \\begin{center}\n' ]); if strcmp(texdirname,viewdirname) %fprintf(fid,[ ' \\fbox{\\input{' texbasenameext '}}\n' ]); fprintf(fid,[ ' \\input{' texbasenameext '}\n' ]); else %fprintf(fid,[ ' \\fbox{\\input{' texdirname texbasenameext '}}\n' ]); fprintf(fid,[ ' \\input{' texdirname texbasenameext '}\n' ]); end fprintf(fid,[ ' %% \\caption{A LaPrint figure}\n' ]); fprintf(fid,[ ' %% \\label{fig:' texbasename '}\n' ]); fprintf(fid,[ ' \\end{center}\n' ]); fprintf(fid,[ '\\end{figure}\n' ]); fprintf(fid,[ '\\vfill\n' ]); fprintf(fid,[ '\\begin{flushright}\n' ]); fprintf(fid,[ '\\tiny printed with LaPrint on ' ... datestr(now) '\\\\\n' ]); fprintf(fid,[ '\\verb+' viewdirname viewbasenameext '+\\\\\n' ]); fprintf(fid,[ '\\verb+( ' texdirname texbasenameext ' )+\\\\\n' ]); fprintf(fid,[ '\\verb+( ' epsdirname epsbasenameext ' )+\n' ]); fprintf(fid,[ '\\end{flushright}\n' ]); fprintf(fid,[ '\\end{document}\n' ]); fclose(fid); if verbose yn=input([ 'Perform LaTeX run on ' viewbasenameext '? (y/n) '],'s'); if strcmp(yn,'y') cmd=[ '!latex ' viewbasenameext ]; disp([ 'executing: '' ' cmd ' ''' ]); eval(cmd); yn=input([ 'Perform dvips run on ' viewbasename '.dvi? (y/n) '],'s'); if strcmp(yn,'y') cmd=[ '!dvips -o' viewbasename '.ps ' viewbasename '.dvi' ]; disp([ 'executing: '' ' cmd ' ''' ]); eval(cmd); yn=input([ 'Call ghostview on ' viewbasename '.ps? (y/n) '],'s'); if strcmp(yn,'y') cmd=[ '!ghostview ' viewbasename '.ps&' ]; disp([ 'executing: '' ' cmd ' ''' ]); eval(cmd); end end end end end if ~directcall && iswarning showtext({'Watch the LaPrint messages in the command window!'},'add') end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% functions used %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function showtext(txt,add) global LAPRINTHAN txt=textwrap(LAPRINTHAN.helptext,txt); if nargin==1 set(LAPRINTHAN.helptext,'string','') set(LAPRINTHAN.helptext,'string',txt) else txt0=get(LAPRINTHAN.helptext,'string'); set(LAPRINTHAN.helptext,'string','') set(LAPRINTHAN.helptext,'string',{txt0{:},txt{:}}) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function showsizes() global LAPRINTOPT global LAPRINTHAN figpos=get(LAPRINTOPT.figno,'position'); latexwidth=LAPRINTOPT.width; latexheight=latexwidth*figpos(4)/figpos(3); epswidth=latexwidth/LAPRINTOPT.factor; epsheight=latexheight/LAPRINTOPT.factor; set(LAPRINTHAN.texsize,'string',[ 'latex figure size: ' num2str(latexwidth) ... 'cm x ' num2str(latexheight) 'cm' ]) set(LAPRINTHAN.epssize,'string',[ 'postscript figure size: ' ... num2str(epswidth) ... 'cm x ' num2str(epsheight) 'cm' ]) % some warnings txt1=' '; txt2=' '; txt3=' '; if (epswidth<13) || (epsheight<13*0.75) txt1=['Warning: The size of the eps-figure is quite small. '... 'Text objects might not be properly set. ']; showtext({txt1},'add') end if LAPRINTOPT.factor<0.5 txt2=['Warning: The ''factor'' is quite small. ' ... 'The text size might be too small.']; showtext({txt2},'add') end if ((figpos(3)-epswidth)/figpos(3)>0.1) && ~LAPRINTOPT.asonscreen txt3=['Warning: The size of the eps-figure is much smaller '... 'than the figure on screen. '... 'Consider using option ''as on sceen''.' ]; showtext({txt3},'add') end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fullnameext,basenameext,basename,dirname]= getfilenames(... filename,extension,verbose); % appends an extension to a filename (as '/home/tom/tt') and determines % fullnameext: filename with extension with dirname, as '/home/tom/tt.tex' % basenameext: filename with extension without dirname, as 'tt.tex' % basename : filename without extension without dirname, as 'tt' % dirname : dirname without filename, as '/home/tom/' % In verbose mode, it asks if to overwrite or to modify. % [dirname, basename] = splitfilename(filename); fullnameext = [ dirname basename '.' extension ]; basenameext = [ basename '.' extension ]; if verbose quest = (exist(fullnameext)==2); while quest yn=input([ fullnameext ' exists. Overwrite? (y/n) '],'s'); if strcmp(yn,'y') quest=0; else filename=input( ... [ 'Please enter new filename (without extension .' ... extension '): ' ],'s'); [dirname, basename] = splitfilename(filename); fullnameext = [ dirname basename '.' extension ]; basenameext = [ basename '.' extension ]; quest = (exist(fullnameext)==2); end end end if ( exist(dirname)~=7 && ~strcmp(dirname,[ '.' filesep ]) ... && ~strcmp(dirname,filesep) ) fm_disp(['LaPrint Error: Directory ',dirname,' does not exist.'],2) return end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [dirname,basename]=splitfilename(filename); % splits filename into dir and base slashpos=findstr(filename,filesep); nslash=length(slashpos); nfilename=length(filename); if nslash dirname = filename(1:slashpos(nslash)); basename = filename(slashpos(nslash)+1:nfilename); else dirname = pwd; nn=length(dirname); if ~strcmp(dirname(nn),filesep) dirname = [ dirname filesep ]; end basename = filename; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function yesno=is3d(haxes); % tries to figure out if axes is 3D yesno=0; CameraPosition=get(haxes,'CameraPosition'); CameraTarget=get(haxes,'CameraTarget'); CameraUpVector=get(haxes,'CameraUpVector'); if CameraPosition(1)~=CameraTarget(1) yesno=1; end if CameraPosition(2)~=CameraTarget(2) yesno=1; end if any(CameraUpVector~=[0 1 0]) yesno=1; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function b=celltoarray(a); % converts a cell of doubles to an array if iscell(a), b=[]; for i=1:length(a), b=[b a{i}]; end else, b=a(:)'; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function b=chartocell(a) % converts a character array into a cell array of characters % convert to cell if isa(a,'char') n=size(a,1); b=cell(1,n); for j=1:n b{j}=a(j,:); end else b=a; end % convert to char n=length(b); for j=1:n if isa(b{j},'double') b{j}=num2str(b{j}); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function b=overwritetail(a,k) % overwrites tail of a by k % a,b: strings % k: integer ks=int2str(k); b = [ a(1:(length(a)-length(ks))) ks ]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
Sinan81/PSAT-master
fm_writexls.m
.m
PSAT-master/psat-mat/psat/fm_writexls.m
6,451
utf_8
d360fea56202b900aa531d108d3cf13d
function fm_writexls(Matrix,Header,Cols,Rows,File) % FM_WRITEXLS export PSAT results to an Microsoft Excel % spreadsheet using Matlab ActiveX interface. % Microsoft Excel is required. % % This function is based on xlswrite.m by Scott Hirsch % % FM_WRITEXLS(MATRIX,HEDAER,COLNAMES,ROWNAMES,FILENAME) % % MATRIX Matrix to write to file % Cell array for multiple matrices. % HEADER String of header information. % Cell array for multiple header. % COLNAMES (Cell array of strings) Column headers. % One cell element per column. % ROWNAMES (Cell array of strings) Row headers. % One cell element per row. % FILENAME (string) Name of Excel file. % If not specified, contents will be % opened in Excel. % %Author: Federico Milano %Date: 13-Sep-2003 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Path if ~iscell(Matrix) Matrix{1,1} = Matrix; Header{1,1} = Header; Cols{1,1} = Cols; Rows{1,1} = Rows; end % Open Excel, add workbook, change active worksheet, % get/put array, save. % First, open an Excel Server. Excel = actxserver('Excel.Application'); % If the user does not specify a filename, we'll make Excel % visible if they do, we'll just save the file and quit Excel % without ever making it visible %if nargin < 5 set(Excel, 'Visible', 1); %end; % Insert a new workbook. Workbooks = Excel.Workbooks; Workbook = invoke(Workbooks, 'Add'); % Make the first sheet active. Sheets = Excel.ActiveWorkBook.Sheets; sheet1 = get(Sheets, 'Item', 1); invoke(sheet1, 'Activate'); % Get a handle to the active sheet. Activesheet = Excel.Activesheet; % -------------------------------------------------------------------- % writing data % -------------------------------------------------------------------- nhr = 0; for i_matrix = 1:length(Matrix) m = Matrix{i_matrix}; colnames = Cols{i_matrix}; rownames = Rows{i_matrix}; header = Header{i_matrix}; [nr,nc] = size(m); if nc > 256 fm_disp(['Matrix is too large. Excel only supports 256' ... ' columns'],2) delete(Excel) return end % Write header % ----------------------------------------------------------------- if ~isempty(header) if iscell(header) % Number header rows for ii=1:length(header) jj = nhr + ii; ActivesheetRange = get(Activesheet, ... 'Range', ... ['A',num2str(jj)], ... ['A',num2str(jj)]); set(ActivesheetRange, 'Value', header{ii}); end nhr = nhr + length(header); else % Number header rows nhr = nhr + 1; hcol = ['A',num2str(nhr)]; ActivesheetRange = get(Activesheet,'Range',hcol,hcol); set(ActivesheetRange, 'Value', header); end end %Add column names % ----------------------------------------------------------------- if nargin > 2 && ~isempty(colnames) [nrows,ncolnames] = size(colnames); for hh = 1:nrows nhr = nhr + 1; for ii = 1:ncolnames colname = localComputLastCol('A',ii); cellname = [colname,num2str(nhr)]; ActivesheetRange = get(Activesheet,'Range',cellname,cellname); set(ActivesheetRange, 'Value', colnames{hh,ii}); end end end % Put a MATLAB array into Excel. % ----------------------------------------------------------------- % Data start right after the headers FirstRow = nhr + 1; LastRow = FirstRow + nr - 1; % First column depends on the dimension of rownames [nrownames,ncols] = size(rownames); if nargin < 3 || isempty(rownames) FirstCol = 'A'; elseif isempty(colnames) FirstCol = 'D'; else switch ncols case 1, FirstCol = 'B'; case 2, FirstCol = 'C'; case 3, FirstCol = 'D'; case 4, FirstCol = 'E'; case 5, FirstCol = 'F'; otherwise, FirstCol = 'G'; end end if ~isempty(m) LastCol = localComputLastCol(FirstCol,nc); ActivesheetRange = get(Activesheet,'Range', ... [FirstCol,num2str(FirstRow)], ... [LastCol,num2str(LastRow)]); set(ActivesheetRange,'Value',full(m)); end %Add row names % ----------------------------------------------------------------- if nargin > 3 && ~isempty(rownames) %nrownames = length(rownames); for ii = 1:nrownames for jj = 1:ncols switch jj case 1, Col = 'A'; case 2, Col = 'B'; case 3, Col = 'C'; case 4, Col = 'D'; case 5, Col = 'E'; otherwise, Col = 'F'; end %rowname = localComputLastCol('A',FirstRow+ii-1); cellname = [Col,num2str(FirstRow + ii - 1)]; ActivesheetRange = get(Activesheet,'Range',cellname,cellname); set(ActivesheetRange, 'Value', rownames{ii,jj}); end end end % add a blank row in between data % ----------------------------------------------------------------- nhr = LastRow + 1; end % If user specified a filename, save the file and quit Excel % ------------------------------------------------------------------- if nargin == 5 invoke(Workbook, 'SaveAs', [Path.data,File]); %invoke(Excel, 'Quit'); fm_disp(['Excel file ',Path.data,File,' has been created.']); end %Delete the ActiveX object % ------------------------------------------------------------------- delete(Excel) % Local functions % ------------------------------------------------------------------- function LastCol = localComputLastCol(FirstCol,nc); % Compute the name of the last column where we will place data % Input: % FirstCol (string) name of first column % nc total number of columns to write % Excel's columns are named: % A B C ... A AA AB AC AD .... BA BB BC ... % Offset from column A FirstColOffset = double(FirstCol) - double('A'); % Easy if single letter % Just convert to ASCII code, add the number of needed columns, % and convert back to a string if nc<=26-FirstColOffset LastCol = char(double(FirstCol)+nc-1); else % Number of groups (of 26) ng = ceil(nc/26); % How many extra in this group beyond A rm = rem(nc,26)+FirstColOffset; LastColFirstLetter = char(double('A') + ng-2); LastColSecondLetter = char(double('A') + rm-1); LastCol = [LastColFirstLetter LastColSecondLetter]; end;
github
Sinan81/PSAT-master
fm_stat.m
.m
PSAT-master/psat-mat/psat/fm_stat.m
25,703
utf_8
0f115765ed53c6cedf9b89e96c923f29
function fig = fm_stat(varargin) % FM_STAT create GUI for power flow reports % % HDL = FM_STAT(VARARGIN) % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 24-Aug-2003 %Version: 2.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Bus DAE Varname Settings Fig Path OPF Theme global Oxl File abus = DAE.y(Bus.a); vbus = DAE.y(Bus.v); if nargin && ischar(varargin{1}) switch varargin{1} case 'report' if OPF.init == 1 || OPF.init == 2 fm_opfrep else fm_report end case 'toplist' value = get(gcbo,'Value'); set(gcbo,'Value',value(end)) set(get(gcf,'UserData'), ... 'Value',value(end), ... 'ListboxTop',get(gcbo,'ListboxTop')); case 'checkabs' hdl = findobj(Fig.stat,'Tag','CheckABS'); switch get(gcbo,'Checked') case 'on' set(gcbo,'Checked','off') Settings.absvalues = 'off'; set(hdl,'Value',0); case 'off' set(gcbo,'Checked','on') Settings.absvalues = 'on'; set(hdl,'Value',1); end case 'report_type' switch get(gcbo,'Checked') case 'on' set(gcbo,'Checked','off') Settings.report = 0; case 'off' set(gcbo,'Checked','on') Settings.report = 1; end case 'violation' hdl = findobj(Fig.stat,'Tag','CheckVIOL'); switch get(gcbo,'Checked') case 'on' set(gcbo,'Checked','off') Settings.violations = 'off'; set(hdl,'Value',0); case 'off' set(gcbo,'Checked','on') Settings.violations = 'on'; set(hdl,'Value',1); end case 'abscheck' hdl = findobj(Fig.stat,'Tag','absvalues'); switch get(gcbo,'Value') case 1 Settings.absvalues = 'on'; set(hdl,'Checked','on'); case 0 Settings.absvalues = 'off'; set(hdl,'Checked','off'); end case 'violcheck' hdl = findobj(Fig.stat,'Tag','violations'); switch get(gcbo,'Value') case 1 Settings.violations = 'on'; set(hdl,'Checked','on'); case 0 Settings.violations = 'off'; set(hdl,'Checked','off'); end case 'sort' hdl = findobj(gcf,'Tag','PushSort'); maxn = 150; switch get(hdl,'UserData') case 'az' [a,ordbus] = sortbus(Bus,maxn); [a,ordbus] = sort(getidx(Bus,ordbus)); h = get(gcf,'UserData'); for i = 1:length(h) String = get(h(i),'String'); set(h(i),'String',String(ordbus)) end set(hdl,'UserData','1n','CData',fm_mat('stat_sort12')) case '1n' [a,ordbus] = sortbus(Bus,maxn); h = get(gcf,'UserData'); for i = 1:length(h) String = get(h(i),'String'); set(h(i),'String',String(ordbus)) end set(hdl,'UserData','az','CData',fm_mat('stat_sortaz')) end case 'kvpu' hdl = findobj(gcf,'Tag','PushVoltage'); switch get(hdl,'UserData') case 'pu' set(findobj(Fig.stat,'Tag','ListboxV'),'String',setvar(vbus.*getkv(Bus,0,0))); set(hdl,'UserData','kv','CData',fm_mat('stat_kv')) case 'kv' set(findobj(Fig.stat,'Tag','ListboxV'),'String',setvar(vbus)); set(hdl,'UserData','pu','CData',fm_mat('stat_pu')) end case 'plotv' hdl = findobj(gcf,'Tag','PushVoltage'); figure switch get(hdl,'UserData') case 'pu' bar(vbus) ylabel('V [p.u.]') case 'kv' bar(vbus.*getkv(Bus,0,0)) ylabel('V [kV]') end title('Voltage Magnitude Profile') xlabel('Bus #') case 'raddeg' hdl = findobj(gcf,'Tag','PushAngle'); switch get(hdl,'UserData') case 'deg' set(findobj(Fig.stat,'Tag','ListboxAng'),'String',setvar(abus)); set(hdl,'UserData','rad','CData',fm_mat('stat_rad')) case 'rad' set(findobj(Fig.stat,'Tag','ListboxAng'),'String',setvar(abus*180/pi)); set(hdl,'UserData','deg','CData',fm_mat('stat_deg')) end case 'plota' hdl = findobj(gcf,'Tag','PushAngle'); figure switch get(hdl,'UserData') case 'rad' bar(abus) ylabel('\theta [rad]') case 'deg' bar(abus*180/pi) ylabel('\theta [deg]') end title('Voltage Phase Profile') xlabel('Bus #') case 'realpower' hdl1 = findobj(gcf,'Tag','PushPGL'); switch get(hdl1,'UserData') case 'I', set(hdl1,'UserData','L') case 'G', set(hdl1,'UserData','I') case 'L', set(hdl1,'UserData','G') end hdl2 = findobj(gcf,'Tag','PushP'); switch get(hdl2,'UserData') case 'mw' set(hdl2,'UserData','pu','CData',fm_mat('stat_pu')) case 'pu' set(hdl2,'UserData','mw','CData',fm_mat('stat_mw')) end fm_stat pgl case 'pgl' hdl1 = findobj(gcf,'Tag','PushPGL'); hdl2 = findobj(gcf,'Tag','PushP'); switch get(hdl2,'UserData') case 'pu', mva = 1; case 'mw', mva = Settings.mva; end switch get(hdl1,'UserData') case 'I' pgl = Bus.Pg; set(hdl1,'UserData','G','CData',fm_mat('stat_pqg')) case 'G' pgl = Bus.Pl; set(hdl1,'UserData','L','CData',fm_mat('stat_pql')) case 'L' pgl = Bus.Pg - Bus.Pl; set(hdl1,'UserData','I','CData',fm_mat('stat_pqi')) end set(findobj(Fig.stat,'Tag','ListboxP'),'String',setvar(pgl*mva)); case 'qgl' hdl1 = findobj(gcf,'Tag','PushQGL'); hdl2 = findobj(gcf,'Tag','PushQ'); switch get(hdl2,'UserData') case 'pu', mva = 1; case 'mvar', mva = Settings.mva; end switch get(hdl1,'UserData') case 'I' qgl = Bus.Qg; set(hdl1,'UserData','G','CData',fm_mat('stat_pqg')) case 'G' qgl = Bus.Ql; set(hdl1,'UserData','L','CData',fm_mat('stat_pql')) case 'L' qgl = Bus.Qg - Bus.Ql; set(hdl1,'UserData','I','CData',fm_mat('stat_pqi')) end set(findobj(Fig.stat,'Tag','ListboxQ'),'String',setvar(qgl*mva)); case 'plotp' switch get(findobj(Fig.stat,'Tag','PushP'),'UserData') case 'pu', mva = 1; unit = 'p.u.'; case 'mw', mva = Settings.mva; unit = 'MW'; end switch get(findobj(Fig.stat,'Tag','PushPGL'),'UserData') case 'I' pgl = Bus.Pg - Bus.Pl; tag = 'P_G - P_L'; case 'G' pgl = Bus.Pg; tag = 'P_G'; case 'L' pgl = Bus.Pl; tag = 'P_L'; end figure bar(pgl*mva) ylabel([tag,' [',unit,']']) title('Real Power Profile') xlabel('Bus #') case 'reactivepower' hdl1 = findobj(gcf,'Tag','PushQGL'); switch get(hdl1,'UserData') case 'I', set(hdl1,'UserData','L') case 'G', set(hdl1,'UserData','I') case 'L', set(hdl1,'UserData','G') end hdl2 = findobj(gcf,'Tag','PushQ'); switch get(hdl2,'UserData') case 'mvar' set(hdl2,'UserData','pu','CData',fm_mat('stat_pu')) case 'pu' set(hdl2,'UserData','mvar','CData',fm_mat('stat_mvar')) end fm_stat qgl case 'plotq' switch get(findobj(Fig.stat,'Tag','PushQ'),'UserData') case 'pu', mva = 1; unit = 'p.u.'; case 'mvar', mva = Settings.mva; unit = 'MVar'; end switch get(findobj(Fig.stat,'Tag','PushQGL'),'UserData') case 'I' qgl = Bus.Qg-Bus.Ql; tag = 'Q_G - Q_L'; case 'G' qgl = Bus.Qg; tag = 'Q_G'; case 'L' qgl = Bus.Ql; tag = 'Q_L'; end figure bar(qgl*mva) ylabel([tag,' [',unit,']']) title('Reactive Power Profile') xlabel('Bus #') end return end % check for data file if isempty(File.data) fm_disp('Set a data file for viewing static report.',2) return end % check for initial power flow solution if ~Settings.init fm_disp('Solve base case power flow...') Settings.show = 0; fm_set('lf') Settings.show = 1; if ~Settings.init, return, end end if ishandle(Fig.stat) figure(Fig.stat) set(findobj(Fig.stat,'Tag','ListboxBus'),'String',setbus); if strcmp(get(findobj(Fig.stat,'Tag','PushAngle'),'UserData'),'rad') set(findobj(Fig.stat,'Tag','ListboxAng'),'String',setvar(abus)); else set(findobj(Fig.stat,'Tag','ListboxAng'),'String',setvar(abus*180/pi)); end if strcmp(get(findobj(Fig.stat,'Tag','PushVoltage'),'UserData'),'pu') set(findobj(Fig.stat,'Tag','ListboxV'),'String',setvar(vbus)); else set(findobj(Fig.stat,'Tag','ListboxV'),'String',setvar(vbus.*getkv(Bus,0,0))); end switch get(findobj(Fig.stat,'Tag','PushP'),'UserData') case 'pu', mva = 1; case 'mw', mva = Settings.mva; end switch get(findobj(Fig.stat,'Tag','PushPGL'),'UserData') case 'I', pgl = Bus.Pg-Bus.Pl; case 'G', pgl = Bus.Pg; case 'L', pgl = Bus.Pl; end set(findobj(Fig.stat,'Tag','ListboxP'),'String',setvar(pgl*mva)); switch get(findobj(Fig.stat,'Tag','PushQ'),'UserData') case 'pu', mva = 1; case 'mvar', mva = Settings.mva; end switch get(findobj(Fig.stat,'Tag','PushQGL'),'UserData') case 'I', qgl = Bus.Qg-Bus.Ql; case 'G', qgl = Bus.Qg; case 'L', qgl = Bus.Ql; end set(findobj(Fig.stat,'Tag','ListboxQ'),'String',setvar(qgl*mva)); set(findobj(Fig.stat,'Tag','ListboxState'),'String',setx); hdl = findobj(Fig.stat,'Tag','ListboxServ'); if nargin > 0 set(hdl,'String',varargin{1}); setyvars(hdl,1); elseif OPF.init set(hdl,'String',OPF.report); else setyvars(hdl,0); end return end if Bus.n > 150, fm_disp(['Only the first 150 buses are reported in the Static', ... ' Report GUI']) end if DAE.n > 100, fm_disp(['Only the first 100 state variables are reported in the Static', ... ' Report GUI']) end h0 = figure('Color',Theme.color01, ... 'Units', 'normalized', ... 'Colormap',[], ... 'CreateFcn','Fig.stat = gcf;', ... 'DeleteFcn','Fig.stat = -1;', ... 'FileName','fm_stat', ... 'MenuBar','none', ... 'Name','Static Report', ... 'NumberTitle','off', ... 'PaperPosition',[18 180 576 432], ... 'PaperUnits','points', ... 'Position',sizefig(0.6984,0.6377), ... 'Resize','on', ... 'ToolBar','none'); % Menu File h1 = uimenu('Parent',h0, ... 'Label','File', ... 'Tag','MenuFile'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat report', ... 'Label','Create report', ... 'Tag','OTV', ... 'Accelerator','r'); h2 = uimenu('Parent',h1, ... 'Callback','close(gcf)', ... 'Label','Exit', ... 'Tag','NetSett', ... 'Accelerator','x', ... 'Separator','on'); % Menu View h1 = uimenu('Parent',h0, ... 'Label','View', ... 'Tag','MenuView'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat plotv', ... 'Label','Voltage Profile', ... 'Tag','v_prof', ... 'Accelerator','v'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat plota', ... 'Label','Angle Profile', ... 'Tag','a_prof', ... 'Accelerator','a'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat plotp', ... 'Label','Real Power Profile', ... 'Tag','v_prof', ... 'Accelerator','p'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat plotq', ... 'Label','Reactive Power Profile', ... 'Tag','a_prof', ... 'Accelerator','q'); % Menu Preferences h1 = uimenu('Parent',h0, ... 'Label','Preferences', ... 'Tag','MenuPref'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat kvpu', ... 'Label','Switch voltage units', ... 'Tag','tvopt', ... 'Accelerator','k'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat raddeg', ... 'Label','Switch radiant/degree', ... 'Tag','tvopt', ... 'Accelerator','d'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat realpower', ... 'Label','Switch real power units', ... 'Tag','tvopt', ... 'Accelerator','w'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat reactivepower', ... 'Label','Switch reactive power units', ... 'Tag','tvopt', ... 'Accelerator','u'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat pgl', ... 'Label','Switch real power type', ... 'Tag','tvopt', ... 'Accelerator','e'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat qgl', ... 'Label','Switch reactive power type', ... 'Tag','tvopt', ... 'Accelerator','f'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat checkabs', ... 'Label','Use absolute values in report files', ... 'Tag','absvalues', ... 'Checked',Settings.absvalues, ... 'Separator','on', ... 'Accelerator','b'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat violation', ... 'Label','Include limit violation checks', ... 'Tag','violations', ... 'Checked',Settings.violations, ... 'Accelerator','l'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat report_type', ... 'Label','Embed line flows in bus report', ... 'Tag','report_type', ... 'Checked','off', ... 'Accelerator','1'); if Settings.report, set(h2,'Checked','on'), end h2 = uimenu('Parent',h1, ... 'Callback','fm_tviewer', ... 'Label','Select Text Viewer', ... 'Tag','tvopt', ... 'Separator','on', ... 'Accelerator','t'); h1 = uicontrol( ... 'Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'ForegroundColor',Theme.color03, ... 'Position',[0.040268 0.48392 0.91499 0.475], ... 'Style','frame', ... 'Tag','Frame1'); hP = uicontrol( ... 'Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color03, ... 'Callback','fm_stat toplist', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color10, ... 'Max',100, ... 'Position',[0.60235 0.51149 0.14094 0.36547], ... 'String',setvar(Bus.Pg-Bus.Pl), ... 'Style','listbox', ... 'Tag','ListboxP', ... 'Value',1); hQ = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color03, ... 'Callback','fm_stat toplist', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color10, ... 'Max',100, ... 'Position',[0.7774 0.51149 0.14094 0.36547], ... 'String',setvar(Bus.Qg-Bus.Ql), ... 'Style','listbox', ... 'Tag','ListboxQ', ... 'Value',1); hB = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color03, ... 'Callback','fm_stat toplist', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color06, ... 'Max',100, ... 'Position',[0.077181 0.51149 0.14094 0.36547], ... 'String',setbus, ... 'Style','listbox', ... 'Tag','ListboxBus', ... 'Value',1); hV = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color03, ... 'Callback','fm_stat toplist', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color10, ... 'Max',100, ... 'Position',[0.25224 0.51149 0.14094 0.36547], ... 'String',setvar(vbus), ... 'Style','listbox', ... 'Tag','ListboxV', ... 'Value',1); hA = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color03, ... 'Callback','fm_stat toplist', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color10, ... 'Max',100, ... 'Position',[0.42729 0.51149 0.14094 0.36547], ... 'String',setvar(abus), ... 'Style','listbox', ... 'Tag','ListboxAng', ... 'Value',1); % Static texts h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[0.7774 0.89227 0.12975 0.030628], ... 'String','Q', ... 'Style','text', ... 'Tag','StaticText1'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[0.60235 0.89227 0.12975 0.030628], ... 'String','P', ... 'Style','text', ... 'Tag','StaticText1'); hT = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HitTest','off', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.42729 0.89227 0.12975 0.030628], ... 'String','Va', ... 'Style','text', ... 'Tag','StaticTextAng'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[0.25224 0.89227 0.12975 0.030628], ... 'String','Vm', ... 'Style','text', ... 'Tag','StaticText1'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[0.077181 0.89227 0.12975 0.030628], ... 'String','Bus', ... 'Style','text', ... 'Tag','StaticText1'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'ForegroundColor',Theme.color03, ... 'Position',[0.040268 0.049005 0.32662 0.41041], ... 'Style','frame', ... 'Tag','Frame2'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[0.072707 0.41348 0.12975 0.030628], ... 'String','State Variables', ... 'Style','text', ... 'Tag','StaticText1'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color03, ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color10, ... 'Max',100, ... 'Position',[0.072707 0.084227 0.26286 0.317], ... 'String',setx, ... 'Style','listbox', ... 'Tag','ListboxState', ... 'Value',1); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'ForegroundColor',Theme.color03, ... 'Position',[0.41051 0.049005 0.32662 0.41041], ... 'Style','frame', ... 'Tag','Frame2'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color03, ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color10, ... 'Max',100, ... 'Position',[0.44295 0.084227 0.26286 0.317], ... 'String',' ', ... 'Style','listbox', ... 'Tag','ListboxServ', ... 'Value',1); if nargin > 0 set(h1,'String',varargin{1}); setyvars(h1,1) elseif ~isempty(OPF.report) set(h1,'String',OPF.report); else setyvars(h1,0) end h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[0.44295 0.41348 0.12975 0.030628], ... 'String','Other Variables', ... 'Style','text', ... 'Tag','StaticText1'); h1 = axes('Parent',h0, ... 'Box','on', ... 'CameraUpVector',[0 1 0], ... 'CameraUpVectorMode','manual', ... 'Color',Theme.color04, ... 'ColorOrder',Settings.color, ... 'Layer','top', ... 'Position',[0.77964 0.050394 0.17785 0.176378], ... 'Tag','Axes1', ... 'XColor',Theme.color03, ... 'XLim',[0.5 190.5], ... 'XLimMode','manual', ... 'XTickLabelMode','manual', ... 'XTickMode','manual', ... 'YColor',Theme.color03, ... 'YDir','reverse', ... 'YLim',[0.5 115.5], ... 'YLimMode','manual', ... 'YTickLabelMode','manual', ... 'YTickMode','manual', ... 'ZColor',[0 0 0]); if Settings.hostver < 8.04 h2 = image('Parent',h1, ... 'CData',imread([Path.images,'stat_fig.jpg'],'jpg'), ... 'Tag','Axes1Image1', ... 'XData',[1 190], ... 'YData',[1 115]); else h2 = image('Parent',h1, ... 'CData',flipud(fliplr(imread([Path.images,'stat_fig.jpg'],'jpg'))), ... 'Tag','Axes1Image1', ... 'XData',[1 190], ... 'YData',[1 115]); end h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat abscheck', ... 'Position',[0.77964 0.050394+0.176378+0.03 0.17785 0.05], ... 'String','Use absolute values', ... 'Style','checkbox', ... 'Tag','CheckABS', ... 'Value',onoff(Settings.absvalues)); % 'Position',[0.77964 0.050394+0.176378+0.01 0.17785 0.05], ... %h1 = uicontrol('Parent',h0, ... % 'Units', 'normalized', ... % 'BackgroundColor',Theme.color02, ... % 'Callback','fm_stat xxx', ... % 'Position',[0.77964 0.1108+0.176378-0.005 0.17785 0.05], ... % 'String','xxx', ... % 'Style','checkbox', ... % 'Tag','CheckSHUNT', ... % 'Value',onoff(xxx)); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat violcheck', ... 'Position',[0.77964 0.1712+0.176378-0.04 0.17785 0.05], ... 'String','Check limit violations', ... 'Style','checkbox', ... 'Tag','CheckVIOL', ... 'Value',onoff(Settings.violations)); % 'Position',[0.77964 0.1712+0.176378-0.02 0.17785 0.05], ... % Push buttons h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color03, ... 'Callback','fm_stat report', ... 'FontWeight','bold', ... 'ForegroundColor',Theme.color09, ... 'Position',[0.77964 0.39051 0.0839 0.061256], ... 'String','Report', ... 'Tag','Pushbutton1'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback','close(gcf)', ... 'Position',[0.8685 0.39051 0.0839 0.061256], ... 'String','Close', ... 'Tag','Pushbutton1'); % 'Position',[0.80425 0.39051 0.12864 0.061256], ... % 'Position',[0.80425 0.317 0.12864 0.061256], ... if isunix, dy = 0.0025; else dy = 0; end h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_profile'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat plotv', ... 'Position',[0.34899 0.89686 0.045861 0.030628+dy], ... 'Tag','Pushbutton3'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_pu'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat kvpu', ... 'UserData','pu', ... 'Position',[0.3 0.89686 0.045861 0.030628+dy], ... 'Tag','PushVoltage'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_profile'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat plota', ... 'Position',[0.52349 0.89686 0.045861 0.030628+dy], ... 'Tag','Pushbutton3'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_rad'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat raddeg', ... 'UserData','rad', ... 'Position',[0.4745 0.89686 0.045861 0.030628+dy], ... 'Tag','PushAngle'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_sortaz'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat sort', ... 'Position',[0.1740 0.89686 0.045861 0.030628+dy], ... 'UserData','az', ... 'Tag','PushSort'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_profile'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat plotp', ... 'Position',[0.6974 0.89686 0.045861 0.030628+dy], ... 'Tag','Pushbutton3'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_pu'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat realpower', ... 'UserData','pu', ... 'Position',[0.6484 0.89686 0.045861 0.030628+dy], ... 'Tag','PushP'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_pqi'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat pgl', ... 'UserData','I', ... 'Position',[0.6224 0.89686 0.0229 0.030628+dy], ... 'Tag','PushPGL'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_profile'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat plotq', ... 'Position',[0.8725 0.89686 0.045861 0.030628+dy], ... 'Tag','Pushbutton3'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_pu'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat reactivepower', ... 'UserData','pu', ... 'Position',[0.8235 0.89686 0.045861 0.030628+dy], ... 'Tag','PushQ'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_pqi'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat qgl', ... 'UserData','I', ... 'Position',[0.7975 0.89686 0.0229 0.030628+dy], ... 'Tag','PushQGL'); set(h0,'UserData',[hB; hV; hA; hP; hQ]); if nargout > 0, fig = h0; end %============================================================== function stringa = setvar(input) global Bus busn = min(150,Bus.n); [buss, ordbus] = sortbus(Bus,busn); hdl = findobj(gcf,'Tag','PushSort'); if ~isempty(hdl) if strcmp(get(hdl,'UserData'),'1n') [a,ordbus] = sort(getidx(Bus,0)); end end stringa = cell(busn,1); for i = 1:busn, stringa{i,1} = fvar(input(ordbus(i)),10); end %============================================================== function stringa = setx global DAE Varname daen = min(100,DAE.n); stringa = cell(daen,1); for i = 1:daen, stringa{i,1} = [fvar(Varname.uvars{i,1},19), fvar(DAE.x(i),10)]; end %============================================================== function stringa = setbus global Bus [stringa, ord] = sortbus(Bus,150); stringa = fm_strjoin('[',int2str(getidx(Bus,ord)),']-',stringa); hdl = findobj(gcf,'Tag','PushSort'); if ~isempty(hdl) if strcmp(get(hdl,'UserData'),'1n') [a,ord] = sort(getidx(Bus,ord)); stringa = stringa(ord); end end %============================================================== function value = onoff(string) switch string case 'on' value = 1; otherwise value = 0; end %============================================================== function setyvars(h1,type) global DAE Bus Varname if DAE.m > 2*Bus.n idx = [2*Bus.n+1:DAE.m]; if type string = get(h1,'String'); if ~iscell(string) string = cellstr(a); end else string = cell(0,0); end string = [string; fm_strjoin(Varname.uvars(DAE.n+idx),' = ',num2str(DAE.y(idx)))]; set(h1,'String',string); end
github
Sinan81/PSAT-master
fm_save.m
.m
PSAT-master/psat-mat/psat/fm_save.m
2,769
utf_8
a1510ea9eb17a263a21ac823d3a4bd19
function fm_save(Comp) % FM_SAVE save UDM to file % % FM_SAVE uses the component name COMP.NAME as file name % and creates a Matlab script. % The file is saved in the folder ./psat/build % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 15-Sep-2003 %Version: 2.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Settings Path Fig global Algeb Buses Initl Param Servc State % check for component name if isempty(Comp.name) fm_disp('No component name set.',2) return end % check for older versions a = dir([Path.build,'*.m']); b = {a.name}; older = strmatch([Comp.name,'.m'],b,'exact'); if ~isempty(older) uiwait(fm_choice(['Overwrite Existing File "',Comp.name,'.m" ?'])) if ~Settings.ok, return, end end % save data if isempty(Comp.init) Comp.init = 0; end if isempty(Comp.descr) Comp.descr = ['DAE function ', Comp.name, '.m']; end [fid,msg] = fopen([Path.build,Comp.name,'.m'],'wt'); if fid == -1 fm_disp(msg,2) fm_disp(['UDM File ',Comp.name,'.m couldn''t be saved.'],2) return end count = fprintf(fid,'%% User Defined Component %s\n',Comp.name); count = fprintf(fid,'%% Created with PSAT v%s\n',Settings.version); count = fprintf(fid,'%% \n'); count = fprintf(fid,'%% Date: %s\n',datestr(now,0)); Comp = rmfield(Comp,{'names','prop','n'}); savestruct(fid,Comp) savestruct(fid,Buses) savestruct(fid,Algeb) savestruct(fid,State) savestruct(fid,Servc) savestruct(fid,Param) savestruct(fid,Initl) count = fprintf(fid,'\n'); fclose(fid); fm_disp(['UDM File ',Comp.name,'.m saved in folder ./build']) % update list in the component browser GUI if ishandle(Fig.comp) fm_comp clist end % ------------------------------------------------------------------- function savestruct(fid,structdata) if isempty(structdata) return end if ~isstruct(structdata) return end fields = fieldnames(structdata); namestruct = inputname(2); count = fprintf(fid,'\n%% Struct: %s\n',namestruct); for i = 1:length(fields) field = getfield(structdata,fields{i}); if isempty(field) count = fprintf(fid,'\n%s.%s = [];',namestruct,fields{i}); end [m,n] = size(field); if isnumeric(field) for mi = 1:m for ni = 1:n count = fprintf(fid,['\n%s.%s(%d,%d) = %d;'], ... namestruct,fields{i},mi,ni,field(mi,ni)); end end elseif iscell(field) for mi = 1:m for ni = 1:n count = fprintf(fid,['\n%s.%s{%d,%d} = ''%s'';'], ... namestruct,fields{i},mi,ni, ... strrep(field{mi,ni},'''','''''')); end end elseif ischar(field) count = fprintf(fid,'\n%s.%s = ''%s'';', ... namestruct,fields{i},strrep(field,'''','''''')); end count = fprintf(fid,'\n'); end
github
Sinan81/PSAT-master
fm_eigen.m
.m
PSAT-master/psat-mat/psat/fm_eigen.m
16,922
utf_8
43a24149470c1302d6449a211bb3ffe3
function fm_eigen(type) % FM_EIGEN compute eigenvalues of static and dynamic Jacobian % matrices % % FM_EIGEN(TYPE,REPORT) % TYPE 1 -> Jlfd eigenvalues % 2 -> Jlfv eigenvalues % 3 -> Jlf eigenvalues % 4 -> As eigenvalues % REPORT 1 -> create report file % 0 -> no report file % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 05-Mar-2004 %Version: 1.1.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global DAE Bus Settings Varname File Path global PQ PV SW Fig Theme SSSA Line clpsat switch type case 'matrix' % set matrix type mat = zeros(4,1); mat(1) = findobj(gcf,'Tag','Checkbox1'); mat(2) = findobj(gcf,'Tag','Checkbox2'); mat(3) = findobj(gcf,'Tag','Checkbox3'); mat(4) = findobj(gcf,'Tag','Checkbox4'); tplot = zeros(3,1); tplot(1) = findobj(gcf,'Tag','Radiobutton1'); tplot(2) = findobj(gcf,'Tag','Radiobutton2'); tplot(3) = findobj(gcf,'Tag','Radiobutton3'); ca = find(mat == gcbo); vals = zeros(4,1); vals(ca) = 1; for i = 1:4 set(mat(i),'Value',vals(i)) end a = get(tplot(3),'Value'); if ca == 4 set(tplot(3),'Enable','on') else if a set(tplot(3),'Value',0) set(tplot(1),'Value',1) SSSA.map = 1; end set(tplot(3),'Enable','off') end if ca == 4 && SSSA.neig > DAE.n-1, set(findobj(Fig.eigen,'Tag','EditText1'),'String','1') SSSA.neig = 1; elseif ca < 4 && SSSA.neig > Bus.n-1, set(findobj(Fig.eigen,'Tag','EditText1'),'String','1') SSSA.neig = 1; end SSSA.matrix = ca; SSSA.report = []; case 'map' % set eigenvalue map type tplot = zeros(3,1); tplot(1) = findobj(gcf,'Tag','Radiobutton1'); tplot(2) = findobj(gcf,'Tag','Radiobutton2'); tplot(3) = findobj(gcf,'Tag','Radiobutton3'); ca = find(tplot == gcbo); vals = zeros(3,1); vals(ca) = 1; for i = 1:3 set(tplot(i),'Value',vals(i)) end SSSA.map = find(vals); SSSA.report = []; case 'neig' % Set number of eigs to be computed if SSSA.matrix == 4 amax = DAE.n; else amax = Bus.n; end number = get(gcbo,'String'); try a = round(str2num(number)); if a > 0 && a < amax SSSA.neig = a; SSSA.report = []; else set(gcbo,'String',num2str(SSSA.neig)); end catch set(gcbo,'String',num2str(SSSA.neig)); end case 'method' % Set method for eigenvalue computation t1 = findobj(Fig.eigen,'Tag','Radiobutton1'); t3 = findobj(Fig.eigen,'Tag','Radiobutton2'); a = get(gcbo,'Value'); hedit = findobj(Fig.eigen,'Tag','EditText1'); if a == 1 set(hedit,'Enable','off') set(t3,'Enable','on') else set(hedit,'Enable','on') if get(t3,'Value') set(t3,'Value',0) set(t1,'Value',1) SSSA.map = 1; end set(t3,'Enable','off') end SSSA.method = a; SSSA.report = []; case 'runsssa' % check for data file if isempty(File.data) fm_disp('Set a data file before running eigenvalue analysis.',2) return end % check for initial power flow solution if ~Settings.init fm_disp('Solve base case power flow...') Settings.show = 0; fm_set('lf') Settings.show = 1; if ~Settings.init, return, end end if PQ.n && Settings.pq2z pq2z = 0; if clpsat.init pq2z = clpsat.pq2z; elseif Settings.donotask pq2z = Settings.pq2z; else uiwait(fm_choice(['Convert PQ loads to constant impedances?'])) pq2z = Settings.ok; end if pq2z % convert PQ loads to shunt admittances PQ = pqshunt(PQ); % update Jacobian matrices fm_call('i'); else % reset PQ loads to constant powers PQ = noshunt(PQ); % update Jacobian matrices fm_call('i'); Settings.pq2z = 0; if ishandle(Fig.setting) set(findobj(Fig.setting,'Tag','CheckboxPQ2Z'),'Value',0) end end end uno = 0; tipo_mat = SSSA.matrix; tipo_plot = SSSA.map; SSSA.report = []; if isempty(Bus.n) fm_disp('No loaded system. Eigenvalue computation cannot be run.',2) return end % build eigenvalue names if (Settings.vs == 0), fm_idx(2), end % initialize report structures Header{1,1}{1,1} = 'EIGENVALUE REPORT'; Header{1,1}{2,1} = ' '; Header{1,1}{3,1} = ['P S A T ',Settings.version]; Header{1,1}{4,1} = ' '; Header{1,1}{5,1} = 'Author: Federico Milano, (c) 2002-2019'; Header{1,1}{6,1} = 'e-mail: [email protected]'; Header{1,1}{7,1} = 'website: faraday1.ucd.ie/psat.html'; Header{1,1}{8,1} = ' '; Header{1,1}{9,1} = ['File: ', Path.data,strrep(File.data,'(mdl)','.mdl')]; Header{1,1}{10,1} = ['Date: ',datestr(now,0)]; Matrix{1,1} = []; Cols{1,1} = ''; Rows{1,1} = ''; if tipo_mat == 4 if DAE.n == 0 fm_disp('No dynamic component loaded. State matrix is not defined',2) return end As = DAE.Fx - DAE.Fy*(DAE.Gy\DAE.Gx) - 1e-6*speye(DAE.n); if tipo_plot == 3 As = (As+8*speye(DAE.n))/(As-8*speye(DAE.n)); end [auto,autor,autoi,num_auto,pf] = compute_eigs(As); names = cellstr(fm_strjoin('Eig As #',num2str([1:num_auto]'))); Header{2,1} = 'STATE MATRIX EIGENVALUES'; Cols{2,1} = {'Eigevalue', 'Most Associated States', ... 'Real part','Imag. Part','Pseudo-Freq.','Frequency'}; Matrix{2,1} = zeros(num_auto,4); Matrix{2,1}(:,[1 2]) = [autor, autoi]; for i = 1:num_auto; if autoi(i) == 0 [part, idxs] = max(pf(i,:)); stat = Varname.uvars{idxs}; pfrec = 0; frec = 0; else [part, idxs] = sort(pf(i,:)); stat = [Varname.uvars{idxs(end)},', ',Varname.uvars{idxs(end-1)}]; pfrec = abs(imag(auto(i))/2/3.1416); frec = abs(auto(i))/2/3.1416; end Rows{2,1}{i,1} = names{i}; Rows{2,1}{i,2} = stat; Matrix{2,1}(i,3) = pfrec; Matrix{2,1}(i,4) = frec; end [uno,Header,Cols,Rows,Matrix] = ... write_pf(pf,DAE.n,Varname.uvars,names,Header,Cols,Rows,Matrix); elseif tipo_mat == 3 Jlf = build_gy(Line); if DAE.m > 2*Bus.n x3 = 1:2*Bus.n; Jlf = Jlf(x3,x3); end x1 = Bus.a; x2 = Bus.v; vbus = [getbus(SW,'a');getbus(SW,'v');getbus(PV,'v')]; Jlf(vbus,:) = 0; Jlf(:,vbus) = 0; Jlf = Jlf + sparse(vbus,vbus,999,2*Bus.n,2*Bus.n); Jlfptheta = Jlf(x1,x1)+1e-5*speye(Bus.n,Bus.n); elementinulli = find(diag(Jlfptheta == 0)); if ~isempty(elementinulli) for i = 1:length(elementinulli) Jlfptheta(elementinulli(i),elementinulli(i)) = 1; end end Jlfr = Jlf(x2,x2) - Jlf(x2,x1)*(Jlfptheta\Jlf(x1,x2)); [auto,autor,autoi,num_auto,pf] = compute_eigs(Jlfr); names = cellstr(fm_strjoin('Eig Jlfr #',num2str([1:num_auto]'))); Header{2,1} = 'EIGENVALUES OF THE STANDARD POWER JACOBIAN MATRIX'; Cols{2,1} = {'Eigevalue', 'Most Associated Bus', 'Real part', ... 'Imaginary Part'}; Rows{2,1} = names; Matrix{2,1} = [autor, autoi]; for i = 1:num_auto; if autoi(i) == 0 [part, idxs] = max(pf(i,:)); stat = Bus.names{idxs}; else [part, idxs] = sort(pf(i,:)); stat = [Bus.names{idxs(end)},', ',Bus.names{idxs(end-1)}]; end Rows{2,1}{i,1} = names{i}; Rows{2,1}{i,2} = stat; end [uno,Header,Cols,Rows,Matrix] = ... write_pf(pf,Bus.n,Bus.names,names,Header,Cols,Rows,Matrix); elseif tipo_mat == 2 x1 = Bus.a; x2 = Bus.v; if DAE.m > 2*Bus.n x3 = 1:2*Bus.n; x4 = 2*Bus.n+1:DAE.m; Gy = DAE.Gy(x3,x3)-DAE.Gy(x3,x4)*(DAE.Gy(x4,x4)\DAE.Gy(x4,x3)); else Gy = DAE.Gy; end Jlfvr = Gy(x2,x2)-Gy(x2,x1)*(Gy(x1,x1)\Gy(x1,x2)); vbus = [getbus(SW);getbus(PV)]; Jlfvr = Jlfvr + sparse(vbus,vbus,998,Bus.n,Bus.n); [auto,autor,autoi,num_auto,pf] = compute_eigs(Jlfvr); names = cellstr(fm_strjoin('Eig Jlfv #',num2str([1:num_auto]'))); Header{2,1} = 'EIGENVALUES OF THE COMPLETE POWER JACOBIAN MATRIX'; Cols{2,1} = {'Eigevalue', 'Most Associated Bus', 'Real part', ... 'Imaginary Part'}; Rows{2,1} = names; Matrix{2,1} = [autor, autoi]; for i = 1:num_auto; if autoi(i) == 0 [part, idxs] = max(pf(i,:)); stat = Bus.names{idxs}; else [part, idxs] = sort(pf(i,:)); stat = [Bus.names{idxs(end)},', ',Bus.names{idxs(end-1)}]; end Rows{2,1}{i,1} = names{i}; Rows{2,1}{i,2} = stat; end [uno,Header,Cols,Rows,Matrix] = ... write_pf(pf,Bus.n,Bus.names,names,Header,Cols,Rows,Matrix); elseif tipo_mat == 1 if DAE.n == 0 fm_disp('Since no dynamic component is loaded, Jlfd = Jlfv.',2) end if DAE.m > 2*Bus.n x3 = 1:2*Bus.n; x4 = 2*Bus.n+1:DAE.m; x5 = 1:DAE.n; Gy = DAE.Gy(x3,x3)-DAE.Gy(x3,x4)*(DAE.Gy(x4,x4)\DAE.Gy(x4,x3)); Gx = DAE.Gx(x3,x5)-DAE.Gy(x3,x4)*(DAE.Gy(x4,x4)\DAE.Gx(x4,x5)); Fx = DAE.Fx(x5,x5)-DAE.Fy(x5,x4)*(DAE.Gy(x4,x4)\DAE.Gx(x4,x5)); Fy = DAE.Fy(x5,x3)-DAE.Fy(x5,x4)*(DAE.Gy(x4,x4)\DAE.Gy(x4,x3)); else Gy = DAE.Gy; Gx = DAE.Gx; Fx = DAE.Fx; Fy = DAE.Fy; end Fx = Fx-1e-5*speye(DAE.n,DAE.n); Jlfd = Gy-Gx*(Fx\Fy); x1 = Bus.a; x2 = Bus.v; Jlfdr = Jlfd(x2,x2)-Jlfd(x2,x1)*(Jlfd(x1,x1)\Jlfd(x1,x2)); vbus = [getbus(SW);getbus(PV)]; Jlfdr = Jlfdr + sparse(vbus,vbus,998,Bus.n,Bus.n); [auto,autor,autoi,num_auto,pf] = compute_eigs(Jlfdr); names = cellstr(fm_strjoin('Eig Jlfd #',num2str([1:num_auto]'))); Header{2,1} = 'EIGENVALUES OF THE DYNAMIC POWER JACOBIAN MATRIX'; Cols{2,1} = {'Eigevalue', 'Most Associated Bus', 'Real part', ... 'Imaginary Part'}; Rows{2,1} = names; Matrix{2,1} = [autor, autoi]; for i = 1:num_auto; if autoi(i) == 0 [part, idxs] = max(pf(i,:)); stat = Bus.names{idxs}; else [part, idxs] = sort(pf(i,:)); stat = [Bus.names{idxs(end)},', ',Bus.names{idxs(end-1)}]; end Rows{2,1}{i,1} = names{i}; Rows{2,1}{i,2} = stat; end [uno,Header,Cols,Rows,Matrix] = ... write_pf(pf,Bus.n,Bus.names,names,Header,Cols,Rows,Matrix); end auto_neg = find(autor < 0); auto_pos = find(autor > 0); auto_real = find(autoi == 0); auto_comp = find(autoi < 0); auto_zero = find(autor == 0); num_neg = length(auto_neg); num_pos = length(auto_pos); num_real = length(auto_real); num_comp=length(auto_comp); num_zero = length(auto_zero); if ishandle(Fig.eigen) hdl = zeros(8,1); hdl(1) = findobj(Fig.eigen,'Tag','Text3'); hdl(2) = findobj(Fig.eigen,'Tag','Text4'); hdl(3) = findobj(Fig.eigen,'Tag','Text5'); hdl(4) = findobj(Fig.eigen,'Tag','Text6'); hdl(5) = findobj(Fig.eigen,'Tag','Axes1'); hdl(6) = findobj(Fig.eigen,'Tag','Listbox1'); hdl(7) = findobj(Fig.eigen,'Tag','Text1'); hdl(8) = findobj(Fig.eigen,'Tag','Text2'); set(hdl(1),'String',num2str(num_pos)); set(hdl(2),'String',num2str(num_neg)); set(hdl(3),'String',num2str(num_comp)); set(hdl(4),'String',num2str(num_zero)); set(hdl(7),'String',num2str(DAE.n)); set(hdl(8),'String',num2str(Bus.n)); autovalori = cell(length(autor),1); if num_auto < 10 d = ''; e = ''; elseif num_auto < 100 d = ' '; e = ''; elseif num_auto < 1000 d = ' '; e = ' '; else d = ' '; e = ' '; end for i = 1:length(autor) if autor(i)>=0 a = ' '; else a = ''; end if autoi(i)>=0 c = '+'; else c = '-'; end if i < 10 f1 = [d,e]; elseif i < 100 f1 = e; else f1 = ''; end if tipo_plot == 3 autovalori{i,1} = ['|',char(181),'(A)| #',num2str(i), ... f1, ' ', fvar(abs(auto(i)),9)]; else autovalori{i,1} = [char(181),'(A) #',num2str(i),f1, ... ' ',a,num2str(autor(i)),' ',c, ... ' j',num2str(abs(autoi(i)))]; end end set(hdl(6),'String',autovalori,'Value',1) end Header{3+uno,1} = 'STATISTICS'; Cols{3+uno} = ''; Rows{3+uno} = ''; Matrix{3+uno,1} = []; if tipo_mat < 4 Rows{3+uno}{1,1} = 'NUMBER OF BUSES'; Matrix{3+uno,1}(1,1) = Bus.n; else Rows{3+uno}{1,1} = 'DYNAMIC ORDER'; Matrix{3+uno,1}(1,1) = DAE.n; end Rows{3+uno}{2,1} = '# OF EIGS WITH Re(mu) < 0'; Matrix{3+uno,1}(2,1) = num_neg; Rows{3+uno}{3,1} = '# OF EIGS WITH Re(mu) > 0'; Matrix{3+uno,1}(3,1) = num_pos; Rows{3+uno}{4,1} = '# OF REAL EIGS'; Matrix{3+uno,1}(4,1) = num_real; Rows{3+uno}{5,1} = '# OF COMPLEX PAIRS'; Matrix{3+uno,1}(5,1) = num_comp; Rows{3+uno}{6,1} = '# OF ZERO EIGS'; Matrix{3+uno,1}(6,1) = num_zero; % save eigenvalues and participation factors in SSSA structure SSSA.eigs = auto; SSSA.pf = pf; if ishandle(Fig.eigen), axes(hdl(5)); fm_eigen('graph') end SSSA.report.Matrix = Matrix; SSSA.report.Header = Header; SSSA.report.Cols = Cols; SSSA.report.Rows = Rows; case 'report' if SSSA.matrix == 4 && DAE.n == 0 fm_disp('No dynamic component loaded. State matrix is not defined',2) return end if isempty(SSSA.report), fm_eigen('runsssa'), end % writing data... fm_write(SSSA.report.Matrix,SSSA.report.Header, ... SSSA.report.Cols,SSSA.report.Rows) case 'graph' hgca = gca; if isempty(SSSA.eigs) fm_eigen('runsssa') end axes(hgca) autor = real(SSSA.eigs); autoi = imag(SSSA.eigs); num_auto = length(SSSA.eigs); idx = find(autor > -990); if ~isempty(idx) autor = autor(idx); autoi = autoi(idx); end if ishandle(Fig.eigen) switch SSSA.map case 1 idxn = find(autor < 0); idxz = find(autor == 0); idxp = find(autor > 0); if SSSA.matrix == 4 hdle = plot(autor(idxn), autoi(idxn),'bx', ... autor(idxz), autoi(idxz),'go', ... autor(idxp), autoi(idxp),'rx'); else hdle = plot(autor(idxn), autoi(idxn),'rx', ... autor(idxz), autoi(idxz),'go', ... autor(idxp), autoi(idxp),'bx'); end hold on plot([0,0],ylim,':k'); plot(xlim,[0,0],':k'); zeta = [0.05, 0.1, 0.15]; colo = {'r:', 'g:', 'b:'}; for i = 1:3 mu = sqrt((1 - zeta(i)^2)/zeta(i)^2); ylimits = ylim; plot([0, -ylimits(2)/mu], [0, ylimits(2)], colo{i}) plot([0, ylimits(1)/mu], [0, ylimits(1)], colo{i}) end set(hdle,'MarkerSize',8); xlabel('Real'); ylabel('Imag'); hold off set(hgca,'Tag','Axes1') case 2 surf(real(SSSA.pf)) set(hgca,'XLim',[1 num_auto],'YLim',[1 num_auto]); view(0,90); box('on') ylabel('Eigenvalues'); if SSSA.matrix == 4 xlabel('State Variables'); else xlabel('Buses'); end shading('interp') colormap('summer'); title('Participation Factors') set(hgca,'Tag','Axes1'); case 3 t = 0:0.01:2*pi+0.01; x = cos(t); y = sin(t); plot(x,y,'k:') hold on idxn = find(autor < 1); idxz = find(autor == 1); idxp = find(autor > 1); hdle = plot(autor(idxn), autoi(idxn),'bx', ... autor(idxz), autoi(idxz),'go', ... autor(idxp), autoi(idxp),'rx'); set(hdle,'MarkerSize',8); xlabel('Real'); ylabel('Imag'); xlim(1.1*xlim); ylim(1.1*ylim); plot([0,0],1.1*ylim,':k'); plot(1.1*xlim,[0,0],':k'); hold off set(hgca,'Tag','Axes1'); end set(hgca,'Color',Theme.color11) end end % ======================================================= function [auto,autor,autoi,num_auto,pf] = compute_eigs(A) global Settings SSSA meth = {'LM';'SM';'LR';'SR';'LI';'SI'}; neig = SSSA.neig; opts = SSSA.method-1; opt.disp = 0; if opts [V, auto] = eigs(A,neig,meth{opts},opt); [W, dummy] = eigs(A',neig,meth{opts},opt); else [V, auto] = eig(full(A)); W = [pinv(V)]'; end auto = diag(auto); auto = round(auto/Settings.lftol)*Settings.lftol; num_auto = length(auto); autor = real(auto); autoi = imag(auto); WtV = sum(abs(W).*abs(V)); pf = [abs(W).*abs(V)]'; %pf = [W.*V].'; % for getting p.f. with their signs for i = 1:length(auto), pf(i,:) = pf(i,:)/WtV(i); end % ======================================================= function [uno,Header,Cols,Rows,Matrix] = write_pf(pf,n,name1,name2,Header,Cols,Rows,Matrix) uno = fix(n/5); due = rem(n,5); if due > 0, uno = uno + 1; end for k = 1:uno Header{2+k,1} = 'PARTICIPATION FACTORS (Euclidean norm)'; Cols{2+k} = {' ',name1{5*(k-1)+1:min(5*k,n)}}; Rows{2+k} = name2; Matrix{2+k,1} = pf(:,5*(k-1)+1:min(5*k,n)); end
github
Sinan81/PSAT-master
fm_simrep.m
.m
PSAT-master/psat-mat/psat/fm_simrep.m
23,427
utf_8
902e764e0854968920998718af1cbb65
function fm_simrep(varargin) % FM_SIMREP generate data report in Simulink models % % FM_SIMREP(FLAG,FONTSIZE,FONTNAME) % FLAG: 1 - set up voltage report on current loaded network % 2 - wipe voltage report on current loaded network % 3 - set up power flows on current loaded network % 4 - wipe power flows on current loaded network % 5 - hide component names except for buses % 6 - show component names % 7 - hide bus names % 8 - show bus names % 9 - set font name % 10 - set font size % 11 - save model diagram to eps file % FONTSIZE: font size (integer) % FONTNAME: font name (string) % %see also FM_LIB, FM_SIMSET % %Author: Federico Milano %Date: 11-Nov-2002 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano fm_var global Settings type = 1; switch nargin case 1 flag = varargin{1}; case 3 flag = varargin{1}; fontsize = varargin{2}; fontname = varargin{3}; case 4 flag = varargin{1}; maptype = varargin{2}; type = varargin{3}; method = varargin{4}; end if isempty(File.data) && type, fm_disp('No loaded system is present at the moment.',2), return end if isempty(strfind(File.data,'(mdl)')) && type fm_disp('The actual data file is not generated from a Simulink model.',2), return end if ~Settings.init && ~strcmp(flag,{'mdl2eps','ViewModel','DrawModel'}) & type fm_disp('Perform Power Flow before using this utility.',2), return end lasterr(''); % load Simulink model cd(Path.data); filedata = File.data(1:end-5); open_sys = find_system('type','block_diagram'); if ~sum(strcmp(open_sys,filedata)) try if nargin > 3 load_system(filedata) else open_system(filedata); end catch fm_disp(lasterr,2) return end end cur_sys = get_param(filedata,'Handle'); if ~strcmp(flag,'DrawModel'), set_param(cur_sys,'Open','on'), end blocks = find_system(cur_sys,'Type','block'); lines = find_system(cur_sys, ... 'FindAll','on', ... 'type','line'); masks = get_param(blocks,'Masktype'); nblock = length(blocks); switch flag case 'ViewModel' % view the current Simulink model. hilite_system(cur_sys,'none') case 'DrawModel' maps = {'jet';'hot';'gray';'bone';'copper';'pink'; 'hsv';'cool';'autumn';'spring';'winter';'summer'}; if ~method switch type case 0 % only one-line diagram zlevel = 0; case 1 % voltage magnitudes zlevel = 1.025*max(DAE.y(Bus.v)); case 2 % voltage phases zmax = max(180*DAE.y(Bus.a)/pi); if zmax >= 0 zlevel = 1.1*zmax; else zlevel = 0.9*zmax; end case 3 % line flows [sij,sji] = flows(Line,3); zlevel = 1.1*max(sij); case 4 % generator rotor angles if ~Syn.n if Settings.static fm_disp('Currently, synchronous machines are not loaded.') fm_disp('Uncheck the option "Discard dynamic data" and try again.') else fm_disp('There are no synchronous machines in the current system.',2) end return end zmax = max(180*DAE.x(Syn.delta)/pi); if zmax >= 0 zlevel = 1.1*zmax; else zlevel = 0.9*zmax; end case 5 % generator rotor speeds if ~Syn.n if Settings.static fm_disp('Currently, synchronous machines are not loaded.') fm_disp('Uncheck the option "Discard dynamic data" and try again.') else fm_disp('There are no synchronous machines in the current system.',2) end return end zlevel = 1.05*max(DAE.x(Syn.omega)); case 6 % locational marginal prices if ~OPF.init fm_disp(['Run OPF before displaying Locational Marginal ' ... 'Prices'],2) return end LMP = OPF.LMP; zlevel = 1.025*max(LMP); case 7 % nodal congestion prices if ~OPF.init fm_disp(['Run OPF before displaying Nodal Congestion Prices'], ... 2) return end NCP = OPF.NCP(1:Bus.n); zlevel = 1.025*max(NCP); otherwise zlevel = 0; end Varout.zlevel = zlevel; end if ishandle(Fig.threed) && type figure(Fig.threed) elseif ishandle(Fig.dir) && ~type figure(Fig.dir) hdla = findobj(Fig.dir,'Tag','Axes1'); cla(hdla) else figure end hold on if ~method if type, colorbar, end if ishandle(Fig.threed), cla(get(Fig.threed,'UserData')), end lines = get_param(cur_sys,'Lines'); end pos = get_param(cur_sys,'Location'); xl = []; yl = []; for i = 1:length(lines)*(~method) z = zlevel*ones(length(lines(i).Points(:,1)),1); plot3(lines(i).Points(:,1),lines(i).Points(:,2),z,'k') xl = [xl; lines(i).Points([1 end],1)]; yl = [yl; lines(i).Points([1 end],2)]; end xb = []; yb = []; zb = []; x_max = 0; x_min = 2000; y_max = 0; y_min = 2000; idx = 0; idx_line = 0; idx_gen = 0; Compnames = cell(0,0); Compidx = []; ncomp = 0; if ~method switch type case 3 Varout.hdl = zeros(Line.n,1); case {4,5} Varout.hdl = zeros(Syn.n,1); otherwise Varout.hdl = zeros(Bus.n,1); end end for i = 1:length(blocks)*(~method) bmask = get_param(blocks(i),'MaskType'); jdx = strmatch(bmask,Compnames,'exact'); if isempty(jdx) ncomp = ncomp + 1; Compnames{ncomp,1} = bmask; Compidx(ncomp,1) = 0; jdx = ncomp; end Compidx(jdx) = Compidx(jdx)+1; bpos = get_param(blocks(i),'Position'); bidx = Compidx(jdx); %str2double(get_param(blocks(i),'UserData')); borien = get_param(blocks(i),'Orientation'); bports = get_param(blocks(i),'Ports'); bvalues = get_param(blocks(i),'MaskValues'); bin = sum(bports([1 6])); bou = sum(bports([2 7])); switch bmask case 'Varname' % nothing to do! x = cell(1,1); y = cell(1,1); s = cell(1,1); x{1} = 0; y{1} = 0; s{1} = 'k'; case 'Ltc' bname = get_param(blocks(i),'NamePlacement'); [x,y,s] = mask(eval(bmask),bidx,{borien;bname},bvalues); case 'Line' bdescr = get_param(blocks(i),'MaskDescription'); [x,y,s] = mask(eval(bmask),bidx,borien,bdescr); case 'PQ' [x,y,s] = mask(eval(bmask),bidx,borien,'PQ'); case 'PQgen' [x,y,s] = mask(eval(bmask),bidx,borien,'PQgen'); case 'Link' rot = strcmp(get_param(blocks(i),'NamePlacement'),'normal'); x = cell(6,1); y = cell(6,1); s = cell(6,1); x{1} = [0.45 0]; y{1} = [0.5 0.5]; s{1} = 'k'; x{2} = [1 0.55]; y{2} = [0.5 0.5]; s{2} = 'k'; x{3} = [0.45 0.55 0.55 0.45 0.45]; y{3} = [0.45 0.45 0.55 0.55 0.45]; s{3} = 'g'; x{4} = [0.5 0.5]; y{4} = rot*0.45+[0.1 0.45]; s{4} = 'g'; x{5} = [0.45 0.55 0.55 0.45 0.45]; y{5} = rot*0.9+[0 0 0.1 0.1 0]; s{5} = 'g'; x{6} = 1-rot; y{6} = 1-rot; s{6} = 'w'; [x,y] = fm_maskrotate(x,y,borien); case 'Link2' x = cell(10,1); y = cell(10,1); s = cell(10,1); x{1} = [0 0.45]; y{1} = [0.5 0.5]; s{1} = 'k'; x{2} = [0.5 0.5]; y{2} = [0 0.4]; s{2} = 'k'; x{3} = [0.5 0.5]; y{3} = [0 0.4]; s{3} = 'k'; x{4} = [0.5 1]; y{4} = [0 0]; s{4} = 'k'; x{5} = [0.5 0.5]; y{5} = [0.6 1]; s{5} = 'g'; x{6} = [0.5 0.9]; y{6} = [1 1]; s{6} = 'g'; x{7} = [0.9 0.985 0.985 0.9 0.9]; y{7} = [0.1 0.1 -0.1 -0.1 0.1]+1; s{7} = 'g'; x{8} = [0.45 0.55 0.55 0.45 0.45]; y{8} = [0.6 0.6 0.4 0.4 0.6]; s{8} = 'g'; x{9} = 0; y{9} = -0.5; s{9} = 'w'; x{10} = 0; y{10} = 1.5; s{10} = 'w'; [x,y] = fm_maskrotate(x,y,borien); otherwise [x,y,s] = mask(eval(bmask),bidx,borien,bvalues); end xt = []; yt = []; for j = 1:length(x) xt = [xt, x{j}]; yt = [yt, y{j}]; end xmin = min(xt); xmax = max(xt); if xmax == xmin, xmax = xmin+1; end ymin = min(yt); ymax = max(yt); if ymax == ymin, ymax = ymin+1; end dx = bpos(3)-bpos(1); dy = bpos(4)-bpos(2); xscale = dx/(xmax-xmin); yscale = dy/(ymax-ymin); xcorr = -xscale*(xmax+xmin)/2 + 0.5*dx; ycorr = -yscale*(ymax+ymin)/2 + 0.5*dy; xmean = bpos(1)+xcorr+xscale*(xmax+xmin)/2; ymean = bpos(4)-ycorr-yscale*(ymax+ymin)/2; if strcmp(bmask,'Bus') idx = idx + 1; if type == 1 || type == 2 || type == 6 || type == 7 xb = [xb; bpos(1)+xcorr+xscale*xmax; xmean]; yb = [yb; bpos(4)-yscale*ymax-ycorr; ymean]; xb = [xb; bpos(1)+xcorr+xscale*xmin]; yb = [yb; bpos(4)-yscale*ymin-ycorr]; end %bcolor = get_param(blocks(i),'BackgroundColor'); bname = get_param(blocks(i),'Name'); switch borien case {'right','left'} switch get_param(blocks(i),'NamePlacement') case 'normal' xtext = xmean; ytext = bpos(4)-ycorr-yscale*ymin+7; bha = 'center'; bva = 'top'; case 'alternate' xtext = xmean; ytext = bpos(4)-ycorr-yscale*ymax-7; bha = 'center'; bva = 'bottom'; end case {'up','down'} switch get_param(blocks(i),'NamePlacement') case 'normal' xtext = bpos(1)+xcorr+xscale*xmax+7; ytext = ymean; bha = 'left'; bva = 'middle'; case 'alternate' xtext = bpos(1)+xcorr+xscale*xmin-7; ytext = ymean; bha = 'right'; bva = 'middle'; end end % write bus names if type h = text(xtext,ytext,zlevel,bname); set(h,'HorizontalAlignment',bha,'VerticalAlignment',bva, ... 'FontSize',8) end if type == 1 || type == 2 || type == 6 || type == 7 switch type case 1, zpeak = DAE.y(Bus.v(idx)); case 2, zpeak = 180*DAE.y(Bus.a(idx))/pi; case 6, zpeak = LMP(idx); case 7, zpeak = NCP(idx); end Varout.hdl(idx) = plot3([xmean xmean],[ymean ymean], ... [zlevel,zpeak],'k:'); end end if strcmp(bmask,'Line') && type == 3 idx_line = idx_line + 1; xb = [xb; bpos(1)+xcorr+xscale*xmax; xmean]; yb = [yb; bpos(4)-yscale*ymax-ycorr; ymean]; xb = [xb; bpos(1)+xcorr+xscale*xmin]; yb = [yb; bpos(4)-yscale*ymin-ycorr]; Varout.hdl(idx_line) = plot3([xmean xmean],[ymean ymean],[zlevel,sij(idx_line)],'k:'); elseif strcmp(bmask,'Syn') && (type == 4 || type == 5) idx_gen = idx_gen + 1; xb = [xb; bpos(1)+xcorr+xscale*xmax; xmean]; yb = [yb; bpos(4)-yscale*ymax-ycorr; ymean]; xb = [xb; bpos(1)+xcorr+xscale*xmin]; yb = [yb; bpos(4)-yscale*ymin-ycorr]; switch type case 4 zpeak = 180*DAE.x(Syn.delta(idx_gen))/pi; case 5 zpeak = DAE.x(Syn.omega(idx_gen)); end Varout.hdl(idx_gen) = plot3([xmean xmean],[ymean ymean], ... [zlevel,zpeak],'k:'); end switch borien case 'right' len = yscale*(ymax-ymin); if bin, in_off = len/bin; end if bou, ou_off = len/bou; end for j = 1:bin yi = bpos(4)-ycorr-yscale*ymin-in_off/2-in_off*(j-1); xi = bpos(1)+xcorr+xscale*xmin; [yf,xf] = closerline(yi,xi-5,yl,xl); plot3([xi, xf],[yf, yf],[zlevel, zlevel],'k') end for j = 1:bou yi = bpos(4)-ycorr-yscale*ymin-ou_off/2-ou_off*(j-1); xi = bpos(1)+xcorr+xscale*xmax; [yf,xf] = closerline(yi,xi+5,yl,xl); plot3([xi, xf],[yf, yf],[zlevel, zlevel],'k') end case 'left' len = yscale*(ymax-ymin); if bin, in_off = len/bin; end if bou, ou_off = len/bou; end for j = 1:bin yi = bpos(4)-ycorr-yscale*ymin-in_off/2-in_off*(j-1); xi = bpos(1)+xcorr+xscale*xmax; [yf,xf] = closerline(yi,xi+5,yl,xl); plot3([xi, xf],[yf, yf],[zlevel, zlevel],'k') end for j = 1:bou yi = bpos(4)-ycorr-yscale*ymin-ou_off/2-ou_off*(j-1); xi = bpos(1)+xcorr+xscale*xmin; [yf,xf] = closerline(yi,xi-5,yl,xl); plot3([xi, xf],[yf, yf],[zlevel, zlevel],'k') end case 'up' len = xscale*(xmax-xmin); if bin, in_off = len/bin; end if bou, ou_off = len/bou; end for j = 1:bin yi = bpos(4)-ycorr-yscale*ymin; xi = bpos(1)+xcorr+xscale*xmin+in_off/2+in_off*(j-1); [xf,yf] = closerline(xi,yi+5,xl,yl); plot3([xf, xf],[yi, yf],[zlevel, zlevel],'k') end for j = 1:bou yi = bpos(4)-ycorr-yscale*ymax; xi = bpos(1)+xcorr+xscale*xmin+ou_off/2+ou_off*(j-1); [xf,yf] = closerline(xi,yi-5,xl,yl); plot3([xf, xf],[yi, yf],[zlevel, zlevel],'k') end case 'down' len = xscale*(xmax-xmin); if bin, in_off = len/bin; end if bou, ou_off = len/bou; end for j = 1:bin yi = bpos(4)-ycorr-yscale*ymax; xi = bpos(1)+xcorr+xscale*xmin+in_off/2+in_off*(j-1); [xf,yf] = closerline(xi,yi-5,xl,yl); plot3([xf, xf],[yi, yf],[zlevel, zlevel],'k') end for j = 1:bou yi = bpos(4)-ycorr-yscale*ymin; xi = bpos(1)+xcorr+xscale*xmin+ou_off/2+ou_off*(j-1); [xf,yf] = closerline(xi,yi+5,xl,yl); plot3([xf, xf],[yi, yf],[zlevel, zlevel],'k') end end for j = 1:length(x) z = zlevel*ones(length(x{j}),1); xx = bpos(1)+xcorr+xscale*(x{j}); yy = bpos(4)-yscale*(y{j})-ycorr; if ~type if ~isempty(xx) x_max = max(x_max,max(xx)); x_min = min(x_min,min(xx)); end if ~isempty(yy) y_max = max(y_max,max(yy)); y_min = min(y_min,min(yy)); end end plot3(xx,yy,z,s{j}) end x1 = [xlim]'; x2 = [ylim]'; x1mean = 0.5*(x1(1)+x1(2)); x2mean = 0.5*(x2(1)+x2(2)); xba = [xb;x1(1);x1(1);x1(2);x1(2);x1mean;x1mean;x1(1);x1(2)]; yba = [yb;x2(1);x2(2);x2(1);x2(2);x2(1);x2(2);x2mean;x2mean]; Varout.xb = xba; Varout.yb = yba; end if ~type % draw only one-line diagram xframe = 0.05*(x_max-x_min); yframe = 0.05*(y_max-y_min); set(hdla,'XLim',[x_min-xframe, x_max+xframe],'YLim',[y_min-yframe, y_max+yframe]) hold off return end x1 = [xlim]'; x2 = [ylim]'; switch type case 1 zb = formz(DAE.y(Bus.v),Bus.n); if abs(mean(DAE.y(Bus.v))-1) < 1e-3 zba = [zb; 0.9999*ones(8,1)]; else zba = [zb; ones(8,1)]; end case 2 zb = formz(180*DAE.y(Bus.a)/pi,Bus.n); zba = [zb; mean(180*DAE.y(Bus.a)/pi)*ones(8,1)]; case 3 [sij,sji] = flows(Line,3); zb = formz(sij,Line.n); zba = [zb; mean(sij)*ones(8,1)]; case 4 zb = formz(180*DAE.x(Syn.delta)/pi,Syn.n); zba = [zb; mean(180*DAE.x(Syn.delta)/pi)*ones(8,1)]; case 5 zb = formz(DAE.x(Syn.omega),Syn.n); zba = [zb; 0.999*ones(8,1)]; case 6 zb = formz(LMP,Bus.n); zba = [zb; mean(LMP)*ones(8,1)]; case 7 zb = formz(NCP,Bus.n); zba = [zb; mean(NCP)*ones(8,1)]; end [XX,YY] = meshgrid(x1(1):5:x1(2),x2(1):5:x2(2)); if length(zba) > length(Varout.xb) zba = zba(1:length(Varout.xb)); elseif length(zba) < length(Varout.xb) zba = [zba, ones(1, length(Varout.xb)-length(zba))]; end ZZ = griddata(Varout.xb,Varout.yb,zba,XX,YY,'cubic'); if method zlevel = Varout.zlevel; switch type case 1 for i = 1:Bus.n set(Varout.hdl(i),'ZData',[zlevel,DAE.y(Bus.v(i))]); end case 2 for i = 1:Bus.n set(Varout.hdl(i),'ZData',[zlevel,180*DAE.y(Bus.a(i))/pi]); end case 3 [sij,sji] = flows(Line,3); for i = 1:Line.n set(Varout.hdl(i),'ZData',[zlevel,sij(i)]); end case 4 for i = 1:Syn.n set(Varout.hdl(i),'ZData',[zlevel,180*DAE.x(Syn.delta(i))/pi]); end case 5 for i = 1:Syn.n set(Varout.hdl(i),'ZData',[zlevel,zlevel,DAE.x(Syn.omega(i))]); end case 6 for i = 1:Bus.n set(Varout.hdl(i),'ZData',[zlevel,zlevel,LMP(i)]); end case 7 for i = 1:Bus.n set(Varout.hdl(i),'ZData',[zlevel,zlevel,NCP(i)]); end end delete(Varout.surf) if strcmp(Settings.xlabel,'Loading Parameter \lambda (p.u.)') xlabel([Settings.xlabel,' = ',sprintf('%8.4f',DAE.lambda)]) else xlabel([Settings.xlabel,' = ',sprintf('%8.4f',DAE.t)]) end Varout.surf = surf(XX,YY,ZZ); alpha(Varout.alpha) shading interp axis manual Varout.movie(end+1) = getframe(findobj(Fig.threed,'Tag','Axes1')); %Varout.movie(end+1) = getframe(Fig.threed); else if type == 1 && Varout.caxis caxis([0.9 1.1]) else caxis('auto') end Varout.surf = surf(XX,YY,ZZ); axis auto shading interp alpha(Varout.alpha) xlabel('') % if Settings.hostver < 8.04 % set(gca,'YDir','reverse') % end set(gca,'YDir','reverse') % set(gca,'XDir','reverse') % set(gca) set(gca,'XTickLabel',[]) set(gca,'YTickLabel',[]) set(gca,'XTick',[]) set(gca,'YTick',[]) switch type case 1 zlabel('Voltage Magnitudes [p.u.]') case 2 zlabel('Voltage Angles [deg]') case 3 zlabel('Line Flows [p.u.]') case 4 zlabel('Gen. Rotor Angles [deg]') case 5 zlabel('Gen. Rotor Speeds [p.u.]') case 6 zlabel('Locational Marginal Prices [$/MWh]') case 7 zlabel('Nodal Congestion Prices [$/MWh]') end colormap(maps{maptype}) colorbar('EastOutside') xlim(x1) box on end hold off case 'VoltageReport' busidx = find(strcmp(masks,'Bus')); for i = 1:Bus.n valore = ['|V| = ', ... fvar(DAE.y(i+Bus.n),7), ... ' p.u.\n<V = ', ... fvar(DAE.y(i),7), ... ' rad ']; set_param(blocks(busidx(i)),'AttributesFormatString',valore); end case 'WipeVoltageReport' busidx = find(strcmp(masks,'Bus')); for i = 1:Bus.n, set_param(blocks(busidx(i)),'AttributesFormatString',''); end case 'PowerFlowReport' simrep(Line, blocks, masks, lines) simrep(Hvdc, blocks, masks, lines) simrep(Ltc, blocks, masks, lines) simrep(Phs, blocks, masks, lines) simrep(Lines, blocks, masks, lines) simrep(Tg, blocks, masks, lines) simrep(Exc, blocks, masks, lines) simrep(Oxl, blocks, masks, lines) simrep(Pss, blocks, masks, lines) simrep(Syn, blocks, masks, lines) simrep(PQ, blocks, masks, lines) simrep(PV, blocks, masks, lines) simrep(SW, blocks, masks, lines) %for i = 1:Comp.n % simrep(eval(Comp.names{i},blocks,masks,lines) %end case 'WipePowerFlowReport' for i = 1:length(lines) set_param(lines(i),'Name','') end case 'HideNames' nobusidx = find(~strcmp(masks,'Bus')); for i = 1:length(nobusidx) set_param(blocks(nobusidx(i)),'ShowName','off') end nobusidx = find(strcmp(masks,'')); for i = 1:length(nobusidx) set_param(blocks(nobusidx(i)),'ShowName','on') end case 'ShowNames' for i = 1:nblock set_param(blocks(i),'ShowName','on') end case 'HideBusNames' busidx = find(strcmp(masks,'Bus')); for i = 1:Bus.n set_param(blocks(busidx(i)),'ShowName','off') end case 'ShowBusNames' busidx = find(strcmp(masks,'Bus')); for i = 1:Bus.n set_param(blocks(busidx(i)),'ShowName','on') end case 'FontType' for i = 1:nblock set_param(blocks(i),'FontName',fontname) end for i = 1:length(lines) set_param(lines(i),'FontName',fontname) end case 'FontSize' for i = 1:nblock, set_param(blocks(i),'FontSize',fontsize); end for i = 1:length(lines), set_param(lines(i),'FontSize',fontsize); end case 'mdl2eps' % fontsize == 0: export to color eps % fontsize == 1: export to grey-scale eps grey_eps = fontsize; pat = '^/c\d+\s\{.* sr\} bdef'; cd(Path.data) fileeps = [filedata,'.eps']; a = dir(fileeps); Settings.ok = 1; if ~isempty(a) uiwait(fm_choice(['Overwrite "',fileeps,'" ?'])) end if ~Settings.ok, return, end orient portrait print('-s','-depsc',fileeps) if ~Settings.noarrows cd(Path.local) fm_disp(['PSAT model saved in ',Path.data,fileeps]) return end file = textread(fileeps,'%s','delimiter','\n'); idx = []; d2 = zeros(1,4); for i = 1:length(file) if grey_eps && ~isempty(regexp(file{i},pat)) matchexp = regexp(file{i},'^/c\d+\s\{','match'); colors = strrep(file{i},matchexp{1},'['); colors = regexprep(colors,' sr\} bdef',']'); rgb = sum(str2num(colors)); colors = num2str([rgb rgb rgb]/3); file{i} = [matchexp{1},colors,' sr} bdef']; end if strcmp(file{i},'PP') if strcmp(file{i-1}(end-1:end),'MP') d1 = str2num(strrep(file{i-1},'MP','')); if length(d1) >= 6 if ~d1(3) d2(2) = d1(6)-d1(2); d2(4) = d1(6)-d1(2); d2(1) = d1(5)-d1(2); d2(3) = d1(5)+d1(1); else d2(2) = d1(6)+d1(2); d2(4) = d1(6)-d1(1); d2(1) = d1(5)-d1(1); d2(3) = d1(5)-d1(1); end file{i-1} = sprintf('%4d %4d mt %4d %4d L',d2); idx = [idx, i]; end end end if ~isempty(findstr(file{i}(max(1,end-1):end),'PO')) d1 = str2num(strrep(file{i},'PO','')); if ~isempty(findstr(file{i+1},'L')) nextline = strrep(file{i+1},'L',''); d2 = str2num(strrep(nextline,'mt','')); if d1(4) == d2(2) if d2(1) > d1(3); d2(1) = d1(3)-d1(1); else d2(1) = d2(1)+d1(1)+abs(d1(3)-d2(1)); end else if d2(2) > d1(4) d2(2) = d1(4)-d1(2); else d2(2) = d2(2)+d1(2)+abs(d1(4)-d2(2)); end end file{i+1} = sprintf('%4d %4d mt %4d %4d L',d2); elseif ~isempty(findstr(file{i+2},'MP stroke')) d2 = str2num(strrep(file{i+2},'MP stroke','')); if d2(1) d2(3) = d2(3)-d2(1); if d2(1) < 0 d2(3) = d2(3) - 4; end end if d2(2) d2(4) = d2(4)-d2(2); if d2(2) < 0 d2(4) = d2(4) - 4; end end file{i+1} = sprintf('%4d %4d %4d %4d %4d MP stroke',d2); end idx = [idx, i]; end end file(idx) = []; fid = fopen(fileeps,'wt+'); for i = 1:length(file) fprintf(fid,'%s\n',file{i}); end fclose(fid); cd(Path.local) fm_disp(['PSAT model saved in ',Path.data,fileeps]) otherwise fm_disp('Unknown command for Simulink Settings GUI...',2) end cd(Path.local) % ------------------------------------------------------------------------- function [xa,ya] = closerline(xa,ya,xl,yl) [err,idx] = min(abs(sqrt((xl-xa).^2+(yl-ya).^2))); if err < 15 xa = xl(idx); ya = yl(idx); end % ------------------------------------------------------------------------- function zb = formz(vec,n) zb = zeros(3*n,1); zb(1:3:3*n) = vec; zb(2:3:3*n) = vec; zb(3:3:3*n) = vec;
github
Sinan81/PSAT-master
fm_view.m
.m
PSAT-master/psat-mat/psat/fm_view.m
2,815
utf_8
8c93d49685f3302ab0c2561bf8b30aa0
function fm_view(flag) % FM_VIEW functions for matrix visualizations % % FM_VIEW(FLAG) % FLAG matrix visualization type % %see also FM_MATRX % %Author: Federico Milano %Date: 11-Nov-2002 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global DAE Bus Theme Line if isempty(Bus.con) fm_disp('No loaded system. Matrix visualization cannot be run.',2) return end switch flag case 1 if DAE.n > 0 matrice = [DAE.Fx, DAE.Fy; DAE.Gx, DAE.Gy]; else fm_disp('Since no dynamic component is loaded, AC coincides with Jlfv.',2) matrice = DAE.Gy; end titolo = 'Complete System Matrix A_c'; visual(matrice,titolo) case 2 if DAE.n > 0 matrice = DAE.Fx - DAE.Fy*inv(DAE.Gy)*DAE.Gx; else fm_disp('No dynamic component loaded.',2); return end titolo = 'State jacobian matrix A_s'; visual(matrice,titolo) case 3 matrice = build_gy(Line); titolo = 'Jacobian matrix J_l_f'; visual(matrice,titolo) case 4 matrice = DAE.Gy; titolo = 'Jacobian matrix J_l_f_v'; visual(matrice,titolo) case 5 if DAE.n > 0 Fx_mod = DAE.Fx+diag(-1e-5*ones(DAE.n,1)); matrice = DAE.Gy - DAE.Gx*inv(Fx_mod)*DAE.Fy; else fm_disp(['Since no dynamic component is loaded, ', ... 'Jlfd coincides with Jlfv.'],2) matrice = DAE.Gy; end titolo = 'Jacobian matrix J_l_f_d'; visual(matrice,titolo) case 6 ch(1) = findobj(gcf,'Tag','toggle1'); ch(2) = findobj(gcf,'Tag','toggle2'); ch(3) = findobj(gcf,'Tag','toggle3'); ch(4) = findobj(gcf,'Tag','toggle4'); ca = find(ch == gcbo); vals = zeros(4,1); vals(ca) = 1; for i = 1:4, set(ch(i),'Value',vals(i)); end hdl = findobj(gcf,'Tag','toggle5'); if ca == 3 set(hdl,'Enable','off'); else set(hdl,'Enable','on'); end end %====================================================================== function visual(matrice,titolo) global DAE Theme ch(1) = findobj(gcf,'Tag','toggle1'); ch(2) = findobj(gcf,'Tag','toggle2'); ch(3) = findobj(gcf,'Tag','toggle3'); ch(4) = findobj(gcf,'Tag','toggle4'); vals = get(ch,'Value'); for i = 1:4, valn(i) = vals{i}; end tre_d = find(valn); switch tre_d case 1 surf(full(matrice)); shading('interp') case 2 mesh(full(matrice)); case 3 rotate3d off hdl = findobj(gcf,'Tag','toggle5'); set(hdl,'Value',0); spy(matrice); if flag == 1 hold on plot([0,DAE.n+DAE.m+2],[DAE.n+0.5,DAE.n+0.5],'k:'); plot([DAE.n+0.5,DAE.n+0.5],[0,DAE.n+DAE.m+2],'k:'); hold off end case 4 surf(full(matrice)); end hdl = findobj(gcf,'Tag','toggle6'); if get(hdl,'Value'), grid on, else grid off, end hdl = findobj(gcf,'Tag','toggle7'); if get(hdl,'Value'), zoom on, else zoom off, end set(gca,'Color',Theme.color11); title(titolo);
github
Sinan81/PSAT-master
fm_int.m
.m
PSAT-master/psat-mat/psat/fm_int.m
10,770
utf_8
ce704b5a7845bdb55770782dfcf0b565
function fm_int % FM_INT time domain integration routines: % 1 - Forward Euler % 2 - Trapezoidal Method % % FM_INT % %see also FM_TSTEP, FM_OUT and the Settings structure % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 16-Jan-2003 %Update: 27-Feb-2003 %Update: 01-Aug-2003 %Update: 11-Sep-2003 %Version: 1.0.4 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Fig Settings Snapshot Hdl global Bus File DAE Theme OMIB global SW PV PQ Fault Ind global Varout Breaker Line Path clpsat if ~autorun('Time Domain Simulation',1), return, end tic % initial messages % ----------------------------------------------------------------------- fm_disp if DAE.n == 0 && ~clpsat.init Settings.ok = 0; uiwait(fm_choice('No dynamic component is loaded. Continue anyway?',1)) if ~Settings.ok fm_disp('Time domain simulation aborted.',2) return end end fm_disp('Time domain simulation') switch Settings.method case 1, fm_disp('Implicit Euler integration method') case 2, fm_disp('Trapezoidal integration method') end fm_disp(['Data file "',Path.data,File.data,'"']) if ~isempty(Path.pert), fm_disp(['Perturbation file "',Path.pert,File.pert,'"']) end if (strcmp(File.pert,'pert') && strcmp(Path.pert,Path.psat)) || ... isempty(File.pert) fm_disp('No perturbation file set.',1) end if ishandle(Fig.main) hdl = findobj(Fig.main,'Tag','PushClose'); set(hdl,'String','Stop'); set(Fig.main,'UserData',1); end if Settings.plot if Settings.plottype == 1 && ~DAE.n Settings.plottype = 2; fm_disp('Cannot plot state variables (dynamic order = 0).') fm_disp('Bus voltages will be plotted during the TD simulation.') end maxlegend = min(Bus.n,7); switch Settings.plottype case 1 maxlegend = min(DAE.n,7); idx0 = 0; case 2 idx0 = DAE.n; case 3 idx0 = DAE.n+Bus.n; case 4 idx0 = DAE.n+DAE.m; case 5 idx0 = DAE.n+DAE.m+Bus.n; case 6 maxlegend = 3; idx0 = DAE.n+DAE.m+2*Bus.n; end end % check settings % ------------------------------------------------------------------ iter_max = Settings.dynmit; tol = Settings.dyntol; Dn = 1; if DAE.n, Dn = DAE.n; end identica = speye(max(Dn,1)); if (Fault.n || Breaker.n) && PQ.n && ~Settings.pq2z if clpsat.init if clpsat.pq2z Settings.pq2z = 1; else Settings.pq2z = 0; end elseif ~Settings.donotask uiwait(fm_choice(['Convert (recommended) PQ loads to constant impedances?'])) if Settings.ok Settings.pq2z = 1; else Settings.pq2z = 0; end end end % convert PQ loads to shunt admittances (if required) PQ = pqshunt(PQ); % set up variables % ---------------------------------------------------------------- DAE.t = Settings.t0; fm_call('i'); DAE.tn = DAE.f; if isempty(DAE.tn), DAE.tn = 0; end % graphical settings % ---------------------------------------------------------------- plot_now = 0; if ~clpsat.init || ishandle(Fig.main) if Settings.plot if ishandle(Fig.plot) figure(Fig.plot); else fm_plotfig; end elseif Settings.status fm_bar('open') fm_simtd('init') idxo = 0; else fm_disp(['t = ',num2str(Settings.t0),' s'],3) perc = 0; perc_old = 0; end drawnow end % ---------------------------------------------------------------- % initializations % ---------------------------------------------------------------- t = Settings.t0; k = 1; h = fm_tstep(1,1,0,Settings.t0); inc = zeros(Dn+DAE.m,1); callpert = 1; % get initial network connectivity fm_flows('connectivity', 'verbose'); % output initialization fm_out(0,0,0); fm_out(2,Settings.t0,k); % time vector of snapshots, faults and breaker events fixed_times = []; n_snap = length(Snapshot); if n_snap > 1 && ~Settings.locksnap snap_times = zeros(n_snap-1,1); for i = 2:n_snap snap_times(i-1,1) = Snapshot(i).time; end fixed_times = [fixed_times; snap_times]; end fixed_times = [fixed_times; gettimes(Fault); ... gettimes(Breaker); gettimes(Ind)]; fixed_times = sort(fixed_times); % compute max rotor angle difference diff_max = anglediff; % ================================================================ % ---------------------------------------------------------------- % Main loop % ---------------------------------------------------------------- % ================================================================ inc = zeros(Dn+DAE.m,1); while (t < Settings.tf) && (t + h > t) && ~diff_max if ishandle(Fig.main) if ~get(Fig.main,'UserData'), break, end end if (t + h > Settings.tf), h = Settings.tf - t; end actual_time = t + h; % check not to jump disturbances index_times = find(fixed_times > t & fixed_times < t+h); if ~isempty(index_times); actual_time = min(fixed_times(index_times)); h = actual_time - t; end % set global time DAE.t = actual_time; % backup of actual variables if isempty(DAE.x), DAE.x = 0; end xa = DAE.x; ya = DAE.y; % initialize NR loop iterazione = 1; inc(1) = 1; if isempty(DAE.f), DAE.f = 0; end fn = DAE.f; % applying faults, breaker interventions and perturbations if ~isempty(fixed_times) if ~isempty(find(fixed_times == actual_time)) Fault = intervention(Fault,actual_time); Breaker = intervention(Breaker,actual_time); end end if callpert try if Settings.hostver >= 6 feval(Hdl.pert,actual_time); else if ~isempty(Path.pert) cd(Path.pert) feval(Hdl.pert,actual_time); cd(Path.local) end end catch fm_disp('* * Something wrong in the perturbation file:') fm_disp(lasterr) fm_disp('* * The perturbation file will be discarded.') callpert = 0; end end % Newton-Raphson loop Settings.error = tol+1; while Settings.error > tol if (iterazione > iter_max), break, end drawnow if ishandle(Fig.main) if ~get(Fig.main,'UserData'), break, end end % DAE equations fm_call('i'); % complete Jacobian matrix DAE.Ac switch Settings.method case 1 % Forward Euler DAE.Ac = [identica - h*DAE.Fx, -h*DAE.Fy; DAE.Gx, DAE.Gy]; DAE.tn = DAE.x - xa - h*DAE.f; case 2 % Trapezoidal Method DAE.Ac = [identica - h*0.5*DAE.Fx, -h*0.5*DAE.Fy; DAE.Gx, DAE.Gy]; DAE.tn = DAE.x - xa - h*0.5*(DAE.f + fn); end % Non-windup limiters fm_call('5'); inc = -DAE.Ac\[DAE.tn; DAE.g]; %inc = -umfpack(DAE.Ac,'\',[DAE.tn; DAE.g]); DAE.x = DAE.x + inc(1:Dn); DAE.y = DAE.y + inc(1+Dn: DAE.m+Dn); iterazione = iterazione + 1; Settings.error = max(abs(inc)); end if (iterazione > iter_max) h = fm_tstep(2,0,iterazione,t); DAE.x = xa; DAE.y = ya; DAE.f = fn; else h = fm_tstep(2,1,iterazione,t); t = actual_time; k = k+1; % extend output stack if k > length(Varout.t), fm_out(1,t,k); end % ---------------------------------------------------------------- % ---------------------------------------------------------------- % update output variables, snapshots and network visualisation % ---------------------------------------------------------------- % ---------------------------------------------------------------- fm_out(2,t,k); % plot variables & display iteration status % ---------------------------------------------------------------- i_plot = 1+k-10*fix(k/10); perc = (t-Settings.t0)/(Settings.tf-Settings.t0); if i_plot == 10 fm_disp([' > Simulation time = ',num2str(DAE.t), ... ' s (',num2str(round(perc*100)),'%)']) end if ~clpsat.init || ishandle(Fig.main) if Settings.plot if i_plot == 10 plot(Varout.t(1:k),Varout.vars(1:k,idx0+[1:maxlegend])); set(gca,'Color',Theme.color11); xlabel('time (s)') drawnow end elseif Settings.status idx = (t-Settings.t0)/(Settings.tf-Settings.t0); fm_bar([idxo,idx]) if i_plot == 10, fm_simtd('update'), end idxo = idx; end end % fill up snapshots if n_snap > 1 && ~Settings.locksnap snap_i = find(snap_times == t)+1; fm_snap('assignsnap',snap_i); end end % compute max rotor angle difference diff_max = anglediff; end if Settings.status && ~Settings.plot fm_bar('close') fm_simtd('update') end if ~DAE.n, DAE.x = []; DAE.f =[]; end % final messages % ----------------------------------------------------------------------- if ishandle(Fig.main) if diff_max && get(Fig.main,'UserData') fm_disp(['Rotor angle max difference is > ', ... num2str(Settings.deltadelta), ... ' deg. Simulation stopped at t = ', ... num2str(t), ' s'],2); elseif (t < Settings.tf) && get(Fig.main,'UserData') fm_disp(['Singularity likely. Simulation stopped at t = ', ... num2str(t), ' s'],2); elseif ~get(Fig.main,'UserData') fm_disp(['Dynamic Simulation interrupted at t = ',num2str(t),' s'],2) else fm_disp(['Dynamic Simulation completed in ',num2str(toc),' s']); end else if diff_max fm_disp(['Rotor angle max difference is > ', ... num2str(Settings.deltadelta), ... ' deg. Simulation stopped at t = ', ... num2str(t), ' s'],2); elseif (t < Settings.tf) fm_disp(['Singularity likely. Simulation stopped at t = ', ... num2str(t), ' s'],2); else fm_disp(['Dynamic Simulation completed in ',num2str(toc),' s']); end end % resize output varibales & final settings % ----------------------------------------------------------------------- fm_out(3,t,k); if Settings.beep, beep, end Settings.xlabel = 'time (s)'; if ishandle(Fig.plot), fm_plotfig, end % future simulations do not need LF computation Settings.init = 2; SNB.init = 0; LIB.init = 0; CPF.init = 0; OPF.init = 0; if ishandle(Fig.main), set(hdl,'String','Close'); end DAE.t = -1; % reset global time % compute delta difference at each step % ----------------------------------------------------------------------- function diff_max = anglediff global Settings Syn Bus DAE SW OMIB diff_max = 0; if ~Settings.checkdelta, return, end if ~Syn.n, return, end delta = DAE.x(Syn.delta); [idx,ia,ib] = intersect(Bus.island,getbus(Syn)); if ~isempty(idx), delta(ib) = []; end if isscalar(delta) delta = [delta; DAE.y(SW.refbus)]; end delta_diff = abs(delta-min(delta)); diff_max = (max(delta_diff)*180/pi) > Settings.deltadelta; if diff_max, return, end % check transient stability %fm_omib %if abs(OMIB.margin) > 1e-2 % fm_disp(['* * Transient stability margin: ',num2str(OMIB.margin)]) %end
github
Sinan81/PSAT-master
fm_writetex.m
.m
PSAT-master/psat-mat/psat/fm_writetex.m
5,097
utf_8
2a8467ad574f2e808e3e851821c9a981
function fm_writetex(Matrix,Header,Cols,Rows,File) % FM_WRITETEX export PSAT results in LaTeX2e format. % % FM_WRITETEX(MATRIX,HEDAER,COLNAMES,ROWNAMES,FILENAME) % % MATRIX Matrix to write to file % Cell array for multiple matrices. % HEADER String of header information. % Cell array for multiple header. % COLNAMES (Cell array of strings) Column headers. % One cell element per column. % ROWNAMES (Cell array of strings) Row headers. % One cell element per row. % FILENAME (string) Name of TeX file. % If not specified, contents will be % opened in the current selected text % viewer. % %Author: Federico Milano %Date: 15-Sep-2003 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Path if ~iscell(Matrix) Matrix{1,1} = Matrix; Header{1,1} = Header; Cols{1,1} = Cols; Rows{1,1} = Rows; end % -------------------------------------------------------------------- % opening text file % -------------------------------------------------------------------- fm_disp fm_disp('Writing the report LaTeX2e file...') [fid,msg] = fopen([Path.data,File], 'wt'); if fid == -1 fm_disp(msg) return end path_lf = strrep(Path.data,'\','\\'); % -------------------------------------------------------------------- % writing data % -------------------------------------------------------------------- nhr = 0; idx_table = 0; for i_matrix = 1:length(Matrix) m = Matrix{i_matrix}; colnames = Cols{i_matrix}; rownames = Rows{i_matrix}; header = Header{i_matrix}; if isempty(colnames) && isempty(rownames) && isempty(m) % treat header as comment if ~isempty(header) if iscell(header) for ii = 1:length(header) count = fprintf(fid,'%% %s\n',specialchar(header{ii})); end else count = fprintf(fid,'%% %s\n',specialchar(header)); end end else % create table idx_table = idx_table + 1; % print the preamble of the table % see Leslie Lamport's LATEX book for details. % open the table environment as a floating body fprintf(fid, '\\begin{table}[htbp] \n'); fprintf(fid, ' \\begin{center} \n'); % Write header % ------------------------------------------------------------------ caption = ''; if iscell(header) for ii = 1:length(header) caption = [caption,' ',header{ii}]; end else caption = [caption,header]; end caption = specialchar(caption); %% include the user-defined or default caption fprintf(fid, ' \\caption{%s} \n', caption); count = fprintf(fid,' \\vspace{0.1cm}\n'); % Write column names % ------------------------------------------------------------------ if nargin > 2 && ~isempty(colnames) [nrows,ncolnames] = size(colnames); tt = '|'; for ii = 1:ncolnames tt = [tt,'c|']; end fprintf(fid, ' \\begin{tabular}{%s} \n', tt); fprintf(fid, ' \\hline \n'); for jj = 1:nrows fprintf(fid, ' '); for ii = 1:ncolnames-1 count = fprintf(fid, '%s & ', specialchar(colnames{jj,ii})); end count = fprintf(fid, '%s \\\\\n', specialchar(colnames{jj,ncolnames})); end count = fprintf(fid,' \\hline \\hline \n'); end % Write data % ------------------------------------------------------------------ if nargin > 3 && ~isempty(rownames) [nrownames,ncols] = size(rownames); ndata = size(m,2); if isempty(colnames) tt = '|'; for ii = 1:(ncols+ndata) tt = [tt,'c|']; end fprintf(fid, ' \\begin{tabular}{%s} \n', tt); fprintf(fid, ' \\hline \n'); end for ii = 1:nrownames fprintf(fid, ' '); for jj = 1:ncols count = fprintf(fid, '%s & ', specialchar(rownames{ii,jj})); end for hh = 1:ndata-1 count = fprintf(fid, '$%8.5f$ & ', m(ii,hh)); end count = fprintf(fid, '$%8.5f$ \\\\ \\hline \n', m(ii,ndata)); end end %% print the footer of the table environment fprintf(fid, ' \\end{tabular} \n'); %% include the user-defined or default label fprintf(fid, ' \\label{%s} \n', ... ['tab:',strrep(File,'.tex',''),'_',num2str(idx_table)]); fprintf(fid, ' \\end{center} \n'); %% close the table environment and return fprintf(fid, '\\end{table} \n'); end count = fprintf(fid,'\n'); end fclose(fid); fm_disp(['Report of Static Results saved in ',File]) % view file fm_text(13,[Path.data,File]) % ------------------------------------------------------- % check for special LaTeX2e character % ------------------------------------------------------- function string = specialchar(string) string = [lower(strrep(string,'#','\#')),' ']; string = strrep(string,'&','\&'); string = strrep(string,'_','\_'); string = strrep(string,'$','\$'); string = strrep(string,'{','\{'); string = strrep(string,'}','\}'); string = strrep(string,'%','\%'); string = strrep(string,'~','$\sim$'); string(1) = upper(string(1));
github
Sinan81/PSAT-master
fm_threed.m
.m
PSAT-master/psat-mat/psat/fm_threed.m
11,096
utf_8
a9f48ea419066334caf6e7e619ec2e0b
function varargout = fm_threed(varargin) % FM_THREED create GUI for network visualisations % % HDL = FM_THREED() % %Author: Federico Milano %Date: 21-Aug-2007 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Settings Theme Varout Path Fig File CPF OPF % check for data file if isempty(File.data) fm_disp('Set a data file for running sparse matrix visualisation.',2) return end % check for initial power flow solution if ~Settings.init fm_disp('Solve base case power flow...') Settings.show = 0; fm_set('lf') Settings.show = 1; if ~Settings.init, return, end end if nargin if ~ishandle(Fig.threed), return, end hdl1 = findobj(Fig.threed,'Tag','PopupMenu1'); hdl2 = findobj(Fig.threed,'Tag','PopupMenu2'); value1 = get(hdl1,'Value'); value2 = get(hdl2,'Value'); switch varargin{1} case 'update' hdl3 = findobj(Fig.threed,'Tag','MenuCaxis'); if value2 == 1 set(hdl3,'Enable','on') else set(hdl3,'Enable','off') end if (value2 == 6 || value2 == 7) && ~OPF.init fm_disp(['Run OPF before displaying Locational Marginal ' ... 'Prices'],2) set(hdl2,'Value',1) set(hdl3,'Enable','on') return end fm_simrep('DrawModel',value1,value2,0) case 'init' Varout.movie = getframe(findobj(Fig.threed,'Tag','Axes1')); hdl = findobj(Fig.threed,'Tag','Axes1'); togglecontrols(Fig.threed,'off') case 'newframe' fm_simrep('DrawModel',value1,value2,1) case 'finish' togglecontrols(Fig.threed,'on') case 'movie' if isempty(Varout.movie), return, end axes(findobj(Fig.threed,'Tag','Axes1')); xlabel('') %axes('Position',[0 0 1 1]) if Settings.init > 1 && ~CPF.init fps = round(length(Varout.movie)/(Settings.tf-Settings.t0)); if ~fps, fps = 12; end movie(Varout.movie,1,fps) else movie(Varout.movie) end case 'savemovie' if isempty(Varout.movie), return, end cd(Path.data) filedata = strrep(File.data,'@ ',''); filedata = strrep(filedata,'(mdl)','_mdl'); mov = VideoWriter(filedata); open(mov); writeVideo(mov, Varout.movie); close(mov); cd(Path.local) case 'openmovie' [filename, pathname] = uigetfile('*.avi', 'Pick an AVI-file'); if ~pathname, return, end cd(pathname) Varout.movie = aviread(filename); cd(Path.local) case 'setcaxis' switch get(gcbo,'Checked') case 'on' set(gcbo,'Checked','off') Varout.caxis = 0; case 'off' set(gcbo,'Checked','on') Varout.caxis = 1; end fm_simrep('DrawModel',value1,value2,0) case 'printfig' togglecontrols(Fig.threed,'off') cd(Path.data) filedata = strrep(File.data,'@ ',''); filedata = strrep(filedata,'(mdl)','_mdl'); print(Fig.threed,'-dpng',filedata) cd(Path.local) togglecontrols(Fig.threed,'on') end return end if ishandle(Fig.threed), figure(Fig.threed), return, end maps = {'jet';'hot';'gray';'bone';'copper';'pink'; 'hsv';'cool';'autumn';'spring';'winter';'summer'}; h0 = figure('Color',Theme.color01, ... 'Units', 'normalized', ... 'CreateFcn','Fig.threed = gcf;', ... 'DeleteFcn','Fig.threed = -1; rotate3d off', ... 'FileName','fm_threed', ... 'MenuBar','none', ... 'Name','Network Visualisation', ... 'NumberTitle','off', ... 'PaperPosition',[18 180 576 432], ... 'PaperUnits','points', ... 'Position',sizefig(0.666,0.74), ... 'Resize','on', ... 'ToolBar','none'); % Menu File h1 = uimenu('Parent',h0, ... 'Label','File', ... 'Tag','MenuFile'); h2 = uimenu('Parent',h1, ... 'Callback','fm_threed openmovie', ... 'Label', 'Open movie', ... 'Tag','OpenMovie', ... 'Accelerator','o'); h2 = uimenu('Parent',h1, ... 'Callback','fm_threed savemovie', ... 'Label', 'Save movie', ... 'Tag','SaveMovie', ... 'Accelerator','s'); h2 = uimenu('Parent',h1, ... 'Callback','fm_threed printfig', ... 'Label', 'Save frame', ... 'Tag','PrintFig', ... 'Accelerator','p'); h2 = uimenu('Parent',h1, ... 'Callback','close(gcf)', ... 'Label','Close', ... 'Tag','FileClose', ... 'Separator','on', ... 'Accelerator','q'); % Menu Edit h1 = uimenu('Parent',h0, ... 'Label','Edit', ... 'Tag','MenuEdit'); h2 = uimenu('Parent',h1, ... 'Callback','fm_threed update', ... 'Label', 'Update', ... 'Accelerator','u', ... 'Tag','MenuUpdate'); h2 = uimenu('Parent',h1, ... 'Callback','fm_threed movie', ... 'Label', 'Play movie', ... 'Accelerator','m', ... 'Tag','MenuPlay'); % Menu View h1 = uimenu('Parent',h0, ... 'Label','View', ... 'Tag','MenuView'); h2 = uimenu('Parent',h1, ... 'Callback','fm_threed setcaxis', ... 'Label', 'Use voltage limits', ... 'Accelerator','v', ... 'Tag','MenuCaxis'); if Varout.caxis set(h1,'Checked','on') else set(h1,'Checked','off') end h2 = uimenu('Parent',h1, ... 'Label', 'Transparency', ... 'Tag','MenuTransparency', ... 'Separator','on'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(1), Varout.alpha = 1;', ... 'Label','None', ... 'Tag','alpha1', ... 'Accelerator','0'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(0.9), Varout.alpha = 0.9;', ... 'Label','alpha = 0.9', ... 'Tag','alpha1', ... 'Accelerator','9'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(0.8), Varout.alpha = 0.8;', ... 'Label','alpha = 0.8', ... 'Tag','alpha1', ... 'Accelerator','8'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(0.7), Varout.alpha = 0.7;', ... 'Label','alpha = 0.7', ... 'Tag','alpha1', ... 'Accelerator','7'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(0.6), Varout.alpha = 0.6;', ... 'Label','alpha = 0.6', ... 'Tag','alpha1', ... 'Accelerator','6'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(0.5), Varout.alpha = 0.5;', ... 'Label','alpha = 0.5', ... 'Tag','alpha1', ... 'Accelerator','5'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(0.4), Varout.alpha = 0.4;', ... 'Label','alpha = 0.4', ... 'Tag','alpha1', ... 'Accelerator','4'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(0.3), Varout.alpha = 0.3;', ... 'Label','alpha = 0.3', ... 'Tag','alpha1', ... 'Accelerator','3'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(0.2), Varout.alpha = 0.2;', ... 'Label','alpha = 0.2', ... 'Tag','alpha1', ... 'Accelerator','2'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(0.1), Varout.alpha = 0.1;', ... 'Label','alpha = 0.1', ... 'Tag','alpha1', ... 'Accelerator','1'); %fm_set colormap h1 = axes('Parent',h0, ... 'Box','on', ... 'CameraUpVector',[0 1 0], ... 'CameraUpVectorMode','manual', ... 'Color',Theme.color11, ... 'Position',[0.09 0.152 0.85 0.779], ... 'Tag','Axes1', ... 'XColor',[0 0 0], ... 'YColor',[0 0 0], ... 'ZColor',[0 0 0]); set(h0,'UserData',h1); h1 = uicontrol('Parent',h0, ... 'CData',fm_mat('threed_matlab'), ... 'BackgroundColor',Theme.color02, ... 'Units', 'normalized', ... 'Callback','fm_threed update', ... 'Position',[0.673 0.0185 0.06 0.08], ... 'TooltipString','Update', ... 'Tag','Pushbutton1'); h1 = uicontrol('Parent',h0, ... 'CData',fm_mat('threed_movie'), ... 'BackgroundColor',Theme.color02, ... 'Units', 'normalized', ... 'Callback','fm_threed movie', ... 'Position',[0.673+0.0650 0.0185 0.06 0.08], ... 'TooltipString','Play Movie', ... 'Tag','Pushbutton2'); h1 = uicontrol('Parent',h0, ... 'BackgroundColor',Theme.color02, ... 'Units', 'normalized', ... 'Callback','close(gcf)', ... 'Position',[0.82 0.044 0.121 0.052], ... 'String','Close', ... 'Tag','Pushbutton3'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'Callback','String = get(gcbo,''String''); eval([''colormap '',String{get(gcbo,''Value'')}]);', ... 'BackgroundColor',Theme.color04, ... 'Position',[0.488 0.041 0.157 0.056], ... 'String',maps, ... 'Style','popupmenu', ... 'Tag','PopupMenu1', ... 'Value',1); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'Callback','fm_threed update', ... 'BackgroundColor',Theme.color04, ... 'Position',[0.27 0.041 0.187 0.056], ... 'String',{'Voltage Magnitudes','Voltage Angles', ... 'Line Flows','Gen. Rotor Angles', ... 'Gen. Rotor Speeds','LMPs','NCPs'}, ... 'Style','popupmenu', ... 'Tag','PopupMenu2', ... 'Value',1); x = 0.02; y = 0.05; % Frame and push buttons for axis manipulation h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'ForegroundColor',Theme.color03, ... 'Position',[0.0726-x 0.0638-y 0.2000 0.0893], ... 'Style','frame', ... 'Tag','Frame2'); h1 = uicontrol('Parent',h0, ... 'CData',fm_mat('mat_rotate'), ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback','rotate3d(gcf), , if(get(gcbo,''Value'')), set(findobj(gcf,''Tag'',''toggle7''),''Value'',0), zoom(gcf,''off''), end', ... 'Position',[0.0776-x 0.0685-y 0.0600 0.0800], ... 'TooltipString','Rotate graph', ... 'Style','togglebutton', ... 'Tag','toggle5'); h1 = uicontrol('Parent',h0, ... 'CData',fm_mat('mat_grid'), ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback','grid(get(Fig.threed,''UserData''))', ... 'Position',[0.1426-x 0.0685-y 0.0600 0.0800], ... 'TooltipString','Grid', ... 'Style','togglebutton', ... 'Tag','toggle6'); h1 = uicontrol('Parent',h0, ... 'CData',fm_mat('mat_zoomxy'), ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback','zoom, if(get(gcbo,''Value'')), set(findobj(gcf,''Tag'',''toggle5''),''Value'',0), rotate3d(gcf,''off''), end', ... 'Position',[0.2076-x 0.0685-y 0.0600 0.0800], ... 'TooltipString','Zoom', ... 'Style','togglebutton', ... 'Tag','toggle7'); if nargout > 0, fig = h0; end function togglecontrols(fig,flag) hdl(1) = findobj(fig,'Tag','PopupMenu1'); hdl(2) = findobj(fig,'Tag','PopupMenu2'); hdl(3) = findobj(fig,'Tag','Frame2'); hdl(4) = findobj(fig,'Tag','toggle5'); hdl(5) = findobj(fig,'Tag','toggle6'); hdl(6) = findobj(fig,'Tag','toggle7'); hdl(7) = findobj(fig,'Tag','Pushbutton1'); hdl(8) = findobj(fig,'Tag','Pushbutton2'); hdl(9) = findobj(fig,'Tag','Pushbutton3'); set(hdl,'Visible',flag)
github
Sinan81/PSAT-master
fm_dirset.m
.m
PSAT-master/psat-mat/psat/fm_dirset.m
30,919
utf_8
5fd21968fdac71735d7ea592d1e51a8e
function varargout = fm_dirset(type) % FM_DIRSET define settings and actions for the data format % conversion GUI % % FM_DIRSET(TYPE) % TYPE action indentifier % %see also FM_DIR % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 05-Jul-2003 %Update: 31-Jul-2003 %Update: 07-Oct-2003 %Version: 1.1.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Path Fig Settings Theme if ishandle(Fig.dir) hdl = findobj(Fig.dir,'Tag','PopupMenu1'); formato = get(hdl,'Value'); hdl_dir = findobj(Fig.dir,'Tag','EditText1'); folder1 = get(hdl_dir,'String'); if ischar(folder1) && isdir(folder1), cd(folder1), end end % codes: IEEE = 1; PSAT = 2; PSATPERT = 3; PSATMDL = 4; CYME = 5; MATPOWER = 6; PST = 7; EPRI = 8; PSSE = 9; PSAP = 10; EUROSTAG = 11; TH = 12; CESI = 13; VST = 14; SIMPOW = 15; NEPLAN = 16; DIGSILENT = 17; POWERWORLD = 18; PET = 19; FLOWDEMO = 20; GEEPC = 21; CHAPMAN = 22; UCTE = 23; PCFLO = 24; WEBFLOW = 25; IPSS = 26; CEPEL = 27; ODM = 28; REDS = 29; VITRUVIO = 30; % all files switch type case 'formatlist' formati = cell(VITRUVIO,1); formati{IEEE} = 'IEEE CDF (.dat, .txt, .cf)'; formati{CYME} = 'CYME (.nnd, .sf)'; formati{MATPOWER} = 'MatPower (.m)'; formati{PSAT} = 'PSAT data (.m)'; formati{PSATPERT} = 'PSAT pert. (.m)'; formati{PSATMDL} = 'PSAT Simulink (.mdl)'; formati{PST} = 'PST (.m)'; formati{EPRI} = 'EPRI (.wsc, .txt, .dat)'; formati{PSSE} = 'PSS/E (.raw)'; formati{PSAP} = 'PSAP (.dat)'; formati{EUROSTAG} = 'Eurostag (.dat)'; formati{TH} = 'TH (.dat)'; formati{CESI} = 'CESI - INPTC1 (.dat)'; formati{VST} = 'VST (.dat)'; formati{SIMPOW} = 'SIMPOW (.optpow)'; formati{NEPLAN} = 'NEPLAN (.ndt)'; formati{DIGSILENT} = 'DigSilent (.dgs)'; formati{POWERWORLD} = 'PowerWorld (.aux)'; formati{PET} = 'PET (.pet)'; formati{FLOWDEMO} = 'Flowdemo.net (.fdn)'; formati{GEEPC} = 'GE format (.epc)'; formati{CHAPMAN} = 'Chapman format'; formati{UCTE} = 'UCTE format'; formati{PCFLO} = 'PCFLO format'; formati{WEBFLOW} = 'WebFlow format'; formati{IPSS} = 'InterPSS format (.ipss)'; formati{CEPEL} = 'CEPEL format (.txt)'; formati{ODM} = 'ODM format (.odm, .xml)'; formati{REDS} = 'REDS format (.pos)'; formati{VITRUVIO} = 'All Files (*.*)'; varargout(1) = {formati}; %================================================================== case 'changedir' hdl = findobj(Fig.dir,'Tag','Listbox1'); cdir = get(hdl,'String'); ndir = get(hdl,'Value'); namedir = cdir{ndir(1),1}; switch namedir case '..' eval('cd ..'); case '.' if ~isempty(dir(namedir)) cd(namedir); end case '[ * DATA * ]' if isempty(Path.data), return, end cd(Path.data) case '[ * PERT * ]' if isempty(Path.pert), return, end cd(Path.pert) case '[ * LOCAL * ]' if isempty(Path.local), return, end cd(Path.local) case '[ * PSAT * ]' if isempty(Path.psat), return, end cd(Path.psat) otherwise cd(namedir) end a = dir; numdir = find([a.isdir] == 1); cdir = {a(numdir).name}'; cdir(strmatch('.',cdir)) = []; cdir(strmatch('@',cdir)) = []; set(hdl,'ListboxTop',1,'String',[{'.'; '..'};cdir;get(hdl,'UserData')],'Value',1); hdl = findobj(Fig.dir,'Tag','EditText1'); set(hdl,'String',pwd); set(Fig.dir,'UserData',pwd); hdl = findobj(Fig.dir,'Tag','Listbox2'); hdlf = findobj(Fig.dir,'Tag','PopupMenu1'); cfile = uform(get(hdlf,'Value')); if isempty(cfile) cfile = 'empty'; else cfile = sort(cfile); end set(hdl,'ListboxTop',1,'String',cfile,'Value',1); %================================================================== case 'chformat' if ~ishandle(Fig.dir), return; end if ~strcmp(get(Fig.dir, 'Type'), 'figure'), return; end hdlf = findobj(Fig.dir,'Tag','PopupMenu1'); formato = get(hdlf,'Value'); if ~length(formato) formato = 1 end % display(formato) hdl = findobj(Fig.dir,'Tag','Listbox2'); hdla = findobj(Fig.dir,'Tag','Axes1'); hdlc = findobj(Fig.dir,'Tag','Pushbutton1'); hdl1 = findobj(Fig.dir,'Tag','CheckboxSilent'); hdl2 = findobj(Fig.dir,'Tag','Checkbox2'); hdl4 = findobj(Fig.dir,'Tag','StaticText2'); hdlp = findobj(Fig.dir,'Tag','PushbuttonPreview'); cfile = uform(formato); switch int32(formato) case IEEE, file = 'ieee'; case CYME, file = 'cyme'; case MATPOWER, file = 'pserc'; case PSAT, file = 'psatdata'; case PSATPERT, file = 'psatpert'; case PSATMDL, file = 'simulink'; case PST, file = 'cherry'; case EPRI, file = 'epri'; case PSSE, file = 'pti'; case PSAP, file = 'pjm'; case EUROSTAG, file = 'eurostag'; case TH, file = 'th'; case CESI, file = 'cesi'; case VST, file = 'cepe'; case SIMPOW, file = 'simpow'; case NEPLAN, file = 'neplan'; case DIGSILENT, file = 'digsilent'; case POWERWORLD, file = 'powerworld'; case PET, file = 'pet'; case FLOWDEMO, file = 'eeh'; case GEEPC, file = 'ge'; case CHAPMAN, file = 'chapman'; case UCTE, file = 'ucte'; case PCFLO, file = 'pcflo'; case WEBFLOW, file = 'webflow'; case IPSS, file = 'ipss'; case CEPEL, file = 'cepel'; case ODM, file = 'odm'; case REDS, file = 'reds'; case VITRUVIO, file = 'vitruvio'; end switch formato case VITRUVIO, if ~get(hdlf,'UserData'), set(hdlc,'Enable','off'), end set(hdl1,'Enable','off') set(hdl2,'Enable','off') set(hdl4,'Enable','off') case PSAT, set(hdlc,'Enable','on') set(hdl1,'Enable','off') if ~get(hdlf,'UserData'), set(hdl2,'Enable','on'), end if ~get(hdlf,'UserData'), set(hdl4,'Enable','on'), end case PSATPERT, if ~get(hdlf,'UserData'), set(hdlc,'Enable','off'), end set(hdl1,'Enable','off') set(hdl2,'Enable','off') set(hdl4,'Enable','off') case {NEPLAN,CESI} set(hdlc,'Enable','on') set(hdl1,'Enable','on') set(hdl2,'Enable','off') set(hdl4,'Enable','off') otherwise % all other formats set(hdlc,'Enable','on') set(hdl1,'Enable','off') set(hdl2,'Enable','off') set(hdl4,'Enable','off') end if formato == PSATMDL set(hdlp,'Enable','on') set(hdlp,'Visible','on') else set(hdlp,'Enable','off') set(hdlp,'Visible','off') end a = imread([Path.images,'logo_',file,'.jpg'],'jpg'); [yl,xl,zl] = size(a); set(Fig.dir,'Units','pixels') figdim = get(Fig.dir,'Position'); % the following if-block is needed for some issues on Matlab R2008a if figdim(3) < 1 if strcmp(get(0,'Units'),'pixels') ssize = get(0,'ScreenSize'); figdim(3) = ssize(3)*figdim(3); figdim(4) = ssize(4)*figdim(4); else set(0,'Units','pixels') ssize = get(0,'ScreenSize'); figdim(3) = ssize(3)*figdim(3); figdim(4) = ssize(4)*figdim(4); end end set(Fig.dir,'Units','normalized') dimx = figdim(3)*0.2616; dimy = figdim(4)*0.3468; rl = xl/yl; if dimx > xl && dimy > yl xd = xl/figdim(3); yd = yl/figdim(4); set(hdla,'Position',[0.8358-xd/2, 0.5722-yd/2, xd, yd]); elseif xl > yl xd = 0.2616; yd = 0.3468/rl; set(hdla,'Position',[0.7050, 0.5722-0.1734/rl, xd, yd]); else xd = 0.2616*rl; yd = 0.3468; set(hdla,'Position',[0.8358-0.1308*rl, 0.3988, xd, yd]); end xd = round(xd*figdim(3)); yd = round(yd*figdim(4)); %disp([xl yl xd yd]) if xd ~= xl && yd ~= yl try if Settings.hostver >= 7.04 a = imresize(a,[yd xd],'bilinear'); else a = imresize(a,[yd xd],'bilinear',11); end catch % imresize is not available!!! end end set(hdla,'XLim',[0.5 xd+0.5],'YLim',[0.5 yd+0.5]); if Settings.hostver < 8.04 if length(get(hdla,'Children')) > 1 h2 = image( ... 'Parent',hdla, ... 'CData',a, ... 'Erase','none', ... 'Tag','Axes1Image1', ... 'XData',[1 xd], ... 'YData',[1 yd]); else set(get(hdla,'Children'),'CData',a,'XData',[1 xd],'YData',[1 yd]); end else if length(get(hdla,'Children')) > 1 set(hdla, 'XDir', 'reverse'); h2 = image( ... 'Parent',hdla, ... 'CData',flipud(a), ... 'Erase','none', ... 'Tag','Axes1Image1', ... 'XData',[1 xd], ... 'YData',[1 yd]); else set(hdla, 'XDir', 'reverse'); set(get(hdla,'Children'), ... 'CData',flipud(a), ... 'XData',[1 xd], ... 'YData',[1 yd]) end end set(hdla,'XTick',[],'XTickLabel','','XColor',Theme.color01); set(hdla,'YTick',[],'YTickLabel','','YColor',Theme.color01); if ispc, set(hdla,'XColor',[126 157 185]/255,'YColor',[126 157 185]/255), end if isempty(cfile), cfile = 'empty'; else, cfile = sort(cfile); end set(hdl,'ListboxTop',1,'String',cfile,'Value',1); Settings.format = formato; %================================================================== case 'editinit' if ~isempty(Path.temp) try cd(Path.temp); catch % nothing to do end elseif ~isempty(Path.data) try cd(Path.data); catch % nothing to do end end set(gcbo,'String',pwd) set(gcf,'UserData',pwd); %================================================================== case 'dirinit' devices = getdevices; devices{end+1,1} = '[ * DATA * ]'; devices{end+1,1} = '[ * PERT * ]'; devices{end+1,1} = '[ * LOCAL * ]'; devices{end+1,1} = '[ * PSAT * ]'; set(gcbo,'UserData',devices) cd(get(gcf,'UserData')) a = dir; numdir = find([a.isdir] == 1); if isempty(numdir) cdir = {' '}; else cdir = {a(numdir).name}'; cdir(strmatch('.',cdir)) = []; cdir(strmatch('@',cdir)) = []; end set(findobj(Fig.dir,'Tag','Listbox1'),'ListboxTop',1, ... 'String',[{'.';'..'}; cdir; devices],'Value',1); %================================================================== case 'dirsel' %values = get(gcbo,'Value'); %set(gcbo,'Value',values(end)); if strcmp(get(Fig.dir,'SelectionType'),'open') cd(Path.local) fm_dirset('changedir'); end %================================================================== case 'diredit' hdl = findobj(Fig.dir,'Tag','EditText1'); cartella = get(hdl,'String'); try cd(cartella); hdl = findobj(Fig.dir,'Tag','Listbox1'); a = dir; cdir = {'.';'..'}; numdir = find([a.isdir] == 1); j = 2; for i = 1:length(numdir) if ~strcmp(a(numdir(i)).name(1),'.') && isunix j = j + 1; cdir{j,1} = a(numdir(i)).name; end end if isempty(cdir), cdir = ' '; else, cdir = sort(cdir); end set(hdl,'ListboxTop',1,'String',[cdir;get(hdl,'UserData')],'Value',1); hdl = findobj(Fig.dir,'Tag','Listbox2'); cfile = uform(formato); if isempty(cfile), cfile = 'empty'; else, cfile = sort(cfile); end set(hdl,'ListboxTop',1,'String',cfile,'Value',1); set(Fig.dir,'UserData',cartella); catch fm_disp(lasterr,2) set(hdl_dir,'String',get(Fig.dir,'UserData')); end %================================================================== case 'getfolder' pathname = get(Fig.dir,'UserData'); cartella = uigetdir(pathname); if cartella hdl = findobj(Fig.dir,'Tag','EditText1'); set(hdl,'String',cartella); cd(Path.local) fm_dirset('diredit'); end %================================================================== case 'convert' hdl = findobj(Fig.dir,'Tag','Listbox2'); numfile = get(hdl,'Value'); nomefile = get(hdl,'String'); if ~iscell(nomefile), nomefile = cellstr(nomefile); end hdl = findobj(Fig.dir,'Tag','PopupMenu1'); if numfile == 1 && strcmp(nomefile{1},'empty') fm_disp('Current folder does not contain files in the selected format.',2) cd(Path.local) return end % if coverting a PSAT file, get destination format hdlpsat = findobj(Fig.dir,'Tag','Checkbox2'); convpsat = get(hdlpsat,'Value'); for i = 1:length(numfile) lasterr(''); filename = nomefile{numfile(i),1}; check = 0; switch get(hdl,'Value') case IEEE check = fm_perl('IEEE CDF','ieee2psat',filename); case CYME check = fm_perl('CYME','cyme2psat',filename); case MATPOWER check = matpower2psat(filename,pwd); case PSAT switch convpsat case 1, check = psat2ieee(filename,pwd); case 2, check = psat2epri(filename,pwd); case 3, check = psat2odm(filename,pwd); end case PSATMDL first = double(filename(1)); if first <= 57 && first >= 48 copyfile(filename,['d',filename]) filename = ['d',filename]; fm_disp(['Use modified file name <',filename,'>']) end check = sim2psat(filename,pwd); case PSATPERT fm_disp('No filter is associated with pertubation files.') case PST check = pst2psat(filename,pwd); case EPRI check = fm_perl('WSCC','epri2psat',filename); case PSSE check = fm_perl('PSS/E','psse2psat',filename); case PSAP check = fm_perl('PSAP','psap2psat',filename); case EUROSTAG check = fm_perl('EUROSTAG','eurostag2psat',filename); case TH, check = fm_perl('TH','th2psat',filename); case CESI, check = fm_perl('CESI','inptc12psat',filename); case VST check = fm_perl('VST','vst2psat',filename); case SIMPOW check = fm_perl('SIMPOW','simpow2psat',filename); case NEPLAN check = fm_perl('NEPLAN','neplan2psat',filename); case DIGSILENT check = fm_perl('DIGSILENT','digsilent2psat',filename); case POWERWORLD check = fm_perl('PowerWorld','pwrworld2psat',filename); case PET fm_choice('Filter for PET data format has not been implemeted yet',2) break case FLOWDEMO check = fm_perl('FlowDemo.net','flowdemo2psat',filename); case GEEPC check = fm_perl('GE','ge2psat',filename); case CHAPMAN check = fm_perl('Chapman','chapman2psat',filename); case UCTE check = fm_perl('UCTE','ucte2psat',filename); case PCFLO check = fm_perl('PCFLO','pcflo2psat',filename); case WEBFLOW check = fm_perl('WebFlow','webflow2psat',filename); case CEPEL check = fm_perl('CEPEL','cepel2psat',filename); case ODM check = fm_perl('ODM','odm2psat',filename); case REDS check = fm_perl('REDS','reds2psat',filename); case IPSS if ~isempty(strfind(filename,'.ipssdat')) check = fm_perl('InterPSS','ipssdat2psat',filename); else check = fm_perl('InterPSS','ipss2psat',filename); end case VITRUVIO % All files fm_disp('Select a Data Format for running the conversion.') end if ~check && ~isempty(lasterr), fm_disp(lasterr), end end if nargout, varargout{1} = check; end %================================================================== case 'openfile' global File Path.temp = 0; File.temp = ''; hdl = findobj(Fig.dir,'Tag','Listbox2'); numfile = get(hdl,'Value'); nomefile = get(hdl,'String'); if ~iscell(nomefile), nomefile = cellstr(nomefile); end if numfile == 1 && strcmp(nomefile{1},'empty') fm_disp('Current folder does not contain files in the selected data format.',2) cd(Path.local) close(Fig.dir) return end hdl = findobj(Fig.dir,'Tag','PopupMenu1'); type = get(hdl,'Value'); if type == PSAT || type == PSATPERT || type == VITRUVIO check = 1; else cd(Path.local) check = fm_dirset('convert'); end if ~check fm_disp('Data conversion failed.',2) return end % determine file name namefile = nomefile{numfile}; switch type case {PSAT,PSATPERT,PSATMDL,VITRUVIO} % nothing to do! case PCFLO namefile = regexprep([namefile,'.m'],'^bdat\.','','ignorecase'); namefile = regexprep(['d_',namefile],'^d*_*','d_'); namefile = regexprep(namefile,'[^\w\.]','_'); case PST namefile = strrep(namefile,'.m','_pst.m'); if ~strcmp(namefile(1), 'd'); namefile = ['d_',namefile]; end case MATPOWER extension = findstr(namefile,'.'); namefile = ['d_',namefile(1:extension(end)-1),'.m']; otherwise namefile = regexprep(['d_',namefile],'^d*_*','d_'); namefile = regexprep(namefile,'^d_d','d_'); namefile = regexprep(namefile,'^d__','d_'); namefile = regexprep(namefile,'[^\w\.]','_'); namefile = regexprep(namefile,'\..+$','.m'); end Path.temp = get(Fig.dir,'UserData'); if ~strcmp(Path.temp(end),filesep) Path.temp = [Path.temp,filesep]; end File.temp = namefile; close(Fig.dir) %================================================================== case 'cancel' Path.temp = 0; File.temp = ''; close(Fig.dir) %================================================================== case 'preview' global File % check whether the selected file is a Simulink model hdl = findobj(Fig.dir,'Tag','PopupMenu1'); type = get(hdl,'Value'); if type ~= PSATMDL cd(Path.local) return end % get the name of the Simulink model hdl = findobj(Fig.dir,'Tag','Listbox2'); numfile = get(hdl,'Value'); if length(numfile) > 1 numfile = numfile(1); temp = get(hdl,'String'); namefile = temp{numfile}; else files = get(hdl,'String'); if iscell(files) namefile = files{numfile}; else namefile = files; end end % make sure that the file name does not start with a number first = double(namefile(1)); if first <= 57 && first >= 48 copyfile(namefile,['d',namefile]) namefile = ['d',namefile]; end oldpath = Path.data; oldfile = File.data; Path.data = pwd; File.data = [namefile(1:end-4),'(mdl)']; hdla = findobj(Fig.dir,'Tag','Axes1'); lasterr('') try fm_simrep('DrawModel',0,0,0) catch disp(' ') fm_disp('* * * The model likely refers to an old PSAT/Simulink library.') fm_disp(' Load and update the model before trying to preview it.') fm_dirset chformat return end %set(hdla,'XLimMode','auto') %set(hdla,'YLimMode','auto') x_lim = get(hdla,'XLim'); y_lim = get(hdla,'YLim'); xl = x_lim(2)-x_lim(1); yl = y_lim(2)-y_lim(1); set(Fig.dir,'Units','pixels') figdim = get(Fig.dir,'Position'); set(Fig.dir,'Units','normalized') dimx = figdim(3)*0.2616; dimy = figdim(4)*0.3468; rl = xl/yl; if dimx > xl && dimy > yl xd = xl/figdim(3); yd = yl/figdim(4); set(hdla,'Position',[0.8358-xd/2, 0.5722-yd/2, xd, yd]); elseif xl > yl xd = 0.2616; yd = 0.3468/rl; set(hdla,'Position',[0.7050, 0.5722-0.1734/rl, xd, yd]); else xd = 0.2616*rl; yd = 0.3468; set(hdla,'Position',[0.8358-0.1308*rl, 0.3988, xd, yd]); end Path.data = oldpath; File.data = oldfile; %================================================================== case 'view' hdl = findobj(Fig.dir,'Tag','Listbox2'); numfile = get(hdl,'Value'); nomefile = get(hdl,'String'); if ~iscell(nomefile), nomefile = cellstr(nomefile); end if strcmp(nomefile{1},'empty') fm_disp('Folder is empty or does not contain files in the selected data format',2) cd(Path.local) return end for i = 1:length(numfile) ext = lower(nomefile{numfile(i),1}(end-2:end)); idx = findstr(ext,'.'); if ~isempty(idx) ext = ext(idx(end)+1:end); end file = nomefile{numfile(i),1}; try switch ext case 'mdl' open_system(file) case 'pdf', switch computer case 'GLNX86', eval(['! xpdf ',file, ' &']), case 'PCWIN', eval(['! acroread ',file, ' &']) otherwise 'SOL2', eval(['! acroread ',file, ' &']) end case '.ps' switch computer case 'GLNX86', eval(['! gsview ',file, ' &']), case 'PCWIN', eval(['! gsview ',file, ' &']) otherwise, eval(['! ghostview ',file, ' &']) end case 'eps' switch computer case 'GLNX86', eval(['! gsview ',file, ' &']), case 'PCWIN', eval(['! gsview ',file, ' &']) otherwise, eval(['! ghostview ',file, ' &']) end case 'doc' switch computer case 'GLNX86', eval(['! AbiWord ',file, ' &']), case 'PCWIN', eval(['! WINWORD ',file, ' &']) otherwise, fm_disp('Unknown viewer on this platform for file "',file,'"') end case 'ppt' switch computer case 'GLNX86', eval(['! AbiWord ',file, ' &']), case 'PCWIN', eval(['! POWERPNT ',file, ' &']) otherwise, fm_disp('Unknown viewer on this platform for file "',file,'"') end case 'dvi' switch computer case 'GLNX86', eval(['! xdvi ',file, ' &']), case 'PCWIN', fm_disp('Unknown viewer on this platform for file "',file,'"') otherwise, eval(['! xdvi ',file, ' &']) end case 'jpg', fm_iview(file) case 'tif', fm_iview(file) case 'gif', fm_iview(file) case 'bmp', fm_iview(file) case 'png', fm_iview(file) case 'hdf', fm_iview(file) case 'pcx', fm_iview(file) case 'xwd', fm_iview(file) case 'ico', fm_iview(file) case 'cur', fm_iview(file) otherwise, fm_text(13,file) end catch fm_disp(['Error in opeining file "',file,'": ',lasterr]) end end end cd(Path.local) %=================================================================== function cfile = uform(formato) % codes IEEE = 1; PSAT = 2; PSATPERT = 3; PSATMDL = 4; CYME = 5; MATPOWER = 6; PST = 7; EPRI = 8; PSSE = 9; PSAP = 10; EUROSTAG = 11; TH = 12; CESI = 13; VST = 14; SIMPOW = 15; NEPLAN = 16; DIGSILENT = 17; POWERWORLD = 18; PET = 19; FLOWDEMO = 20; GEEPC = 21; CHAPMAN = 22; UCTE = 23; PCFLO = 24; WEBFLOW = 25; IPSS = 26; CEPEL = 27; ODM = 28; REDS = 29; VITRUVIO = 30; % all files a = dir; numfile = find([a.isdir] == 0); jfile = 1; cfile = []; for i = 1:length(numfile) nomefile = a(numfile(i)).name; lfile = length(nomefile); add_file = 0; % display(formato) switch int32(formato) case IEEE extent = nomefile(max(1,lfile-2):lfile); if strcmpi(extent,'dat') || strcmpi(extent,'txt') || ... strcmpi(extent,'.cf'), if isfile(nomefile,'BUS DATA FOLLOW',20) add_file = 1; end end case CYME extent1 = nomefile(max(1,lfile-3):lfile); extent2 = nomefile(max(1,lfile-2):lfile); if strcmpi(extent1,'.nnd') || strcmpi(extent2,'.sf') add_file = 1; end case MATPOWER extent = nomefile(lfile); if strcmpi(extent,'m') if isfile(nomefile,'baseMVA',5), add_file = 1; end end case PSAT extent = nomefile(lfile); if strcmpi(extent,'m') if strcmp(nomefile(1),'d') add_file = 1; elseif isfile(nomefile,'Bus.con',50) add_file = 1; end end case PSATPERT extent = nomefile(lfile); if strcmpi(extent,'m') if strcmp(nomefile(1),'p') add_file = 1; elseif isfile(nomefile,'(t)',5) add_file = 1; end end case PSATMDL extent = nomefile(max(1,lfile-2):lfile); if strcmpi(extent,'mdl') if strcmpi(nomefile,'fm_lib.mdl') add_file = 0; %elseif strcmp(nomefile(1),'d') % add_file = 1; %elseif isfile(nomefile,'PSATblock',1000) %% THIS IS TOO SLOW!! % add_file = 1; else add_file = 1; end end case PST extent = nomefile(lfile); if strcmpi(extent,'m') && strcmp(nomefile(1),'d') if isfile(nomefile,'bus = [',50), add_file = 1; end if ~add_file if isfile(nomefile,'bus=',50), add_file = 1; end end end case EPRI extent = nomefile(max(1,lfile-2):lfile); if strcmpi(extent,'wsc') || strcmpi(extent,'txt') || ... strcmpi(extent,'dat') if isfile(nomefile,'HDG',15) add_file = 1; elseif isfile(nomefile,'/NETWORK_DATA\',20) add_file = 1; end end case PSSE extent = nomefile(max(1,lfile-2):lfile); if strcmpi(extent,'raw'), fid = fopen(nomefile, 'rt'); sline = fgets(fid); out = 0; if isempty(sline), sline = ' 2'; end if sline == -1; sline = ' 2'; end if length(sline) == 1; sline = [sline,' ']; end if isempty(str2num(sline(1:4))), sline = ' 2'; end if str2num(sline(1:2)) == 0 || str2num(sline(1:2)) == 1 out = 1; end if strcmp(sline(1:3),'001'), out = 0; end count = fclose(fid); if out, add_file = 1; end end case PSAP extent = nomefile(max(1,lfile-2):lfile); if strcmpi(extent,'dat'), fid = fopen(nomefile, 'rt'); sline = fgets(fid); count = fclose(fid); if strfind(sline,'1'), add_file = 1; end end case EUROSTAG extent = nomefile(max(1,lfile-2):lfile); if strcmpi(extent,'dat'), if isfile(nomefile,'HEADER ',20), add_file = 1; end end case TH extent = nomefile(max(1,lfile-2):lfile); if strcmpi(extent,'dat'), if isfile(nomefile,'SYSBASE',50) || ... isfile(nomefile,'THLINE',50) add_file = 1; end end case CESI extent = nomefile(max(1,lfile-2):lfile); if strcmpi(extent,'dat'), if isfile(nomefile,'VNOM',25), add_file = 1; end end case VST extent = nomefile(max(1,lfile-7):lfile); if strcmpi(extent,'_vst.dat'), add_file = 1; end case SIMPOW extent = nomefile(max(1,lfile-6):lfile); %if strcmpi(extent,'.optpow') || strcmpi(extent,'.dynpow') if strcmpi(extent,'.optpow'), add_file = 1; end case IPSS extent1 = nomefile(max(1,lfile-7):lfile); extent2 = nomefile(max(1,lfile-4):lfile); if strcmpi(extent1,'.ipssdat') || strcmpi(extent2,'.ipss') add_file = 1; end case NEPLAN extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.ndt'), add_file = 1; end case ODM extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.odm'), add_file = 1; end if strcmpi(extent,'.xml') if isfile(nomefile,'PSSStudyCase',10), add_file = 1; end end case DIGSILENT extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.dgs'), add_file = 1; end case POWERWORLD extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.aux'), add_file = 1; end case PET extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.pet'), add_file = 1; end case FLOWDEMO extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.fdn'), add_file = 1; end case CHAPMAN if isempty(findstr(nomefile,'.')), if isfile(nomefile,'SYSTEM',10), add_file = 1; end end case UCTE extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.uct'), add_file = 1; end case REDS extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.pos') if isfile(nomefile,'.PU',10), add_file = 1; end end case PCFLO if strmatch('bdat.',lower(nomefile)), add_file = 1; end case WEBFLOW extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.txt') if isfile(nomefile,'BQ',10) add_file = 1; end end case CEPEL extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.txt') if isfile(nomefile,'TITU',5) add_file = 1; end end case GEEPC extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.epc'), add_file = 1; end otherwise % all files % add only files that do not begin with a dot that are % hidden files on UNIX systems if ~(strcmp(nomefile(1),'.') && isunix) add_file = 1; end end if add_file, cfile{jfile,1} = a(numfile(i)).name; jfile = jfile + 1; end end %============================================================================ function out = isfile(file,stringa,nrow) % checking the first nrow to figure out the data format out = 0; [fid, message] = fopen(file, 'rt'); if ~isempty(message) fm_disp(['While inspecting the current folder, ', ... 'error found in file "',file,'". ',message]) return end n_row = 0; while 1 sline = fgets(fid); n_row = n_row + 1; if ~isempty(sline), if sline == -1, break; end, end vec = strfind(sline,stringa); if ~isempty(vec), out = 1; break, end if n_row == nrow, break, end end count = fclose(fid); %============================================================================ function devices = getdevices if isunix devices = {'/'}; else devices = {'a:\'}; ndev = 1; for i = 99:122 device_name = [char(i),':\']; %if exist(device_name) == 7 if ~isempty(dir(device_name)) ndev = ndev + 1; devices{ndev,1} = device_name; end end end %============================================================================ function check = fm_perl(program_name,filter_name,file_name) global Path Fig cmd = [Path.filters,filter_name]; % last minute option for certain filters hdl = findobj(Fig.dir,'Tag','CheckboxSilent'); if ~get(hdl,'Value') switch program_name case 'CESI' [add_file,add_path] = uigetfile('*.dat','Select COLAS ADD file'); if strcmp(add_path,[pwd,filesep]) file_name = ['-a" "',add_file,'" "',file_name]; elseif add_path == 0 % no COLAS ADD file else % COLAS ADD file is not in the current folder fm_disp(['* * COLAS ADD file must be in the same folder as base ' ... 'data file.']) end case 'NEPLAN' [add_file,add_path] = uigetfile('*.edt','Select EDT file'); if strcmp(add_path,[pwd,filesep]) file_name = ['-a" "',add_file,'" "',file_name]; elseif add_path == 0 % no NEPLAN EDT file else % NEPLAN EDT file is not in the current folder fm_disp(['* * NEPLAN EDT file must be in the same folder as NDT ' ... 'file.']) end case 'SIMPOW' [add_file,add_path] = uigetfile('*.dynpow','Select DYNPOW file'); if strcmp(add_path,[pwd,filesep]) file_name = [file_name,'" "',add_file]; elseif add_path == 0 % no DYNPOW file file_name = ['-n" "',file_name]; else file_name = [file_name,'" "',add_path,filesep,add_file]; end otherwise % nothing to do end end % verbose conversion hdl = findobj(Fig.dir,'Tag','CheckboxVerbose'); if get(hdl,'Value') file_name = ['-v" "',file_name]; end if ispc cmdString = ['"',Path.filters,filter_name,'" "',file_name,'"']; else cmdString = [filter_name,' "',file_name,'"']; end % Execute Perl script errTxtNoPerl = 'Unable to find Perl executable.'; if isempty(cmdString) % nothing to do ... elseif ispc % PC perlCmd = fullfile(matlabroot, 'sys\perl\win32\bin\'); cmdString = ['perl ' cmdString]; perlCmd = ['set PATH=',perlCmd, ';%PATH%&' cmdString]; [status, results] = dos(perlCmd); else % UNIX [status, perlCmd] = unix('which perl'); if (status == 0) [status, results] = unix(cmdString); else error(errTxtNoPerl); end end fm_disp(results) check = ~status;
github
Sinan81/PSAT-master
fm_input.m
.m
PSAT-master/psat-mat/psat/fm_input.m
13,124
utf_8
a4a7b367ecb64f3f86fd6e1ea1f62c27
function Answer = fm_input(Prompt, Title, NumLines, DefAns,Resize) %INPUTDLG Input dialog box. % Answer = INPUTDLG(Prompt) creates a modal dialog box that returns % user input for multiple prompts in the cell array Answer. Prompt % is a cell array containing the Prompt strings. % % INPUTDLG uses WAITFOR to suspend execution until the user responds. % % Answer = INPUTDLG(Prompt,Title) specifies the Title for the dialog. % % Answer = INPUTDLG(Prompt,Title,LineNo) specifies the number of lines % for each answer in LineNo. LineNo may be a constant value or a % column vector having one element per Prompt that specifies how many % lines per input. LineNo may also be a matrix where the first % column specifies how many rows for the input field and the second % column specifies how many columns wide the input field should be. % % Answer = INPUTDLG(Prompt,Title,LineNo,DefAns) specifies the default % answer to display for each Prompt. DefAns must contain the same % number of elements as Prompt and must be a cell array. % % Answer = INPUTDLG(Prompt,Title,LineNo,DefAns,AddOpts) specifies whether % the dialog may be resized or not. Acceptable values for AddOpts are % 'on' or 'off'. If the dialog can be resized, then the dialog is % not modal. % % AddOpts may also be a data structure with fields Resize, % WindowStyle and Interpreter. Resize may be 'on' or 'off'. % WindowStyle may be 'modal' or 'normal' and Interpreter may be % 'tex' or 'none'. The interpreter applies to the prompt strings. % % Examples: % % prompt={'Enter the matrix size for x^2:','Enter the colormap name:'}; % def={'20','hsv'}; % dlgTitle='Input for Peaks function'; % lineNo=1; % answer=fm_input(prompt,dlgTitle,lineNo,def); % % AddOpts.Resize='on'; % AddOpts.WindowStyle='normal'; % AddOpts.Interpreter='tex'; % answer=fm_input(prompt,dlgTitle,lineNo,def,AddOpts); % % See also TEXTWRAP, QUESTDLG, WAITFOR. % Loren Dean May 24, 1995. % Copyright 1998-2001 The MathWorks, Inc. % $Revision: 1.57 $ % %Modified by: Federico Milano %Date: 11-Nov-2002 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html global Settings Black =[0 0 0 ]/255; LightGray =[192 192 192 ]/255; LightGray2 =[160 160 164 ]/255; MediumGray =[128 128 128 ]/255; White =[255 255 255 ]/255; %%%%%%%%%%%%%%%%%%%% %%% Nargin Check %%% %%%%%%%%%%%%%%%%%%%% if nargin == 1 && nargout == 0, if strcmp(Prompt,'InputDlgResizeCB'), LocalResizeFcn(gcbf) return end end error(nargchk(1,5,nargin)); if Settings.hostver > 6, error(nargoutchk(1,1,nargout)); end if nargin==1, Title=' '; end if nargin<=2, NumLines=1;end if ~iscell(Prompt), Prompt={Prompt}; end NumQuest=prod(size(Prompt)); if nargin<=3, DefAns=cell(NumQuest,1); for lp=1:NumQuest, DefAns{lp}=''; end end WindowStyle='modal'; Interpreter='none'; if nargin<=4, Resize = 'off'; end if nargin==5 && isstruct(Resize), Interpreter=Resize.Interpreter; WindowStyle=Resize.WindowStyle; Resize=Resize.Resize; end if strcmp(Resize,'on'), WindowStyle='normal'; end % Backwards Compatibility if ischar(NumLines), warning(['Please see the INPUTDLG help for correct input syntax.' 10 ... ' OKCallback no longer supported.' ]); NumLines=1; end [rw,cl]=size(NumLines); OneVect = ones(NumQuest,1); if (rw == 1 && cl == 2) NumLines=NumLines(OneVect,:); elseif (rw == 1 && cl == 1) NumLines=NumLines(OneVect); elseif (rw == 1 && cl == NumQuest) NumLines = NumLines'; elseif rw ~= NumQuest || cl > 2, error('NumLines size is incorrect.') end if ~iscell(DefAns), error('Default Answer must be a cell array in INPUTDLG.'); end %%%%%%%%%%%%%%%%%%%%%%% %%% Create InputFig %%% %%%%%%%%%%%%%%%%%%%%%%% FigWidth=300;FigHeight=100; FigPos(3:4)=[FigWidth FigHeight]; FigColor=get(0,'Defaultuicontrolbackgroundcolor'); TextForeground = Black; if sum(abs(TextForeground - FigColor)) < 1 TextForeground = White; end InputFig=dialog( ... 'Visible' ,'off' , ... 'Name' ,Title , ... 'Pointer' ,'arrow' , ... 'Units' ,'points' , ... 'UserData' ,'' , ... 'Tag' ,Title , ... 'HandleVisibility','on' , ... 'Color' ,FigColor , ... 'NextPlot' ,'add' , ... 'WindowStyle' ,WindowStyle, ... 'Resize' ,Resize ... ); %%%%%%%%%%%%%%%%%%%%% %%% Set Positions %%% %%%%%%%%%%%%%%%%%%%%% DefOffset=5; SmallOffset=2; DefBtnWidth=50; BtnHeight=20; BtnYOffset=DefOffset; BtnFontSize=get(0,'FactoryUIControlFontSize'); BtnWidth=DefBtnWidth; TextInfo.Units ='points' ; TextInfo.FontSize =BtnFontSize; TextInfo.HorizontalAlignment='left' ; TextInfo.HandleVisibility ='callback' ; StInfo=TextInfo; StInfo.Style ='text' ; StInfo.BackgroundColor =FigColor; StInfo.ForegroundColor =TextForeground ; TextInfo.VerticalAlignment='bottom'; EdInfo=StInfo; EdInfo.Style='edit'; EdInfo.BackgroundColor=White; BtnInfo=StInfo; BtnInfo.Style='pushbutton'; BtnInfo.HorizontalAlignment='center'; % Determine # of lines for all Prompts ExtControl=uicontrol(StInfo, ... 'String' ,'' , ... 'Position' ,[DefOffset DefOffset ... 0.96*(FigWidth-2*DefOffset) BtnHeight ... ] , ... 'Visible' ,'off' ... ); WrapQuest=cell(NumQuest,1); QuestPos=zeros(NumQuest,4); for ExtLp=1:NumQuest, if size(NumLines,2)==2 [WrapQuest{ExtLp},QuestPos(ExtLp,1:4)]= ... textwrap(ExtControl,Prompt(ExtLp),NumLines(ExtLp,2)); else, [WrapQuest{ExtLp},QuestPos(ExtLp,1:4)]= ... textwrap(ExtControl,Prompt(ExtLp),80); end end % for ExtLp delete(ExtControl); QuestHeight=QuestPos(:,4); TxtHeight=QuestHeight(1)/size(WrapQuest{1,1},1); EditHeight=TxtHeight*NumLines(:,1); EditHeight(NumLines(:,1)==1)=EditHeight(NumLines(:,1)==1)+4; FigHeight=(NumQuest+2)*DefOffset + ... BtnHeight+sum(EditHeight) + ... sum(QuestHeight); TxtXOffset=DefOffset; TxtWidth=FigWidth-2*DefOffset; QuestYOffset=zeros(NumQuest,1); EditYOffset=zeros(NumQuest,1); QuestYOffset(1)=FigHeight-DefOffset-QuestHeight(1); EditYOffset(1)=QuestYOffset(1)-EditHeight(1);% -SmallOffset; for YOffLp=2:NumQuest, QuestYOffset(YOffLp)=EditYOffset(YOffLp-1)-QuestHeight(YOffLp)-DefOffset; EditYOffset(YOffLp)=QuestYOffset(YOffLp)-EditHeight(YOffLp); %-SmallOffset; end % for YOffLp QuestHandle=[]; EditHandle=[]; FigWidth =1; AxesHandle=axes('Parent',InputFig,'Position',[0 0 1 1],'Visible','off'); for lp=1:NumQuest, QuestTag=['Prompt' num2str(lp)]; EditTag=['Edit' num2str(lp)]; if ~ischar(DefAns{lp}), delete(InputFig); error('Default answers must be strings in INPUTDLG.'); end QuestHandle(lp)=text('Parent',AxesHandle, ... TextInfo , ... 'Position' ,[ TxtXOffset QuestYOffset(lp)], ... 'String' ,WrapQuest{lp} , ... 'Color' ,TextForeground , ... 'Interpreter',Interpreter , ... 'Tag' ,QuestTag ... ); EditHandle(lp)=uicontrol(InputFig ,EdInfo , ... 'Max' ,NumLines(lp,1) , ... 'Position' ,[ TxtXOffset EditYOffset(lp) ... TxtWidth EditHeight(lp) ... ] , ... 'String' ,DefAns{lp} , ... 'Tag' ,QuestTag ... ); if size(NumLines,2) == 2, set(EditHandle(lp),'String',char(ones(1,NumLines(lp,2))*'x')); Extent = get(EditHandle(lp),'Extent'); NewPos = [TxtXOffset EditYOffset(lp) Extent(3) EditHeight(lp) ]; NewPos1= [TxtXOffset QuestYOffset(lp)]; set(EditHandle(lp),'Position',NewPos,'String',DefAns{lp}) set(QuestHandle(lp),'Position',NewPos1) FigWidth=max(FigWidth,Extent(3)+2*DefOffset); else FigWidth=max(175,TxtWidth+2*DefOffset); end end % for lp FigPos=get(InputFig,'Position'); Temp=get(0,'Units'); set(0,'Units','points'); ScreenSize=get(0,'ScreenSize'); set(0,'Units',Temp); FigWidth=max(FigWidth,2*(BtnWidth+DefOffset)+DefOffset); FigPos(1)=(ScreenSize(3)-FigWidth)/2; FigPos(2)=(ScreenSize(4)-FigHeight)/2; FigPos(3)=FigWidth; FigPos(4)=FigHeight; set(InputFig,'Position',FigPos); CBString='set(gcbf,''UserData'',''Cancel'');uiresume'; CancelHandle=uicontrol(InputFig , ... BtnInfo , ... 'Position' ,[FigWidth-BtnWidth-DefOffset DefOffset ... BtnWidth BtnHeight ... ] , ... 'String' ,'Cancel' , ... 'Callback' ,CBString , ... 'Tag' ,'Cancel' ... ); CBString='set(gcbf,''UserData'',''OK'');uiresume'; OKHandle=uicontrol(InputFig , ... BtnInfo , ... 'Position' ,[ FigWidth-2*BtnWidth-2*DefOffset DefOffset ... BtnWidth BtnHeight ... ] , ... 'String' ,'OK' , ... 'Callback' ,CBString , ... 'Tag' ,'OK' ... ); Data.OKHandle = OKHandle; Data.CancelHandle = CancelHandle; Data.EditHandles = EditHandle; Data.QuestHandles = QuestHandle; Data.LineInfo = NumLines; Data.ButtonWidth = BtnWidth; Data.ButtonHeight = BtnHeight; Data.EditHeight = TxtHeight+4; Data.Offset = DefOffset; set(InputFig ,'Visible','on','UserData',Data); % This drawnow is a hack to work around a bug drawnow set(findall(InputFig),'Units','normalized','HandleVisibility','callback'); set(InputFig,'Units','points') try uiwait(InputFig); catch delete(InputFig); end TempHide=get(0,'ShowHiddenHandles'); set(0,'ShowHiddenHandles','on'); if any(get(0,'Children')==InputFig), Answer={}; if strcmp(get(InputFig,'UserData'),'OK'), Answer=cell(NumQuest,1); for lp=1:NumQuest, Answer(lp)=get(EditHandle(lp),{'String'}); end % for end % if strcmp delete(InputFig); else, Answer={}; end % if any set(0,'ShowHiddenHandles',TempHide); function LocalResizeFcn(FigHandle) Data=get(FigHandle,'UserData'); %Data.ButtonHandles = [ OKHandles CancelHandle]; %Data.EditHandles = EditHandle; %Data.QuestHandles = QuestHandle; %Data.LineInfo = NumLines; %Data.ButtonWidth = BtnWidth; %Data.ButtonHeight = BtnHeight; %Data.EditHeight = TxtHeight; set(findall(FigHandle),'Units','points'); FigPos = get(FigHandle,'Position'); FigWidth = FigPos(3); FigHeight = FigPos(4); OKPos = [ FigWidth-Data.ButtonWidth-Data.Offset Data.Offset ... Data.ButtonWidth Data.ButtonHeight ]; CancelPos =[Data.Offset Data.Offset Data.ButtonWidth Data.ButtonHeight]; set(Data.OKHandle,'Position',OKPos); set(Data.CancelHandle,'Position',CancelPos); % Determine the height of all question fields YPos = sum(OKPos(1,[2 4]))+Data.Offset; QuestPos = get(Data.QuestHandles,{'Extent'}); QuestPos = cat(1,QuestPos{:}); QuestPos(:,1) = Data.Offset; RemainingFigHeight = FigHeight - YPos - sum(QuestPos(:,4)) - ... Data.Offset - size(Data.LineInfo,1)*Data.Offset; Num1Liners = length(find(Data.LineInfo(:,1)==1)); RemainingFigHeight = RemainingFigHeight - ... Num1Liners*Data.EditHeight; Not1Liners = find(Data.LineInfo(:,1)~=1); %Scale the 1 liner heights appropriately with remaining fig height TotalLines = sum(Data.LineInfo(Not1Liners,1)); % Loop over each quest/text pair for lp = 1:length(Data.QuestHandles), CurPos = get(Data.EditHandles(lp),'Position'); NewPos = [Data.Offset YPos CurPos(3) Data.EditHeight ]; if Data.LineInfo(lp,1) ~= 1, NewPos(4) = RemainingFigHeight*Data.NumLines(lp,1)/TotalLines; end set(Data.EditHandles(lp),'Position',NewPos) YPos = sum(NewPos(1,[2 4])); QuestPos(lp,2) = YPos;QuestPos(lp,3) = NewPos(3); set(Data.QuestHandles(lp),'Position',QuestPos(lp,:)); YPos = sum(QuestPos(lp,[2 4]))+Data.Offset; end if YPos>FigHeight - Data.Offset, FigHeight = YPos+Data.Offset; FigPos(4)=FigHeight; set(FigHandle,'Position',FigPos); drawnow end set(FigHandle,'ResizeFcn','fm_input InputDlgResizeCB'); set(findall(FigHandle),'Units','normalized')
github
Sinan81/PSAT-master
zbuildpi.m
.m
PSAT-master/psat-mat/psat/zbuildpi.m
3,207
utf_8
77e32ffc8651729d7ba2a3fb4c88cb6c
% This program forms the complex bus impedance matrix by the method % of building algorithm. Bus zero is taken as reference. % This program is compatible with power flow data. % Copyright (C) 1998 by H. Saadat. function [Zbus, linedata] = zbuildpi(linedata, gendata, yload) % gendata generator data syn.con ng = length(gendata(:,1)); nlg = gendata(:,1); nrg = zeros(size(gendata(:,1))); zg = gendata(:,7) + j*gendata(:,6); nl = linedata(:,1); nr = linedata(:,2); R = linedata(:,8); X = linedata(:,9); ZB = R + j*X; nbr = length(linedata(:,1)); nbus = max(max(nl), max(nr)); nc = length(linedata(1,:)); BC = 0.5*linedata(:,10); yc = zeros(nbus,1); nlc = zeros(nbus,1); nrc = zeros(nbus,1); for n = 1:nbus yc(n) = 0; nlc(n) = 0; nrc(n) = n; for k = 1:nbr if nl(k) == n || nr(k) == n yc(n) = yc(n) + j*BC(k); end end end if exist('yload') == 1 yload = yload.'; yc = yc + yload; end m = 0; havecc = 0; % have cc ? for n = 1:nbus if abs(yc(n)) ~=0 m = m + 1; nlcc(m) = nlc(n); nrcc(m) = nrc(n); zc(m) = 1/yc(n); havecc = 1; end end if havecc == 1 nlcc = nlcc'; nrcc = nrcc'; zc = zc.'; nl = [nlg; nlcc; nl]; nr = [nrg; nrcc; nr]; ZB = [zg; zc; ZB]; else nl = [nlg; nl]; nr = [nrg; nr]; ZB = [zg; ZB]; end % standard line data consist of line generator capacitor of line model and load linedata = [nl nr real(ZB) imag(ZB)]; nbr = length(nl); Zbus = zeros(nbus, nbus); tree = 0; %%%%new % Adding a branch from a new bus to reference bus 0 for I = 1:nbr ntree(I) = 1; if nl(I) == 0 || nr(I) == 0 if nl(I) == 0 n = nr(I); elseif nr(I) == 0 n = nl(I); end if abs(Zbus(n, n)) == 0 Zbus(n,n) = ZB(I); tree = tree+1; %%new else Zbus(n,n) = Zbus(n,n)*ZB(I)/(Zbus(n,n) + ZB(I)); end ntree(I) = 2; end end % Adding a branch from new bus to an existing bus while tree < nbus %%% new for n = 1:nbus nadd = 1; if abs(Zbus(n,n)) == 0 for I = 1:nbr if nadd == 1 if nl(I) == n || nr(I) == n if nl(I) == n k = nr(I); elseif nr(I) == n k = nl(I); end if abs(Zbus(k,k)) ~= 0 for m = 1:nbus if m ~= n Zbus(m,n) = Zbus(m,k); Zbus(n,m) = Zbus(m,k); end end Zbus(n,n) = Zbus(k,k) + ZB(I); tree=tree+1; %%new nadd = 2; ntree(I) = 2; end end end end end end end %%%%%%new % Adding a link between two old buses for n = 1:nbus for I = 1:nbr if ntree(I) == 1 if nl(I) == n || nr(I) == n if nl(I) == n k = nr(I); elseif nr(I) == n k = nl(I); end DM = Zbus(n,n) + Zbus(k,k) + ZB(I) - 2*Zbus(n,k); for jj = 1:nbus AP = Zbus(jj,n) - Zbus(jj,k); for kk = 1:nbus AT = Zbus(n,kk) - Zbus(k, kk); DELZ(jj,kk) = AP*AT/DM; end end Zbus = Zbus - DELZ; ntree(I) = 2; end end end end disp('end of zbus build')
github
Sinan81/PSAT-master
fm_gams.m
.m
PSAT-master/psat-mat/psat/fm_gams.m
44,661
utf_8
29b7edaa35e48dc8aa6c2013171a86be
function fm_gams % FM_GAMS initialize and call GAMS to solve % several kind of Market Clearing Mechanisms % % FM_GAMS % %GAMS settings are stored in the structure GAMS, with %the following fields: % % METHOD 1 -> simple auction % 2 -> linear OPF (DC power flow) % 3 -> nonlinear OPF (AC power flow) % 4 -> nonlinear VSC-OPF % 5 -> maximum loading condition % 6 -> continuation OPF % % TYPE 1 -> single period auction % 2 -> multi period auction % 3 -> VSC single period auction % 4 -> VSC multi period auction % %see also FM_GAMS.GMS, FM_GAMSFIG and %structures CPF and OPF for futher settings % %Author: Federico Milano %Date: 29-Jan-2003 %Update: 01-Feb-2003 %Update: 06-Feb-2003 %Version: 1.0.2 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global DAE OPF CPF GAMS Bus File clpsat global Path Settings Snapshot Varname global PV PQ SW Line Shunt jay Varout global Supply Demand Rmpl Rmpg Ypdp [u,w] = system('gams'); if u fm_disp('GAMS is not properly installed on your system.',2) return end if ~autorun('PSAT-GAMS Interface',0) return end if DAE.n fm_disp(['Dynamic data are not supported within the PSAT-GAMS interface.'],2) return end if ~Supply.n, fm_disp(['Supply data have to be specified before in order to ', ... 'run PSAT-GAMS interface'],2) return end if ~Demand.n, if GAMS.basepg && ~clpsat.init Settings.ok = 0; uiwait(fm_choice(['Exclude (recommended) base generator powers?'])) GAMS.basepg = ~Settings.ok; end noDem = 1; Demand = add(Demand,'dummy'); else noDem = 0; end length(Snapshot.y); if ~GAMS.basepl buspl = Snapshot(1).Pl; busql = Snapshot(1).Ql; Bus.Pl(:) = 0; Bus.Ql(:) = 0; PQ = pqzero(PQ,'all'); end if ~GAMS.basepg ploss = Snapshot(1).Ploss; Snapshot(1).Ploss = 0; buspg = Snapshot(1).Pg; busqg = Snapshot(1).Qg; Bus.Pg(:) = 0; Bus.Qg(:) = 0; SW = swzero(SW,'all'); PV = pvzero(PV,'all'); end fm_disp fm_disp('---------------------------------------------------------') fm_disp(' PSAT-GAMS Interface') fm_disp('---------------------------------------------------------') fm_disp tic method = GAMS.method; modelstat = 0; solvestat = 0; type = GAMS.type; omega = GAMS.omega; if GAMS.method == 6 && GAMS.type ~= 1 fm_disp(['WARNING: Continuation OPF can be run only with Single' ... ' Period Auctions.']) fm_disp('Voltage Stability Constrained OPF will be solved.') method = 4; end if GAMS.method == 6 && GAMS.flow ~= 1 fm_disp(['WARNING: Continuation OPF can be run only with Current ' ... 'Limits.']) fm_disp('Current limits in transmission lines will be used.') GAMS.flow = 1; end if GAMS.type == 3 && GAMS.method ~= 4 fm_disp(['WARNING: Pareto Set Single Period Auction can be run ' ... 'only for VSC-OPF.']) fm_disp( ' Single Period Auction will be solved.') fm_disp type = 1; end if GAMS.type == 3 && length(GAMS.omega) == 1 fm_disp(['WARNING: Weighting factor is scalar. ', ... 'Single Period Auction will be solved.']) fm_disp type = 1; end if GAMS.type == 1 && length(GAMS.omega) > 1 fm_disp(['WARNING: Weighting factor is a vector. ', ... 'First omega entry will be used.']) fm_disp omega = omega(1); end if ~rem(GAMS.type,2) && ~Rmpg.n type = 1; fm_disp(['WARNING: No Ramping data were found. ', ... 'Single Period Auction will be solved.']) fm_disp end if GAMS.type == 2 && Rmpg.n && ~Ypdp.n type = 4; fm_disp(['WARNING: No Power Demand Profile was found. Single ' ... 'Period Auction with Unit Commitment will be solved.']) fm_disp end % resetting time vector in case of previous time simulations if type == 3, Varout.t = []; end switch method case 1, fm_disp(' Simple Auction') case 2, fm_disp(' Market Clearing Mechanism') case 3, fm_disp(' Standard OPF') case 4, fm_disp(' Voltage Stability Constrained OPF') case 5, fm_disp(' Maximum Loading Condition') case 6, fm_disp(' Continuation OPF') case 7, fm_disp(' Congestion Management') end switch type case 1, fm_disp(' Single-Period Auction') case 2, fm_disp(' Multi-Period Auction') case 3, fm_disp(' Pareto Set Single-Period Auction') case 4, fm_disp(' Single-Period Auction with Unit Commitment') end if (GAMS.flatstart || isempty(Snapshot)) && GAMS.method > 2 DAE.y(Bus.a) = getzeros(Bus); DAE.y(Bus.v) = getones(Bus); else DAE.y = Snapshot(1).y; end % ------------------------------------------------------------ % Parameter definition % ------------------------------------------------------------ % dimensions nBus = int2str(Bus.n); nQg = int2str(PV.n+SW.n); nBusref = int2str(SW.refbus); [nSW,SW_idx,ksw] = gams(SW); [nPV,PV_idx,kpv] = gams(PV); [nLine,L,Li,Lj,Gh,Bh,Ghc,Bhc] = gams(Line,method); [Gh,Bh,Ghc,Bhc] = gams(Shunt,method,Gh,Bh,Ghc,Bhc); [nPd,Pd_idx,D] = gams(Demand); [nPs,Ps_idx,S] = gams(Supply,type); [nH,Ch] = gams(Ypdp,type); % indexes iBPs = Supply.bus; iBPd = Demand.bus; iBQg = [SW.bus; PV.bus]; % Fixed powers Pg0 = Bus.Pg; Pl0 = Bus.Pl; Ql0 = Bus.Ql; % Generator reactive powers and associated limits Qg0 = getzeros(Bus); Qg0(iBQg) = Bus.Qg(iBQg); [Qgmax,Qgmin] = fm_qlim('all'); % Voltage limits V0 = DAE.y(Bus.v); t0 = DAE.y(Bus.a); [Vmax,Vmin] = fm_vlim(1.5,0.2); % ------------------------------------------------------------ % Data structures % ------------------------------------------------------------ X.val = [V0,t0,Pg0,Qg0,Pl0,Ql0,Qgmax,Qgmin,Vmax,Vmin,ksw,kpv]; lambda.val = [GAMS.lmin(1),GAMS.lmax(1),GAMS.omega(1),GAMS.line]; X.labels = {cellstr(num2str(Bus.a)), ... {'V0','t0','Pg0','Qg0','Pl0','Ql0', ... 'Qgmax','Qgmin','Vmax','Vmin','ksw','kpv'}}; lambda.labels = {'lmin','lmax','omega','line'}; X.name = 'X'; lambda.name = 'lambda'; % ------------------------------------------------------------ % Launch GAMS solver % ------------------------------------------------------------ control = int2str(method); flow = int2str(GAMS.flow); currentpath = pwd; file = 'fm_gams'; if ~rem(type,2) file = [file,'2']; end if GAMS.libinclude file = [file,' ',GAMS.ldir]; end if clpsat.init || ispc, cd(Path.psat), end switch control % ------------------------------------------------------------------ case '1' % S I M P L E A U C T I O N % ------------------------------------------------------------------ if type == 1 % Single Period Auction [Ps,Pd,MCP,modelstat,solvestat] = psatgams(file,nBus,nLine,nPs,nPd,nSW,nPV, ... nBusref,control,flow,S,D,X); [Pij,Pji,Qg] = updatePF(Pd,Ps,iBQg); elseif ~rem(type,2) % Single/Multi Period Auction with UC [Ps,Pd,MCP,modelstat,solvestat] = psatgams(file,nBus,nLine,nPs,nPd,nSW,nPV, ... nBusref,nH,control,flow,S,D,X,Ch); numh = size(MCP,1); a = zeros(numh,Bus.n); V = zeros(numh,Bus.n); Qg = zeros(numh,Bus.n); Pij = zeros(numh,Line.n); Qij = zeros(numh,Line.n); for i = 1:numh [Piji,Pjii,Qgi] = updatePF(Pd(i,:)',Ps(i,:)',iBQg); a(i,:) = [DAE.y(Bus.a)]'; V(i,:) = [DAE.y(Bus.v)]'; Pij(i,:) = Piji'; Pji(i,:) = Pjii'; Qg(i,iBQg) = Qgi'; end ro = MCP*ones(1,Bus.n); end % ------------------------------------------------------------------ case '2' % M A R K E T C L E A R I N G M E C H A N I S M % ------------------------------------------------------------------ if type == 1 % Single Period Auction [Ps,Pd,MCP,modelstat,solvestat] = psatgams(file,nBus, ... nLine,nPs,nPd,nSW,nPV,nBusref,control, ... flow,Gh,Bh,Li,Lj,Ps_idx,Pd_idx,SW_idx,PV_idx, ... S,D,X,L); [Pij,Pji,Qg] = updatePF(Pd,Ps,iBQg); elseif ~rem(type,2) % Single/Multi Period Auction with UC [Ps,Pd,MCP,modelstat,solvestat] = psatgams(file,nBus, ... nLine,nPs,nPd,nSW,nPV,nBusref,nH,control, ... flow,Gh,Bh,Li,Lj,Ps_idx,Pd_idx,SW_idx,PV_idx, ... S,D,X,L,Ch); numh = size(MCP,1); a = zeros(numh,Bus.n); V = zeros(numh,Bus.n); Qg = zeros(numh,Bus.n); Pij = zeros(numh,Line.n); Qij = zeros(numh,Line.n); for i = 1:numh [Piji,Pjii,Qgi] = updatePF(Pd(i,:)',Ps(i,:)',iBQg); a(i,:) = [DAE.y(Bus.a)]'; V(i,:) = [DAE.y(Bus.v)]'; Pij(i,:) = Piji'; Pji(i,:) = Pjii'; Qg(i,iBQg) = Qgi'; end ro = MCP; end % ------------------------------------------------------------------ case '3' % S T A N D A R D O P T I M A L P O W E R F L O W % ------------------------------------------------------------------ if type == 1 % Single Period Auction [Ps,Pd,V,a,Qg,ro,Pij,Pji,mV,mFij,mFji,modelstat,solvestat] = ... psatgams(file,nBus,nLine,nPs,nPd,nSW,nPV,nBusref,control, ... flow,Gh,Bh,Li,Lj,Ps_idx,Pd_idx,S,D,X,L); NCP = compNCP(V,a,mV,mFij,mFji); elseif ~rem(type,2) % Single/Multi Period Auction with UC [Ps,Pd,V,a,Qg,ro,Pij,Pji,mV,mFij,mFji,modelstat,solvestat] = ... psatgams(file,nBus,nLine,nPs,nPd,nSW,nPV,nBusref,nH,control, ... flow,Gh,Bh,Li,Lj,Ps_idx,Pd_idx,S,D,X,L,Ch); NCP = zeros(length(Ps(:,1)),Bus.n); for i = 1:length(Ps(:,1)) NCPi = compNCP(V(i,:)',a(i,:)',mV(i,:)',mFij(i,:)',mFji(i,:)'); NCP(i,:) = NCPi'; end end % ------------------------------------------------------------------ case '7' % C O N G E S T I O N M A N A G E M E N T % ------------------------------------------------------------------ %lambda_values = [0.0:0.01:0.61]; %n_lambda = length(lambda_values); %GAMS.dpgup = zeros(Supply.n,n_lambda); %GAMS.dpgdw = zeros(Supply.n,n_lambda); %GAMS.dpdup = zeros(Demand.n,n_lambda); %GAMS.dpddw = zeros(Demand.n,n_lambda); %for i = 1:length(lambda_values) %lambda.val(1) = lambda_values(i); iteration = 0; idx_gen = zeros(Supply.n,1); Psc_idx = Ps_idx; Psm_idx = zeros(Bus.n,Supply.n); while 1 [Ps,Pd,dPSup,dPSdw,dPDup,dPDdw,V,a,Qg,ro,Pij,Pji,mV,mFij,mFji, ... lambdac,kg,Vc,ac,Qgc,Pijc,Pjic,Pceq,lambdam,modelstat,solvestat] = ... psatgams('fm_cong',nBus,nLine,nPs,nPd,nBusref,nSW,nPV,control,flow, ... Gh,Bh,Ghc,Bhc,Li,Lj,Ps_idx,Psc_idx,Psm_idx,Pd_idx, ... SW_idx,PV_idx,S,D,X,L,lambda); iteration = iteration + 1; if iteration > 10 fm_disp('* * * Maximum number of iteration with no convergence!') break end idx = psupper(Supply,(1+lambdac+kg)*Ps); if sum(idx_gen(idx)) == length(idx) fm_disp(['* * * iter = ',num2str(iteration), ... ', #viol., ',num2str(length(find(idx_gen))), ... ' lambda = ', num2str(lambdac), ... ' kg = ', num2str(kg)]) break else % loop until there are no violations of power supply limits idx_gen(idx) = 1; fm_disp(['* * * iter = ',num2str(iteration),', #viol. = ', ... num2str(length(idx)),', lambda = ', ... num2str(lambdac),' kg = ', num2str(kg)]) drawnow; Psc_idx = psidx(Supply,~idx_gen); Psm_idx = psidx(Supply,idx_gen); end end %GAMS.dpgup(:,i) = dPSup; %GAMS.dpgdw(:,i) = dPSdw; %GAMS.dpdup(:,i) = dPDup; %GAMS.dpddw(:,i) = dPDdw; %if ~rem(i,10), disp(['Current lambda = ',num2str(lambda_values(i))]),end %end %GAMS.lvals = lambda_values; NCP = compNCP(V,a,mV,mFij,mFji); % ------------------------------------------------------------------ case '4' % V O L T A G E S T A B I L I T Y C O N S T R A I N E D % O P T I M A L P O W E R F L O W % ------------------------------------------------------------------ if type == 1 % Single Period Auction [Ps,Pd,V,a,Qg,ro,Pij,Pji,mV,mFij,mFji, ... lambdac,kg,Vc,ac,Qgc,Pijc,Pjic,Pceq,modelstat,solvestat] = ... psatgams(file,nBus,nLine,nPs,nPd,nBusref,nSW,nPV,control,flow, ... Gh,Bh,Ghc,Bhc,Li,Lj,Ps_idx,Pd_idx,SW_idx,PV_idx,S,D,X,L,lambda); NCP = compNCP(V,a,mV,mFij,mFji); elseif ~rem(type,2) % Single/Multi Period Auction with UC [Ps,Pd,V,a,Qg,ro,Pij,Pji,mV,mFij,mFji, ... lambdac,kg,Vc,ac,Qgc,Pijc,Pjic,Pceq,modelstat,solvestat] = ... psatgams(file,nBus,nLine,nPs,nPd,nBusref,nH,control,flow, ... Gh,Bh,Ghc,Bhc,Li,Lj,Ps_idx,Pd_idx,S,D,X,L,lambda,Ch); NCP = zeros(length(lambdac),Bus.n); for i = 1:length(lambdac) NCPi = compNCP(V(i,:)',a(i,:)',mV(i,:)',mFij(i,:)',mFji(i,:)'); NCP(i,:) = NCPi'; end elseif type == 3 % Pareto Set Single Period Auction fm_disp for i = 1:length(omega) fm_disp(sprintf(' VSC-OPF #%d, %3.1f%% - omega: %5.4f', ... i,100*i/length(omega),omega(i))) lambda.val = [GAMS.lmin(1),GAMS.lmax(1),omega(i),GAMS.line]; [Psi,Pdi,Vi,ai,Qgi,roi,Piji,Pjii,mV,mFij,mFji, ... lambdaci,kgi,Vci,aci,Qgci,Pijci,Pjici,Pceq,modelstat,solvestat] = ... psatgams(file,nBus,nLine,nPs,nPd,nBusref,nSW,nPV,control,flow, ... Gh,Bh,Ghc,Bhc,Li,Lj,Ps_idx,Pd_idx,SW_idx,PV_idx, ... S,D,X,L,lambda); gams_mstat(modelstat) gams_sstat(solvestat) Ps(i,:) = Psi'; Pd(i,:) = Pdi'; V(i,:) = Vi'; a(i,:) = ai'; Qg(i,:) = Qgi'; ro(i,:) = roi'; Pij(i,:) = Piji'; Pji(i,:) = Pjii'; lambdac(i,:) = lambdaci'; kg(i,:) = kgi'; Vc(i,:) = Vci'; ac(i,:) = aci'; Qgc(i,:) = Qgci'; Pijc(i,:) = Pijci'; Pjic(i,:) = Pjici'; NCPi = compNCP(Vi,ai,mV,mFij,mFji); NCP(i,:) = NCPi'; end fm_disp end % ------------------------------------------------------------------ case '5' % M A X I M U M L O A D I N G C O N D I T I O N % ------------------------------------------------------------------ if type == 1 % Single Period Auction [Ps,Pd,V,a,Qg,ro,Pij,Pji,lambdac,kg,modelstat,solvestat] = ... psatgams(file,nBus,nLine,nPs,nPd,nSW,nPV,nBusref, ... control,flow,Gh,Bh,Li,Lj,Ps_idx,Pd_idx, ... SW_idx,PV_idx,S,D,X,L); elseif ~rem(type,2) % Single/Multi Period Auction with UC [Ps,Pd,V,a,Qg,ro,Pij,Pji,lambdac,kg,modelstat,solvestat] = ... psatgams(file,nBus,nLine,nPs,nPd,nSW,nPV,nBusref,nH, ... control,flow,Gh,Bh,Li,Lj,Ps_idx,Pd_idx,SW_idx, ... PV_idx,S,D,X,L,Ch); end % ------------------------------------------------------------------ case '6' % C O N T I N U A T I O N % O P T I M A L P O W E R F L O W % ------------------------------------------------------------------ initial_time = clock; if type == 1 % single period OPF, no discrete variables % number of steps i = 0; last_point = 0; % initial lambda = 0. Base case has to be feasible lmin = 0; lmax = 0; Lambda = lmin; % save actual CPF settings CPF_old = CPF; %CPF.nump = 50; CPF.show = 0; CPF.type = 3; CPF.sbus = 0; CPF.vlim = 1; CPF.ilim = 1; CPF.qlim = 1; CPF.init = 0; CPF.step = 0.25; control = '6'; % save actual power flow data % ------------------------------------------------------ snappg = Snapshot(1).Pg; %Snapshot(1).Pg = []; Bus_old = Bus; % defining voltage limits [Vmax,Vmin] = fm_vlim(1.2,0.8); fm_disp stop_opf = 0; while 1 % OPF step % ------------------------------------------------------ i = i + 1; fm_disp(sprintf('Continuation OPF #%d, lambda_c = %5.4f', ... i,lmin)) lambda.val = [lmin,lmax,0,GAMS.line]; % call GAMS [Psi,Pdi,Vi,ai,Qgi,roi,Piji,Pjii,mV,mFij,mFji, ... lambdaci,kgi,Vci,aci,Qgci,Pijci,Pjici,mPceq,ml,modelstat,solvestat] = ... psatgams(file,nBus,nLine,nPs,nPd,nBusref,nSW,nPV,control,flow, ... Gh,Bh,Ghc,Bhc,Li,Lj,Ps_idx,Pd_idx,SW_idx,PV_idx,S,D,X,L,lambda); gams_mstat(modelstat) gams_sstat(solvestat) Lambda(i,1) = lambdaci; Ps(i,:) = Psi'; Pd(i,:) = Pdi'; V(i,:) = Vi'; a(i,:) = ai'; Qg(i,:) = Qgi'; ro(i,:) = roi'; Pij(i,:) = Piji'; Pji(i,:) = Pjii'; lambdac(i,:) = lambdaci; kg(i,:) = kgi; Vc(i,:) = Vci'; ac(i,:) = aci'; Qgc(i,:) = Qgci'; Pijc(i,:) = Pijci'; Pjic(i,:) = Pjici'; NCPi = compNCP(Vi,ai,mV,mFij,mFji); NCP(i,:) = NCPi'; ML(i,1) = ml; % check consistency of the solution (LMP > 0) if modelstat > 3 %min(abs(roi)) < 1e-5 fm_disp('Unfeasible OPF solution. Discarding last solution.') Lambda(end) = []; Ps(end,:) = []; Pd(end,:) = []; V(end,:) = []; a(end,:) = []; Qg(end,:) = []; ro(end,:) = []; Pij(end,:) = []; Pji(end,:) = []; lambdac(end) = []; kg(end) = []; Vc(end,:) = []; ac(end,:) = []; Qgc(end,:) = []; Pijc(end,:) = []; Pjic(end,:) = []; NCP(end,:) = []; ML(end) = []; lambdaci = lambdac(end,:); break end % ------------------------------------------------------ % Bid variations to allow loading parameter increase % % d mu_Pceq_i % D P_i = -sign(P_i) ------------- % d mu_lambda % % where: % % P_i = power bid i % mu_Pceq_i = Lagrangian multiplier of critical PF eq. i % mu_lambda = Lagrangian multiplier of lambda % ------------------------------------------------------ delta = 0.05; while 1 if abs(ml) > 1e-5 deltaPd = ml./mPceq(Demand.bus)/(1+lambdaci); deltaPs = -ml./mPceq(Supply.bus)/(1+lambdaci+kgi); delta_max = norm([deltaPs; deltaPd]); if delta_max == 0, delta_max = 1; end deltaPd = deltaPd/delta_max; deltaPs = deltaPs/delta_max; else deltaPd = zeros(Demand.n,1); deltaPs = zeros(Supply.n,1); end %ml %mPceq %delta_max = max(norm([deltaPs; deltaPd])); %if delta_max == 0, delta_max = 1; end DPs(i,:) = deltaPs'/Settings.mva; DPd(i,:) = deltaPd'/Settings.mva; Pdi = pdbound(Demand,Pd(i,:)' + delta*deltaPd.*Pd(i,:)'); Psi = psbound(Supply,Ps(i,:)' + delta*deltaPs.*Ps(i,:)'); % CPF step % ------------------------------------------------------ if GAMS.basepl PQ = pqreset(PQ,'all'); PV = pvreset(PV,'all'); SW = swreset(SW,'all'); Snapshot(1).Pg = snappg; else PQ = pqzero(PQ,'all'); PV = pvzero(PV,'all'); SW = swzero(SW,'all'); Snapshot(1).Pg = getzeros(Bus); end Demand = pset(Demand,Pdi); pqsum(Demand,1); Supply = pset(Supply,Psi); pgsum(Supply,1); swsum(Supply,1); DAE.y(Bus.a) = aci; DAE.y(Bus.v) = Vci; PV = setvg(PV,'all',DAE.y(PV.vbus)); SW = setvg(SW,'all',DAE.y(SW.vbus)); DAE.x = Snapshot(1).x; Bus.Pg = Bus_old.Pg; Bus.Qg = Bus_old.Qg; Bus.Pl = Bus_old.Pl; Bus.Ql = Bus_old.Ql; % avoid aborting CPF routine due to limits % ------------------------------------------------------ % voltage limits Vbus = DAE.y(Bus.v); idx = find(abs(Vbus-Vmax) < CPF.tolv | Vbus > Vmax); if ~isempty(idx) DAE.y(idx+Bus.n) = Vmax(idx)-1e-6-CPF.tolv; end idx = find(abs(Vbus-Vmin) < CPF.tolv | Vbus < Vmin); if ~isempty(idx) DAE.y(idx+Bus.n) = Vmin(idx)+1e-6+CPF.tolv; end CPF.kg = 0; CPF.lambda = 1; %lambdaci + 1; CPF.linit = 1+lambdaci*0.25; CPF.init = 0; % set contingency for CPF analysis if GAMS.line status = Line.u(GAMS.line); Line = setstatus(Line,GAMS.line,0); end % --------------------------------------------- % call continuation power flow routine fm_cpf('gams'); %CPF.lambda = CPF.lambda + 1; % --------------------------------------------- % reset admittance line if GAMS.line Line = setstatus(Line,GAMS.line,status); end if isempty(CPF.lambda) fm_disp([' * CPF solution: <empty>']) elseif isnan(CPF.lambda) fm_disp([' * CPF solution: <NaN>']) else fm_disp([' * CPF solution: ',num2str(CPF.lambda-1)]) end if isnan(CPF.lambda) stop_opf = 1; break end if isempty(CPF.lambda) stop_opf = 1; break end if CPF.lambda ~= lambdaci CPF.lambda = CPF.lambda - 0.995; end if CPF.lambda < lambdaci && abs(ml) <= 1e-5 ml = 0; CPF.lambda = lmin+1e-5; end if CPF.lambda < lmin && abs(ml) > 1e-5 fm_disp([' * Decrease Delta Ps and Delta Pd']) delta = 0.5*delta; if delta < 5e-8 fm_disp([' * CPF method cannot find a higher lambda']) stop_opf = 1; break end repeat_cpf = 1; else repeat_cpf = 0; end % maximum lambda increment if (CPF.lambda - lmin) > 0.025 % && (abs(ml) > 1e-5 || CPF.lambda > 0.6) fm_disp(['lambda critical = ',num2str(CPF.lambda)]) fm_disp(['Limit lambda increment to threshold (0.025)']) CPF.lambda = lmin + 0.025; end % stopping criterion % ------------------------------------------------------ if last_point fm_disp('Reached maximum lambda.') if CPF.lambda > lmin fm_disp('Desired maximum lambda is not critical.') end stop_opf = 1; break end if i >= CPF.nump fm_disp('Reached maximum # of continuation steps.') stop_opf = 1; break end if CPF.lambda >= GAMS.lmax CPF.lambda = GAMS.lmax; last_point = 1; end if CPF.lambda == 0 fm_disp('Base case solution is likely unfeasible.') stop_opf = 1; break end if abs(lmin-CPF.lambda) < 1e-5 %fm_disp(['||lambda(i+1) - lambda(i)|| = ', ... % num2str(abs(lmin-CPF.lambda))]) fm_disp('Lambda increment is lower than the desired tolerance.') stop_opf = 1; break elseif ~repeat_cpf if abs(ml) < 1e-5 lmin = CPF.lambda+0.001; lmax = CPF.lambda+0.001; else lmin = CPF.lambda; lmax = CPF.lambda; end break end end %end if stop_opf, break, end end % restore original data and settings % -------------------------------------------------------- DAE.y = Snapshot(1).y; Snapshot(1).Pg = snappg; Bus.Pg = Bus_old.Pg; Bus.Qg = Bus_old.Qg; Bus.Pl = Bus_old.Pl; Bus.Ql = Bus_old.Ql; PV = restore(PV); SW = restore(SW); PQ = pqreset(PQ,'all'); CPF = CPF_old; CPF.init = 4; Varout.t = []; Varout.vars = []; fm_disp % uncomment to plot [dP/d lambda] instead of [P] %Ps = DPs; %Pd = DPd; else fm_disp('Continuation OPF not implemented yet...') cd(currentpath) return end end % ------------------------------------------------------------------- % Output % ------------------------------------------------------------------- MVA = Settings.mva; TPQ = MVA*totp(PQ); % character for backslash bslash = char(92); if GAMS.method == 6, type = 3; end if type == 2 || type == 3 switch GAMS.flow case 0, flow = 'I_'; case 1, flow = 'I_'; case 2, flow = 'P_'; case 3, flow = 'S_'; end Lf = cellstr(num2str(Line.fr)); Lt = cellstr(num2str(Line.to)); TD = MVA*sum(Pd')'; if type == 2 TD = MVA*sum(Pd,2); TTL = TD + TPQ*Ch.val'; TL = MVA*sum(Ps')' + MVA*sum(Bus.Pg)*Ch.val' - TTL; TBL = TL - MVA*Snapshot(1).Ploss*Ch.val'; for i = 1:size(Ps,1) PG(i,:) = full(sparse(1,iBPs,Ps(i,:),1,Bus.n)+Ch.val(i)*Bus.Pg')*MVA; end for i = 1:size(Pd,1) PL(i,:) = full(sparse(1,iBPd,Pd(i,:),1,Bus.n)+Ch.val(i)*Bus.Pl')*MVA; end elseif type == 3 TTL = TD + TPQ; TL = MVA*sum(Ps')' + MVA*sum(Bus.Pg) - TTL; TBL = TL - MVA*Snapshot(1).Ploss; for i = 1:size(Ps,1) PG(i,:) = full(sparse(1,iBPs,Ps(i,:),1,Bus.n)+Bus.Pg')*MVA; end for i = 1:size(Pd,1) PL(i,:) = full(sparse(1,iBPd,Pd(i,:),1,Bus.n)+Bus.Pl')*MVA; end end PayS = -PG.*ro; PayD = PL.*ro; ISO = sum(PayS')'+sum(PayD')'; if GAMS.method == 4 || GAMS.method == 6 MLC = TTL.*(1+lambdac); elseif GAMS.method == 5 MLC = TTL.*lambdac; end Varname.uvars = fm_strjoin('PS_',{Bus.names{Supply.bus}}'); Varname.uvars = [Varname.uvars;fm_strjoin('PD_',{Bus.names{Demand.bus}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('PG_',{Bus.names{:}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('PL_',{Bus.names{:}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('Pay_S_',{Bus.names{:}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('Pay_D_',{Bus.names{:}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('theta_',{Bus.names{:}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('V_',{Bus.names{:}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('Qg_',{Bus.names{iBQg}}')]; if GAMS.method > 2 && GAMS.method ~= 5 Varname.uvars = [Varname.uvars;fm_strjoin('LMP_',{Bus.names{:}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('NCP_',{Bus.names{:}}')]; elseif GAMS.method == 2 Varname.uvars = [Varname.uvars;fm_strjoin('LMP_',{Bus.names{:}}')]; elseif GAMS.method == 5 Varname.uvars = [Varname.uvars;fm_strjoin(bslash,'rho_',{Bus.names{:}}')]; else Varname.uvars = [Varname.uvars;{'MCP'}]; end Varname.uvars = [Varname.uvars;fm_strjoin(flow,Lf,'-',Lt)]; Varname.uvars = [Varname.uvars;fm_strjoin(flow,Lt,'-',Lf)]; Varname.uvars = [Varname.uvars;{'Total Demand';'TTL';'Total Losses'; ... 'Total Bid Losses';'IMO Pay'}]; if GAMS.method >= 4 Varname.uvars = [Varname.uvars;{'MLC'}]; Varname.uvars = [Varname.uvars;{'ALC'}]; end Varname.fvars = fm_strjoin('P_{S',{Bus.names{Supply.bus}}','}'); Varname.fvars = [Varname.fvars;fm_strjoin('P_{D',{Bus.names{Demand.bus}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin('P_{G',{Bus.names{:}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin('P_{L',{Bus.names{:}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin('Pay_{S',{Bus.names{:}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin('Pay_{D',{Bus.names{:}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin(bslash,'theta_{',{Bus.names{:}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin('V_{',{Bus.names{:}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin('Q_{g',{Bus.names{iBQg}}','}')]; if GAMS.method > 2 && GAMS.method ~= 5 Varname.fvars = [Varname.fvars;fm_strjoin('LMP_{',{Bus.names{:}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin('NCP_{',{Bus.names{:}}','}')]; elseif GAMS.method == 2 Varname.fvars = [Varname.fvars;fm_strjoin('LMP_{',{Bus.names{:}}','}')]; elseif GAMS.method == 5 Varname.fvars = [Varname.fvars;fm_strjoin(bslash,'rho_',{Bus.names{:}}')]; else Varname.fvars = [Varname.fvars;{'MCP'}]; end Varname.fvars = [Varname.fvars;fm_strjoin(flow,'{',Lf,'-',Lt,'}')]; Varname.fvars = [Varname.fvars;fm_strjoin(flow,'{',Lt,'-',Lf,'}')]; Varname.fvars = [Varname.fvars;{'Total Demand';'TTL';'Total Losses'; ... 'Total Bid Losses';'IMO Pay'}]; if GAMS.method >= 4 Varname.fvars = [Varname.fvars;{'MLC'}]; Varname.fvars = [Varname.fvars;{'ALC'}]; end switch GAMS.method case 3 % OPF Varout.vars = [Ps*MVA,Pd*MVA,PG,PL,PayS,PayD,a,V,Qg(:,iBQg)*MVA, ... ro,NCP,Pij,Pji,TD,TTL,TL,TBL,ISO]; case {4,6} % VSC-OPF Varname.uvars = [Varname.uvars;{'lambda_c';'kg_c'}]; Varname.uvars = [Varname.uvars;fm_strjoin('thetac_',{Bus.names{:}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('Vc_',{Bus.names{:}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('Qgc_',{Bus.names{iBQg}}')]; Varname.uvars = [Varname.uvars;fm_strjoin(flow,'c',Lf,'-',Lt)]; Varname.uvars = [Varname.uvars;fm_strjoin(flow,'c',Lt,'-',Lf)]; Varname.fvars = [Varname.fvars;{[bslash,'lambda_c'];'k_g_c'}]; Varname.fvars = [Varname.fvars;fm_strjoin(bslash,'theta_{c',{Bus.names{:}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin('V_{c',{Bus.names{:}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin('Q_{gc',{Bus.names{iBQg}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin(flow,'{c',Lf,'-',Lt,'}')]; Varname.fvars = [Varname.fvars;fm_strjoin(flow,'{c',Lt,'-',Lf,'}')]; Varout.vars = [Ps*MVA,Pd*MVA,PG,PL,PayS,PayD,a,V,Qg(:,iBQg)*MVA, ... ro,NCP,Pij,Pji,TD,TTL,TL,TBL,ISO,MLC,MLC-TTL,lambdac,kg, ... ac,Vc,Qgc(:,iBQg)*MVA,Pijc,Pjic]; case 5 % MLC Varname.uvars = [Varname.uvars;{'lambda_c';'kg_c'}]; Varname.fvars = [Varname.fvars;{bslash,'lambda_c';'k_g_c'}]; Varout.vars = [Ps*MVA,Pd*MVA,PG,PL,PayS,PayD,a,V,Qg(:,iBQg)*MVA, ... ro,Pij,Pji,TD,TTL,TL,TBL,ISO,MLC,lambdac,kg]; otherwise % SA and MCM Varout.vars = [Ps*MVA,Pd*MVA,PG,PL,PayS,PayD,a,V,Qg(:,iBQg)*MVA, ... MCP,Pij,Pji,TD,TTL,TL,TBL,ISO]; end if GAMS.method == 6 % Continuation OPF Settings.xlabel = [bslash,'lambda (loading parameter)']; Varout.t = Lambda'; elseif type == 2 % Multi Period Auction Varout.vars = Varout.vars([2:end],:); Settings.xlabel = 'hour [h]'; Varout.t = [1:Ypdp.len]'; elseif type == 3 % Pareto Set Single Period Auction Settings.xlabel = [bslash,'omega (weighting factor)']; Varout.t = GAMS.omega'; end Varout.idx = [1:length(Varout.vars(1,:))]; fm_disp(' ---------------------------------------------------------------') fm_disp([' Check file ',Path.psat,'fm_gams.lst for GAMS report.']) if strcmp(control,'6') fm_disp([' PSAT-GAMS Optimization Routine completed in ', ... num2str(etime(clock,initial_time)),' s']) else fm_disp([' PSAT-GAMS Optimization Routine completed in ',num2str(toc),' s']) end Demand = restore(Demand); if ~GAMS.basepl Bus.Pl = buspl; Bus.Ql = busql; PQ = pqreset(PQ,'all'); end if ~GAMS.basepg Snapshot(1).Ploss = ploss; Bus.Pg = buspg; Bus.Qg = busqg; PV = pvreset(PV,'all'); end % restore original bus power injections Bus.Pg = Snapshot(1).Pg; Bus.Qg = Snapshot(1).Qg; Bus.Pl = Snapshot(1).Pl; Bus.Ql = Snapshot(1).Ql; return end if type == 4 Ps = Ps(2,:)'; Pd = Pd(2,:)'; V = V(2,:)'; a = a(2,:)'; Qg = Qg(2,iBQg)'; Pij = Pij(2,:)'; Pji = Pji(2,:)'; if GAMS.method <= 2 MCP = MCP(2,:); end if GAMS.method >= 3 ro = ro(2,:)'; if GAMS.method ~= 5 NCP = NCP(2,:)'; end end if GAMS.method == 4 || GAMS.method == 6 Vc = Vc(2,:)'; ac = ac(2,:)'; Qgc = Qgc(2,iBQg)'; Pijc = Pijc(2,:)'; Pjic = Pjic(2,:)'; end if GAMS.method >= 4 lambdac = lambdac(2); kg = kg(2); end end Demand = pset(Demand,Pd); Supply = pset(Supply,Ps); if GAMS.method == 4 || GAMS.method == 6 DAE.y(Bus.a) = ac; DAE.y(Bus.v) = Vc; Line = gcall(Line); glfpc = Line.p; glfqc = Line.q; end if GAMS.method >= 3 DAE.y(Bus.a) = a; DAE.y(Bus.v) = V; Line = gcall(Line); Qg = Qg(iBQg); end if GAMS.method == 1 ro = MCP*getones(Bus); end if GAMS.method == 2 [rows,cols] = size(MCP); if rows == 1, ro = MCP'; else ro = MCP; end end Qgmin = Qgmin(iBQg); Qgmax = Qgmax(iBQg); if GAMS.basepl PG = full((sparse(iBPs,1,Ps,Bus.n,1)+Bus.Pg)*MVA); PL = full((sparse(iBPd,1,Pd,Bus.n,1)+Bus.Pl)*MVA); else PG = full(sparse(iBPs,1,Ps,Bus.n,1)*MVA); PL = full(sparse(iBPd,1,Pd,Bus.n,1)*MVA); end QG = full(sparse(iBQg,1,Qg,Bus.n,1)*MVA); QL = full((sparse(iBPd,1,Pd.*tanphi(Demand),Bus.n,1)+Bus.Ql)*MVA); PayS = -ro(Bus.a).*PG; PayD = ro(Bus.a).*PL; ISOPay = -sum(ro(Bus.a).*Line.p*MVA); if (Settings.showlf || GAMS.show) && clpsat.showopf fm_disp fm_disp(' Power Supplies') fm_disp(' ---------------------------------------------------------------') [Psmax,Psmin] = plim(Supply); if GAMS.method == 7 fm_disp({'Bus','Ps','Ps max','Ps min','dPs_up','dPs_dw'}) fm_disp({'<i>','[MW]','[MW]','[MW]','[MW]','[MW]'}) fm_disp([getidx(Bus,Supply.bus),Ps*MVA,Psmax*MVA,Psmin*MVA,dPSup*MVA,dPSdw*MVA]) else fm_disp({'Bus','Ps','Ps max','Ps min'}) fm_disp({'<i>','[MW]','[MW]','[MW]'}) fm_disp([getidx(Bus,Supply.bus),Ps*MVA,Psmax*MVA,Psmin*MVA]) end fm_disp fm_disp(' Power Demands') fm_disp(' ---------------------------------------------------------------') [Pdmax,Pdmin] = plim(Demand); if GAMS.method == 7 fm_disp({'Bus','Pd','Pd max','Pd min','dPd_up','dPd_dw'}) fm_disp({'<i>','[MW]','[MW]','[MW]'}) fm_disp([getidx(Bus,Demand.bus),Pd*MVA,Pdmax*MVA,Pdmin*MVA,dPDup*MVA,dPDdw*MVA]) else fm_disp({'Bus','Pd','Pd max','Pd min'}) fm_disp({'<i>','[MW]','[MW]','[MW]'}) fm_disp([getidx(Bus,Demand.bus),Pd*MVA,Pdmax*MVA,Pdmin*MVA]) end fm_disp fm_disp(' Generator Reactive Powers') fm_disp(' ---------------------------------------------------------------') if GAMS.method == 4 || GAMS.method == 6 fm_disp({'Bus','Qg','Qgc','Qg max','Qg min'}) fm_disp({'<i>','[MVar]','[MVar]','[MVar]','[MVar]'}) fm_disp([getidx(Bus,iBQg),Qg*MVA,Qgc(iBQg)*MVA,Qgmax*MVA,Qgmin*MVA]) else fm_disp({'Bus','Qg','Qg max','Qg min'}) fm_disp({'<i>','[MVar]','[MVar]','[MVar]'}) fm_disp([getidx(Bus,iBQg),Qg*MVA,Qgmax*MVA,Qgmin*MVA]) end fm_disp fm_disp(' Power Flow Solution') fm_disp([' ----------------------------------------------------' ... '-----------']) fm_disp({'Bus','V','theta','PG','PL','QG','QL'}) fm_disp({'<i>','[p.u.]','[rad]','[MW]','[MW]','[MVar]','[MVar]'}) fm_disp([getidx(Bus,0),DAE.y(Bus.v),DAE.y(Bus.a),PG,PL,QG,QL]) fm_disp fm_disp(' Prices and Pays') fm_disp([' ----------------------------------------------------' ... '-----------']) if GAMS.method == 3 || GAMS.method == 4 || GAMS.method == 6 fm_disp({'Bus','LMP','NCP','Pay S','Pay D'}) fm_disp({'<i>','[$/MWh]','[$/MWh]','[$/h]','[$/h]'}) fm_disp([getidx(Bus,0),ro(Bus.a), NCP, PayS, PayD]) else fm_disp({'Bus','LMP','Pay S','Pay D'}) fm_disp({'<i>','[$/MWh]','[$/h]','[$/h]'}) fm_disp([getidx(Bus,0),ro(Bus.a), PayS, PayD]) end if GAMS.method == 4 || GAMS.method == 6 fm_disp fm_disp(' "Critical" Power Flow Solution') fm_disp(' ---------------------------------------------------------------') fm_disp({'Bus','Vc','thetac','PGc','PLc','QGc','QLc'}) fm_disp({'<i>','[p.u.]','[rad]','[MW]','[MW]','[MVar]', ... '[MVar]'}) PG = (1+lambdac+kg)*PG; PL = (1+lambdac)*PL; QL = (1+lambdac)*QL; fm_disp([getidx(Bus,0),Vc,ac,PG,PL,Qgc*MVA,QL]) end fm_disp if GAMS.flow fm_disp(' Flows on Transmission Lines') fm_disp(' ---------------------------------------------------------------') switch GAMS.flow case 1, fm_disp({'From Bus','To Bus','Iij','Iijmax', ... 'Iij margin','Iji','Ijimax','Iji margin'},1) case 2, fm_disp({'From Bus','To Bus','Pij','Pijmax', ... 'Pij margin','Pji','Pjimax','Pji margin'},1) case 3, fm_disp({'From Bus','To Bus','Sij','Sijmax', ... 'Sij margin','Sji','Sjimax','Sji margin'},1) end fm_disp({'<i>','<j>','[p.u.]','[p.u.]', ... '[p.u.]','[p.u.]','[p.u.]','[p.u.]'}) fm_disp([Line.fr, Line.to,Pij, ... L.val(:,5),abs((-abs(Pij)+L.val(:,5))), ... Pji,L.val(:,5),abs((-abs(Pji)+L.val(:,5)))]) fm_disp else fm_disp('Flow limits are disabled.') end if GAMS.method == 4 || GAMS.method == 6 fm_disp(' Flows on Transmission Lines of the "Critical" System') fm_disp(' ---------------------------------------------------------------') switch GAMS.flow case 1, fm_disp({'From Bus','To Bus','Iijc','Iijcmax', ... 'Iijc margin','Ijic','Ijicmax','Ijic margin'}) case 2, fm_disp({'From Bus','To Bus','Pijc','Pijcmax', ... 'Pijc margin','Pjic','Pjicmax','Pjic margin'}) case 3, fm_disp({'From Bus','To Bus','Sijc','Sijcmax', ... 'Sijc margin','Sjic','Sjicmax',['Sjic margin']}) end fm_disp({'<i>','<j>','[p.u.]','[p.u.]', ... '[p.u.]','[p.u.]','[p.u.]','[p.u.]'}) if GAMS.flow fm_disp([Line.fr, Line.to,Pijc, ... L.val(:,5),abs((-abs(Pijc)+L.val(:,5))), ... Pjic,L.val(:,5),abs((-abs(Pjic)+L.val(:,5)))]) fm_disp end end fm_disp fm_disp(' Totals') fm_disp(' ---------------------------------------------------------------') if GAMS.method >= 4, fm_disp([' omega = ',num2str(omega(1))]) fm_disp([' lambda_c = ',num2str(lambdac),' [p.u.]']) fm_disp([' kg = ',num2str(kg),' [p.u.]']) end if GAMS.method == 1 fm_disp([' Market Clearing Price = ',num2str(MCP),' [$/MWh]']) end total_loss = 1e-5*round(sum(Line.p)*1e5)*MVA; bid_loss = 1e-5*round((sum(Line.p)-Snapshot(1).Ploss)*1e5)*MVA; fm_disp([' Total Losses = ',num2str(total_loss),' [MW]']) fm_disp([' Bid Losses = ',num2str(bid_loss),' [MW]']) fm_disp([' Total demand = ',num2str(sum(Pd)*MVA),' [MW]']) fm_disp([' Total Transaction Level = ', ... fvar(sum(Pd)*MVA+TPQ,8),' [MW]']); if GAMS.method == 4 || GAMS.method == 6 fm_disp([' Maximum Loading Condition = ', ... fvar((1+lambdac)*(sum(Pd)*MVA+TPQ),8),' [MW]']); fm_disp([' Available Loading Capability = ', ... fvar(lambdac*(sum(Pd)*MVA+TPQ),8),' [MW]']); end if GAMS.method == 5 fm_disp([' Maximum Loading Condition = ', ... fvar(lambdac*(sum(Pd)*MVA+TPQ),8),' [MW]']); end fm_disp([' IMO Pay = ',num2str(ISOPay),' [$/h]']); fm_disp end fm_disp(' ---------------------------------------------------------------') fm_disp([' Check file ',Path.psat,'fm_gams.lst for GAMS report.']) gams_mstat(modelstat) gams_sstat(solvestat) if strcmp(control,'6') fm_disp([' PSAT-GAMS Optimization Routine completed in ', ... num2str(etime(clock,initial_time)),' s']) else fm_disp([' PSAT-GAMS Optimization Routine completed in ',num2str(toc),' s']) end if noDem, Demand = restore(Demand); end if ~GAMS.basepl Bus.Pl = buspl; Bus.Ql = busql; PQ = pqreset(PQ,'all'); end if ~GAMS.basepg Snapshot(1).Ploss = ploss; Bus.Pg = buspg; Bus.Qg = busqg; PV = pvreset(PV,'all'); end % restore original bus power injections Bus.Pg = Snapshot(1).Pg; Bus.Qg = Snapshot(1).Qg; Bus.Pl = Snapshot(1).Pl; Bus.Ql = Snapshot(1).Ql; % =============================================================== function [Pij,Pji,Qg] = updatePF(Pd,Ps,iBQg) % Power FLow Solution with the current simple auction solution % =============================================================== global Settings Bus Line PQ PV SW Demand Supply GAMS Busold = Bus; Demand = pset(Demand,Pd); Supply = pset(Supply,Ps); pg = SW.pg; pqsum(Demand,1); pgsum(Supply,1); show_old = Settings.show; Settings.show = 0; Settings.locksnap = 1; fm_spf Settings.locksnap = 0; Settings.show = show_old; [Pij,Pji] = flows(Line,max(GAMS.flow,1)); Qg = Bus.Qg(iBQg); Bus = Busold; SW = setpg(SW,'all',pg); PQ = restore(PQ); PV = pvreset(PV,'all'); % ========================================================================== function NCP = compNCP(V,a,mV,mFij,mFji) % Nodal Congestion Prices % ========================================================================== global DAE SW GAMS Line Bus yold = DAE.y; Gyold = DAE.Gy; DAE.y(Bus.a) = a; DAE.y(Bus.v) = V; Gycall(Line) fm_setgy(SW.refbus) [Fij,Jij,Fji,Jji] = fjh2(Line,max(GAMS.flow,1)); dH_dtV = Jij'*mFij + Jji'*mFji + [getzeros(Bus);mV]; dH_dtV(SW.refbus,:) = 0; NCP = DAE.Gy'\dH_dtV; NCP = NCP(Bus.a); DAE.y = yold; DAE.Gy = Gyold; % ========================================================================== function varargout = psatgams(varargin) % PSAT-GAMS interface % ========================================================================== global Settings Path % writing GAMS input data %--------------------------------------------------------------------- fid1 = fopen('psatglobs.gms','wt+'); fid2 = fopen('psatdata.gms','wt+'); fprintf(fid2,'%s\n','$onempty'); for i = 2:nargin if ischar(varargin{i}) fprintf(fid1,'$setglobal %s ''%s''\n',inputname(i), ... varargin{i}); elseif isnumeric(varargin{i}) fprintf(fid2,'$kill %s\n',inputname(i)); if length(varargin{i}) == 1 fprintf(fid2,'scalar %s /%f/;\n',inputname(i),varargin{i}); else fprintf(fid2,'parameter %s /\n',inputname(i)); [x,y,v] = find(varargin{i}); fprintf(fid2,'%d.%d %f\n',[x y v]'); fprintf(fid2,'/;\n'); end elseif isstruct(varargin{i}) labels = varargin{i}.labels; fprintf(fid2,'$kill %s\n',varargin{i}.name); fprintf(fid2,'parameter %s /\n',varargin{i}.name); [x,y,v] = find(varargin{i}.val); if iscell(labels{1}) %a = fm_strjoin(labels{1}(x),'.',labels{2}(y)',[blanks(length(x))',num2str(v)]); %fprintf(fid2,'%s\n',a{:}); for j = 1:length(x) fprintf(fid2,'%s.%s %f\n',labels{1}{x(j)},labels{2}{y(j)},v(j)); end else for j = 1:length(x) fprintf(fid2,'%s %f\n',labels{y(j)},v(j)); end end fprintf(fid2,'/;\n'); end end fprintf(fid2,'%s\n','$offempty'); fclose(fid1); fclose(fid2); % Lauching GAMS %--------------------------------------------------------------------- status = 0; t0 = clock; %disp(['gams ',varargin{1},' -error=PSAT']) [status,result] = system(['gams ',varargin{1}]); fm_disp([' GAMS routine completed in ',num2str(etime(clock,t0)),' s']) if status fm_disp(result) return end % Reading GAMS output %--------------------------------------------------------------------- nout = 0; EPS = eps; clear psatsol psatsol if nout < nargout for i = nout+1:nargout varargout{i} = []; end end if nout > nargout varargout(nargout+1:nout) = []; end %--------------------------------------------------------------------- function gams_mstat(status) if isempty(status), return, end switch status case 0, fm_disp(' GAMS model status: not available') case 1, fm_disp(' GAMS model status: optimal') case 2, fm_disp(' GAMS model status: locally optimal') case 3, fm_disp(' GAMS model status: unbounded') case 4, fm_disp(' GAMS model status: infeasible') case 5, fm_disp(' GAMS model status: locally infeasible') case 6, fm_disp(' GAMS model status: intermediate infeasible') case 7, fm_disp(' GAMS model status: intermediate non-optimal') case 8, fm_disp(' GAMS model status: integer solution') case 9, fm_disp(' GAMS model status: intermediate non-integer') case 10, fm_disp(' GAMS model status: integer infeasible') case 11, fm_disp(' GAMS model status: ???') case 12, fm_disp(' GAMS model status: error unknown') case 13, fm_disp(' GAMS model status: error no solution') otherwise, fm_disp(' GAMS model status: unknown model status') end %--------------------------------------------------------------------- function gams_sstat(status) if isempty(status), return, end switch status case 0, fm_disp(' GAMS solver status: not available') case 1, fm_disp(' GAMS solver status: normal completion') case 2, fm_disp(' GAMS solver status: iteration interrupt') case 3, fm_disp(' GAMS solver status: resource interrupt') case 4, fm_disp(' GAMS solver status: terminated by solver') case 5, fm_disp(' GAMS solver status: evaluation error limit') case 6, fm_disp(' GAMS solver status: unknown') case 7, fm_disp(' GAMS solver status: ???') case 8, fm_disp(' GAMS solver status: error preprocessor error') case 9, fm_disp(' GAMS solver status: error setup failure') case 10, fm_disp(' GAMS solver status: error solver failure') case 11, fm_disp(' GAMS solver status: error internal solver error') case 12, fm_disp(' GAMS solver status: error post-processor error') case 13, fm_disp(' GAMS solver status: error system failure') otherwise, fm_disp(' GAMS solver status: unknown solver status') end
github
Sinan81/PSAT-master
fm_build.m
.m
PSAT-master/psat-mat/psat/fm_build.m
25,468
utf_8
688cdaed0380b34975aab856abfbaf9e
function fm_build %FM_BUILD build new component functions (Symbolic Toolbox is needed) % %FM_BUILD % %see also FM_MAKE FM_COMPONENT % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 19-Dec-2003 %Version: 1.0.1 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Comp Settings Fig Path global Algeb Buses Initl Param Servc State % *********************************************************************** % some control variables error_v = []; lasterr(''); null = '0'; % useful strings c_name = Comp.name; c_name(1) = upper(c_name(1)); % variable arrays state_vect = varvect(State.name, ' '); algeb_vect = varvect(Algeb.name, ' '); param_vect = varvect(Param.name, ' '); initl_vect = varvect(Initl.name, ' '); servc_vect = varvect(Servc.name, ' '); pq_Servc = 0; % equation arrays servc_eq = varvect(Servc.eq,'; '); state_eq = varvect(State.eq,'; '); algeb_eq = varvect(Algeb.eq,'; '); % ******************************************************************************** % check equations if State.neq > 0 state_check = strmatch('null',State.eq,'exact'); if state_check error_v = [error_v; ... fm_strjoin('Differential equation for "', ... State.eqidx(state_check), ... '" has not been defined.')]; end end if Servc.neq > 0 servc_foo = fm_strjoin(Servc.type,Servc.eq); servc_check = strmatch('Innernull',servc_foo,'exact'); servc_check = [servc_check; strmatch('Outputnull',servc_foo,'exact')]; if servc_check error_v = [error_v; ... fm_strjoin('Service equation for "', ... Servc.eqidx(servc_check), ... '" has not been defined.')]; end end % ******************************************************************************** % check variable usage servc_idx = [strmatch('Inner',Servc.type); strmatch('Output',Servc.type)]; total_var = [State.name; Algeb.name; Servc.eqidx(servc_idx); Param.name; Initl.name]; total_eqn = [' ',servc_eq,' ',state_eq,' ',algeb_eq,' ',varvect(State.time,'*'),' ']; for i = 1:length(total_var) idx = findstr(total_eqn,total_var{i}); if isempty(idx) error_v{end+1,1} = ['The variable "',total_var{i},'" is not used in any equation.']; else before = total_eqn(idx-1); after = total_eqn(idx+length(total_var{i})); check = 1; for j = 1:length(idx) a = double(after(j)); b = double(before(j)); a1 = ~isletter(after(j)); a2 = (a ~= 95); a3 = (a > 57 || a < 48); b1 = ~isletter(before(j)); b2 = (b ~= 95); b3 = (b > 57 || b < 48); if a1 && a2 && a3 && b1 && b2 && b3, check = 0; break, end end if check error_v{end+1,1} = ['The variable "',total_var{i}, ... '" is not used in any equation.']; end end end % ******************************************************************************** % symbolic variables try if state_vect, eval(['syms ',state_vect]), end if algeb_vect, eval(['syms ',algeb_vect]), end if param_vect, eval(['syms ',param_vect]), end if servc_vect, eval(['syms ',servc_vect]), end if initl_vect, eval(['syms ',initl_vect]), end % compute Jacobians matrices (Maple Symbolic Toolbox) if ~isempty(state_eq) if ~isempty(state_vect) eval(['Fx = jacobian([',state_eq, '],[', state_vect, ']);']); end if ~isempty(algeb_vect) eval(['Fy = jacobian([',state_eq, '],[', algeb_vect, ']);']); end if ~isempty(servc_vect) eval(['Fz = jacobian([',state_eq, '],[', servc_vect, ']);']); end if pq_Servc eval(['Fpq = jacobian([',state_eq, '],[', pq_vect, ']);']); end end if ~isempty(algeb_eq) if ~isempty(state_vect) eval(['Gx = jacobian([',algeb_eq, '],[', state_vect, ']);']); end if ~isempty(algeb_vect) eval(['Gy = jacobian([',algeb_eq, '],[', algeb_vect, ']);']); end if ~isempty(servc_vect) eval(['Gz = jacobian([',algeb_eq, '],[', servc_vect, ']);']); end if pq_Servc eval(['Gpq = jacobian([',alg_eqeb, '],[', pq_vect, ']);']); end end if ~isempty(servc_eq) if ~isempty(state_vect) eval(['Zx = jacobian([',servc_eq, '],[', state_vect, ']);']); end if ~isempty(algeb_vect) eval(['Zy = jacobian([',servc_eq, '],[', algeb_vect, ']);']); end if ~isempty(servc_vect) eval(['Zz = jacobian([',servc_eq, '],[', servc_vect, ']);']); end if pq_Servc eval(['Zpq = jacobian([',servc_eq, '],[', pq_vect, ']);']); end end end % ******************************************************************************** % check synthax of equations for i = 1:State.neq try eval([State.eq{i,1},';']) catch error_v{end+1,1} = [lasterr, ' (In differential equation "', ... State.eq{i,1}, '")']; end try eval([State.init{i,1},';']) catch error_v{end+1,1} = [lasterr, ' (In state variable "', ... State.name{i,1}, '" initialization expression)']; end state_init{i,1} = vectorize(State.init{i,1}); end for i = 1:Algeb.neq try eval([Algeb.eq{i,1},';']) catch error_v{end+1,1} = [lasterr, ' (In algebraic equation "', ... State.eq{i,1}, '")']; end end for j = 1:Servc.neq try eval([Servc.eq{i,1},';']) catch error_v{end+1,1} = [lasterr, ' (In service equation "', ... Servc.eqidx{i,1}, '")']; end end % check component name if isempty(Comp.name) error_v{end+1,1} = 'Component name is empty.'; return end % ******************************************************************************** % display errors if ~isempty(error_v) error_v = fm_strjoin('Error#',num2str([1:length(error_v)]'),': ',error_v); error_v = [{['REPORT OF ERRORS ENCOUNTERED WHILE BUILDING ', ... 'NEW COMPONENT "',Comp.name,'.m"']}; error_v]; error_v{end+1,1} = ['BUILDING NEW COMPONENT FILE "', ... Comp.name,'.m" FAILED']; fm_disp fm_disp(error_v{1:end-1}) fm_disp(['BUILDING NEW COMPONENT FILE "',Comp.name,'.m" FAILED']) fm_update set(findobj(Fig.update,'Tag','Listbox1'),'String',error_v, ... 'BackgroundColor','w', ... 'ForegroundColor','r', ... 'Enable','inactive', ... 'max',2, ... 'Value',[]); set(findobj(Fig.update,'Tag','Pushbutton2'),'Enable','off'); return end % *********************************************************************** % check for previous versions a = what(Path.psat); olderfile = strmatch(['fm_',Comp.name,'.m'],a.m,'exact'); if ~isempty(olderfile) uiwait(fm_choice(['Overwrite Existing File "fm_',Comp.name,'.m" ?'])); if ~Settings.ok, return, end end % *********************************************************************** % open new component file fid = fopen([Path.psat, 'fm_', Comp.name,'.m'], 'wt'); if fid == -1 fm_disp(['Cannot open file fm_',Comp.name,'. Check permissions']) return end fprintf(fid, ['function fm_', Comp.name, '(flag)']); % write help of the function if isempty(Comp.descr) Comp.descr = ['Algebraic Differential Equation ', ... Comp.name, '.m']; end fprintf(fid, ['\n\n%%FM_', upper(Comp.name),' defines ',Comp.descr]); % ******************************************************************** % data format .con fprintf(fid, ['\n%%\n%%Data Format ', c_name, '.con:']); fprintf(fid, '\n%% col #%d: Bus %d number',[1:Buses.n;1:Buses.n]); idx_inn = strmatch('Inner', Servc.type, 'exact'); idx_inp = strmatch('Input', Servc.type, 'exact'); idx_out = strmatch('Output', Servc.type, 'exact'); fprintf(fid, '\n%% col #%d: Power rate [MVA]',Buses.n+1); fprintf(fid, '\n%% col #%d: Bus %d Voltage Rate [kV]', ... [Buses.n+1+[1:Buses.n];1:Buses.n]); fprintf(fid, '\n%% col #%d: Frequency rate [Hz]',2*Buses.n+2); inip = 2*Buses.n+3; endp = 2*Buses.n+2+Param.n; pidx = inip:endp; for i=1:length(pidx) fprintf(fid, '\n%% col #%d: %s %s [%s]', ... pidx(i),Param.name{i},Param.descr{i},Param.unit{i}); end x_max = [1:State.n]; if State.n x_idx = strmatch('None',State.limit(:,1),'exact'); x_max(x_idx) = []; end x_min = [1:State.n]; if State.n x_idx = strmatch('None',State.limit(:,2),'exact'); x_min(x_idx) = []; end n_xmax = length(x_max); n_xmin = length(x_min); for i=1:n_xmax fprintf(fid,'\n%% col #%d: %s',endp+i, ... State.limit{x_max(i),1}); end for i=1:n_xmin fprintf(fid,'\n%% col #%d: %s',endp+n_xmax+i, ... State.limit{x_min(i),1}); end s_max = [1:Servc.neq]; if Servc.n s_idx = strmatch('None',Servc.limit(:,1),'exact'); s_max(s_idx) = []; end s_min = [1:Servc.neq]; if Servc.n s_idx = strmatch('None',Servc.limit(:,2),'exact'); s_min(s_idx) = []; end n_smax = length(s_max); n_smin = length(s_min); for i=1:n_smax fprintf(fid,'\n%% col #%d: %s', ... endp+n_xmax+n_xmin+i,Servc.limit{s_max(i),1}); end for i=1:n_smin fprintf(fid,'\n%% col #%d: %s', ... endp+n_xmax+n_xmin+n_smax+i,Servc.limit{s_min(i),1}); end okdata = 0; nidx = 0; if ~isempty(idx_inn) || ~isempty(idx_out) okdata = 1; end if Initl.n || okdata fprintf(fid, ['\n%% \n%%Data Structure: ', c_name, '.dat:']); end for i=1:Initl.n fprintf(fid,'\n%% col #%d: %s', i,Initl.name{i}); end if okdata nidx = length(idx_inn)+length(idx_out); iidx = [idx_inn;idx_out]; for i=1:nidx fprintf(fid,'\n%% col #%d: %s', ... Initl.n+i,Servc.eqidx{iidx(i)}); end end % function calls fprintf(fid, ['\n%% \n%%FM_', upper(Comp.name),'(FLAG)']); if Comp.init fprintf(fid, ['\n%% FLAG = 0 -> initialization']); end if ~isempty(algeb_eq) fprintf(fid, ['\n%% FLAG = 1 -> algebraic equations']); fprintf(fid, ['\n%% FLAG = 2 -> algebraic Jacobians']); end if ~isempty(state_eq); fprintf(fid, ['\n%% FLAG = 3 -> differential equations']); fprintf(fid, ['\n%% FLAG = 4 -> state Jacobians']); end if n_xmax || n_xmin > 0 fprintf(fid, ['\n%% FLAG = 5 -> non-windup limiters)']); end fprintf(fid, '\n%% \n%%Author: File automatically generated by PSAT'); fprintf(fid, '\n%%Date: %s',date); % global variables fprintf(fid, ['\n\nglobal ',c_name,' DAE Bus Settings']); % ************************************************************************ % general settings fprintf(fid, '\n'); for i=1:State.n fprintf(fid,'\n%s = DAE.x(%s.%s);',State.name{i},c_name, ... State.name{i}); end if Algeb.n idx_v = strmatch('V',Algeb.name); idx_a = strmatch('t',Algeb.name); if idx_v num_v = strrep(Algeb.name(idx_v),'V',''); if Buses.n == 1 fprintf(fid,'\n%s = DAE.y(%s.bus+Bus.n);', ... Algeb.name{idx_v},c_name); else for i=1:length(idx_v) fprintf(fid,'\n%s = DAE.y(%s.bus%s+Bus.n);', ... Algeb.name{idx_v(i)},c_name,num_v{i}); end end end if idx_a num_a = strrep(Algeb.name(idx_a),'theta',''); if Buses.n == 1 fprintf(fid,'\n%s = DAE.y(%s.bus);', ... Algeb.name{idx_a},c_name); else for i=1:length(idx_a) fprintf(fid,'\n%s = DAE.y(%s.bus%s);', ... Algeb.name{idx_a(i)},c_name,num_a{i}); end end end end for i=1:Param.n fprintf(fid,'\n%s = %s.con(:,%d);',Param.name{i},c_name,pidx(i)); end for i=1:n_xmax, fprintf(fid,'\n%s = %s.con(:,%d);',State.limit{x_max(i),1}, ... c_name,endp+i); end for i=1:n_xmin, fprintf(fid,'\n%s = %s.con(:,%d);',State.limit{x_min(i),2}, ... c_name,endp+n_xmax+i); end for i=1:n_smax, fprintf(fid,'\n%s = %s.con(:,%d);',Servc.limit{s_max(i),1}, ... c_name,endp+n_xmax+n_xmin+i); end for i=1:n_smin, fprintf(fid,'\n%s = %s.con(:,%d);',Servc.limit{s_min(i),2}, ... c_name,endp+n_xmax+n_xmin+n_smax+i); end for i=1:Initl.n, fprintf(fid,'\n%s = %s.dat(:,%d);',Initl.name{i},c_name,i); end for i=1:nidx, fprintf(fid,'\n%s = %s.dat(:,%d);',Servc.eqidx{iidx(i)},c_name, ... Initl.n+i); end % ********************************************************************** % initialization if Comp.init fprintf(fid, '\n\nswitch flag\n case 0 %% initialization'); msg = ['Component']; idx_T = [1:State.n]; idx = strmatch('None',State.time,'exact'); idx_T(idx) = []; if idx_T fprintf(fid,'\n\n %%check time constants'); end for i=1:length(idx_T), fprintf(fid,['\n idx = find(%s == 0);\n if idx\n ', ... Comp.name,'warn(idx, ''Time constant %s ', ... 'cannot be zero. %s = 0.001 s will be used.''),\n ' ... 'end'],State.time{idx_T(i)}, ... State.time{idx_T(i)},State.time{idx_T(i)}); fprintf(fid,'\n %s.con(idx,%d) = 0.001;', ... c_name,pidx(strmatch(State.time{idx_T(i)}, ... Param.name,'exact'))); end fprintf(fid,'\n\n %%variable initialization'); for i=1:State.n, fprintf(fid,'\n DAE.x(%s.%s) = %s;',c_name,State.name{i},state_init{i}); fprintf(fid,'\n %s = DAE.x(%s.%s);',State.name{i},c_name,State.name{i}); end for i=1:nidx, fprintf(fid,'\n %s.dat(:,%d) = %s;',Initl.n+i,c_name,vectorize(Servc.eq{i})); fprintf(fid,'\n %s = %s.dat(:,%d);',Servc.eqidx{iidx(i)},c_name,Initl.n+i); end for i=1:Initl.n fprintf(fid,'\n %s.dat(:,%d) = %s;',c_name,i, ... strrep(Initl.name{i},'_0','')); end fprintf(fid,'\n\n %%check limits'); for i=1:n_xmax fprintf(fid,['\n idx = find(%s > %s_max); if idx, ', ... Comp.name,'warn(idx, '' State variable %s ', ... 'is over its maximum limit.''), end'], ... State.name{x_max(i)},State.name{x_max(i)}, ... State.name{x_max(i)}); end for i=1:n_xmin fprintf(fid,['\n idx = find(%s < %s_min); if idx, ', ... Comp.name,'warn(idx, '' State variable %s ', ... 'is under its minimum limit.''), end'], ... State.name{x_min(i)},State.name{x_min(i)}, ... State.name{x_min(i)}); end for i=1:n_smax fprintf(fid,['\n idx = find(%s > %s_max); if idx, ', ... Comp.name,'warn(idx, '' State variable %s ', ... 'is over its maximum limit.''), end'], ... Servc.name{s_max(i)},Servc.name{s_max(i)}, ... Servc.name{s_max(i)}); end for i=1:n_smin fprintf(fid,['\n idx = find(%s < %s_min); if idx, ', ... Comp.name,'warn(idx, '' State variable %s ', ... 'is under its minimum limit.''), end'], ... Servc.name{s_min(i)},Servc.name{s_min(i)}, ... Servc.name{s_min(i)}); end fprintf(fid,['\n fm_disp(''Initialization of ',c_name, ... 'components completed.'')\n']); end % ********************************************************************** % algebraic equations if ~isempty(algeb_eq) if Comp.init fprintf(fid, '\n case 1 %% algebraic equations\n'); else fprintf(fid, '\n\nswitch flag\n case 1 %% algebraic equations\n'); end end aidx = [1:Algeb.neq]; idx = strmatch('null',Algeb.eq); aidx(idx) = []; idx = strmatch('0',Algeb.eq); aidx(idx) = []; for i = 1:length(aidx) if Buses.n == 1 a1 = ''; else a1 = num2str(ceil(aidx(i)/2)); end if rem(aidx(i),2) fprintf(fid,'\n DAE.g = DAE.g + sparse(%s.bus%s,1,%s,DAE.m,1);', ... c_name,a1,vectorize(Algeb.eq{aidx(i)})); else fprintf(fid,'\n DAE.g = DAE.g + sparse(%s.bus%s+Bus.n,1,%s,DAE.m,1);', ... c_name,a1,vectorize(Algeb.eq{aidx(i)})); end end % ******************************************************************** % algebraic Jacobians % substitution of inner service variables for j = 1:5 for i = 1:Servc.neq if strcmp(Servc.type{i},'Inner') && ~strcmp(Servc.eq{i},'null') state_eq = strrep(state_eq,Servc.eqidx{i},['(',Servc.eq{i},')']); algeb_eq = strrep(algeb_eq,Servc.eqidx{i},['(',Servc.eq{i},')']); servc_eq = strrep(servc_eq,Servc.eqidx{i},['(',Servc.eq{i},')']); end end end if ~isempty(algeb_eq) fprintf(fid, '\n\n case 2 %% algebraic Jacobians\n'); end eqformat = '\n DAE.J%d%d = DAE.J%d%d + sparse(%s.bus%s,%s.bus%s,%s,Bus.n,Bus.n);'; for j = 1:length(aidx) i = aidx(j); a1 = 2-rem(i,2); if Buses.n == 1 a2 = ''; else a2 = num2str(ceil(i/2)); end for h = 1:Algeb.n type = Algeb.name{h,1}; if strcmp(type(1), 'V'); a3 = 2; if Buses.n == 1 a4 = ''; else a4 = type(2:length(type)); end elseif strcmp(type(1:5), 'theta'); a3 = 1; if Buses.n == 1 a4 = ''; else a4 = type(6:length(type)); end end if ~strcmp(char(Gy(i,h)),'0') fprintf(fid,eqformat,a1,a3,a1,a3,c_name,a2,c_name,a4, ... vectorize(char(Gy(i,h)))); end end end % check limits in case of state variable dependancies Temp = 0; for i = 1:Servc.neq; Temp = ~strcmp(Servc.limit{i},'None'); break; end S = 0; if Temp for i = 1:Servc.neq; S = ~strcmp(Servc.type{i},'Input'); break; end end if S fprintf(fid,'\n'); for i = 1:length(Servc.eqidx) s_var = Servc.eqidx{i}; for k = 1:Servc.neq; if strcmp(s_var,Servc.name{k}); break; end; end if ~strcmp(Servc.type{k},'Input') && ~isempty(findstr(algeb_eq,s_var)) a = strcmp(Servc.limit{k,1},'None'); b = strcmp(Servc.limit{k,2},'None'); if ~a || ~b fprintf(fid, ['\n if (']); if ~a fprintf(fid,[Servc.name{k},'(i) <= ',Servc.name{k},'_max(i)']); else fprintf(fid,'('); end if ~a && ~b fprintf(fid,' || '); end if ~b fprintf(fid,[Servc.name{k},'(i) >= ',Servc.name{k},'_min(i))']); else fprintf(fid,')'); end fprintf(fid,'\n end'); end end end end % ********************************************************************* % differential & service equations if ~isempty(state_eq) if Comp.init || ~isempty(algeb_eq) fprintf(fid, '\n\n case 3 %% differential equations\n'); else fprintf(fid, '\n\nswitch flag\n case 3 %% differential equations\n'); end end for i = 1:Servc.neq Temp = Servc.type{i}; if strcmp(Temp,'Inner') s_eq = vectorize(Servc.eq{i}); fprintf(fid,['\n ',Servc.name{i},' = ',s_eq,';']); if ~strcmp(Servc.limit{i,1},'None') fprintf(fid, ['\n ',Servc.name{i}, ... ' = min(',Servc.name{i},',',Servc.name{i},'_max);']); end if ~strcmp(Servc.limit{i,2},'None') fprintf(fid, ['\n ',Servc.name{i}, ... ' = max(',Servc.name{i},',',Servc.name{i},'_min);']); end end end for i = 1:State.n if strcmp(State.nodyn{i},'Yes') fprintf(fid, ['\n no_dyn_',State.name{i},' = find(',State.time{i},' == 0);']); fprintf(fid, ['\n ', State.time{i}, '(no_dyn_',State.name{i},') = 1;']); end if strcmp(State.time{i},'None') s_eq = vectorize(State.eq{i}); else s_eq = vectorize(['(',State.eq{i},')/',State.time{i}]); end fprintf(fid, ['\n DAE.f(',c_name,'.',State.name{i},') = ',s_eq,';']); if strcmp(State.nodyn{i},'Yes') fprintf(fid, ['\n DAE.f(',c_name,'.',State.name{i},'(no_dyn_',State.name{i},')) = 0;']); end end if State.n > 0; if strcmp(State.nodyn{State.n},'Yes'); fprintf(fid, '\n'); end; end % set hard limits fprintf(fid,'\n %% non-windoup limits'); limfor1 = '\n idx = find(%s >= %s_max && DAE.f(%s) > 0);'; limfor2 = '\n if idx, DAE.f(%s(idx)) = 0; end'; limfor3 = '\n DAE.x(%s) = min(%s,%s_max);'; limfor4 = '\n idx = find(%s <= %s_min && DAE.f(%s) < 0);'; limfor5 = '\n DAE.x(%s) = max(%s,%s_min);'; for i = 1:State.n varidx = [c_name,'.',State.name{i}]; a = strcmp(State.limit{i,1},'None'); if ~a fprintf(fid,limfor1,State.name{i},State.name{i},varidx); fprintf(fid,limfor2,State.name{i}); fprintf(fid,limfor3,varidx,State.name{i},State.name{i}); end b = strcmp(State.limit{i,2},'None'); if ~b fprintf(fid,limfor4,State.name{i},State.name{i},varidx); fprintf(fid,limfor2,State.name{i}); fprintf(fid,limfor5,varidx,State.name{i},State.name{i}); end end fprintf(fid, '\n'); numdata = Initl.n; for i = 1:Servc.neq Temp = Servc.type{i}; if okdata && strcmp(Temp,'Inner') numdata = numdata + 1; fprintf(fid,['\n ',c_name,'.dat(:,',int2str(numdata),') = ', Servc.name{i},';']); elseif strcmp(Temp,'Output') numdata = numdata + 1; s_eq = vectorize(Servc.eq{i}); TempT = [c_name,'.dat(:,',int2str(numdata),')']; fprintf(fid,['\n ',TempT,' = ',s_eq,';']); zz = ['z(',Servc.name{i},'_',Comp.name,'_idx)']; if ~strcmp(Servc.limit{i,1},'None') fprintf(fid, ['\n ',TempT,' = min(',TempT,',',Servc.name{i},'_max);']); end if ~strcmp(Servc.limit{i,2},'None') fprintf(fid, ['\n ',TempT,' = max(',TempT,',',Servc.name{i},'_min);']); end fprintf(fid,['\n ',zz,' = ',zz,' + ',TempT,';']); end end fprintf(fid, '\n'); % ********************************************************************* % state variable Jacobians if ~isempty(state_eq) fprintf(fid, '\n\n case 4 %% state variable Jacobians\n'); end % DAE.Fx for j = 1:State.n if strcmp(State.nodyn{j},'Yes') fprintf(fid, ['\n no_dyn_',State.name{j},' = find(',State.time{j},' == 0);']); fprintf(fid, ['\n ', State.time{j}, '(no_dyn_',State.name{j},') = 1;']); end end fprintf(fid, '\n'); if State.n, fprintf(fid,'\n %% DAE.Fx'); end fxformat = '\n DAE.Fx = DAE.Fx + sparse(%s,%s,%s,DAE.n,DAE.n);'; for j = 1:State.n x_idx1 = [c_name,'.',State.name{j}]; for i = 1:State.n x_idx2 = [c_name,'.',State.name{i}]; if strcmp(State.time{j},'None') && ~strcmp(char(Fx(j,i)),'0') fxexp = vectorize(char(Fx(j,i))); else fxexp = ['(',vectorize(char(Fx(j,i))),')./',State.time{j}]; end if ~strcmp(fxexp,['(0)./',State.time{j}]) fprintf(fid,fxformat,x_idx1,x_idx2,fxexp); end end end fprintf(fid,'\n'); % DAE.Fy if State.n && Algeb.n, fprintf(fid,'\n %% DAE.Fy'); end fyformat = '\n DAE.Fy = DAE.Fy + sparse(%s,%s,%s,DAE.n,DAE.m);'; for j = 1:State.n x_idx1 = [c_name,'.',State.name{j}]; for i = 1:Algeb.n type = Algeb.name{i}; if strcmp(type(1),'V') if Buses.n == 1 x_idx2 = [c_name,'.bus','','+Bus.n']; else x_idx2 = [c_name,'.bus',type(2:length(type)),'+Bus.n']; end elseif strcmp(type(1:5),'theta') if Buses.n == 1 x_idx2 = [c_name,'.bus','']; else x_idx2 = [c_name,'.bus',type(6:length(type))]; end end if strcmp(State.time{j},'None') && ~strcmp(char(Fy(j,i)),'0') fyexp = vectorize(char(Fy(j,i))); else fyexp = ['(',vectorize(char(Fy(j,i))),')./',State.time{j}]; end if ~strcmp(fyexp,['(0)./',State.time{j}]) fprintf(fid,fyformat,x_idx1,x_idx2,fyexp); end end end fprintf(fid,'\n'); % DAE.Gx if State.n && Algeb.n, fprintf(fid,'\n %% DAE.Gx'); end gxformat = '\n DAE.Gx = DAE.Gx + sparse(%s,%s,%s,DAE.m,DAE.n);'; for j = 1:Algeb.neq if ~strcmp(Algeb.eq{1},'null') type = Algeb.eqidx{j,1}; if strcmp(type(1),'P') if Buses.n == 1 a_idx = [c_name,'.bus','']; else a_idx = [c_name,'.bus',type(2:length(type))]; end elseif strcmp(type(1),'Q') if Buses.n == 1 a_idx = [c_name,'.bus','','+Bus.n']; else a_idx = [c_name,'.bus',type(2:length(type)),'+Bus.n']; end end for h = 1:State.n x_idx = [c_name,'.',State.name{h}]; algexp = vectorize(char(Gx(j,h))); if ~strcmp(algexp,'0') fprintf(fid,gxformat,a_idx,x_idx,algexp); end end end end %if State.n > 0, fprintf(fid, ['\n\n end']); end % *************************************************************** % non-windup limiters if n_xmax || n_xmin fprintf(fid, '\n\n case 5 %% non-windup limiters\n'); for i = 1:State.n M = ~strcmp(State.limit{i,1},'None'); m = ~strcmp(State.limit{i,2},'None'); if M || m fprintf(fid, ['\n idx = find((']); if M, fprintf(fid,'%s >= %s_max',State.name{i},State.name{i}); end if M && m; fprintf(fid,' || '); end if m, fprintf(fid,'%s <= %s_min',State.name{i},State.name{i}); end fprintf(fid,[') && DAE.f(',c_name,'.%s) == 0);'],State.name{i}); fprintf(fid, '\n if ~isempty(idx)'); fprintf(fid,['\n k = ',c_name,'.%s(idx);'],State.name{i}); fprintf(fid,['\n DAE.tn(k) = 0;']); fprintf(fid,['\n DAE.Ac(:,k) = 0;']); fprintf(fid,['\n DAE.Ac(k,:) = 0;']); fprintf(fid,['\n DAE.Ac = DAE.Ac - sparse(k,k,1,DAE.m+DAE.n,DAE.m+DAE.n);']); fprintf(fid,['\n end']); end end end fprintf(fid, '\n\nend\n'); % ******************************************************************* % warning message function fprintf(fid,'\n\n%% -------------------------------------------------------------------'); fprintf(fid,'\n%% function for creating warning messages'); fprintf(fid,['\nfunction ',Comp.name,'warn(idx, msg)']); %fprintf(fid,['\nglobal ',c_name]); fprintf(fid,['\nfm_disp(fm_strjoin(''Warning: ',upper(Comp.name),' #'',int2str(idx),msg))']); % close component file and return fclose(fid); fm_choice(['Function "fm_',Comp.name,'" built.'],2) % **************************************************************** function vect = varvect(vect,sep) n = length(sep)-1; if iscell(vect) vect = fm_strjoin(vect,'#'); vect = strrep([vect{:}],'#',sep); vect(end-n:end) = []; end
github
Sinan81/PSAT-master
symfault.m
.m
PSAT-master/psat-mat/psat/symfault.m
4,578
utf_8
7a0f660fadb898109463adb029ac24ae
% The program symfault is designed for the balanced three-phase % fault analysis of a power system network. The program requires % the bus impedance matrix Zbus. Zbus may be defined by the % user, obtained by the inversion of Ybus or it may be % determined either from the function Zbus = zbuild(zdata) % or the function Zbus = zbuildpi(linedata, gendata, yload). % The program prompts the user to enter the faulted bus number % and the fault impedance Zf. The prefault bus voltages are % defined by the reserved Vector V. The array V may be defined or % it is returned from the power flow programs lfgauss, lfnewton, % decouple or perturb. If V does not exist the prefault bus voltages % are automatically set to 1.0 per unit. The program obtains the % total fault current, the postfault bus voltages and line currents. % % Copyright (C) 1998 H. Saadat function symfault(zdata, Zbus, V) fm_var if ~autorun('Short Circuit Analysis',0) return end if isempty(Fault.con) fm_disp('No fault found', 2) return end zdata = Line.con; [Zbus, zdata]= zbuildpi(zdata, Syn.con); nl = zdata(:,1); nr = zdata(:,2); R = zdata(:,3); X = zdata(:,4); nc = length(zdata(1,:)); if nc > 4 BC = zdata(:,11); elseif nc == 4 BC = zeros(length(zdata(:,1)), 1); end ZB = R + j*X nbr = length(zdata(:,1)); nbus = max(max(nl), max(nr)); if exist('V') == 1 if length(V) == nbus V0 = V; end else V0 = ones(nbus, 1) + j*zeros(nbus, 1); end fprintf('\nThree-phase balanced fault analysis \n') for ff = 1:Fault.n nf = Fault.bus(ff); fprintf('Faulted bus No. = %g \n', nf) fprintf('\n Fault Impedance Zf = R + j*X = ') Zf = Fault.con(ff,7) + j*Fault.con(ff,8); fprintf('%8.5f + j(%8.5f) \n', real(Zf), imag(Zf)) fprintf('Balanced three-phase fault at bus No. %g\n', nf) If = V0(nf)/(Zf + Zbus(nf, nf)); Ifm = abs(If); Ifmang = angle(If)*180/pi; fprintf('Total fault current = %8.4f per unit \n\n', Ifm) fprintf('Bus Voltages during fault in per unit \n\n') fprintf(' Bus Voltage Angle\n') fprintf(' No. Magnitude degrees\n') for n = 1:nbus if n == nf Vf(nf) = V0(nf)*Zf/(Zf + Zbus(nf,nf)); Vfm = abs(Vf(nf)); angv = angle(Vf(nf))*180/pi; else Vf(n) = V0(n) - V0(n)*Zbus(n,nf)/(Zf + Zbus(nf,nf)); Vfm = abs(Vf(n)); angv=angle(Vf(n))*180/pi; end fprintf(' %4g', n), fprintf('%13.4f', Vfm),fprintf('%13.4f\n', angv) end fprintf(' \n') fprintf('Line currents for fault at bus No. %g\n\n', nf) fprintf(' From To Current Angle\n') fprintf(' Bus Bus Magnitude degrees\n') for n = 1:nbus %Ign=0; for I = 1:nbr if nl(I) == n || nr(I) == n if nl(I) == n k = nr(I); elseif nr(I) == n k = nl(I); end if k==0 Ink = (V0(n) - Vf(n))/ZB(I); Inkm = abs(Ink); th = angle(Ink); %if th <= 0 if real(Ink) > 0 fprintf(' G '), fprintf('%7g',n), fprintf('%12.4f', Inkm) fprintf('%12.4f\n', th*180/pi) elseif real(Ink) ==0 && imag(Ink) < 0 fprintf(' G '), fprintf('%7g',n), fprintf('%12.4f', Inkm) fprintf('%12.4f\n', th*180/pi) end Ign = Ink; elseif k ~= 0 Ink = (Vf(n) - Vf(k))/ZB(I)+BC(I)*Vf(n); %Ink = (Vf(n) - Vf(k))/ZB(I); Inkm = abs(Ink); th=angle(Ink); %Ign=Ign+Ink; %if th <= 0 if real(Ink) > 0 fprintf('%7g', n) fprintf('%10g', k), fprintf('%12.4f', Inkm) fprintf('%12.4f\n', th*180/pi) elseif real(Ink) ==0 && imag(Ink) < 0 fprintf('%7g', n) fprintf('%10g', k), fprintf('%12.4f', Inkm) fprintf('%12.4f\n', th*180/pi) end end end end if n == nf % show Fault Current fprintf('%7g',n) fprintf(' F') fprintf('%12.4f', Ifm) fprintf('%12.4f\n', Ifmang) end end resp=0; %while strcmp(resp, 'n')~=1 && strcmp(resp, 'N')~=1 && strcmp(resp, 'y')~=1 && strcmp(resp, 'Y')~=1 %resp = input('Another fault location? Enter ''y'' or ''n'' within single quote -> '); %if strcmp(resp, 'n')~=1 && strcmp(resp, 'N')~=1 && strcmp(resp, 'y')~=1 && strcmp(resp, 'Y')~=1 %fprintf('\n Incorrect reply, try again \n\n'), end %end %if resp == 'y' || resp == 'Y' nf = 999; %else ff = 0; %end end % end for while fm_disp(['Finished "',filedata,'"']),
github
Sinan81/PSAT-master
fm_plot.m
.m
PSAT-master/psat-mat/psat/fm_plot.m
29,891
utf_8
e2aeca5f9c574ad045538279e9f72007
function fm_plot(flag) % FM_PLOT plot results of Continuation Power Flow, % Optimal Power Flow and Time Domain % Simulations. % % FM_PLOT(FLAG) % FLAG 0 -> create variable list % 1 -> plot selected variables % 2 -> save graph % 3 -> set layout % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 25-Feb-2003 %Update: 26-Jan-2005 %Version: 1.0.2 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global DAE Bus Syn Settings Fig Snapshot Hdl CPF Theme global Varout Varname Path File OPF Line Mass SSR Pmu %hdls = get(Fig.plot, 'Children') %display(hdls) hdlfig = findobj(Fig.plot, 'Tag','Axes1'); hdlfig2 = findobj(Fig.plot, 'Tag','Axes2'); Hdl_grid = findobj(Fig.plot,'Tag','Checkbox1'); Hdl_legend = findobj(Fig.plot,'Tag','Checkbox2'); Hdl_listvar = findobj(Fig.plot,'Tag','Listbox1'); Hdl_listplot = findobj(Fig.plot,'Tag','Listbox2'); Hdl_tipoplot = findobj(Fig.plot,'Tag','PopupMenu1'); Hdl_angref = findobj(Fig.plot,'Tag','PopupMenu2'); Hdl_snap = findobj(Fig.plot,'Tag','Radiobutton1'); hdl_zoom1 = findobj(Fig.plot,'Tag','Pushbutton12'); hdl_zoom2 = findobj(Fig.plot,'Tag','Pushbutton11'); hdl_zoom3 = findobj(Fig.plot,'Tag','Pushbutton4'); hdl_x = findobj(Fig.plot,'Tag','Pushbutton9'); hdl_y = findobj(Fig.plot,'Tag','Pushbutton5'); hdl_xy = findobj(Fig.plot,'Tag','Pushbutton10'); switch flag case 'exporttext', % output data as plain text file flag = 'plotvars'; out_matlab = 0; out_mtv = 0; out_text = 1; case 'exportmtv', % output data as plain text file flag = 'plotvars'; out_matlab = 0; out_mtv = 1; out_text = 0; case 'exportscript', % output data as plain text file flag = 'plotvars'; out_matlab = 1; out_mtv = 0; out_text = 0; otherwise out_matlab = 0; out_mtv = 0; out_text = 0; end switch flag case 'initlist' if ~strcmp(get(Fig.plot,'UserData'),File.modify) set(Hdl_listvar, ... 'String',enum(Varname.uvars(Varout.idx)), ... 'Value',1); if Settings.hostver < 8.04 set(Fig.plot,'DefaultAxesColorOrder',Settings.color, ... 'DefaultAxesLineStyle','-'); end end set(Fig.plot,'UserData',File.modify) Varname.pos = 1; case 'initxlabel' first = strrep(Settings.xlabel,'\',''); hdl = findobj(Fig.plot,'Tag','Listbox1'); stringa = get(hdl,'String'); hdl = findobj(Fig.plot,'Tag','PopupMenu3'); if ~isempty(stringa) set(hdl,'String',[{first}; stringa],'Enable','on','Value',1) end case 'plotvars' if isempty(Varout.t) fm_disp('Plotting Utilities: No data available for plotting.') return end if isempty(Varname.pos) fm_disp('Plotting Utilities: Select variables to be plotted.') return end nB = Bus.n; nD = DAE.n; Value = get(Hdl_listvar,'Value'); if isempty(Value), return, end hdlfig = findobj(Fig.plot, 'Tag', 'Axes1'); AxesFont = get(hdlfig,'FontName'); %AxesColor = get(hdlfig,'Color'); %if ~length(AxesColor) AxesColor = [1, 1, 1]; %end AxesWeight = get(hdlfig,'FontWeight'); AxesAngle = get(hdlfig,'FontAngle'); AxesSize = get(hdlfig,'FontSize'); AxesUnits = get(hdlfig,'FontUnits'); plot_snap = get(Hdl_snap,'Value'); snap_idx = zeros(length(Snapshot),1); if plot_snap && ~OPF.init for i = 1:length(Snapshot); a = find(Varout.t == Snapshot(i).time); if isempty(a) fm_disp('Plotting utilities: Snapshots do not match current simulation data',2) Hdl_rad1 = findobj(gcf,'Tag','Radiobutton1'); set(Hdl_rad1,'Value',0); plot_snap = 0; break else snap_idx(i) = a; end end end legenda = Varname.fvars(Varout.idx(Value(Varname.pos))); leg_value = get(Hdl_legend,'Value'); hdlab = findobj(Fig.plot,'Tag','PopupMenu3'); AbValue = get(hdlab,'Value'); Y = Varout.vars(:,Value); if isempty(Y), return, end % set angle unit if Settings.usedegree kdx = get_angle_idx(Value); Y(:,kdx) = 180*Y(:,kdx)/pi; end % set rotor speed unit and values if Settings.usehertz || Settings.userelspeed kdx = get_rotor_idx(Value); if Settings.userelspeed Y(:,kdx) = Y(:,kdx)-1; end if Settings.usehertz Y(:,kdx) = Settings.freq*Y(:,kdx); end end % set reference angle if ~OPF.init ang_idx = get(Hdl_angref,'Value')-1; if ~ang_idx angolo = zeros(length(Varout.t),1); else ref_idx = get(Hdl_angref,'UserData'); ang_ref = ref_idx(ang_idx); angolo = Varout.vars(:,ang_ref); end for i = 1:length(Value) kk = Varout.idx(Value(i)); if isdelta(Syn,kk) || isdelta(Mass,kk) || isdelta(SSR,kk) || isdelta(Pmu,kk) Y(:,i) = Y(:,i) - angolo; elseif kk >= nD+1 && kk <= nD+nB Y(:,i) = Y(:,i) - angolo; end end end hdlnorm = findobj(Fig.plot,'Tag','NormSij'); if strcmp(get(hdlnorm,'Checked'),'on') for i = 1:length(Value) kk = Varout.idx(Value(i)); Y(:,i) = isflow(Line,Y(:,i),kk); end end if AbValue == 1 X = Varout.t; else X = Varout.vars(:,AbValue-1); % set angle unit check = get_angle_idx(AbValue-1); if Settings.usedegree && ~isempty(check) X = 180*X/pi; end % set rotor speed unit and values if Settings.usehertz || Settings.userelspeed check = get_rotor_idx(AbValue-1); if Settings.userelspeed && check X = X-1; end if Settings.usehertz && check X = Settings.freq*X; end end end tipoplot = get(Hdl_tipoplot,'Value'); if out_text plainfile = fm_filenum('txt'); fid = fopen([Path.data,plainfile,'.txt'],'wt'); if fid == -1 fm_disp('Cannot open file. Data not saved.') return end fprintf(fid,'C Legend:\n'); fprintf(fid,'C %s, ',Settings.xlabel); for i = 1:size(Y,2) fprintf(fid,'%s, ',legenda{i}); end fprintf(fid,'\nC Data:\n'); fprintf(fid,[repmat('%8.5f ',1,1+size(Y,2)),'\n'],[X,Y]'); fclose(fid); fm_disp(['Data exported to plain text file "',plainfile,'.txt"']) end if out_mtv plainfile = fm_filenum('mtv'); fid = fopen([Path.data,plainfile,'.mtv'],'wt'); if fid == -1 fm_disp('Cannot open file. Data not saved.') return end %fprintf(fid,'$ DATA=CURVE2D\n'); fprintf(fid,'%% xlabel = "%s"\n',Settings.xlabel); if min(X) < max(X) fprintf(fid,'%% xmin = %8.5f\n',min(X)); fprintf(fid,'%% xmax = %8.5f\n',max(X)); end fprintf(fid,'\n'); if tipoplot == 3 || tipoplot == 6 fm_disp('MTV format does not support numbered plots.') end for i = 1:size(Y,2) labelmtv = strrep(legenda{i},'{',''); labelmtv = strrep(labelmtv,'}',''); labelmtv = strrep(labelmtv,'_',' '); labelmtv = strrep(labelmtv,'\',''); fprintf(fid,'%% linelabel="%s"\n',labelmtv); switch tipoplot case 2 linetype = rem(i-1,10)+1; linecolor = 1; markertype = 0; markercolor = 1; case 4 linetype = 1; linecolor = 1; markertype = rem(i-1,13)+1; markercolor = 1; case 5 linetype = 1; linecolor = rem(i-1,10)+1; markertype = rem(i-1,13)+1; markercolor = linecolor; otherwise linetype = 1; linecolor = rem(i-1,10)+1; markertype = 0; markercolor = 1; end fprintf(fid,'%% linetype=%d linecolor=%d markertype=%d markercolor=%d\n', ... linetype,linecolor,markertype,markercolor); fprintf(fid,'%8.5f %8.5f\n',[X,Y(:,i)]'); fprintf(fid,'\n'); end fclose(fid); fm_disp(['Data exported to MTV plot file "',plainfile,'.mtv"']) end if out_matlab plainfile = fm_filenum('m'); fid = fopen([Path.data,plainfile,'.m'],'wt'); if fid == -1 fm_disp('Cannot open file. Data not saved.') return end fprintf(fid,'x_label = ''%s'';\n',Settings.xlabel); fprintf(fid,'\nvar_legend = {'); for i = 1:size(Y,2)-1 fprintf(fid,'''%s'', ',legenda{i}); end fprintf(fid,'''%s''};\n',legenda{end}); fprintf(fid,'\noutput_data = [ ...\n'); fprintf(fid,[repmat('%8.5f ',1,1+size(Y,2)),';\n'], ... [X(1:end-1),Y(1:end-1,:)]'); fprintf(fid,[repmat('%8.5f ',1,1+size(Y,2)),'];\n'], ... [X(end),Y(end,:)]'); fclose(fid); fm_disp(['Data exported to plain text file "',plainfile,'.m"']) end set(Fig.plot,'CurrentAxes',hdlfig); plot(X,Y(:,Varname.pos)); set(hdlfig, 'Tag', 'Axes1') if AbValue == 1 xlabel(Settings.xlabel); else xlabel(Varname.fvars{Varout.idx(AbValue-1)}); end if min(X) < max(X) set(hdlfig,'XLim',[min(X),max(X)]) end %legend if leg_value == 1 || Settings.hostver >= 7 if Settings.hostver >= 8.04 hleg = legend(legenda, 'Location', 'northeast'); else hleg = legend(legenda, 0); end Hdl.legend = hleg; set(hleg,'Color',AxesColor) hchild = get(hleg,'Child'); if ishandle(hchild) set(hchild(end), ... 'FontName',AxesFont, ... 'FontWeight',AxesWeight, ... 'FontAngle',AxesAngle) end end hdlfig = findobj(Fig.plot, 'Tag', 'Axes1'); % display(hdlfig) % axes(hdlfig) if tipoplot == 3 || tipoplot == 6 [quanti,tanti] = size(Y); colori = get(gcf,'DefaultAxesColorOrder'); for i = 1:tanti if plot_snap sequenza = snap_idx; else tmin = min(X); tmax = max(X); deltat = (tmax-tmin)/5; tmin = tmin + i*(tmax-tmin)/43; seqt = tmin:deltat:tmax; for j = 1:length(seqt), [valt, sequenza(j)] = min(abs(X-seqt(j))); end end hdl = text(X(sequenza),Y(sequenza,i),num2str(Varname.pos(i))); if tipoplot == 6, set(hdl,'Color',colori(rem(i-1,7)+1,:)); end end if leg_value == 1 || Settings.hostver >= 7 hdl = findobj(Fig.plot,'Tag','legend'); %get(hdl) oldh = gca; set(gca,'HandleVisibility','off') set(hdl,'Interruptible','on') h = findobj(hdl,'Type','line'); %get(hdl) for i = 1:tanti j = i*2; xdata = get(h(j),'XData'); ydata = get(h(j),'YData'); htext = text((xdata(2)-xdata(1))/2,ydata(1), ... int2str(tanti-i+1)); set(htext,'Color',get(h(j),'Color')); end set(oldh,'HandleVisibility','on') set(Fig.plot,'CurrentAxes',oldh); end elseif tipoplot == 4 || tipoplot == 5 [quanti,tanti] = size(Y); hold on simboli = {'o';'s';'d';'v';'^';'<';'>';'x'}; colori = get(Fig.plot,'DefaultAxesColorOrder'); for i = 1:tanti if plot_snap sequenza = snap_idx; if tanti == 1 && CPF.init y1 = get(hdlfig,'YLim'); yoff = 0.05*(y1(2)-y1(1)); for hh = 1:length(sequenza) text(X(sequenza(hh)), ... Y(sequenza(hh),Varname.pos(i))+yoff, ... Snapshot(hh).name) end end else tmin = min(X); tmax = max(X); deltat = (tmax-tmin)/5; tmin = tmin + i*(tmax-tmin)/43; seqt = tmin:deltat:tmax; for j = 1:length(seqt), [valt, sequenza(j)] = min(abs(X-seqt(j))); end end set(hdlfig,'LineStyle',simboli{rem(i-1,8)+1}, 'Tag', 'Axes1'); hmarker = plot(X(sequenza),Y(sequenza,Varname.pos(i))); set(hmarker,'MarkerSize',7,'MarkerFaceColor',AxesColor); if tipoplot == 5, set(hmarker,'Color',colori(rem(i-1,7)+1,:)); end end hold off; if leg_value == 1 || Settings.hostver >= 7 hdl = findobj(Fig.plot,'Tag','legend'); set(Fig.plot,'CurrentAxes',hdl); h = findobj(hdl,'Type','line'); for i = 1:tanti j = i*2; xdata = get(h(j),'XData'); ydata = get(h(j),'YData'); set(hdl,'LineStyle',simboli{rem(tanti-i,8)+1}); if Settings.hostver >= 7 hmarker = plot(hdl,(xdata(2)-xdata(1))/1.2,ydata(1)); else hmarker = plot((xdata(2)-xdata(1))/1.2,ydata(1)); end set(hmarker,'MarkerSize',7, ... 'Color',get(h(j),'Color'), ... 'MarkerFaceColor',AxesColor); end set(Fig.plot,'CurrentAxes',hdlfig); end end if get(Hdl_grid,'Value'); grid on; end if ~get(Hdl_legend,'Value') && Settings.hostver >= 7 && Settings.hostver < 8.04 legend(findobj(Fig.plot,'Tag','Axes1'),'hide') end set(get(hdlfig,'XLabel'), ... 'FontName',AxesFont, ... 'FontWeight',AxesWeight, ... 'FontAngle',AxesAngle, ... 'FontSize',AxesSize, ... 'FontUnits',AxesUnits) set(hdlfig, ... 'FontName',AxesFont, ... 'Color',AxesColor, ... 'FontWeight',AxesWeight, ... 'FontAngle',AxesAngle, ... 'FontSize',AxesSize, ... 'FontUnits',AxesUnits, ... 'Tag','Axes1') if ishandle(Fig.line), fm_plot('createlinelist'), end if get(hdl_x, 'Value'), fm_plot('axesx'), end if get(hdl_y, 'Value'), fm_plot('axesy'), end if get(hdl_xy,'Value'), fm_plot('axesxy'), end fm_plot plotvlims fm_plot plotslims set(hdlfig,'Position',[0.09 0.4050 0.4754 0.5000], 'Tag', 'Axes1') %display('ciao') %display(hdlfig) case 'export' % export the figure to file tag = get(gcbo,'Tag'); axs_pos = get(Hdl.axesplot,'Position'); fig_pos = get(Fig.plot,'Position'); pap_pos = get(Fig.plot,'PaperPosition'); pap_siz = get(Fig.plot,'PaperSize'); leg_value = get(Hdl_legend,'Value'); if leg_value pos_leg = get(Hdl.legend,'Position'); end shrink = 0.8; % axes scale factor set(Hdl.axesplot,'Position',[0.13 0.11 0.855 0.875]) set(Fig.plot,'Position',[fig_pos(1), fig_pos(2), ... fig_pos(3)*shrink, fig_pos(4)*shrink]) if leg_value pos_leg2(1) = 0.13 + 0.855*(pos_leg(1) - axs_pos(1))/axs_pos(3); pos_leg2(2) = 0.11 + 0.875*(pos_leg(2) - axs_pos(2))/axs_pos(4); pos_leg2(3) = pos_leg(3)*0.855/axs_pos(3); pos_leg2(4) = pos_leg(4)*0.875/axs_pos(4); set(Hdl.legend,'Position',pos_leg2); if pos_leg2(1)+pos_leg2(3) > 0.985 Resize = (pos_leg2(1)+pos_leg2(3))/0.985; fig_pos2 = [0.13 0.11 0.855 0.875]; fig_pos2(3) = fig_pos2(3)/Resize; fig_pos2(1) = fig_pos2(1)/Resize; pos_leg2(3) = pos_leg2(3)/Resize; pos_leg2(1) = pos_leg2(1)/Resize; set(Hdl.axesplot,'Position',fig_pos2) set(Hdl.legend,'Position',pos_leg2) end end if Settings.hostver > 5.03, set(Fig.plot,'PaperSize',[pap_siz(1)*shrink, pap_siz(2)*shrink]) end ppos(3) = pap_pos(3)*shrink; ppos(4) = pap_pos(4)*shrink; ppos(1) = (pap_siz(1)-ppos(3))/2; ppos(2) = (pap_siz(2)-ppos(4))/2; set(Fig.plot,'PaperPosition',ppos) ax2_pos = get(Hdl.axeslogo,'Position'); set(Hdl.axeslogo,'Position',[10 10 0.2 0.2]); Hdl_all = get(Fig.plot,'Children'); idx = find(Hdl_all==Hdl.axesplot); if idx, Hdl_all(idx) = []; end idx = find(Hdl_all==Hdl.axeslogo); if idx, Hdl_all(idx) = []; end if leg_value, idx = find(Hdl_all==Hdl.legend); if idx, Hdl_all(idx) = []; end end set(Hdl_all,'Visible','off'); lastwarn('') switch tag case 'PushEPS' nomefile = fm_filenum('eps'); print(Fig.plot,'-depsc',[Path.data,nomefile]) set(hdlfig,'Position',axs_pos); set(hdlfig2,'Position',ax2_pos); set(Fig.plot,'Position',fig_pos) set(Fig.plot,'PaperPosition',pap_pos) if Settings.hostver > 5.03, set(Fig.plot,'PaperSize',pap_siz) end set(Hdl_all,'Visible','on'); if leg_value set(Hdl.legend,'Position',pos_leg); end case 'PushMeta' print(Fig.plot,'-dmeta') set(hdlfig,'Position',axs_pos); set(hdlfig2,'Position',ax2_pos); set(Fig.plot,'Position',fig_pos) set(Fig.plot,'PaperPosition',pap_pos) if Settings.hostver > 5.03, set(Fig.plot,'PaperSize',pap_siz) end set(Hdl_all,'Visible','on'); if leg_value set(Hdl.legend,'Position',pos_leg); end case 'PushFig' figplot = Fig.plot; Fig.plot = -1; try figpos = get(0,'factoryFigurePosition'); axspos = get(0,'factoryAxesPosition'); figunit = get(0,'factoryFigureUnits'); axsunit = get(0,'factoryAxesUnits'); catch figpos = [100 100 660 520]; axspos = [0.1300 0.1100 0.7750 0.8150]; figunit = 'pixels'; axsunit = 'normalized'; end set(figplot, ... 'Units',figunit, ... 'Position',figpos, ... 'Menubar','figure', ... 'Name','', ... 'NumberTitle','on', ... 'CreateFcn','', ... 'DeleteFcn','', ... 'UserData',[], ... 'FileName','') set(Hdl.axesplot,'Color',[1 1 1],'Units',axsunit,'Position',axspos) if leg_value set(Hdl.legend,'Color',[1 1 1]) end delete(Hdl_all) delete(hdlfig2) fm_plotfig figure(figplot) end if ~isempty(lastwarn) && ~strcmp(lastwarn,'File not found or permission denied') fm_disp(lastwarn,2), end case 'plottypes' tipoplot = get(Hdl_tipoplot,'Value'); if Settings.hostver < 8.04 switch tipoplot case 1, set(Fig.plot, ... 'DefaultAxesColorOrder',Settings.color, ... 'DefaultAxesLineStyleOrder','-'); case 2, set(Fig.plot, ... 'DefaultAxesColorOrder',[ 0 0 0 ], ... 'DefaultAxesLineStyleOrder','-|-.|--|:'); case 3, set(Fig.plot, ... 'DefaultAxesColorOrder',[ 0 0 0 ], ... 'DefaultAxesLineStyleOrder','-'); case 4, set(Fig.plot, ... 'DefaultAxesColorOrder',[ 0 0 0 ], ... 'DefaultAxesLineStyleOrder','-'); otherwise, set(Fig.plot, ... 'DefaultAxesColorOrder',Settings.color, ... 'DefaultAxesLineStyleOrder','-'); end else switch tipoplot case 1, set(Fig.plot, ... 'DefaultAxesColorOrder',Settings.color, ... 'DefaultAxesLineStyleOrder','-'); otherwise, set(Fig.plot, ... 'DefaultAxesColorOrder',[ 0 0 0 ], ... 'DefaultAxesLineStyleOrder','-|-.|--|:'); end end fm_plot('plotvars') case 'editvarname' value = get(Hdl_listplot,'Value'); if ~isempty(get(Hdl_listplot,'String')) valori = get(Hdl_listvar,'Value'); val = valori(Varname.pos(value)); stringa = Varname.fvars(Varname.idx); nomeattuale = popupstr(Hdl_listplot); idx = findstr(nomeattuale,']'); nomeattuale = nomeattuale(idx+2:end); nomenuovo = fm_input('Input Formatted Text:', ... 'Legend Name',1,{stringa{val}}); if isempty(nomenuovo), return, end Varname.fvars{Varname.idx(val)} = nomenuovo{1}; set(Fig.plot,'UserData',stringa); fm_disp(['Formatted text of variable "', ... nomeattuale,'" has been changed in "', ... nomenuovo{1},'"']) else fm_disp('No variable selected') end case 'zoomy' zoom yon set(Fig.plot,'WindowButtonMotionFcn','fm_plot motion'); set(hdl_zoom1,'Value',0); set(hdl_zoom2,'Value',0); if get(hdl_zoom3,'Value') Settings.zoom = 'zoom yon'; else Settings.zoom = ''; zoom off end case 'axesy' if get(hdl_x,'Value') set(hdl_x,'Value',0) delete(findobj(allchild(hdlfig),'UserData','x axis')) end if get(hdl_xy,'Value') set(hdl_xy,'Value',0) delete(findobj(allchild(hdlfig),'UserData','x axis')) delete(findobj(allchild(hdlfig),'UserData','y axis')) end value = get(gcbo,'Value'); if value ylim = get(hdlfig,'YLim'); hold on h = plot([0 0],[ylim(1), ylim(2)],'k:'); set(h,'UserData','y axis') hold off else hdl_child = allchild(hdlfig); delete(findobj(hdl_child,'UserData','y axis')) end if ishandle(Fig.line), fm_plot('createlinelist'), end case 'axescolor' currentColor = get(hdlfig,'Color'); c = uisetcolor(currentColor); if ~isequal(c,currentColor) set(hdlfig,'Color',c) hdl_line = findobj(allchild(hdlfig),'Type','line'); set(hdl_line,'MarkerFaceColor',c) hlegend = findobj(Fig.plot,'Tag','legend'); set(hlegend,'Color',c) end case 'axesx' if get(hdl_y,'Value') set(hdl_y,'Value',0) delete(findobj(allchild(hdlfig),'UserData','y axis')) end if get(hdl_xy,'Value') set(hdl_xy,'Value',0) delete(findobj(allchild(hdlfig),'UserData','y axis')) delete(findobj(allchild(hdlfig),'UserData','x axis')) end value = get(gcbo,'Value'); if value xlim = get(hdlfig,'XLim'); hold on h = plot([xlim(1), xlim(2)], [0, 0],'k:'); set(h,'UserData','x axis') hold off else hdl_child = allchild(hdlfig); delete(findobj(hdl_child,'UserData','x axis')) end if ishandle(Fig.line), fm_plot('createlinelist'), end case 'axesxy' if get(hdl_x,'Value') set(hdl_x,'Value',0) delete(findobj(allchild(hdlfig),'UserData','x axis')) end if get(hdl_y,'Value') set(hdl_y,'Value',0) delete(findobj(allchild(hdlfig),'UserData','y axis')) end value = get(gcbo,'Value'); if value xlim = get(hdlfig,'XLim'); ylim = get(hdlfig,'YLim'); hold on h = plot([xlim(1), xlim(2)], [0, 0],'k:'); set(h,'UserData','x axis') h = plot([0, 0],[ylim(1), ylim(2)],'k:'); set(h,'UserData','y axis') hold off else hdl_child = allchild(hdlfig); try delete(findobj(hdl_child,'UserData','x axis')) catch % nothing to do end try delete(findobj(hdl_child,'UserData','y axis')) catch % nothing to do end end if ishandle(Fig.line), fm_plot('createlinelist'), end case 'zoomx' zoom xon set(Fig.plot,'WindowButtonMotionFcn','fm_plot motion'); set(hdl_zoom1,'Value',0); set(hdl_zoom3,'Value',0); if get(hdl_zoom2,'Value') Settings.zoom = 'zoom xon'; else Settings.zoom = ''; zoom off end case 'zoomxy' zoom on set(Fig.plot,'WindowButtonMotionFcn','fm_plot motion'); set(hdl_zoom2,'Value',0); set(hdl_zoom3,'Value',0); if get(hdl_zoom1,'Value') Settings.zoom = 'zoom on'; else Settings.zoom = ''; zoom off end case 'moveup' value = get(Hdl_listplot,'Value'); NameString = get(Hdl_listplot,'String'); Value = 1:length(NameString); if value > 1 dummy = Varname.pos(value); Varname.pos(value) = Varname.pos(value-1); Varname.pos(value-1) = dummy; dummy = Value(value); Value(value) = Value(value-1); Value(value-1) = dummy; set(Hdl_listplot, ... 'String',NameString(Value), ... 'Value',value-1); end case 'movedown' value = get(Hdl_listplot,'Value'); NameString = get(Hdl_listplot,'String'); Value = 1:length(NameString); if value < length(Varname.pos) && ~isempty(NameString) dummy = Varname.pos(value); Varname.pos(value) = Varname.pos(value+1); Varname.pos(value+1) = dummy; dummy = Value(value); Value(value) = Value(value+1); Value(value+1) = dummy; set(Hdl_listplot, ... 'String',NameString(Value), ... 'Value',value+1); end case 'togglegrid' if get(gcbo,'Value') grid on else grid off end case 'togglelegend' if Settings.hostver >= 8.04 % axes(findobj(Fig.plot, 'Tag', 'Axes1')) legend toggle elseif Settings.hostver >= 7 legend(findobj(Fig.plot,'Tag','Axes1'),'toggle') else onoff = {'off','on'}; if strcmp(get(gcbo,'Tag'),'PushLegend') set(Hdl_legend,'Value',~get(Hdl_legend,'Value')) set(gcbo,'Checked',onoff{get(Hdl_legend,'Value')+1}) value = get(Hdl_legend,'Value'); else hdl = findobj(Fig.plot,'Tag','PushLegend'); set(hdl,'Checked',onoff{get(gcbo,'Value')+1}) value = get(gcbo,'Value'); end if value fm_plot('plotvars') else legend off end end case 'listvars' Value = get(Hdl_listvar,'Value'); if isempty(Value), return, end NameString = get(Hdl_listvar,'String'); if isempty(NameString), return, end set(Hdl_listplot,'String',NameString(Value)); set(Hdl_listplot,'Value',1); Varname.pos = 1:length(Value); if strcmp(get(Fig.plot,'SelectionType'),'open'), fm_plot('plotvars') end case 'listlines' hdl = findobj(Fig.line,'Tag','Listbox1'); Value = get(hdl,'Value'); hdl_line = get(Fig.line,'UserData'); hdl_line = hdl_line(end:-1:1); fm_linedlg(hdl_line(Value)) case 'createlinelist' hdl_line = findobj(allchild(hdlfig),'Type','line'); variabili = get(Hdl_listplot,'String'); set(Fig.line,'UserData',hdl_line); hdl_list = findobj(Fig.line,'Tag','Listbox1'); line_string = cell(length(hdl_line),1); hdl_line = hdl_line(end:-1:1); for i = 1:length(hdl_line) if strcmp(get(hdl_line(i),'UserData'),'x axis') line_string{i,1} = ['x axis ',fvar(i,4)]; elseif strcmp(get(hdl_line(i),'UserData'),'y axis') line_string{i,1} = ['y axis ',fvar(i,4)]; elseif i <= length(variabili) line_string{i,1} = ['line ',fvar(i,4),variabili{i}]; else line_string{i,1} = ['symbol ',fvar(i,4), ... variabili{i-length(variabili)}]; end end set(hdl_list,'String',line_string,'Value',1); case 'axesprops' fm_axesdlg(hdlfig) case 'textprops' TextProp = uisetfont; if isstruct(TextProp) set(hdlfig,TextProp) set(get(hdlfig,'XLabel'),TextProp) set(get(hdlfig,'YLabel'),TextProp) set(get(hdlfig,'Title'),TextProp) if get(Hdl_legend,'Value') hlegend = findobj(Fig.plot,'Tag','legend'); hchild = get(hlegend,'Child'); set(hchild(end), ... 'FontName',TextProp.FontName, ... 'FontWeight', TextProp.FontWeight, ... 'FontAngle',TextProp.FontAngle) end end case 'setxlabel' value = get(gcbo,'Value'); set(gcbo,'Value',value(end)) if strcmp(get(Fig.plot,'SelectionType'),'open') fm_plot('plotvars') end case 'setangles' [idx,kdx] = get_angle_idx; set(gcbo,'String',[{'None'}; Varname.uvars(idx)],'UserData',kdx) case 'limits' status = get(gcbo,'Checked'); switch status case 'on' set(gcbo,'Checked','off') case 'off' set(gcbo,'Checked','on') end fm_plot plotvars case 'usedegrees' status = get(gcbo,'Checked'); switch status case 'on' Settings.usedegree = 0; set(gcbo,'Checked','off') case 'off' Settings.usedegree = 1; set(gcbo,'Checked','on') end fm_plot plotvars case 'usehertzs' status = get(gcbo,'Checked'); switch status case 'on' Settings.usehertz = 0; set(gcbo,'Checked','off') case 'off' Settings.usehertz = 1; set(gcbo,'Checked','on') end fm_plot plotvars case 'userelspeeds' status = get(gcbo,'Checked'); switch status case 'on' Settings.userelspeed = 0; set(gcbo,'Checked','off') case 'off' Settings.userelspeed = 1; set(gcbo,'Checked','on') end fm_plot plotvars case 'plotvlims' hdl = findobj(Fig.plot,'Tag','PlotVLim'); value = get(hdl,'Checked'); if ~strcmp(value,'on'), return, end xlimits = get(hdlfig,'XLim'); hold on plot(hdlfig,[xlimits(1) xlimits(2)],[0.9 0.9],'k:') plot(hdlfig,[xlimits(1) xlimits(2)],[1.1 1.1],'k:') hold off case 'plotslims' hdl = findobj(Fig.plot,'Tag','NormSij'); value = get(hdl,'Checked'); if ~strcmp(value,'on'), return, end xlimits = get(hdlfig,'XLim'); hold on plot(hdlfig,[xlimits(1) xlimits(2)],[1.0 1.0],'k:') hold off case 'lowestv' idx = find(Varname.idx > DAE.n+Bus.n && Varname.idx <= DAE.n+2*Bus.n); if isempty(idx), return, end out = Varout.vars(:,idx); vals = min(out,[],1); [y,jdx] = sort(vals); if length(jdx) > 3, jdx = jdx(1:3); end set(Hdl_listvar,'Value',idx(jdx)); fm_plot listvars fm_plot plotvars case 'highestv' idx = find(Varname.idx > DAE.n+Bus.n && Varname.idx <= DAE.n+2*Bus.n); if isempty(idx), return, end out = Varout.vars(:,idx); vals = max(out,[],1); [y,jdx] = sort(vals,2,'descend'); if length(jdx) > 3, jdx = jdx(1:3); end set(Hdl_listvar,'Value',idx(jdx)); fm_plot listvars fm_plot plotvars case 'highests' values = highests(Line); if isempty(values), return, end set(Hdl_listvar,'Value',values); fm_plot listvars fm_plot plotvars end if ~isempty(Settings.zoom), eval(Settings.zoom), end % ------------------------------------------------------------------------ % Some useful functions % ----------------------------------------------------------------------- function stringa = enum(stringa) for i = 1:length(stringa), stringa{i} = ['[',int2str(i),'] ',stringa{i}]; end function kdx = get_rotor_idx(idx) global DAE Syn COI Cswt Dfig Ddsg Busfreq Mass SSR Tg kdx = []; for i = 1:length(idx) kkk = idx(i); if kkk > DAE.n+DAE.m break elseif kkk <= DAE.n if isomega(Syn,kkk) || isomega(Cswt,kkk) || isomega(Dfig,kkk) ... || isomega(Ddsg,kkk) || isomega(Mass,kkk) || isomega(SSR,kkk) ... || isomega(Busfreq) kdx = [kdx, i]; end elseif isomega(COI,kkk) || isomega(Tg,kkk) kdx = [kdx, i]; end end function varargout = get_angle_idx(varargin) global Varout DAE Syn Bus COI Mass SSR Phs Svc Cswt Ddsg Dfig Pmu Hvdc idx = []; kdx = []; if ~nargin varidx = Varout.idx; else varidx = varargin{1}; end for i = 1:length(varidx) kkk = varidx(i); if kkk > DAE.n+DAE.m break elseif kkk <= DAE.n if isdelta(Syn,kkk) || isdelta(Mass,kkk) || isdelta(SSR,kkk) ... || isdelta(Phs,kkk) || isdelta(Svc,kkk) || isdelta(Cswt,kkk) ... || isdelta(Ddsg,kkk) || isdelta(Dfig,kkk) || isdelta(Pmu,kkk) idx = [idx, kkk]; kdx = [kdx, i]; end elseif kkk > DAE.n && kkk <= DAE.n+Bus.n idx = [idx, kkk]; kdx = [kdx, i]; elseif isdelta(COI,kkk) || isdelta(Hvdc,kkk) idx = [idx, kkk]; kdx = [kdx, i]; end end switch nargout case 1 varargout{1} = kdx; case 2 varargout{1} = idx; varargout{2} = kdx; end
github
Sinan81/PSAT-master
fm_uwfig.m
.m
PSAT-master/psat-mat/psat/fm_uwfig.m
36,174
utf_8
e21245f8662dfac8f223c8e9980016a2
function fig = fm_uwfig(varargin) % FM_UWFIG create GUI for PSAT/UWPFLOW interface. % % FIG = FM_UWFIG % %see UWPFLOW structure for settings % %Author: Federico Milano %Date: 31-Mar-2003 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Settings Path PQ UWPFLOW GAMS Theme Fig Hdl History % initialize UWPFLOW.opt, if necessary fm_uwpflow('init') % check for options if nargin, checkon(varargin{1}), return, end % do not redraw figure if open if ishandle(Fig.uwpflow), figure(Fig.uwpflow), return, end [u,w] = system('uwpflow'); if isempty(strmatch('UW Continuation Power Flow',w)) uiwait(fm_choice('UWPFLOW is not properly installed on your system.',2)) return end % constants and lists D = 0.9394; dy = 0.025; dx = (D-4*dy)/3; x1 = 0.0329 + dy; x2 = 0.0329 + 2*dy + dx; x3 = 0.0329 + 3*dy + 2*dx; methods = {'[ ] Power Flow'; '[-c] Continuation Method'; '[-C] Direct Method'; '[-H] Parameterized CM'}; output = {'.k'; '.v'; '.w'; '.pf'; '.jac'; '.cf'; '.cpf'; '.mis'; '.var'; '.log'; '.oh'; '.vp'; '.gen'; '.ini'; '.poc'; '.ntv'}; output = fm_strjoin(UWPFLOW.file,output); if PQ.n PQbuses = fm_strjoin('PQ_',num2str(PQ.bus)); if PQ.n < UWPFLOW.opt.B.num, UWPFLOW.opt.B.num = 1; end if PQ.n < UWPFLOW.opt.f.num, UWPFLOW.opt.f.num = 1; end if PQ.n < UWPFLOW.opt.one.num, UWPFLOW.opt.one.num = 1; end else PQbuses = {'<none>'}; end if strcmp(Settings.platform,'MAC') aligntxt = 'center'; dm = 0.0075; else aligntxt = 'left'; dm = 0; end h0 = figure('Units','normalized', ... 'Color',Theme.color02, ... 'Colormap',[], ... 'CreateFcn', 'Fig.uwpflow = gcf;', ... 'DeleteFcn', 'Fig.uwpflow = -1;', ... 'MenuBar','none', ... 'Name','PSAT-UWPFLOW', ... 'NumberTitle','off', ... 'PaperPosition',[18 180 576 432], ... 'PaperUnits','points', ... 'Position',sizefig(1.2*0.5645,1.1*0.8451), ... 'Resize','on', ... 'ToolBar','none', ... 'FileName','fm_uwfig'); fm_set colormap % Menu File h1 = uimenu('Parent',h0, ... 'Label','File', ... 'Tag','MenuFile'); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwpflow view', ... 'Label','View UWPFLOW Input/Output files', ... 'Tag','OTV', ... 'Accelerator','g'); h2 = uimenu('Parent',h1, ... 'Callback','close(gcf)', ... 'Label','Exit', ... 'Tag','NetSett', ... 'Accelerator','x', ... 'Separator','on'); % Menu Edit h1 = uimenu('Parent',h0, ... 'Label','Edit', ... 'Tag','MenuEdit'); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwpflow makecom', ... 'Label','Create UWPFLOW command line', ... 'Tag','ToolUWcom', ... 'Accelerator','c'); h2 = uimenu('Parent',h1, ... 'Callback','fm_setting', ... 'Label','General Settings', ... 'Tag','ToolSett', ... 'Separator', 'on', ... 'Accelerator','s'); % Menu Run h1 = uimenu('Parent',h0, ... 'Label','Run', ... 'Tag','MenuRun'); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwpflow uwrun', ... 'Label','Run UWPFLOW', ... 'Tag','ToolOPFSett', ... 'Accelerator','z'); % Menu Options h1 = uimenu('Parent',h0, ... 'Label','Options', ... 'Tag','MenuOpt'); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig a', ... 'Label','[-a] No tap/angle limit control', ... 'Tag','aopt', ... 'Checked',onoff(UWPFLOW.opt.a.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig A', ... 'Label','[-A] No intercahnge area control', ... 'Tag','Aopt', ... 'Checked',onoff(UWPFLOW.opt.A.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig b', ... 'Label','[-b] No interchange area control', ... 'Tag','bopt', ... 'Checked',onoff(UWPFLOW.opt.b.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig d', ... 'Label','[-d] Generate debug output', ... 'Tag','dopt', ... 'Checked',onoff(UWPFLOW.opt.d.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig g', ... 'Label','[-g] Force Qg to 0 (IEEE CDF)', ... 'Tag','gopt', ... 'Checked',onoff(UWPFLOW.opt.g.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig G', ... 'Label','[-G] Turn off ac device recovery', ... 'Tag','Gopt', ... 'Checked',onoff(UWPFLOW.opt.G.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig n', ... 'Label','[-n] Turn off all ac limits', ... 'Tag','nopt', ... 'Checked',onoff(UWPFLOW.opt.n.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig N', ... 'Label','[-N] Turn off all ac system controls', ... 'Tag','Nopt', ... 'Checked',onoff(UWPFLOW.opt.N.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig p', ... 'Label','[-p] Turn off P/Q limits in reg. transf.', ... 'Tag','popt', ... 'Checked',onoff(UWPFLOW.opt.p.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig P', ... 'Label','[-P] Turn off P/Q control by reg. transf.', ... 'Tag','Popt', ... 'Checked',onoff(UWPFLOW.opt.P.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig q', ... 'Label','[-q] Turn off Q limits in PV buses', ... 'Tag','qopt', ... 'Checked',onoff(UWPFLOW.opt.q.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig qx', ... 'Label','[-qx] Turn off V limits in BX buses', ... 'Tag','qxopt', ... 'Checked',onoff(UWPFLOW.opt.qx.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig qz', ... 'Label','[-qz] Turn off Q limits in BZ buses', ... 'Tag','qzopt', ... 'Checked',onoff(UWPFLOW.opt.qz.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig Q', ... 'Label','[-Q] Turn off remote Vg control', ... 'Tag','Qopt', ... 'Checked',onoff(UWPFLOW.opt.Q.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig QX', ... 'Label','[-QX] Turn off remote Vg control in BX buses', ... 'Tag','QXopt', ... 'Checked',onoff(UWPFLOW.opt.QX.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig r', ... 'Label','[-r] Turn off V limits in reg. tranf. and PV buses', ... 'Tag','ropt', ... 'Checked',onoff(UWPFLOW.opt.r.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig R', ... 'Label','[-R] Turn off V control by reg. transf.', ... 'Tag','Ropt', ... 'Checked',onoff(UWPFLOW.opt.R.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig s', ... 'Label','[-s] Suppress ASCII output file', ... 'Tag','sopt', ... 'Checked',onoff(UWPFLOW.opt.s.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig x', ... 'Label','[-x] Use single slack bus', ... 'Tag','xopt', ... 'Checked',onoff(UWPFLOW.opt.x.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig X', ... 'Label','[-X] Turn off max Pg limits', ... 'Tag','Xopt', ... 'Checked',onoff(UWPFLOW.opt.X.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig four', ... 'Label','[-4] Turn off Eq limits in all gen.', ... 'Tag','fouropt', ... 'Checked',onoff(UWPFLOW.opt.four.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig five', ... 'Label','[-5] Turn off Ia limits in all gen.', ... 'Tag','fiveopt', ... 'Checked',onoff(UWPFLOW.opt.five.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig seven', ... 'Label','[-7] Enforce Vmax and Vmin', ... 'Tag','sevenopt', ... 'Checked',onoff(UWPFLOW.opt.seven.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig eight', ... 'Label','[-8] Enforce Imax limits', ... 'Tag','eightopt', ... 'Checked',onoff(UWPFLOW.opt.eight.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig nine', ... 'Label','[-9] Do not enforce gen. Smax limits', ... 'Tag','nineopt', ... 'Checked',onoff(UWPFLOW.opt.nine.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig bound', ... 'Label','[-#] Use secondary voltage control', ... 'Tag','boundopt', ... 'Checked',onoff(UWPFLOW.opt.bound.status)); % Menu Output files h1 = uimenu('Parent',h0, ... 'Label','Output', ... 'Tag','MenuOut'); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig E', ... 'Label','[-E] Print PoC right e-vector', ... 'Tag','eopt', ... 'Checked',onoff(UWPFLOW.opt.E.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig j', ... 'Label','[-j] Write Jacobian matrix (2n+1)x(2n+1)', ... 'Tag','eopt', ... 'Checked',onoff(UWPFLOW.opt.j.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig J', ... 'Label','[-J] Write Jacobian matrix (2n)x(2n)', ... 'Tag','eopt', ... 'Checked',onoff(UWPFLOW.opt.j.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig E', ... 'Label','[-E] Print PoC right e-vector', ... 'Tag','eopt', ... 'Checked',onoff(UWPFLOW.opt.E.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig l', ... 'Label','[-l] Write standard error output', ... 'Tag','lopt', ... 'Checked',onoff(UWPFLOW.opt.l.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig w', ... 'Label','[-w] Write solution in IEEE CARD format', ... 'Tag','wopt', ... 'Checked',onoff(UWPFLOW.opt.w.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig W', ... 'Label','[-W] Write solution in IEEE TAPE format', ... 'Tag','wopt', ... 'Checked',onoff(UWPFLOW.opt.W.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig y', ... 'Label','[-y] Print left e-vector of smallest |e-value|', ... 'Tag','yopt', ... 'Checked',onoff(UWPFLOW.opt.y.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig Y', ... 'Label','[-Y] Print right e-vector of smallest |e-value|', ... 'Tag','Yopt', ... 'Checked',onoff(UWPFLOW.opt.Y.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig Z', ... 'Label','[-Z] Print normalized tangent vector', ... 'Tag','Zopt', ... 'Checked',onoff(UWPFLOW.opt.Z.status)); % Menu Preferences h1 = uimenu('Parent',h0, ... 'Label','Preferences', ... 'Tag','MenuPref'); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwpflow filename', ... 'Label','Modify input/output file name', ... 'Tag','OTV', ... 'Accelerator','e'); h2 = uimenu('Parent',h1, ... 'Callback','fm_tviewer', ... 'Label','Select Text Viewer', ... 'Tag','tvopt', ... 'Separator', 'on', ... 'Accelerator','t'); % Menu Help h1 = uimenu('Parent',h0, ... 'Label','Help', ... 'Tag','MenuHelp'); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwpflow help', ... 'Label','UWPFLOW help', ... 'Accelerator','h', ... 'Tag','UWHelp'); h2 = uimenu('Parent',h1, ... 'Callback','web(''http://thunderbox.uwaterloo.ca/~claudio/software/pflow.html'');', ... 'Label','UWPFLOW website', ... 'Accelerator','w', ... 'Tag','UWLink'); % Frame h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'ForegroundColor',Theme.color03, ... 'Position',[0.0329 0.1399 0.9394 0.8405], ... 'Style','frame', ... 'Tag','Frame1'); % List Boxes h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig B', ... 'HorizontalAlignment','left', ... 'Position',[x3 0.9199 dx 0.0339], ... 'String','[-B] Bus for fixed voltage:', ... 'Style','checkbox', ... 'Tag','Check_B', ... 'Value', UWPFLOW.opt.B.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.B.num = get(gcbo,''Value''); UWPFLOW.opt.B.num = UWPFLOW.opt.B.num(end); set(gcbo,''Value'',UWPFLOW.opt.B.num)', ... 'Enable', onoff(UWPFLOW.opt.B.status), ... 'FontName', Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'ListboxTop',UWPFLOW.opt.B.num, ... 'Max', 100, ... 'Position',[x3 0.7439 dx 0.1595], ... 'String',PQbuses, ... 'Style','listbox', ... 'Tag','Edit_B', ... 'Value',UWPFLOW.opt.B.num); dyy = 0.015; h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig f', ... 'HorizontalAlignment','left', ... 'Position',[x3 0.6835+dyy dx 0.0339], ... 'String','[-f] Bus for SF, VSF and TG:', ... 'Style','checkbox', ... 'Tag','Check_f', ... 'Value', UWPFLOW.opt.f.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.f.num = get(gcbo,''Value''); UWPFLOW.opt.f.num = UWPFLOW.opt.f.num(end); set(gcbo,''Value'',UWPFLOW.opt.f.num)', ... 'Enable', onoff(UWPFLOW.opt.f.status), ... 'FontName', Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'ListboxTop',UWPFLOW.opt.f.num, ... 'Max', 100, ... 'Position',[x3 0.5076+dyy dx 0.1595], ... 'String',PQbuses, ... 'Style','listbox', ... 'Tag','Edit_f', ... 'Value',UWPFLOW.opt.f.num); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig one', ... 'HorizontalAlignment','left', ... 'Position',[x3 0.4471+2*dyy dx 0.0339], ... 'String','[-1] Bus for test functions:', ... 'Style','checkbox', ... 'Tag','Check_one', ... 'Value', UWPFLOW.opt.one.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.one.num = get(gcbo,''Value''); UWPFLOW.opt.one.num = UWPFLOW.opt.one.num(end); set(gcbo,''Value'',UWPFLOW.opt.one.num)', ... 'Enable', onoff(UWPFLOW.opt.one.status), ... 'FontName', Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'ListboxTop',UWPFLOW.opt.one.num, ... 'Max', 100, ... 'Position',[x3 0.2712+2*dyy dx 0.1595], ... 'String',PQbuses, ... 'Style','listbox', ... 'Tag','Edit_one', ... 'Value',UWPFLOW.opt.one.num); % Popup Menus h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwpflow methods', ... 'FontName', Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment','left', ... 'Position',[x2 0.2712+2*dyy dx 0.0308], ... 'String',methods, ... 'Style','popupmenu', ... 'Tag','PopupMenuMethod', ... 'Value',UWPFLOW.method); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[x2 0.305+2*dyy dx 0.0308], ... 'String','Solver method:', ... 'Style','text', ... 'Tag','StaticText12'); h1 = uicontrol('Parent', h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', '', ... 'FontName', Theme.font01, ... 'HorizontalAlignment','left', ... 'Position',[x1 0.2712+2*dyy dx 0.0308], ... 'String',output, ... 'Style','popupmenu', ... 'Tag','PopupUWFile', ... 'Value',1); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[x1 0.305+2*dyy dx 0.0308], ... 'String','UWPFLOW input/output file:', ... 'Style','text', ... 'Tag','StaticText11'); % Pushbuttons h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color03, ... 'Callback','fm_uwpflow uwrun', ... 'FontWeight','bold', ... 'ForegroundColor',Theme.color09, ... 'Position',[x1 0.1576-2*dm dx 0.045+2*dm], ... 'String','Run UWPFLOW', ... 'Tag','Pushbutton1'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback','close(gcf)', ... 'Position',[x3 0.1576-2*dm dx 0.045+2*dm], ... 'String','Close', ... 'Tag','Pushbutton2'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_uwpflow view', ... 'Position',[x2 0.1576-2*dm dx 0.045+2*dm], ... 'String','View Input/Output File', ... 'Tag','Pushbutton3'); % UWPFLOW Command Line h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback','UWPFLOW.command = get(gcbo,''String'');', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment',aligntxt, ... 'Position',[x1 0.225 x3+dx-x1 0.0308+dm], ... 'Style','edit', ... 'String', UWPFLOW.command, ... 'Tag','EditCom'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[x1 0.225+0.0308+dm dx 0.0308], ... 'String','Command Line:', ... 'Style','text', ... 'Tag','TextCom'); % Parameters (left column) h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.F.num = fval(gcbo,UWPFLOW.opt.F.num);', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'Enable', onoff(UWPFLOW.opt.F.status), ... 'HorizontalAlignment',aligntxt, ... 'Position',[x1 0.8731 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.F.num), ... 'Tag','Edit_F'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig F', ... 'HorizontalAlignment','left', ... 'Position',[x1 0.9199 dx 0.0339], ... 'String','[-F] Stability/sparsity [0,1]', ... 'Style','checkbox', ... 'Tag','Check_F', ... 'Value', UWPFLOW.opt.F.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.t.num = fval(gcbo,UWPFLOW.opt.t.num)', ... 'Enable', onoff(UWPFLOW.opt.t.status), ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment',aligntxt, ... 'Position',[x1 0.7764 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.t.num), ... 'Tag','Edit_t'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'Callback', 'fm_uwfig t', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[x1 0.8232 dx 0.0339], ... 'String','[-t] Iteration mismatch tol.', ... 'Style','checkbox', ... 'Tag','Check_t', ... 'Value', UWPFLOW.opt.t.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback','UWPFLOW.opt.o.num = fval(gcbo,UWPFLOW.opt.o.num);', ... 'Enable', onoff(UWPFLOW.opt.o.status), ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment',aligntxt, ... 'Position',[x1 0.6798 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.o.num), ... 'Tag','Edit_o'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig o', ... 'HorizontalAlignment','left', ... 'Position',[x1 0.7266 dx 0.0339], ... 'String','[-o] Limit control tol.', ... 'Style','checkbox', ... 'Tag','Check_o', ... 'Value', UWPFLOW.opt.o.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.L.num = fval(gcbo,UWPFLOW.opt.L.num);', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'Enable', onoff(UWPFLOW.opt.L.status), ... 'HorizontalAlignment',aligntxt, ... 'Position',[x1 0.5831 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.L.num), ... 'Tag','Edit_L'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig L', ... 'HorizontalAlignment','left', ... 'Position',[x1 0.6299 dx 0.0339], ... 'String','[-L] Initial loading factor', ... 'Style','checkbox', ... 'Tag','Check_L', ... 'Value', UWPFLOW.opt.L.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.O.num = fval(gcbo,UWPFLOW.opt.O.num)', ... 'Enable', onoff(UWPFLOW.opt.O.status), ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment',aligntxt, ... 'Position',[x1 0.4865 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.O.num), ... 'Tag','Edit_O'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'Callback', 'fm_uwfig O', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[x1 0.5333 dx 0.0339], ... 'String','[-O] ac/dc TEF digits [6-10]', ... 'Style','checkbox', ... 'Tag','Check_O', ... 'Value', UWPFLOW.opt.O.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback','UWPFLOW.opt.S.num = fval(gcbo,UWPFLOW.opt.S.num);', ... 'Enable', onoff(UWPFLOW.opt.S.status), ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment',aligntxt, ... 'Position',[x1 0.3898 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.S.num), ... 'Tag','Edit_S'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig S', ... 'HorizontalAlignment','left', ... 'Position',[x1 0.4366 dx 0.0339], ... 'String','[-S] Max. loading factor [0,1]', ... 'Style','checkbox', ... 'Tag','Check_S', ... 'Value', UWPFLOW.opt.S.status); % Parameters (middle column) h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.k.num = fval(gcbo,UWPFLOW.opt.k.num);', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'Enable', onoff(UWPFLOW.opt.k.status), ... 'HorizontalAlignment',aligntxt, ... 'Position',[x2 0.8731 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.k.num), ... 'Tag','Edit_k'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig k', ... 'HorizontalAlignment','left', ... 'Position',[x2 0.9199 dx 0.0339], ... 'String','[-k] Loading factor increment', ... 'Style','checkbox', ... 'Tag','Check_k', ... 'Value', UWPFLOW.opt.k.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.u.num = fval(gcbo,UWPFLOW.opt.u.num)', ... 'Enable', onoff(UWPFLOW.opt.u.status), ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment',aligntxt, ... 'Position',[x2 0.7764 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.u.num), ... 'Tag','Edit_u'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'Callback', 'fm_uwfig u', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[x2 0.8232 dx 0.0339], ... 'String','[-u] Reduce eq. tol. [0,0.2]', ... 'Style','checkbox', ... 'Tag','Check_u', ... 'Value', UWPFLOW.opt.u.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback','UWPFLOW.opt.U.num = fval(gcbo,UWPFLOW.opt.U.num);', ... 'Enable', onoff(UWPFLOW.opt.U.status), ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment',aligntxt, ... 'Position',[x2 0.6798 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.U.num), ... 'Tag','Edit_U'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig U', ... 'HorizontalAlignment','left', ... 'Position',[x2 0.7266 dx 0.0339], ... 'String','[-U] Step # for sys. red. [2,100]', ... 'Style','checkbox', ... 'Tag','Check_U', ... 'Value', UWPFLOW.opt.U.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.v.num = fval(gcbo,UWPFLOW.opt.v.num);', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'Enable', onoff(UWPFLOW.opt.v.status), ... 'HorizontalAlignment',aligntxt, ... 'Position',[x2 0.5831 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.v.num), ... 'Tag','Edit_v'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig v', ... 'HorizontalAlignment','left', ... 'Position',[x2 0.6299 dx 0.0339], ... 'String','[-v] PQ bus voltage magnitude', ... 'Style','checkbox', ... 'Tag','Check_v', ... 'Value', UWPFLOW.opt.v.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.z.num = fval(gcbo,UWPFLOW.opt.z.num)', ... 'Enable', onoff(UWPFLOW.opt.z.status), ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment',aligntxt, ... 'Position',[x2 0.4865 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.z.num), ... 'Tag','Edit_z'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'Callback', 'fm_uwfig z', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[x2 0.5333 dx 0.0339], ... 'String','[-z] Max. # of CM steps', ... 'Style','checkbox', ... 'Tag','Check_z', ... 'Value', UWPFLOW.opt.z.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback','UWPFLOW.opt.two.num = fval(gcbo,UWPFLOW.opt.two.num);', ... 'Enable', onoff(UWPFLOW.opt.two.status), ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment',aligntxt, ... 'Position',[x2 0.3898 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.two.num), ... 'Tag','Edit_two'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig two', ... 'HorizontalAlignment','left', ... 'Position',[x2 0.4366 dx 0.0339], ... 'String','[-2] Step # for dir. change', ... 'Style','checkbox', ... 'Tag','Check_two', ... 'Value', UWPFLOW.opt.two.status); % Banner h1 = axes('Parent',h0, ... 'Box','on', ... 'CameraUpVector',[0 1 0], ... 'Color',Theme.color04, ... 'ColorOrder',Settings.color, ... 'Layer','top', ... 'Position',[0.0329 0.0169 0.8*0.1540 0.8*0.1371], ... 'Tag','Axes1', ... 'XColor',Theme.color02, ... 'XLim',[0.5 100.5], ... 'XLimMode','manual', ... 'XTick',[], ... 'YColor',Theme.color02, ... 'YDir','reverse', ... 'YLim',[0.5 100.5], ... 'YLimMode','manual', ... 'YTick',[], ... 'ZColor',[0 0 0]); if Settings.hostver < 8.04 h2 = image('Parent',h1, ... 'CData',fm_mat('logo_psat'), ... 'Tag','Axes1Image1', ... 'XData',[1 101], ... 'YData',[1 101]); else h2 = image('Parent',h1, ... 'CData',flipud(fliplr(fm_mat('logo_psat'))), ... 'Tag','Axes1Image1', ... 'XData',[1 101], ... 'YData',[1 101]); end h1 = axes('Parent',h0, ... 'Box','on', ... 'CameraUpVector',[0 1 0], ... 'Color',Theme.color02, ... 'ColorOrder',Settings.color, ... 'Layer','top', ... 'Position',[0.8491 0.0169 0.8*0.1540 0.8*0.1371], ... 'Tag','Axes1', ... 'XColor',Theme.color02, ... 'XLim',[0.5 100.5], ... 'XLimMode','manual', ... 'XTick',[], ... 'YColor',Theme.color02, ... 'YDir','reverse', ... 'YLim',[0.5 100.5], ... 'YLimMode','manual', ... 'YTick',[], ... 'ZColor',[0 0 0]); if Settings.hostver < 8.04 h2 = image('Parent',h1, ... 'CData',fm_mat('logo_uwpflow'), ... 'Tag','Axes1Image1', ... 'XData',[1 101], ... 'YData',[1 101]); else h2 = image('Parent',h1, ... 'CData',flipud(fliplr(fm_mat('logo_uwpflow'))), ... 'Tag','Axes1Image1', ... 'XData',[1 101], ... 'YData',[1 101]); end h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'ForegroundColor', [0 0 1], ... 'FontSize', 12, ... 'FontName', 'Times', ... 'FontWeight', 'bold', ... 'FontAngle', 'italic',... 'Position',[0.2915 0.0516 0.4221 0.0355], ... 'String','PSAT-UWPFLOW Interface', ... 'Style','text', ... 'Tag','StaticText3'); if nargout > 0, fig = h0; end % --------------------------------------------------------- function output = onoff(input) if input, output = 'on'; else, output = 'off'; end % --------------------------------------------------------- function checkon(field) global UWPFLOW Fig if isfield(UWPFLOW.opt,field) a = getfield(UWPFLOW.opt,field); a.status = ~a.status; UWPFLOW.opt = setfield(UWPFLOW.opt,field,a); try % strcmp(get(gcbo,'Style'),'checkbox') set(gcbo,'Value',a.status) hdl = findobj(Fig.uwpflow,'Tag',['Edit_',field]); set(hdl,'Enable',onoff(a.status)) catch set(gcbo,'Checked',onoff(a.status)) end end
github
Sinan81/PSAT-master
sim2psat.m
.m
PSAT-master/psat-mat/psat/filters/sim2psat.m
29,948
utf_8
eaf79c62c1825a9a71b6f65fe0cb7b15
function check_model = sim2psat(varargin) % SIM2PSAT convert Simulink models into PSAT data files % % CHECK = SIM2PSAT % CHECK = 0 conversion failed % CHECK = 1 conversion completed % %see also FM_LIB, FM_SIMREP, FM_SIMSET % %Author: Federico Milano %Date: 01-Jan-2006 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2009 Federico Milano global File Fig Settings Hdl Path Theme History if ~nargin File_Data = File.data; Path_Data = Path.data; else File_Data = varargin{1}; Path_Data = varargin{2}; end if ~strcmp(Path_Data(end),filesep) Path_Data = [Path_Data,filesep]; end check_model = 1; fm_disp fm_disp('Simulink Model Conversion'); fm_disp(['Simulink File <',File_Data,'>.']); % component names % NB. 'Varname' must be the last element Compnames = {'Bus','Line','Shunt','Breaker', ... 'Fault','SW','PV','PQ','PQgen', ... 'Mn','Pl','Fl','Lines','Twt','Syn', ... 'Ind','Mot','Ltc','Thload','Tg','Exc', ... 'Pss','Oxl','Hvdc','Svc','Tcsc', ... 'Statcom','Sssc','Upfc','Mass','SSR', ... 'Tap','Demand','Supply','Rsrv','Rmpg', ... 'Rmpl','Vltn','Ypdp','Sofc','Cac','Spv','Spq', ... 'Cluster','Exload','Phs','Cswt','Dfig', ... 'Ddsg','Wind','Busfreq','Pmu','Jimma', ... 'Mixload','Pod','Areas','Regions','Varname'}; lasterr(''); for i = 1:length(Compnames), eval([Compnames{i}, ' = [];']); end tipi = length(Compnames)-1; % constants used in the component masks % ---------------------------------------------------------------- on = 1; off = 0; omega = 1; power = 2; voltage = 3; monday = 1; tuesday = 2; wednesday = 3; thursday = 4; friday = 5; saturday = 6; sunday = 7; winter_week_day = 1; winter_week_end = 2; summer_week_day = 3; summer_week_end = 4; spring_fall_week_day = 5; spring_fall_week_end = 6; measurements = 1; weibull = 2; composite = 3; mexican_hat = 4; Bus_V = 1; Line_P_from_bus = 2; Line_P_to_bus = 3; Line_I_from_bus = 4; Line_I_to_bus = 5; Line_Q_from_bus = 6; Line_Q_to_bus = 7; in = 1; out = 1; ins = 1; ous = 1; constant_voltage = 1; constant_reactance = 2; constant_power = 3; constant_line_power = 1; constant_angle = 2; SVC_control = 1; TCSC_control = 2; STATCOM_control = 3; SSSC_control = 4; UPFC_control = 5; Xc = 1; Alpha = 2; constant_admittance = 1; constant_power_flow = 2; Current_control = 1; Power_control = 2; Voltage_control = 3; % loading Simulink model % ---------------------------------------------------------------- File_Data = strrep(File_Data,'(mdl)',''); File_Data = strrep(File_Data,'.mdl',''); fm_disp('Loading Simulink Model') %cd(Path_Data); open_sys = find_system('type','block_diagram'); OpenModel = sum(strcmp(open_sys,File_Data)); if OpenModel cur_sys = get_param(File_Data,'Handle'); else localpath = pwd; cd(Path_Data) if exist(File_Data,'file') ~= 4 fm_disp(['File <',File_Data,'> is not a Simulink model.'],2) check_model = 0; return end warning('off', 'Simulink:Engine:InvalidDomainRegistrationKey'); cur_sys = load_system(File_Data); cd(localpath) end % open status bar fm_bar open % load block and mask properties % ---------------------------------------------------------------- fm_disp(' * * *') fm_disp('Check model version and blocks ...') SimUpdate(cur_sys) Settings.mv = str2num(get_param(cur_sys,'ModelVersion')); blocks = find_system(cur_sys,'Type','block'); if strcmp(get_param(cur_sys,'Open'),'on') hilite_system(cur_sys,'none') end masks = get_param(blocks,'MaskType'); nblock = length(blocks); tipi3 = 1/(tipi + 1 + 2*nblock); fm_bar([1e-3,tipi3]) fm_disp(' * * *') fm_disp('Statistics ...') vector = zeros(13,1); vector(1) = length(find_system(blocks,'Description','Connection')); vector(2) = length(find_system(blocks,'Description','Power Flow')); vector(3) = length(find_system(blocks,'Description','OPF & CPF')); vector(4) = length(find_system(blocks,'Description','Faults & Breakers')); vector(5) = length(find_system(blocks,'Description','Loads')); vector(6) = length(find_system(blocks,'Description','Machines')); vector(7) = length(find_system(blocks,'Description','ULTC')); vector(8) = length(find_system(blocks,'Description','Controls')); vector(9) = length(find_system(blocks,'Description','FACTS')); vector(10) = length(find_system(blocks,'Description','Sparse Dynamic Component')); vector(11) = length(find_system(blocks,'Description','Wind Turbines')); vector(12) = length(find_system(blocks,'Description','Measurements')); dispno(vector(1),'Connections') dispno(vector(2),'Power Flow Components') dispno(vector(3),'OPF & CPF Components') dispno(vector(4),'Faults & Breakers') dispno(vector(5),'Special Loads') dispno(vector(6),'Machines') dispno(vector(7),'Regulating Transformers') dispno(vector(8),'Controls') dispno(vector(9),'FACTS') dispno(vector(10),'Spare Dynamic Components') dispno(vector(11),'Wind Power Components') dispno(vector(12),'Measurement Components') % component data matrices % ---------------------------------------------------------------- fm_disp(' * * *') fm_disp('Definition of component data ...') kinds = zeros(length(Compnames),1); idx_old = 0; for i = 1:nblock tipo = masks{i}; idx = strmatch(tipo,Compnames,'exact'); if ~isempty(idx) kinds(idx) = kinds(idx)+1; sidx = num2str(kinds(idx)); if idx ~= idx_old idx_old = idx; fm_disp(['Data "',tipo,'.con"']) end comp_data = get_param(blocks(i),'MaskVariables'); comp_value = get_param(blocks(i),'MaskValueString'); valori = strrep(['[',comp_value,']'],'|',','); indici = comp_data; if strmatch(indici,'pxq=@1;','exact') indici = ':'; else indici = ['[',indici,']']; indici = strrep(indici,'x',':'); indici = strrep(indici,'p',''); indici = strrep(indici,'_',' '); indici = strrep(indici,'q',''); end indici = regexprep(indici,'=@([0-9]*);',' '); try eval([tipo,'(',sidx,',',indici,') = ',valori,';']); catch %[tipo,'(',sidx,',',indici,') = ',valori,';'] fm_disp(['Error: ',tipo,' block <', ... get_param(blocks(i),'Name'), ... '> has a wrong number of data.'],2) hilite_system(blocks(i),'default') eval([tipo,'(',sidx,',',indici,') = 0;']); end set_param(blocks(i),'UserData',sidx); end if ~rem(i,5), fm_bar([(i-1)*tipi3,i*tipi3]), end end % "Bus" number % ---------------------------------------------------------------- busidx = find(strcmp(masks,'Bus')); busname = get_param(blocks(busidx),'Name'); Bus_n = length(busidx); Bus(:,1) = [1:Bus_n]'; fm_disp(' * * *') fm_disp('Definition of system connections ...') for i = 1:nblock if isempty(masks{i}), continue, end if strcmp(get_param(blocks(i),'Description'),'Connection') continue end rowno = get_param(blocks(i),'UserData'); % define connections switch masks{i} case {'Exc','Tg','Mass'} Destin = {'Syn'}; dst = 1; posdst = 1; Source = ''; src = []; possrc = []; case {'Pss','Oxl'} Destin = {'Exc'}; dst = 1; posdst = 1; Source = ''; src = []; possrc = []; case 'Rmpg' Destin = {'Supply'}; dst = 1; posdst = 1; Source = ''; src = []; possrc = []; case 'Rmpl' Destin = ''; dst = []; posdst = []; Source = {'Demand'}; src = 1; possrc = 1; case 'Breaker' Destin = {'Bus'}; dst = 2; posdst = 2; Source = {'Line'}; src = 1; possrc = 1; case 'Pod' Destin = {'Statcom','Sssc','Svc','Upfc','Tcsc','Dfig'}; dst = 2; posdst = 2; MaskValues = get_param(blocks(i),'MaskValues'); if strcmp(MaskValues{1},'Bus_V') Source = {'Bus'}; else Source = {'Line'}; end src = 1; possrc = 1; case 'Cluster' Source = {'Cac'}; src = 1; possrc = 1; Destin = {'Exc','Svc'}; dst = 2; posdst = 2; case {'PV','SW','Supply','Rsrv','Rmpg','Vltn', ... 'SSR','Sofc','PQgen','Syn','Supply','Spv','Spq'} Destin = {'Bus'}; dst = 1; posdst = 1; Source = ''; src = []; possrc = []; case {'Line','Lines','Phs','RLC','Hvdc'} Destin = {'Bus'}; dst = 2; posdst = 2; Source = {'Bus'}; src = 1; possrc = 1; case {'Sssc','Upfc','Tcsc'} Destin = ''; dst = []; posdst = []; Source = {'Line'}; src = 1; possrc = 1; case 'Ltc' MaskValues = get_param(blocks(i),'MaskValues'); if strcmp(MaskValues{3},'3') Destin = {'Bus'}; dst = 3; posdst = 2; Source = {'Bus'}; src = [1 2]; possrc = [15 1]; else Destin = {'Bus'}; dst = 2; posdst = 2; Source = {'Bus'}; src = 1; possrc = 1; end case {'Cswt','Dfig','Ddsg'} Destin = {'Bus'}; dst = 2; posdst = 1; Source = {'Wind'}; src = 1; possrc = 2; case 'Twt' Destin = {'Bus'}; dst = [2 3]; posdst = [2 3]; Source = {'Bus'}; src = 1; possrc = 1; %case {'SAE1','SAE2','SAE3'} % Source = {'Bus'}; % src = [1 2]; possrc = [1 2]; % Destin = ''; % dst = []; posdst = []; case {'Ypdp','Wind','Varname'} Source = ''; src = []; possrc = []; Destin = ''; dst = []; posdst = []; case {'Areas','Regions'} Source = ''; src = []; possrc = []; MaskValues = get_param(blocks(i),'MaskValues'); if strcmp(MaskValues{1},'1') Destin = {'Bus'}; dst = 1; posdst = 2; else Destin = ''; dst = []; posdst = []; end otherwise Destin = ''; dst = []; posdst = []; Source = {'Bus'}; src = 1; possrc = 1; end % find connections for j = 1:length(dst) block2_handle = SeekDstBlock(blocks(i),Destin,dst(j)); busno = get_param(block2_handle,'UserData'); eval([masks{i},'(',rowno,',',num2str(posdst(j)),') = ',busno,';']); if strcmp(masks(i),'Cluster') switch get_param(block2_handle,'MaskType') case 'Exc', ctype = '1'; case 'Svc', ctype = '2'; end eval([masks{i},'(',rowno,',3) = ',ctype,';']); end if strcmp(masks(i),'Pod') switch get_param(block2_handle,'MaskType') case 'Svc', ctype = '1'; case 'Tcsc', ctype = '2'; case 'Statcom', ctype = '3'; case 'Sssc', ctype = '4'; case 'Upfc', ctype = '5'; case 'Dfig', ctype = '6'; end eval([masks{i},'(',rowno,',4) = ',ctype,';']); end end for j = 1:length(src) block2_handle = SeekSrcBlock(blocks(i),Source,src(j)); busno = get_param(block2_handle,'UserData'); eval([masks{i},'(',rowno,',',num2str(possrc(j)),') = ',busno,';']); end fm_bar([(nblock+i-1)*tipi3,(nblock+i)*tipi3]) end fm_disp(' * * *') % writing data file idx1 = strmatch('Definition of component data ...',History.text); idx2 = strmatch('Definition of system connections ...',History.text); idx3 = strmatch('Error:',History.text); if isempty(idx3), idx3 = 0; end if idx3(end) > idx1(end) if idx3(end) > idx2(end), message = 'Simulink model is not well-formed (check links).'; end if find(idx3 < idx2(end) & idx3 > idx1(end)), message = ['Component data are not well-formed (check ' ... 'masks).']; end else File_Data = [File_Data,'_mdl']; [fid, message] = fopen([Path_Data,File_Data,'.m'], 'wt'); end if ~isempty(message), if strcmp(message, ... ['Sorry. No help in figuring out the problem ...']), fm_disp(['Most likely the folder "',Path_Data, ... '" is read only. Try to change the permission.']) else fm_disp(['Failed conversion from Simulink model: ',message],2) end if ishandle(Fig.main) set(Fig.main,'Pointer','arrow'); delete(Hdl.bar); Hdl.bar = 0; set(Hdl.frame,'Visible','on'); set(Hdl.text,'Visible','on'); end check_model = 0; return else fm_disp('Writing Data File',1) end fm_bar([(2*nblock)*tipi3,(2*nblock+1)*tipi3]) for j = 1:length(Compnames)-1 values = eval(Compnames{j}); if ~isempty(values) count = fprintf(fid,'%s.con = [ ... \n',Compnames{j}); for i = 1:length(values(:,1)) count = fprintf(fid,[' ',regexprep(num2str(values(i,:)),'\s*',' '),';\n']); end count = fprintf(fid,' ];\n\n'); end fm_bar([(2*nblock+j-1)*tipi3,(2*nblock+j)*tipi3]) end % count = fprintf(fid, 'Bus.names = {... \n '); % for i = 1:Bus_n-1 % namebus = strrep(busname{i,1},char(10),' '); % count = fprintf(fid, ['''',namebus,'''; ']); % if rem(i,5) == 0; count = fprintf(fid,'\n '); end % end % if iscell(busname) % namebus = strrep(busname{length(busname),1},char(10),' '); % count = fprintf(fid, ['''',namebus,'''};\n\n']); % else % namebus = strrep(busname,char(10),' '); % count = fprintf(fid, ['''',namebus,'''};\n\n']); % end WriteNames(fid,'Bus',busname); areaidx = find(strcmp(masks,'Areas')); areaname = get_param(blocks(areaidx),'Name'); WriteNames(fid,'Areas',areaname); zoneidx = find(strcmp(masks,'Regions')); zonename = get_param(blocks(zoneidx),'Name'); WriteNames(fid,'Regions',zonename); % print indexes of variables to be plotted if ~isempty(Varname) count = fprintf(fid, 'Varname.idx = [... \n'); nidx = length(Varname); count = fprintf(fid,'%5d; %5d; %5d; %5d; %5d; %5d; %5d;\n',Varname); if rem(nidx,7) ~= 0, count = fprintf(fid,'\n'); end count = fprintf(fid,' ];\n'); end % closing data file count = fclose(fid); exist(File_Data); % closing Simulink model if ~OpenModel && ~strcmp(get_param(cur_sys,'Dirty'),'on') close_system(cur_sys); end fm_disp(['Construction of Data File <',File_Data,'.m> completed.']) % close status bar fm_bar close % last operations % cd(Path.local); if Settings.beep, beep, end if ~nargin, File.data = [File_Data(1:end-4),'(mdl)']; end %------------------------------------------------------------------ function dispno(num,msg) %------------------------------------------------------------------ if num, fm_disp([msg,': #',num2str(num),'#']), end %------------------------------------------------------------------ function block_name = MaskType(block_handle) %------------------------------------------------------------------ block_name = get_param(block_handle,'MaskType'); if isempty(block_name) block_name = get_param(block_handle,'BlockType'); end if isempty(block_name) hilite_system(block_handle) block_name = 'Error'; return end if iscell(block_name) block_name = block_name{1}; end %------------------------------------------------------------------ function hdl2 = SeekDstBlock(hdl1,name2,pos) %------------------------------------------------------------------ ports = get_param(hdl1,'PortConnectivity'); if length(ports) < pos SimWarnMsg(hdl1,'has the wrong number of ports') hdl2 = hdl1; % to avoid errors in evaluating UserData return end handles = [ports.DstBlock]; try idx = find(strcmp({ports.Type},'RConn1')); if isempty(idx), idx = pos; end if idx(pos) ~= pos hdl2 = ports(idx(pos)).DstBlock; else hdl2 = handles(pos); end catch hdl2 = ports(pos).DstBlock; end hdl0 = hdl1; while 1 switch MaskType(hdl2) case name2 break case 'Outport' port_no = str2num(get_param(hdl2,'Port')); ports = get_param(hdl2,'PortConnectivity'); hdl0 = hdl2; hdl2 = ports(port_no).DstBlock; case 'PMIOPort' port_no = str2num(get_param(hdl2,'Port')); ports = get_param(hdl2,'PortConnectivity'); hdl0 = hdl2; hdl2 = ports(port_no).DstBlock; case 'SubSystem' ports = get_param(hdl2,'PortConnectivity'); port_no = num2str(find([ports(:).SrcBlock] == hdl1)); if isempty(port_no) port_no = num2str(find([ports(:).DstBlock] == hdl1)); end hdl0 = hdl2; hdl2 = find_system(hdl2,'SearchDepth',1,'Port',port_no); case 'Goto' tag = get_param(hdl2,'GotoTag'); name = find_system(gcs,'BlockType','From','GotoTag',tag); from = get_param(name{1},'Handle'); ports = get_param(from,'PortConnectivity'); hdl0 = hdl2; hdl2 = ports(1).DstBlock; case 'Link' ports = get_param(hdl2,'PortConnectivity'); if sum(strcmp(MaskType(hdl1),{'Pod','Cluster'})) if strcmp(ports(3).DstBlock,'Bus') hdl0 = hdl2; hdl2 = ports(2).DstBlock; % Input Port else hdl0 = hdl2; hdl2 = ports(3).DstBlock; % Output Port end elseif strcmp(MaskType(hdl0),MaskType(ports(2).DstBlock)) hdl0 = hdl2; hdl2 = ports(3).DstBlock; % Output Port else hdl0 = hdl2; hdl2 = ports(2).DstBlock; % Input Port end case 'Line' switch MaskType(hdl1) case {'Breaker','Upfc','Tcsc','Sssc'} hdl0 = hdl2; hdl2 = SeekSrcBlock(hdl1,'Bus',1); otherwise SimWarnMsg(hdl1,'cannot be connected to',hdl2) end break case {'Breaker','Sssc','Upfc','Tcsc','Mass'} ports = get_param(hdl2,'PortConnectivity'); hdl_temp = hdl0; hdl0 = hdl2; hdl2 = ports(2).DstBlock; % Output Port if hdl2 == hdl_temp hdl2 = ports(1).DstBlock; % Output Port end case 'Link2' ports = get_param(hdl2,'PortConnectivity'); hdl0 = hdl2; hdl2 = ports(3).DstBlock; % Output Port case 'Error' SimWarnMsg(hdl1,'is badly connected') hdl0 = hdl2; hdl2 = hdl1; % to avoid errors in evaluating UserData break otherwise SimWarnMsg(hdl1,'cannot be connected to',hdl2) break end end %------------------------------------------------------------------ function hdl2 = SeekSrcBlock(hdl1,name2,pos) %------------------------------------------------------------------ ports = get_param(hdl1,'PortConnectivity'); if length(ports) < pos SimWarnMsg(hdl1,'has the wrong number of ports') hdl2 = hdl1; % to avoid errors in evaluating UserData return end switch ports(pos).Type case {'1','enable'} hdl2 = ports(pos).SrcBlock; otherwise hdl2 = ports(pos).DstBlock; end hdl0 = hdl1; while 1 switch MaskType(hdl2) case name2 break case 'Inport' port_no = str2num(get_param(hdl2,'Port')); ports = get_param(hdl2,'PortConnectivity'); hdl0 = hdl2; hdl2 = ports(port_no).SrcBlock; case 'PMIOPort' port_no = str2num(get_param(hdl2,'Port')); ports = get_param(hdl2,'PortConnectivity'); hdl0 = hdl2; hdl2 = ports(port_no).DstBlock; case 'SubSystem' ports = get_param(hdl2,'PortConnectivity'); port_no = num2str(find([ports(:).DstBlock] == hdl1)); hdl0 = hdl2; hdl2 = find_system(hdl2,'SearchDepth',1,'Port',port_no); case 'From' tag = get_param(hdl2,'GotoTag'); name = find_system(gcs,'BlockType','Goto','GotoTag',tag) goto = get_param(name{1},'Handle'); ports = get_param(goto,'PortConnectivity'); hdl0 = hdl2; hdl2 = ports(1).SrcBlock; case 'Link' ports = get_param(hdl2,'PortConnectivity'); if strcmp(MaskType(hdl0),MaskType(ports(2).DstBlock)) hdl0 = hdl2; hdl2 = ports(3).DstBlock; % Output Port else hdl0 = hdl2; hdl2 = ports(2).DstBlock; % Input Port end case 'Bus' switch MaskType(hdl1) case {'Breaker','Sssc','Upfc','Tcsc'} hdl0 = hdl2; hdl2 = SeekDstBlock(hdl1,'Line',2); otherwise SimWarnMsg(hdl1,'cannot be connected to',hdl2) end break case {'Breaker','Sssc','Upfc','Tcsc'} ports = get_param(hdl2,'PortConnectivity'); hdl_temp = hdl0; hdl0 = hdl2; hdl2 = ports(1).DstBlock; % Output Port if hdl2 == hdl_temp hdl2 = ports(2).DstBlock; % Output Port end case 'Link2' ports = get_param(hdl2,'PortConnectivity'); hdl0 = hdl2; if strcmp(MaskType(hdl1),'Pod') if strcmp(MaskType(ports(2).DstBlock),name2) hdl2 = ports(2).DstBlock; % Input Port break elseif strcmp(MaskType(ports(3).DstBlock),name2) hdl2 = ports(3).DstBlock; % Output Port break else % try to follow one path (50% likely to succeed) hdl2 = ports(3).DstBlock; % Output Port end else hdl2 = ports(2).DstBlock; % Input Port end case 'Error' SimWarnMsg(hdl1,'is badly connected') hdl0 = hdl2; hdl2 = hdl1; % to avoid errors in evaluating UserData break otherwise SimWarnMsg(hdl1,'cannot be connected to',hdl2) break end end %------------------------------------------------------------------ function SimWarnMsg(varargin) %------------------------------------------------------------------ handle1 = varargin{1}; msg = varargin{2}; hilite_system(handle1,'default') name1 = get_param(handle1,'Name'); if nargin == 2 fm_disp(['Error: Block <',name1,'> ',msg,'.']) elseif nargin == 3 handle2 = varargin{3}; name2 = get_param(handle2,'Name'); fm_disp(['Error: Block <',name1,'> ',msg,' block <',name2,'>.']) end %------------------------------------------------------------------ function WriteNames(fid,type,names) %------------------------------------------------------------------ if isempty(names), return, end n = length(names); count = fprintf(fid, [type,'.names = {... \n ']); for i = 1:n-1 name = strrep(names{i,1},char(10),' '); count = fprintf(fid, ['''',name,'''; ']); if rem(i,5) == 0; count = fprintf(fid,'\n '); end end if iscell(names) name = strrep(names{n,1},char(10),' '); count = fprintf(fid, ['''',name,'''};\n\n']); else name = strrep(names,char(10),' '); count = fprintf(fid, ['''',name,'''};\n\n']); end %------------------------------------------------------------------ function SimUpdate(sys) %------------------------------------------------------------------ global Settings sys = getfullname(sys); hilite_system(sys,'none') block = find_system(sys,'Type','block'); mask = get_param(block,'MaskType'); nblock = length(block); % check if all blocks belong to the PSAT Library Tags = get_param(block,'Tag'); BlockTypes = get_param(block,'BlockType'); idx = ones(nblock,1); idx(strmatch('PSATblock',Tags,'exact')) = 0; idx(strmatch('SubSystem',BlockTypes,'exact')) = 0; idx(strmatch('PMIOPort',BlockTypes,'exact')) = 0; if sum(idx) idx = find(idx); fm_disp(fm_strjoin('* * Warning: Block <',get_param(block(idx),'Name'), ... '> does not belong to the PSAT Simulink Library.')) Settings.ok = 0; uiwait(fm_choice(['Some blocks do not seem to belong to the ', ... 'PSAT library, but could be old blocks. ', ... 'Do you want to fix them?'])) if Settings.ok for iii = 1:length(idx) blocktype = mask{idx(iii)}; if isempty(blocktype) blocktype = get_param(block{idx(iii)},'BlockType'); end switch blocktype case {'Bus','Link','Goto','From'} prop = 'Connection'; case {'Supply','Demand','Rmpg','Rrsv','Vltn','Rmpl','Ypdp'} prop = 'OPF & CPF'; case {'Breaker','Fault'} prop = 'Faults & Breakers'; case 'Busfreq' prop = 'Measurements'; case {'Mn','Pl','Thload','Fl','Exload'} prop = 'Loads'; case {'Syn','Ind','Mot'} prop = 'Machines'; case {'Ltc','Tap'} prop = 'ULTC'; case 'Phs' prop = 'Phase Shifter'; case {'Tg','Exc','Cac','Cluster','Pss','Oxl'} prop = 'Controls'; case {'Statcom','Upfc','Svc','Hvdc','Tcsc','Sssc'} prop = 'FACTS'; case {'Dfig','Cswt','Ddsg'} prop = 'Wind Turbines'; case {'Sofc','SSR','RLC','Mass','Spv','Spq'} prop = 'Sparse Dynamic Component'; %case {'SAE1','SAE2','SAE3'} % prop = 'SAE'; otherwise prop = 'Power Flow'; end set_param(block{idx(iii)}, ... 'Tag','PSATblock', ... 'Description',prop) end save_system(sys); end else fm_disp(' ') fm_disp('* * All blocks belong to the PSAT-Simulink Library.') end % check for old models slackbus = find_system(sys,'MaskType','SW'); ports = get_param(slackbus,'Ports'); if isempty(ports) fm_disp('* * * Error: No Slack bus found!') pvbus = find_system(sys,'MaskType','PV'); ports = get_param(pvbus,'Ports'); end if isempty(ports) check = 1; fm_disp('* * Error: No connections found!') elseif iscell(ports) check = sum(ports{1}); elseif isnumeric(ports) check = sum(ports); end % check if model needs to be updated if ~check disp(' ') fm_disp('* * Warning: The model refers to an old PSAT-Simulink') fm_disp(' library. PSAT will try to update models.') disp(' ') Settings.ok = 0; uiwait(fm_choice(['The model refers to an old PSAT-Simulink ' ... 'library. Update?'],1)) if ~Settings.ok, return, end else return end load_system('fm_lib'); open_system(sys); for i = 1:nblock % fix source block if it has changed try source = get_param(block{i},'SourceBlock'); switch source case 'fm_lib/Power Flow/Transf5' set_param(block{i},'SourceBlock','fm_lib/Power Flow/Twt') case ['fm_lib/Wind',char(10),'Turbines/Cswt1'] set_param(block{i},'SourceBlock',['fm_lib/Wind',char(10),'Turbines/Cswt']) case ['fm_lib/Wind',char(10),'Turbines/Dfig1'] set_param(block{i},'SourceBlock',['fm_lib/Wind',char(10),'Turbines/Ddsg']) case ['fm_lib/Wind',char(10),'Turbines/Dfig2'] set_param(block{i},'SourceBlock',['fm_lib/Wind',char(10),'Turbines/Dfig']) case ['fm_lib/Wind',char(10),'Turbines/Wind1'] set_param(block{i},'SourceBlock',['fm_lib/Wind',char(10),'Turbines/Wind']) case 'fm_lib/Power Flow/Extra Line' set_param(block{i},'SourceBlock','fm_lib/Power Flow/Lines') case 'fm_lib/Power Flow/PQ1' set_param(block{i},'SourceBlock','fm_lib/Power Flow/PQgen') case 'fm_lib/Machines/Gen' set_param(block{i},'SourceBlock','fm_lib/Machines/Syn') case 'fm_lib/ULTC/LTC' set_param(block{i},'SourceBlock','fm_lib/ULTC/Ltc') case 'fm_lib/ULTC/OLTC' set_param(block{i},'SourceBlock','fm_lib/ULTC/Tap') case 'fm_lib/ULTC/PHS' set_param(block{i},'SourceBlock','fm_lib/ULTC/Phs') case 'fm_lib/Others/SOFC' set_param(block{i},'SourceBlock','fm_lib/Others/Sofc') case 'fm_lib/Others/SSR' set_param(block{i},'SourceBlock','fm_lib/Others/Ssr') case 'fm_lib/Measurements/SPV' set_param(block{i},'SourceBlock','fm_lib/Others/Spv') case 'fm_lib/Measurements/SPQ' set_param(block{i},'SourceBlock','fm_lib/Others/Spq') case 'fm_lib/Measurements/PMU' set_param(block{i},'SourceBlock','fm_lib/Measurements/Pmu') case 'fm_lib/Loads/FDL' set_param(block{i},'SourceBlock','fm_lib/Loads/Fl') case 'fm_lib/Loads/LRL' set_param(block{i},'SourceBlock','fm_lib/Loads/Exload') case 'fm_lib/Loads/TCL' set_param(block{i},'SourceBlock','fm_lib/Loads/Thload') case 'fm_lib/Loads/Mixed' set_param(block{i},'SourceBlock','fm_lib/Loads/Mixload') case 'fm_lib/Loads/VDL' set_param(block{i},'SourceBlock','fm_lib/Loads/Mn') case 'fm_lib/Loads/ZIP' set_param(block{i},'SourceBlock','fm_lib/Loads/Pl') case 'fm_lib/FACTS/HVDC' set_param(block{i},'SourceBlock','fm_lib/FACTS/Hvdc') case 'fm_lib/FACTS/SSSC' set_param(block{i},'SourceBlock','fm_lib/FACTS/Sssc') case 'fm_lib/FACTS/SVC (1)' set_param(block{i},'SourceBlock','fm_lib/FACTS/Svc') case 'fm_lib/FACTS/SVC (2)' set_param(block{i},'SourceBlock','fm_lib/FACTS/Svc2') case 'fm_lib/FACTS/StatCom' set_param(block{i},'SourceBlock','fm_lib/FACTS/Statcom') case 'fm_lib/FACTS/TCSC (1)' set_param(block{i},'SourceBlock','fm_lib/FACTS/Tcsc') case 'fm_lib/FACTS/TCSC (2)' set_param(block{i},'SourceBlock','fm_lib/FACTS/Tcsc2') case 'fm_lib/FACTS/UPFC' set_param(block{i},'SourceBlock','fm_lib/FACTS/Upfc') case 'fm_lib/Connections/Link' set_param(block{i},'SourceBlock','fm_lib/Connections/Link1') case 'fm_lib/OPF & CPF/RMPG' set_param(block{i},'SourceBlock','fm_lib/OPF & CPF/Rmpg') case 'fm_lib/OPF & CPF/RMPL' set_param(block{i},'SourceBlock','fm_lib/OPF & CPF/Rmpl') case 'fm_lib/OPF & CPF/RSRV' set_param(block{i},'SourceBlock','fm_lib/OPF & CPF/Rsrv') case 'fm_lib/OPF & CPF/VLTN' set_param(block{i},'SourceBlock','fm_lib/OPF & CPF/Vltn') case 'fm_lib/OPF & CPF/YPDP' set_param(block{i},'SourceBlock','fm_lib/OPF & CPF/Ypdp') case 'fm_lib/OPF & CPF/YPDP1' set_param(block{i},'SourceBlock','fm_lib/OPF & CPF/Ypdp1') case 'fm_lib/Controls/AVR' set_param(block{i},'SourceBlock','fm_lib/Controls/Exc') case 'fm_lib/Controls/TG' set_param(block{i},'SourceBlock','fm_lib/Controls/Tg') case 'fm_lib/Controls/SSCL' set_param(block{i},'SourceBlock','fm_lib/Controls/Pod') case 'fm_lib/Controls/OXL' set_param(block{i},'SourceBlock','fm_lib/Controls/Oxl') case 'fm_lib/Controls/PSS' set_param(block{i},'SourceBlock','fm_lib/Controls/Pss') case 'fm_lib/Controls/CAC' set_param(block{i},'SourceBlock','fm_lib/Controls/Cac') case 'fm_lib/Controls/Shaft' set_param(block{i},'SourceBlock','fm_lib/Others/Mass') end mask{i} = get_param(block{i},'MaskType'); catch % the source block has not changed end switch mask{i} case {'Bus','Link','Line','Lines','Breaker','Twt' ... 'Phs','Tcsc','Sssc','Upfc','Hvdc','Dfig', ... 'Cswt','Ddsg','RLC','PV','SW','PQgen','Spv','Spq', ... 'Rmpg','Rsrv','Vltn','Wind','Sofc','Ssr', ... 'PQ','Shunt','Rmpl','Fault','Mn','Pl','Ind','Mot', ... 'Fl','Exload','Mixload','Thload','Jimma','Tap', ... 'Svc','Statcom','Busfreq','Pmu','Supply', ... 'Demand','Syn','Ltc','SAE1','SAE2','SAE3', ... 'Exc','Tg','Sscl','Cac','Oxl','Pss','Cluster'} cloneblock(block{i},sys) end end lines = find_system(sys,'FindAll','on','type','line'); for i = 1:length(lines) points = get_param(lines(i),'Points'); parent = get_param(lines(i),'Parent'); delete_line(parent,points(1,:)); try add_line(parent,points); catch fm_disp(['* * Connection line ',num2str(i),' could not be replaced.']) end end uiwait(fm_choice('Now please take a moment to doublecheck connections...',2)) fm_disp(' ') fm_disp(['* * Update of model <',sys,'> completed.'])
github
Sinan81/PSAT-master
psat2epri.m
.m
PSAT-master/psat-mat/psat/filters/psat2epri.m
9,998
utf_8
41d11211dc3adce16c04643c65971fdc
function check = psat2epri(filename, pathname) % PSAT2EPRI converts PSAT data file into EPRI Data Format % % CHECK = PSAT2EPRI(FILENAME,PATHNAME) % FILENAME name of the file to be converted % PATHNAME path of the file to be converted % % CHECK = 1 conversion completed % CHECK = 0 problem encountered (no data file created) % %Author: Federico Milano %Date: 06-Oct-2003 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2009 Federico Milano global DAE Varname Settings DAE_old = DAE; Varname_old = Varname; Settings_old = Settings; if strcmp(pathname(end),filesep) pathname = pathname(1:end-1); end if ~strcmp(pathname,pwd) cd(pathname) end fm_disp fm_disp(['Opening PSAT file "',filename,'"...']) % General Settings % ----------------------------------------------------------- check = 1; b128 = [blanks(128),'\n']; b12 = blanks(12); % Defining local data structures % ----------------------------------------------------------- Bus = BUclass; Twt = TWclass; Line = LNclass; Shunt = SHclass; SW = SWclass; PV = PVclass; PQ = PQclass; PQgen = PQclass; Ltc = LTclass; Phs = PHclass; % Reading Data from PSAT Data File % ----------------------------------------------------------- a = exist(filename); if a == 2, eval(filename(1:end-2)) else, fm_disp(['File "',filename,'" not found or not an m-file'],2) check = 0; return end % Completing data settings % ----------------------------------------------------------- Bus = setup(Bus); Line = setup(Line,Bus); Twt = setup(Twt,Bus,Line); Shunt = setup(Shunt,Bus); PV = setup(PV,Bus); SW = setup(SW,Bus,PV); PQ = setup(PQ,Bus); PQgen = setup(PQgen,Bus); PQ = addgen(PQ,PQgen,Bus); Ltc = setup(Ltc,Bus); Phs = setup(Phs,Bus); % Opening File % ----------------------------------------------------------- newfile = [filename(1:end-2),'.wsc']; fm_disp(['Writing WSCC file "',newfile,'"...']) fid = fopen([pathname,filesep, newfile], 'wt'); comment = ['C\nC',repmat('*',1,79),'\nC\n']; count = fprintf(fid,comment); % Header and Title % ----------------------------------------------------------- count = fprintf(fid,'HDG\n'); count = fprintf(fid,['PSAT ARCHIVE\n']); count = fprintf(fid,[num2str(Bus.n),'-Bus ', ... num2str(Line.n),'-Line System\n']); count = fprintf(fid,[date,'\n']); count = fprintf(fid,'BAS\n'); count = fprintf(fid,comment); % Bus Data % ----------------------------------------------------------- % Section Start card idxPV = []; idxPQ = []; idxSW = []; idxSH = []; Busnames = cell(Bus.n,1); % Scan each bus for data for i = 1:Bus.n % the following lines ensure that bus names % are unique and with no repetitions busname = Bus.names{i}; if length(busname) > 8, busname = busname([1:8]); end idx = strmatch(busname,Bus.names); if length(idx) > 1 idx = find(idx == i); nn = length(num2str(idx)); busname([(end-idx+1):end]) = num2str(idx); end busname = [busname,blanks(8)]; busname = busname([1:8]); Busnames{i,1} = busname; count = fprintf(fid,'B'); idxPV = findbus(PV,i); idxPQ = findbus(PQ,i); idxSW = findbus(SW,i); if ~isempty(Shunt.con) idxSH = find(Shunt.bus == i); end % Bus type if ~isempty(idxSW) count = fprintf(fid,'S '); slackname = busname; slackkV = Bus.con(i,2); slackang = SW.con(idxSW,5); elseif ~isempty(idxPV) if PV.con(idxPV,6) == 0 && PV.con(idxPV,7) == 0 count = fprintf(fid,'E '); else count = fprintf(fid,'Q '); end elseif ~isempty(idxPQ) if PQ.con(idxPQ,6) == 0 && PQ.con(idxPQ,7) == 0 count = fprintf(fid,' '); else count = fprintf(fid,'V '); PQ.con(idxPQ,4) = PQ.con(idxPQ,4); PQ.con(idxPQ,5) = PQ.con(idxPQ,5); end else count = fprintf(fid,' '); end % Bus name, voltage rate and zone kV = Bus.con(i,2); count = fprintf(fid,['%s',tr(kV,4),' '],busname,kV); % Load powers if ~isempty(idxPQ) P = PQ.con(idxPQ,4)*PQ.con(idxPQ,2); Q = PQ.con(idxPQ,5)*PQ.con(idxPQ,2); count = fprintf(fid,[tr(P,5),tr(Q,5)],P,Q); else count = fprintf(fid,blanks(10)); end % Shunts if ~isempty(idxSH) G = Shunt.con(idxSH,5)*Shunt.con(idxSH,2)/(Shunt.con(idxSH,3)^2); B = Shunt.con(idxSH,6)*Shunt.con(idxSH,2)/(Shunt.con(idxSH,3)^2); count = fprintf(fid,[tr(G,4),tr(B,4)],G,B); else count = fprintf(fid,blanks(8)); end % Generator powers and limits if ~isempty(idxPV) PM = PV.con(idxPV,2); Pg = PV.con(idxPV,4)*PV.con(idxPV,2); count = fprintf(fid,[tr(PM,4),tr(Pg,5)],PM,Pg); if PV.con(idxPV,6) ~= 0 || PV.con(idxPV,7) ~= 0 QM = PV.con(idxPV,6)*PV.con(idxPV,2); Qm = PV.con(idxPV,7)*PV.con(idxPV,2); if QM < Qm dummy = QM; QM = Qm; Qm = dummy; end count = fprintf(fid,[tr(QM,5),tr(Qm,5)],QM,Qm); else count = fprintf(fid,blanks(10)); end elseif ~isempty(idxSW) PM = SW.con(idxSW,2); Pg = SW.con(idxSW,10)*SW.con(idxSW,2); count = fprintf(fid,[tr(PM,4),tr(Pg,5)],PM,Pg); if SW.con(idxSW,6) ~= 0 || SW.con(idxSW,7) ~= 0 QM = SW.con(idxSW,6)*SW.con(idxSW,2); Qm = SW.con(idxSW,7)*SW.con(idxSW,2); if QM < Qm dummy = QM; QM = Qm; Qm = dummy; end count = fprintf(fid,[tr(QM,5),tr(Qm,5)],QM,Qm); else count = fprintf(fid,blanks(10)); end else count = fprintf(fid,blanks(19)); end % Desired or maximum voltage if ~isempty(idxPV) count = fprintf(fid,'%-4.2f',PV.con(idxPV,5)); elseif ~isempty(idxSW) count = fprintf(fid,'%-4.2f',SW.con(idxSW,4)); elseif ~isempty(idxPQ) if PQ.con(idxPQ,6) ~= 0 count = fprintf(fid,'%-4.2f',PQ.con(idxPQ,6)); else count = fprintf(fid,blanks(4)); end else count = fprintf(fid,blanks(4)); end % Minimum voltage if ~isempty(idxPQ) if PQ.con(idxPQ,7) ~= 0 count = fprintf(fid,'%-4.2f',PQ.con(idxPQ,7)); else count = fprintf(fid,blanks(4)); end else count = fprintf(fid,blanks(4)); end % Remote name, kV and %Q are not Used by PSAT % ... % End of line count = fprintf(fid,'\n'); end count = fprintf(fid,comment); % Line and transformer data % ----------------------------------------------------------- % Scan each line for data for i = 1:Line.n m = Line.con(i,1); n = Line.con(i,2); if Line.con(i,7) count = fprintf(fid,'T '); else count = fprintf(fid,'L '); end count = fprintf(fid,'%s',Busnames{m}); count = fprintf(fid,tr(Bus.con(m,2),4),Bus.con(m,2)); count = fprintf(fid,' %s',Busnames{n}); count = fprintf(fid,tr(Bus.con(n,2),4),Bus.con(n,2)); if Line.con(i,7) In = Line.con(i,3); else In = Line.con(i,3)*1e3/Line.con(i,4)/sqrt(3); end count = fprintf(fid,[' ',tr(In,4)],In); R = Line.con(i,8); X = Line.con(i,9); B = Line.con(i,10)/2; count = fprintf(fid,' %-6.4f%-6.4f%-6.4f%-6.4f',R,X,0.0,B); if Line.con(i,7) if Line.con(i,11) T = Line.con(i,11)*Line.con(i,4); count = fprintf(fid,'%-5.2f',T); T = Line.con(i,4)/Line.con(i,7); count = fprintf(fid,'%-5.2f',T); end else if Line.con(i,6) % conversion to miles L = Line.con(i,6)*0.621371; count = fprintf(fid,tr(L,4),L); end end count = fprintf(fid,'\n'); end % End line data count = fprintf(fid,comment); % Regulating Transformer Data % ----------------------------------------------------------- for i = 1:Ltc.n switch Ltc.con(i,16) case 1, count = fprintf(fid,'R '); case 2, count = fprintf(fid,'RQ '); case 3, count = fprintf(fid,'R '); end m = Ltc.bus1(i); n = Ltc.bus2(i); k = Ltc.busc; count = fprintf(fid,'%s',Busnames{m}); count = fprintf(fid,tr(Bus.con(m,2),4),Bus.con(m,2)); count = fprintf(fid,' %s',Busnames{n}); count = fprintf(fid,tr(Bus.con(n,2),4),Bus.con(n,2)); count = fprintf(fid,'%s',Busnames{k}); count = fprintf(fid,tr(Bus.con(k,2),4),Bus.con(k,2)); count = fprintf(fid,'%-5.2f%-5.2f', ... Ltc.con(i,9)*Bus.con(m,2), ... Ltc.con(i,10)*Bus.con(m,2)); if Ltc.con(i,11) ntap = (Ltc.con(i,9)-Ltc.con(i,10))/Ltc.con(i,11); else ntap = 11; end count = fprintf(fid,tr(ntap,2),ntap); if Ltc.con(i,16) == 2 count = fprintf(fid,tr(Ltc.con(i,12),5),Ltc.con(i,12)); end end for i = 1:Phs.n count = fprintf(fid,'RP '); m = Phs.bus1(i); n = Phs.bus2(i); count = fprintf(fid,'%s',Busnames{m}); count = fprintf(fid,tr(Bus.con(m,2),4),Bus.con(m,2)); count = fprintf(fid,' %s',Busnames{n}); count = fprintf(fid,tr(Bus.con(n,2),4),Bus.con(n,2)); count = fprintf(fid,'%s',Busnames{n}); count = fprintf(fid,tr(Bus.con(n,2),4),Bus.con(n,2)); count = fprintf(fid,'%-5.2f%-5.2f', ... Phs.con(i,13)*180/pi, ... Phs.con(i,14)*180/pi); count = fprintf(fid,'%d',11); count = fprintf(fid,tr(Phs.con(i,10),5),Phs.con(i,10)); end if Ltc.n || Phs.n % End of regulating transformer data count = fprintf(fid,comment); end % Area Data % ----------------------------------------------------------- % ... PSAT does not currently support areas ... % Solution control data % ----------------------------------------------------------- count = fprintf(fid,['SOL',blanks(20)]); count = fprintf(fid,'%-5i ',Settings.lfmit); count = fprintf(fid,'%s',slackname); count = fprintf(fid,tr(slackkV,4),slackkV); count = fprintf(fid,' %-10.4f\n',slackang); % Closing the file % ----------------------------------------------------------- count = fprintf(fid,'ZZ\n'); count = fprintf(fid,'END\n'); fclose(fid); DAE = DAE_old; Varname = Varname_old; Settings = Settings_old; fm_disp('Conversion completed.') if Settings.beep, beep, end % ----------------------------------------------------------- function string = tr(value,n) threshold = 10^(n-2); if value >= threshold || value < 0 string = '0'; else string = '1'; end string = ['%-',num2str(n),'.',string,'f'];
github
Sinan81/PSAT-master
fm_spf.m
.m
PSAT-master/psat-oct/psat/fm_spf.m
12,912
utf_8
54e27550e51d0eb7a495b4191e701a8d
function fm_spf % FM_SPF solve standard power flow by means of the NR method % and fast decoupled power flow (XB and BX variations) % with either a single or distributed slack bus model. % % FM_SPF % %see the properties of the Settings structure for options. % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 09-Jul-2003 %Version: 1.0.1 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global DAE Pl Mn Lines Line SW PV PQ Bus global History Theme Fig Settings LIB Snapshot Path File fm_disp fm_disp('Newton-Raphson Method for Power Flow Computation') if Settings.show fm_disp(['Data file "',Path.data,File.data,'"']) end nodyn = 0; % these computations are needed only the first time the power flow is run if ~Settings.init % bus type initialization fm_ncomp if ~Settings.ok, return, end % report components parameters to system bases if Settings.conv, fm_base, end % create the admittance matrix Line = build_y_line(Line); % create the FM_CALL FUNCTION if Settings.show, fm_disp('Writing file "fm_call" ...',1), end fm_wcall; fm_dynlf; % indicization of components used in power flow computations end % memory allocation for equations and Jacobians DAE.g = ones(DAE.m,1); DAE.Gy = sparse(DAE.m,DAE.m); if (DAE.n~=0) DAE.f = ones(DAE.n,1); % differential equations DAE.x = ones(DAE.n,1); % state variables fm_xfirst; DAE.Fx = sparse(DAE.n,DAE.n); % df/dx DAE.Fy = sparse(DAE.n,DAE.m); % df/dy DAE.Gx = sparse(DAE.m,DAE.n); % dg/dx else % no dynamic elements nodyn = 1; DAE.n = 1; DAE.f = 0; DAE.x = 0; DAE.Fx = 1; DAE.Fy = sparse(1,DAE.m); DAE.Gx = sparse(DAE.m,1); end % check PF solver method PFmethod = Settings.pfsolver; ncload = getnum_mn(Mn) + getnum_pl(Pl) + getnum_lines(Lines) + (~nodyn); if (ncload || Settings.distrsw) && (PFmethod == 2 || PFmethod == 3) if ncload fm_disp('Fast Decoupled PF cannot be used with dynamic components') end if Settings.distrsw fm_disp('Fast Decoupled PF cannot be used with distributed slack bus model') end PFmethod = 1; % force using standard NR method end switch PFmethod case 1, fm_disp('PF solver: Newton-Raphson method') case 2, fm_disp('PF solver: XB fast decoupled method') case 3, fm_disp('PF solver: BX fast decoupled method') case 4, fm_disp('PF solver: Runge-Kutta method') case 5, fm_disp('PF solver: Iwamoto method') case 6, fm_disp('PF solver: Robust power flow method') case 7, fm_disp('PF solver: DC power flow') end DAE.lambda = 1; Jrow = 0; if Settings.distrsw DAE.Fk = sparse(DAE.n,1); DAE.Gk = sparse(DAE.m,1); Jrow = sparse(1,DAE.n+SW.refbus,1,1,DAE.n+DAE.m+1); DAE.kg = 0; if ~swgamma_sw(SW,'sum') fm_disp('Slack buses have zero power loss participation factor.') fm_disp('Single slack bus model will be used') Setting.distrsw = 0; end if totp_sw(SW) == 0 SW = setpg(totp_pq(PQ)-totp_pv(PV),1); fm_disp('Slack buses have zero generated power.') fm_disp('P_slack = sum(P_load)-sum(P_gen) will be used.') fm_disp('Only PQ loads and PV generators are used.') fm_disp('If there are convergence problems, use the single slack bus model.') end Gkcall_sw(SW); Gkcall_pv(PV); end switch Settings.distrsw case 1 fm_disp('Distributed slack bus model') case 0 fm_disp('Single slack bus model') end iter_max = Settings.lfmit; convergence = 1; if iter_max < 2, iter_max = 2; end iteration = 0; tol = Settings.lftol; Settings.error = tol+1; Settings.iter = 0; err_max_old = 1e6; err_vec = []; alfatry = 1; alfa = 1; %0.85; safety = 0.9; pgrow = -0.2; pshrnk = -0.25; robust = 1; try errcon = (5/safety)^(1/pgrow); catch errcon = 1.89e-4; end % Graphical settings fm_status('pf','init',iter_max,{'r'},{'-'},{Theme.color11}) islands_line(Line) % Newton-Raphson routine t0 = clock; while (Settings.error > tol) && (iteration <= iter_max) && (alfa > 1e-5) if ishandle(Fig.main) if ~get(Fig.main,'UserData'), break, end end switch PFmethod case 1 % Standard Newton-Raphson method inc = calcInc(nodyn,Jrow); DAE.x = DAE.x + inc(1:DAE.n); DAE.y = DAE.y + inc(1+DAE.n:DAE.m+DAE.n); if Settings.distrsw, DAE.kg = DAE.kg + inc(end); end case {2,3} % Fast Decoupled Power Flow if ~iteration % initialize variables Line = build_b_line(Line); no_sw = Bus.a; no_sw(getbus(SW)) = []; no_swv = no_sw + Bus.n; no_g = Bus.a; no_g([getbus_sw(SW); getbus_pv(PV)]) = []; Bp = Line.Bp(no_sw,no_sw); Bpp = Line.Bpp(no_g,no_g); [Lp, Up, Pp] = lu(Bp); [Lpp, Upp, Ppp] = lu(Bpp); no_g = no_g + Bus.n; fm_call('fdpf') end % P-theta da = -(Up\(Lp\(Pp*(DAE.g(no_sw)./DAE.y(no_swv))))); DAE.y(no_sw) = DAE.y(no_sw) + da; fm_call('fdpf') normP = norm(DAE.g,inf); % Q-V dV = -(Upp\(Lpp\(Ppp*(DAE.g(no_g)./DAE.y(no_g))))); DAE.y(no_g) = DAE.y(no_g)+dV; fm_call('fdpf') normQ = norm(DAE.g,inf); inc = [normP; normQ]; % recompute Bpp if some PV bus has been switched to PQ bus if Settings.pv2pq && strmatch('Switch',History.text{end}) fm_disp('Recomputing Bpp matrix for Fast Decoupled PF') no_g = Bus.a; no_g([getbus_sw(SW); getbus_pv(PV)]) = []; Bpp = Line.Bpp(no_g,no_g); [Lpp, Upp, Ppp] = lu(Bpp); no_g = no_g + Bus.n; end case 4 % Runge-Kutta method xold = DAE.x; yold = DAE.y; kold = DAE.kg; k1 = alfa*calcInc(nodyn,Jrow); Jac = -[DAE.Fx, DAE.Fy; DAE.Gx, DAE.Gy]; DAE.x = xold + 0.5*k1(1:DAE.n); DAE.y = yold + 0.5*k1(1+DAE.n:DAE.m+DAE.n); if Settings.distrsw, DAE.kg = kold + 0.5*k1(end); end k2 = alfa*calcInc(nodyn,Jrow); DAE.x = xold + 0.5*k2(1:DAE.n); DAE.y = yold + 0.5*k2(1+DAE.n:DAE.m+DAE.n); if Settings.distrsw, DAE.kg = kold + 0.5*k2(end); end k3 = alfa*calcInc(nodyn,Jrow); DAE.x = xold + k3(1:DAE.n); DAE.y = yold + k3(1+DAE.n:DAE.m+DAE.n); if Settings.distrsw, DAE.kg = kold + k3(end); end k4 = alfa*calcInc(nodyn,Jrow); % compute RK4 increment of variables inc = (k1+2*(k2+k3)+k4)/6; % to estimate RK error, use the RK2:Dy and RK4:Dy. yerr = max(abs(abs(k2)-abs(inc))); if yerr > 0.01 alfa = max(0.985*alfa,0.75); else alfa = min(1.015*alfa,0.75); end DAE.x = xold + inc(1:DAE.n); DAE.y = yold + inc(1+DAE.n:DAE.m+DAE.n); if Settings.distrsw, DAE.kg = kold + inc(end); end case 5 % Iwamoto method xold = DAE.x; yold = DAE.y; kold = DAE.kg; inc = calcInc(nodyn,Jrow); vec_a = -[DAE.Fx, DAE.Fy; DAE.Gx, DAE.Gy]*inc; vec_b = -vec_a; DAE.x = inc(1:DAE.n); DAE.y = inc(1+DAE.n:DAE.m+DAE.n); if Settings.distrsw DAE.kg = inc(end); fm_call('kgpf'); if nodyn, DAE.Fx = 1; end vec_c = -[DAE.f; DAE.g; DAE.y(SW.refbus)]; else refreshJac; fm_call('l'); refreshGen(nodyn); vec_c = -[DAE.f; DAE.g]; end g0 = (vec_a')*vec_b; g1 = sum(vec_b.*vec_b + 2*vec_a.*vec_c); g2 = 3*(vec_b')*vec_c; g3 = 2*(vec_c')*vec_c; % mu = fsolve(@(x) g0 + x*(g1 + x*(g2 + x*g3)), 1.0); % Cardan's formula pp = -g2/3/g3; qq = pp^3 + (g2*g1-3*g3*g0)/6/g3/g3; rr = g1/3/g3; mu = (qq+sqrt(qq*qq+(rr-pp*pp)^3))^(1/3) + ... (qq-sqrt(qq*qq+(rr-pp*pp)^3))^(1/3) + pp; mu = min(abs(mu),0.75); DAE.x = xold + mu*inc(1:DAE.n); DAE.y = yold + mu*inc(1+DAE.n:DAE.n+DAE.m); if Settings.distrsw, DAE.kg = kold + mu*inc(end); end case 6 % simple robust power flow method inc = robust*calcInc(nodyn,Jrow); Settings.error = max(abs(inc)); if Settings.error > 1.5*err_max_old && iteration robust = 0.25*robust; if robust < tol fm_disp('The otpimal multiplier is too small.') iteration = iter_max+1; break end else DAE.x = DAE.x + inc(1:DAE.n); DAE.y = DAE.y + inc(1+DAE.n:DAE.m+DAE.n); if Settings.distrsw, DAE.kg = DAE.kg + inc(end); end err_max_old = Settings.error; robust = 1; end end iteration = iteration + 1; Settings.error = max(abs(inc)); Settings.iter = iteration; err_vec(iteration) = Settings.error; if Settings.error < 1e-2 && PFmethod > 3 && Settings.switch2nr fm_disp('Switch to standard Newton-Raphson method.') PFmethod = 1; end fm_status('pf','update',[iteration, Settings.error],iteration) if Settings.show if Settings.error == Inf, Settings.error = 1e3; end fm_disp(['Iteration = ', num2str(iteration), ... ' Maximum Convergency Error = ', ... num2str(Settings.error)],1) end % stop if the error increases too much if iteration > 4 if err_vec(iteration) > 1000*err_vec(1) fm_disp('The error is increasing too much.') fm_disp('Convergence is likely not reachable.') convergence = 0; break end end end Settings.lftime = etime(clock,t0); if iteration > iter_max fm_disp(['Reached maximum number of iteration of NR routine without ' ... 'convergence'],2) convergence = 0; end % Total power injections and consumptions at network buses % Pl and Ql computation (shunts only) DAE.g = zeros(DAE.m,1); fm_call('load0'); Bus.Pl = DAE.g(Bus.a); Bus.Ql = DAE.g(Bus.v); %Pg and Qg computation fm_call('gen0'); Bus.Pg = DAE.g(Bus.a); Bus.Qg = DAE.g(Bus.v); if ~Settings.distrsw SW = setpg_sw(SW,'all',Bus.Pg(SW.bus)); end % adjust powers in case of PQ generators adjgen_pq(PQ) % memory allocation for dynamic variables & state variables indicization if nodyn == 1; DAE.x = []; DAE.f = []; DAE.n = 0; end DAE.npf = DAE.n; m_old = DAE.m; fm_dynidx; % rebuild algebraic variables and vectors m_diff = DAE.m-m_old; if m_diff DAE.y = [DAE.y;zeros(m_diff,1)]; DAE.g = [DAE.g;zeros(m_diff,1)]; DAE.Gy = sparse(DAE.m,DAE.m); end % rebuild state variables and vectors if DAE.n ~= 0 DAE.f = [DAE.f; ones(DAE.n-DAE.npf,1)]; % differential equations DAE.x = [DAE.x; ones(DAE.n-DAE.npf,1)]; % state variables DAE.Fx = sparse(DAE.n,DAE.n); % state Jacobian df/dx DAE.Fy = sparse(DAE.n,DAE.m); % state Jacobian df/dy DAE.Gx = sparse(DAE.m,DAE.n); % algebraic Jacobian dg/dx end % build cell arrays of variable names fm_idx(1) if (Settings.vs == 1), fm_idx(2), end % initializations of state variables and components if Settings.static fm_disp('* * * Dynamic components are not initialized * * *') end if convergence Settings.init = 1; else Settings.init = -1; end fm_rmgen(-1); % initialize function for removing static generators fm_call('0'); % compute initial state variables % power flow result visualization fm_disp(['Power Flow completed in ',num2str(Settings.lftime),' s']) if Settings.showlf == 1 || ishandle(Fig.stat) fm_stat; else if Settings.beep, beep, end end if ishandle(Fig.threed), fm_threed('update'), end % initialization of all equations & Jacobians refreshJac fm_call('i'); % build structure "Snapshot" if isempty(Settings.t0) && ishandle(Fig.main) hdl = findobj(Fig.main,'Tag','EditText3'); Settings.t0 = str2num(get(hdl,'String')); end if ~Settings.locksnap && Bus.n <= 5000 && DAE.n < 5000 Snapshot = struct( ... 'name','Power Flow Results', ... 'time',Settings.t0, ... 'y',DAE.y, ... 'x',DAE.x,... 'Ybus',Line.Y, ... 'Pg',Bus.Pg, ... 'Qg',Bus.Qg, ... 'Pl',Bus.Pl, ... 'Ql',Bus.Ql, ... 'Gy',DAE.Gy, ... 'Fx',DAE.Fx, ... 'Fy',DAE.Fy, ... 'Gx',DAE.Gx, ... 'Ploss',sum(Bus.Pg)-sum(Bus.Pl), ... 'Qloss',sum(Bus.Qg)-sum(Bus.Ql), ... 'it',1); else if Bus.n > 5000 fm_disp(['Snapshots are disabled for networks with more than 5000 ' ... 'buses.']) end if DAE.n > 5000 fm_disp(['Snapshots are disabled for networks with more than 5000 ' ... 'state variables.']) end end fm_status('pf','close') LIB.selbus = min(LIB.selbus,Bus.n); if ishandle(Fig.lib), set(findobj(Fig.lib,'Tag','Listbox1'), ... 'String',Bus.names, ... 'Value',LIB.selbus); end % ----------------------------------------------- function refreshJac global DAE DAE.g = zeros(DAE.m,1); % ----------------------------------------------- function refreshGen(nodyn) global DAE SW PV if nodyn, DAE.Fx = 1; end Fxcall_sw(SW,'full') Fxcall_pv(PV) % ----------------------------------------------- function inc = calcInc(nodyn,Jrow) global DAE Settings SW PV DAE.g = zeros(DAE.m,1); if Settings.distrsw % distributed slack bus fm_call('kgpf'); if nodyn, DAE.Fx = 1; end inc = -[DAE.Fx,DAE.Fy,DAE.Fk;DAE.Gx,DAE.Gy,DAE.Gk;Jrow]\ ... [DAE.f; DAE.g; DAE.y(SW.refbus)]; else % single slack bus fm_call('l'); if nodyn, DAE.Fx = 1; end Fxcall_sw(SW,'full') Fxcall_pv(PV) inc = -[DAE.Fx, DAE.Fy; DAE.Gx, DAE.Gy]\[DAE.f; DAE.g]; end
github
Sinan81/PSAT-master
zbuild.m
.m
PSAT-master/psat-oct/psat/zbuild.m
2,232
utf_8
19b01a90de020a329cd2a597231ecf5a
% This program forms the complex bus impedance matrix by the method % of building algorithm. Bus zero is taken as reference. % Copyright (c) 1998 by H. Saadat % % Update By s.m. Shariatzadeh For Psat Data Format function [Zbus] = zbuild(linedata) nl = linedata(:,1); nr = linedata(:,2); R = linedata(:,8); X = linedata(:,9); nbr = length(linedata(:,1)); nbus = max(max(nl), max(nr)); for k=1:nbr if R(k) == inf || X(k) == inf R(k) = 99999999; X(k) = 99999999; end end ZB = R + j*X; Zbus = zeros(nbus, nbus); tree = 0; %%%%new % Adding a branch from a new bus to reference bus 0 for I = 1:nbr ntree(I) = 1; if nl(I) == 0 || nr(I) == 0 if nl(I) == 0 n = nr(I); elseif nr(I) == 0 n = nl(I); end if abs(Zbus(n, n)) == 0 Zbus(n,n) = ZB(I); tree = tree + 1; %%new else Zbus(n,n) = Zbus(n,n)*ZB(I)/(Zbus(n,n) + ZB(I)); end ntree(I) = 2; end end Zbus % Adding a branch from new bus to an existing bus while tree < nbus %%% new for n = 1:nbus nadd = 1; if abs(Zbus(n,n)) == 0 for I = 1:nbr if nadd == 1; if nl(I) == n || nr(I) == n if nl(I) == n k = nr(I); elseif nr(I) == n k = nl(I); end %if abs(Zbus(k,k)) ~= 0 for m = 1:nbus if m ~= n Zbus(m,n) = Zbus(m,k); Zbus(n,m) = Zbus(m,k); end end Zbus(n,n) = Zbus(k,k) + ZB(I); tree=tree+1; %%new nadd = 2; ntree(I) = 2; %else, end end end end end end end %%%%%%new % Adding a link between two old buses for n = 1:nbus for I = 1:nbr if ntree(I) == 1 if nl(I) == n || nr(I) == n if nl(I) == n k = nr(I); elseif nr(I) == n k = nl(I); end DM = Zbus(n,n) + Zbus(k,k) + ZB(I) - 2*Zbus(n,k); for jj = 1:nbus AP = Zbus(jj,n) - Zbus(jj,k); for kk = 1:nbus AT = Zbus(n,kk) - Zbus(k, kk); DELZ(jj,kk) = AP*AT/DM; end end Zbus = Zbus - DELZ; ntree(I) = 2; end end end end
github
Sinan81/PSAT-master
fm_cpf.m
.m
PSAT-master/psat-oct/psat/fm_cpf.m
21,292
utf_8
7609245ef32db6f92230691609da6df6
function lambda_crit = fm_cpf(fun) % FM_CPF continuation power flow routines for computing nose curves % and determining critical points (saddle-node bifurcations) % % [LAMBDAC] = FM_CPF % % LAMBDAC: loading paramter at critical or limit point % %see also CPF structure and FM_CPFFIG % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 16-Sep-2003 %Version: 1.0.1 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano fm_var global Settings if ~autorun('Continuation Power Flow',0), return, end lambda_crit = []; lastwarn('') % Settings if CPF.ilim ilim = CPF.flow; else ilim = 0; end type = double(~CPF.sbus); if type && SW.n == 1 && Supply.n == 1 if Supply.bus ~= SW.bus fm_disp(' * * ') fm_disp('Only one Supply found. Single slack bus model will be used.') type = 0; end end stop = CPF.type - 1; vlim = CPF.vlim; qlim = CPF.qlim; perp = ~(CPF.method - 1); hopf = 1; if strcmp(fun,'atc') || strcmp(fun,'gams') one = 1; else one = 0; end %if PV.n+SW.n == 1, type = 0; end if CPF.show fm_disp if type fm_disp('Continuation Power Flow - Distribuited Slack Bus') else fm_disp('Continuation Power Flow - Single Slack Bus') end fm_disp(['Data file "',Path.data,File.data,'"']) fm_disp if perp fm_disp('Corrector Method: Perpendicular Intersection') else fm_disp('Corrector Method: Local Parametrization') end if vlim fm_disp('Check Voltage Limits: Yes') else fm_disp('Check Voltage Limits: No') end if qlim fm_disp('Check Generator Q Limits: Yes') else fm_disp('Check Generator Q Limits: No') end if ilim fm_disp('Check Flow Limits: Yes') else fm_disp('Check Flow Limits: No') end fm_disp end % Initializations of vectors and matrices % ---------------------------------------------------------------------- % disable conversion to impedance for PQ loads forcepq = Settings.forcepq; Settings.forcepq = 1; nodyn = 0; % initialization of the state vector and Jacobian matices if DAE.n > 0 DAE.f = ones(DAE.n,1); % state variable time derivatives fm_xfirst; DAE.Fx = sparse(DAE.n,DAE.n); % Dx(f) DAE.Fy = sparse(DAE.n,DAE.m); % Dy(f) DAE.Gx = sparse(DAE.m,DAE.n); % Dx(g) DAE.Fl = sparse(DAE.n,1); DAE.Fk = sparse(DAE.n,1); else % no dynamic components nodyn = 1; DAE.n = 1; DAE.f = 0; DAE.x = 0; DAE.Fx = 1; DAE.Fy = sparse(1,DAE.m); DAE.Gx = sparse(DAE.m,1); DAE.Fl = 0; DAE.Fk = 0; end PV2PQ = Settings.pv2pq; noDem = 0; noSup = 0; sp = ' * '; Settings.pv2pq = 0; Imax = getflowmax_line(Line,ilim); switch ilim case 1, fw = 'I '; case 2, fw = 'P '; case 3, fw = 'S '; end if CPF.areaannualgrowth, growth_areas(Areas,'area'), end if CPF.regionannualgrowth, growth_areas(Regions,'region'), end % if no Demand.con is found, the load direction % is assumed to be the one of the PQ load if Demand.n no_dpq = findzero_demand(Demand); if ~isempty(no_dpq), fm_disp for i = 1:length(no_dpq) fm_disp(['No power direction found in "Demand.con" for Bus ', ... Bus.names{Demand.bus(no_dpq(i))}]) end fm_disp('Continuation load flow routine may have convergence problems.',2) fm_disp end else noDem = 1; idx = findpos_pq(PQ); Demand = add_demand(Demand,dmdata_pq(PQ,idx)); PQ = pqzero_pq(PQ,idx); end PQgen = pqzero_pq(PQgen,'all'); % if no Supply.con is found, the load direction % is assumed to be the one of the PV or the SW generator if Supply.n && ~Syn.n no_sp = findzero_supply(Supply); if ~isempty(no_sp), fm_disp if length(no_sp) == Supply.n fm_disp(['No power directions found in "Supply.con" for all buses.']) if noDem fm_disp('Supply data will be ignored.') noSup = 1; Supply = remove_supply(Supply,[1:Supply.n]); if qlim && type, SW = move2sup_sw(SW); end %SW = move2sup_sw(SW); %PV = move2sup_pv(PV); else fm_disp('Remove "Supply" components or set power directions.') fm_disp('Continuation power flow interrupted',2) if CPF.show set(Fig.main,'Pointer','arrow'); end return end else for i = 1:length(no_sp) fm_disp(['No power direction found in "Supply.con" for Bus ', ... Bus.names{Supply.bus(no_sp(i))}]) end fm_disp('Continuation power flow routine may have convergence problems.',2) fm_disp end end else noSup = 1; Supply = remove_supply(Supply,[1:Supply.n]); if qlim && type, SW = move2sup_sw(SW); end end % Newton-Raphson routine settings iter_max = Settings.lfmit; iterazione = 0; tol = CPF.tolc; tolf = CPF.tolf; tolv = CPF.tolv; proceed = 1; sigma_corr = 1; if DAE.n == 0, DAE.n = 1; end Kjac = sparse(1,DAE.m+DAE.n+2); Ljac = sparse(1,DAE.m+DAE.n+2); kjac = sparse(1,DAE.m+DAE.n+1); Kjac(1,DAE.n+SW.refbus) = 1; kjac(1,DAE.n+SW.refbus) = 1; % chose a PQ to display the CPF progress in the main window PQidx = pqdisplay_pq(PQ); fm_snap('cleansnap') if ~PQidx % absence of PQ buses PQidx = pqdisplay_demand(Demand); if ~PQidx if ~perp perp = 1; fm_disp('* * * Switch to perpendicular intersection * * * ') end PQidx = 1; end end PQvdx = PQidx + Bus.n; % --------------------------------------------------------------------- % Continuation Power Flow Routine % --------------------------------------------------------------------- tic fm_status('cpf','init',12,{'m'},{'-'},{Theme.color11},[0 1.2]) l_vect = []; lambda = CPF.linit; DAE.lambda = lambda; lambda_crit = CPF.linit; kg = 0; lambda_old = -1; Jsign = 0; Jsign_old = 0; Sflag = 1; ksign = 1; Qmax_idx = []; Qmin_idx = []; Vmax_idx = []; Vmin_idx = []; Iij_idx = []; Iji_idx = []; Iij = ones(Line.n,1); Iji = ones(Line.n,1); Qswmax_idx = []; Qswmin_idx = []; pqlim_pq(PQ,vlim,0,0,0); fm_out(0,0,0) if nodyn DAE.Fx = 1; Varout.idx = Varout.idx+1; end fm_out(1,0,0) % initial Jacobian Gk DAE.Gk = sparse(DAE.m,1); if type, Gkcall_supply(Supply), end if type, Gkcall_pv(PV), end Gkcall_sw(SW) DAE.kg = 0; Gycall_line(Line) if noSup Gyreactive_pv(PV) else Gycall_pv(PV) end Gyreactive_sw(SW) % First predictor step % --------------------------------------------------------------- Jsign = 1; count_qmin = 0; kqmin = 1; d_lambda = 0; lambda_old = CPF.linit; inc = zeros(DAE.n+DAE.m+2,1); Ljac(end) = 1; % critical point y_crit = DAE.y; x_crit = DAE.x; k_crit = kg; l_crit = lambda; while 1 cpfmsg = []; % corrector step % --------------------------------------------------------------- lim_hb = 0; lim_lib = 0; y_old = DAE.y; x_old = DAE.x; kg_old = kg; lambda_old = lambda; corrector = 1; if PV.n, inc(DAE.n+getbus_pv(PV,'v')) = 0; end if SW.n, inc(DAE.n+getbus_sw(SW,'v')) = 0; end while corrector if ishandle(Fig.main) if ~get(Fig.main,'UserData'), break, end end iter_corr = 0; Settings.error = tol+1; while Settings.error > tol if (iter_corr > iter_max), break, end if ishandle(Fig.main) if ~get(Fig.main,'UserData'), break, end end DAE.lambda = lambda; DAE.Fl = sparse(DAE.n,1); DAE.Gl = sparse(DAE.m,1); DAE.Gk = sparse(DAE.m,1); % call component functions fm_call('kg') if nodyn, DAE.Fx = 1; end gcall_pq(PQgen) glambda_demand(Demand,lambda) glambda_supply(Supply,lambda,type*kg) glambda_syn(Syn,lambda,kg) glambda_tg(Tg,lambda,kg) Glcall_pl(Pl) Glcall_mn(Mn) Glcall_demand(Demand) Glcall_supply(Supply) Glcall_syn(Syn) Glcall_tg(Tg) Glcall_wind(Wind) Flcall_ind(Ind) if type, Gkcall_supply(Supply), end if noSup glambda_pv(PV,lambda,type*kg) glambda_sw(SW,lambda,kg) greactive_pv(PV) if type, Gkcall_pv(PV), end Glcall_pv(PV) Gyreactive_pv(PV) Glcall_sw(SW) else gcall_pv(PV); Gycall_pv(PV) glambda_sw(SW,1,kg) end Glreac_pv(PV) Fxcall_pv(PV) Gkcall_sw(SW) greactive_sw(SW) Gyreactive_sw(SW) Glreac_sw(SW) Fxcall_sw(SW,'onlyq') if perp*iterazione Cinc = sigma_corr*inc; %cont_eq = Cinc'*([DAE.x;DAE.y;kg;lambda]- ... % [x_old; y_old; kg_old; lambda_old]-Cinc); Cinc(end-1) = 0; cont_eq = Cinc'*([DAE.x;DAE.y;0;lambda]- ... [x_old; y_old; 0; lambda_old]-Cinc); inc_corr = -[DAE.Fx, DAE.Fy, DAE.Fk, DAE.Fl; DAE.Gx, DAE.Gy, ... DAE.Gk, DAE.Gl; Cinc'; Kjac]\[DAE.f; DAE.g; ... cont_eq; DAE.y(SW.refbus)]; if strcmp(lastwarn,['Matrix is singular to working ' ... 'precision.']) Cinc(end) = 0; cont_eq = Cinc'*([DAE.x;DAE.y;0;0]- ... [x_old; y_old; 0; 0]-Cinc); inc_corr = -[DAE.Fx, DAE.Fy, DAE.Fk, DAE.Fl; DAE.Gx, DAE.Gy, ... DAE.Gk, DAE.Gl; Cinc'; Kjac]\[DAE.f; DAE.g; ... cont_eq; DAE.y(SW.refbus)]; end else if iterazione cont_eq = DAE.y(PQvdx)-sigma_corr*inc(PQvdx+DAE.n)-y_old(PQvdx); else cont_eq = lambda - sigma_corr*d_lambda - lambda_old; end inc_corr = -[DAE.Fx, DAE.Fy, DAE.Fk, DAE.Fl; DAE.Gx, DAE.Gy, ... DAE.Gk, DAE.Gl; Ljac; Kjac]\[DAE.f; DAE.g; ... cont_eq; DAE.y(SW.refbus)]; end DAE.x = DAE.x + inc_corr(1:DAE.n); DAE.y = DAE.y + inc_corr(1+DAE.n:DAE.m+DAE.n); kg = kg + inc_corr(end-1); %[xxx,iii] = max(abs(inc_corr)); %disp([xxx,iii]) lambda = lambda + inc_corr(end); iter_corr = iter_corr + 1; Settings.error = max(abs(inc_corr)); end % Generator reactive power computations if qlim DAE.g = zeros(DAE.m,1); fm_call('load'); glambda_demand(Demand,lambda) Bus.Ql = DAE.g(Bus.v); fm_call('gen'); glambda_demand(Demand,lambda) Bus.Qg = DAE.g(Bus.v); DAE.g = zeros(DAE.m,1); [Qmax_idx,Qmin_idx] = pvlim_pv(PV); [Qswmax_idx,Qswmin_idx] = swlim_sw(SW); if ~kqmin Qmin_idx = []; Qswmin_idx = []; end end [PQ,lim_v] = pqlim_pq(PQ,vlim,sp,lambda,one); if lim_v sigma_corr = 1; proceed = 1; if stop > 1 sigma_corr = -1; break end end if ilim [Fij,Fji] = flows_line(Line,ilim); Iij_idx = find(Fij > Imax & Iij); Iji_idx = find(Fji > Imax & Iji); end % determination of the initial loading factor in case % of infeasible underexcitation of generator at zero % load condition if ~iterazione && qlim && ~isempty(Qmin_idx) && count_qmin <= 5 count_qmin = count_qmin+1; if count_qmin > 5 fm_disp([sp,'There are generator Qmin limit violations at ' ... 'the initial point.']) fm_disp([sp,'Generator Qmin limits will be disabled.']) kqmin = 0; lambda_old = CPF.linit; lambda = CPF.linit; sigma_corr = 1; else lambda_old = lambda_old + d_lambda; fm_disp([sp,'Initial loading parameter changed to ', ... fvar(lambda_old-one,4)]) end proceed = 0; break end % Check for Hopf Bifurcations if DAE.n >= 2 && CPF.hopf && hopf As = DAE.Fx-DAE.Fy*(DAE.Gy\DAE.Gx); if DAE.n > 100 opt.disp = 0; auto = eigs(As,20,'SR',opt); else auto = eig(full(As)); end auto = round(auto/Settings.lftol)*Settings.lftol; hopf_idx = find(real(auto) > 0); if ~isempty(hopf_idx) hopf = 0; hopf_idx = find(abs(imag(auto(hopf_idx))) > 1e-5); if ~isempty(hopf_idx) lim_hb = 1; fm_disp([sp,'Hopf bifurcation encountered.']) end if stop sigma_corr = -1; break end end end if ~isempty(Iij_idx) && ilim Iij_idx = Iij_idx(1); Iij(Iij_idx) = 0; fm_disp([sp,fw,'from bus #',fvar(Line.fr(Iij_idx),4), ... ' to bus #',fvar(Line.to(Iij_idx),4), ... ' reached I_max at lambda = ',fvar(lambda-one,9)],1) sigma_corr = 1; proceed = 1; if stop > 1 proceed = 1; sigma_corr = -1; break end end if ~isempty(Iji_idx) && ilim Iji_idx = Iji_idx(1); Iji(Iji_idx) = 0; fm_disp([sp,fw,'from bus #',fvar(Line.to(Iji_idx),4), ... ' to bus #',fvar(Line.fr(Iji_idx),4), ... ' reached I_max at lambda = ',fvar(lambda-one,9)],1) sigma_corr = 1; proceed = 1; if stop > 1 proceed = 1; sigma_corr = -1; break end end if lambda < CPF.linit cpfmsg = [sp,'lambda is lower than initial value']; if iterazione > 5 proceed = 0; break end end if abs(lambda-lambda_old) > 5*abs(d_lambda) && perp && iterazione ... && ~Hvdc.n fm_disp([sp,'corrector solution is too far from predictor value']) proceed = 0; break end if lambda > lambda_old && lambda < max(l_vect) && ~Hvdc.n fm_disp([sp,'corrector goes back increasing lambda']) proceed = 0; break end lim_q = (~isempty(Qmax_idx) || ~isempty(Qmin_idx) || ... (~isempty(Qswmax_idx) || ~isempty(Qswmin_idx))*type) && qlim; lim_i = (~isempty(Iij_idx) || ~isempty(Iji_idx)) && ilim; anylimit = (lim_q || lim_v || lim_i) && CPF.stepcut; if iter_corr > iter_max % no convergence if lambda_old < 0.5*max(l_vect) fm_disp([sp,'Convergence problems in the unstable curve']) lambda = -1; proceed = 1; break end if sigma_corr < 1e-3 proceed = 1; break end if CPF.show fm_disp([sp,'Max # of iters. at corrector step.']) fm_disp([sp,'Reduced Variable Increments in ', ... 'Corrector Step ', num2str(0.5*sigma_corr)]) end cpfmsg = [sp,'Reached maximum number of iterations ', ... 'for corrector step.']; proceed = 0; break elseif anylimit && sigma_corr > 0.11 proceed = 0; break elseif lim_q if ~isempty(Qmax_idx) PQgen = add_pq(PQgen,pqdata_pv(PV,Qmax_idx(1),'qmax',sp,lambda,one,noSup)); if noSup, PV = move2sup_pv(PV,Qmax_idx(1)); else PV = remove_pv(PV,Qmax_idx(1)); end elseif ~isempty(Qmin_idx) PQgen = add_pq(PQgen,pqdata_pv(PV,Qmin_idx(1),'qmin',sp,lambda,one,noSup)); if noSup PV = move2sup_pv(PV,Qmin_idx(1)); else PV = remove_pv(PV,Qmin_idx(1)); end elseif ~isempty(Qswmax_idx) PQgen = add_pq(PQgen,pqdata_sw(SW,Qswmax_idx(1),'qmax',sp,lambda,one)); SW = remove_sw(SW,Qswmax_idx(1)); elseif ~isempty(Qswmin_idx) PQgen = add_pq(PQgen,pqdata_sw(SW,Qswmin_idx(1),'qmin',sp,lambda,one)); SW = remove_sw(SW,Qswmin_idx(1)); end lim_lib = 1; Qmax_idx = []; Qmin_idx = []; Qswmax_idx = []; Qswmin_idx = []; if ~iterazione d_lambda = 0; lambda_old = CPF.linit; lambda = CPF.linit; if perp inc(end) = 1e-5; else Ljac(end) = 1; end else lambda = lambda_old; sigma_corr = 1; proceed = 0; break end else proceed = 1; sigma_corr = 1; if stop && ksign < 0, if lim_lib fm_disp([sp,'Saddle-Node Bifurcation encountered.']) else fm_disp([sp,'Limit-Induced Bifurcation encountered.']) end sigma_corr = -1; end break end end switch proceed case 1 if lambda < 0 && iterazione > 1 % needed to make consistent the last snapshot fm_call('kg') gcall_pq(PQgen) fm_disp([sp,'lambda < 0 at iteration ',num2str(iterazione)]) break end l_vect = [l_vect; lambda]; if CPF.show fm_disp(['Point = ',fvar(iterazione+1,5),'lambda =', ... fvar(lambda-one,9), ' kg =',fvar(kg,9)],1) end iterazione = iterazione + 1; fm_out(2,lambda,iterazione) fm_status('cpf','update',[lambda, DAE.y(PQvdx)],iterazione) if sigma_corr < tol, break, end sigma_corr = 1; if lambda > lambda_old y_crit = DAE.y; x_crit = DAE.x; k_crit = kg; l_crit = lambda; end case 0 DAE.y = y_old; DAE.x = x_old; if abs(lambda-CPF.linit) < 0.001 && ... abs(lambda-lambda_old) <= 10*abs(d_lambda) && ... iterazione > 1 fm_disp([sp,'Reached initial lambda.']) % needed to make consistent the last snapshot fm_call('kg') gcall_pq(PQgen) break end kg = kg_old; lambda = lambda_old; sigma_corr = 0.1*sigma_corr; if sigma_corr < tol, if ~isempty(cpfmsg) fm_disp(cpfmsg) end if iterazione == 0 fm_disp([sp,'Infeasible initial loading condition.']) else fm_disp([sp,'Convergence problem encountered.']) end break end end % stop routine % -------------------------------------------------------------- if iterazione >= CPF.nump && ~strcmp(fun,'gams') fm_disp([sp,'Reached maximum number of points.']) break end if ishandle(Fig.main) if ~get(Fig.main,'UserData'), break, end end % predictor step % -------------------------------------------------------------- DAE.lambda = lambda; % update Jacobians fm_call('kg') if nodyn, DAE.Fx = 1; end if noSup Gyreactive_pv(PV) else Gycall_pv(PV); end Gyreactive_sw(SW) if (DAE.m+DAE.n) > 500 [L,U,P] = luinc([DAE.Fx,DAE.Fy,DAE.Fk;DAE.Gx,DAE.Gy,DAE.Gk;kjac],1e-6); else [L,U,P] = lu([DAE.Fx,DAE.Fy,DAE.Fk;DAE.Gx,DAE.Gy,DAE.Gk;kjac]); end dz_dl = -U\(L\(P*[DAE.Fl;DAE.Gl;0])); Jsign_old = Jsign; Jsign = signperm(P)*sign(prod(diag(U))); if lim_lib fm_snap('assignsnap','new','LIB',lambda) elseif lim_hb fm_snap('assignsnap','new','HB',lambda) end if iterazione == 1 if noDem && lambda == 1 fm_snap('assignsnap','start','OP',lambda) elseif ~noDem && lambda == 0 fm_snap('assignsnap','start','OP',lambda) else fm_snap('assignsnap','start','Init',lambda) end end if Jsign ~= Jsign_old && Sflag && iterazione > 1 ksign = -1; Sflag = 0; if ~lim_lib, fm_snap('assignsnap','new','SNB',lambda), end end Norm = norm(dz_dl,2); if Norm == 0, Norm = 1; end d_lambda = ksign*CPF.step/Norm; d_lambda = min(d_lambda,0.35); d_lambda = max(d_lambda,-0.35); if ksign > 0, d_lambda = max(d_lambda,0); end if ksign < 0, d_lambda = min(d_lambda,0); end d_z = d_lambda*dz_dl; inc = [d_z; d_lambda]; if ~perp && iterazione a = inc(DAE.n+PQvdx); a = min(a,0.025); a = max(a,-0.025); inc(DAE.n+PQvdx) = a; Ljac(end) = 0; Ljac(DAE.n+PQvdx) = 1; end end fm_out(3,0,iterazione) fm_snap('assignsnap','new','End',Varout.t(end)) [lambda_crit, idx_crit] = max(Varout.t); if isnan(lambda_crit), lambda_crit = lambda; end if isempty(lambda_crit), lambda_crit = lambda; end if CPF.show fm_disp([sp,'Maximum Loading Parameter lambda_max = ', ... fvar(lambda_crit-one,9)],1) end % Visualization of results % -------------------------------------------------------------- if nodyn DAE.n = 0; Varout.idx = Varout.idx-1; end Settings.lftime = toc; Settings.iter = iterazione; DAE.y = y_crit; DAE.x = x_crit; kg = k_crit; lambda = l_crit; if ~isempty(DAE.y) if CPF.show fm_disp(['Continuation Power Flow completed in ', ... num2str(toc),' s'],1); end DAE.g = zeros(DAE.m,1); fm_call('load'); glambda_demand(Demand,lambda) % load powers Bus.Pl = DAE.g(Bus.a); Bus.Ql = DAE.g(Bus.v); % gen powers fm_call('gen') Bus.Qg = DAE.g(Bus.a); Bus.Pg = DAE.g(Bus.v); DAE.g = Settings.error*ones(DAE.m,1); if (Settings.showlf == 1 && CPF.show) || ishandle(Fig.stat) SDbus = [Supply.bus;Demand.bus]; report = cell(1,1); report{1,1} = ['Lambda_max = ', fvar(lambda_crit,9)]; %for i = 1:length(dl_dp) % report{2+i,1} = ['d lambda / d P ', ... % Bus.names{SDbus(i)},' = ', ... % fvar(dl_dp(i),9)]; %end fm_stat(report); end if CPF.show && ishandle(Fig.plot) fm_plotfig end end % Reset of SW, PV and PQ structures Settings.forcepq = forcepq; %PQgen = restore_pq(PQgen,0); %PQ = restore_pq(PQ); %PV = restore_pv(PV); %SW = restore_sw(SW); Demand = restore_demand(Demand); Supply = restore_supply(Supply); if CPF.show && ishandle(Fig.main) set(Fig.main,'Pointer','arrow'); Settings.xlabel = ['Loading Parameter ',char(92),'lambda (p.u.)']; Settings.tf = 1.2*lambda_crit; end fm_status('cpf','close') Settings.pv2pq = PV2PQ; CPF.lambda = lambda_crit; CPF.kg = kg; fm_snap('viewsnap',0) SNB.init = 0; LIB.init = 0; CPF.init = 1; OPF.init = 0; % -------------------------------- function s = signperm(P) % -------------------------------- [i,j,p] = find(sparse(P)); idx = find(i ~= j); q = P(idx,idx); s = det(q);
github
Sinan81/PSAT-master
fm_equiv.m
.m
PSAT-master/psat-oct/psat/fm_equiv.m
9,242
utf_8
67b053d39752e31aec4b900979ed8caf
function check = fm_equiv % FM_EQUIV computes simple static and dynamic network equivalents % %see also the function FM_EQUIVFIG % %Author: Federico Milano %Update: 02-Apr-2008 %Version: 0.1 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global EQUIV Settings Path File DAE Bus global Line PQ Shunt PV SW Syn Exc Pl Mn check = 0; if ~autorun('Network Equivalent',1) return end fm_disp(' ') switch EQUIV.equivalent_method case 1 fm_disp('Equivalencing procedure. Thevenin equivalents.') case 2 fm_disp('Equivalencing procedure. Dynamic equivalents.') otherwise fm_disp('Error: Unknown equivalencing procedure.',2) return end % define the bus list write_buslist if isempty(EQUIV.buslist) fm_disp('Error: There were problems in writing the bus list selection.',2) return end if EQUIV.island && EQUIV.stop_island fm_disp('Error: The equivalent procedure cannot continue',2) return end % check equivalent method consistency %if ~DAE.n && EQUIV.equivalent_method == 2 % fm_disp('The network does not contain dynamic data.') % fm_disp('Thevenin equivalent method will be used.') % EQUIV.equivalent_method = 1; %end % open data file for the equivalent network cd(Path.data) jobname = strrep(File.data,'(mdl)',''); fid = fopen([jobname,'_equiv.m'],'wt'); % headers fprintf(fid,['%% ',jobname,' (Equivalent network created by EQUIV)\n']); fprintf(fid,'%%\n\n'); % restore static data that can have been modified during power flow. SW = restore_sw(SW); PV = restore_pv(PV); PQ = restore_pq(PQ); Pl = restore_pl(Pl); Mn = restore_mn(Mn); Settings.init = 0; % write data write_bus(Bus,fid,EQUIV.buslist) write_line(Line,fid,EQUIV.buslist) write_pq(PQ,fid,EQUIV.buslist,'PQ') write_pl(Pl,fid,EQUIV.buslist) write_mn(Mn,fid,EQUIV.buslist) write_shunt(Shunt,fid,EQUIV.buslist) slack = write_sw(SW,fid,EQUIV.buslist); slack = write_pv(PV,fid,EQUIV.buslist,slack); [borderbus,gengroups,yi,y0,zth] = equiv_line(Line,fid); synidx = write_syn(Syn,fid,EQUIV.buslist); write_exc(Exc,fid,synidx,0); xbus = borderbus + Bus.n; nborder = length(borderbus); % write external buses Buseq = BUclass; Buseq.con = Bus.con(borderbus,:); Buseq.con(:,1) = xbus; Buseq.names = fm_strjoin('X',Bus.names(borderbus)); write(Buseq,fid,1:length(Buseq.names)) [idx1,idx2,busidx1,busidx2] = filter_line(Line,EQUIV.buslist); beq = zeros(length(EQUIV.buslist),1); peq = beq; qeq = beq; for i = 1:length(busidx1) [Pij,Qij,Pji,Qji] = flows_line(Line,'pq',idx1{i}); h = busidx1(i); beq(h) = EQUIV.buslist(h); peq(h) = -sum(Pij); qeq(h) = -sum(Qij); end for i = 1:length(busidx2) [Pij,Qij,Pji,Qji] = flows_line(Line,'pq',idx2{i}); h = busidx2(i); beq(h) = EQUIV.buslist(h); peq(h) = peq(h)-sum(Pji); qeq(h) = qeq(h)-sum(Qji); end ieq = find(beq); beq = beq(ieq); peq = peq(ieq); qeq = qeq(ieq); zth = zth(ieq); % take into account that the REI equivalent add a shunt load at the border if EQUIV.equivalent_method == 2 vbd = DAE.y(borderbus + Bus.n); vb2 = vbd.*vbd; peq = peq-real(y0).*vb2; % qeq = qeq-imag(y0).*vb2; end % compute and write synchronous machine equivalents if EQUIV.equivalent_method == 2 && Syn.n Syneq = SYclass; [Syneq.con,pf] = equiv_syn(Syn,borderbus,gengroups,yi); % discard generators that are producing negative active power gdx = find(peq > 1e-3); if ~isempty(gdx) % synchronous machines bdx = find(ismember(Syneq.con(:,1),beq(gdx)+Bus.n)); Syneq.con = Syneq.con(bdx,:); Syneq.bus = Syneq.con(:,1); nsyn = length(Syneq.bus); Syneq.u = ones(nsyn,1); Syneq.n = nsyn; write(Syneq,fid,xbus); % automatic voltage regulators AVReq = AVclass; AVReq.con = equiv_exc(Exc,gengroups(gdx),pf(bdx),length(synidx)); AVReq.syn = AVReq.con(:,1); AVReq.n = length(AVReq.syn); AVReq.u = ones(AVReq.n,1); write(AVReq,fid,AVReq.syn,length(synidx)); end end % write slack bus data if needed if ~slack [pmax,h] = max(abs(peq)); [v,a,p] = veq(zth(h),peq(h),qeq(h),beq(h)); data = [beq(h)+Bus.n,Settings.mva,getkv_bus(Bus,beq(h),1),v,a,0,0,1.1,0.9,p,1,1,1]; SWeq = SWclass; SWeq.con = data; SWeq.bus = beq(h)+Bus.n; SWeq.n = 1; SWeq.u = 1; slack = write(SWeq,fid,beq(h)+Bus.n); beq(h) = []; peq(h) = []; qeq(h) = []; end % write equivalent PV or PQ generators at external buses xbeq = beq+Bus.n; switch EQUIV.gentype case 1 data = zeros(length(beq),11); for h = 1:length(beq) [v,a,p,q] = veq(zth(h),peq(h),qeq(h),beq(h)); data(h,:) = [xbeq(h),Settings.mva,getkv_bus(Bus,beq(h),1),p,v,0,0,1.1,0.9,1,1]; end PVeq = PVclass; PVeq.con = data; PVeq.bus = xbeq; PVeq.n = length(beq); PVeq.u = ones(length(beq),1); write(PVeq,fid,xbeq,slack); case 2 data = zeros(length(beq),9); pdx = []; for h = 1:length(beq) [v,a,p,q] = veq(zth(h),peq(h),qeq(h),beq(h)); data(h,:) = [xbeq(h),Settings.mva,getkv_bus(Bus,beq(h),1),p,q,1.1,0.9,1,1]; if abs(p) < 1e-3 && abs(q) < 1e-3 pdx = [pdx; h]; end end PQeq = PQclass; if ~isempty(pdx) data(pdx,:) = []; xbeq(pdx) = []; end PQeq.con = data; PQeq.bus = xbeq; PQeq.n = length(xbeq); PQeq.u = ones(length(xbeq),1); write(PQeq,fid,xbeq,'PQgen'); end % close file fclose(fid); cd(Path.local) % everything ok check = 1; % ------------------------------------------------------------------------- % This function returns the indexes of the current bus list % ------------------------------------------------------------------------- function write_buslist global EQUIV Line Bus Path File EQUIV.buslist = []; switch EQUIV.bus_selection case 1 % voltage level buslist = find(getkv_bus(Bus,0,0) == EQUIV.bus_voltage); if isempty(buslist) disp(['There is no bus whose nominal voltage is ', ... num2str(EQUIV.bus_voltage)]) return end case 2 % area buslist = find(getarea_bus(Bus,0,0) == EQUIV.area_num); if isempty(buslist) disp(['There is no bus whose nominal voltage is >= ', ... num2str(EQUIV.bus_voltage)]) return end case 3 % region buslist = find(getregion_bus(Bus,0,0) == EQUIV.region_num); if isempty(buslist) disp(['There is no bus whose nominal voltage is >= ', ... num2str(EQUIV.bus_voltage)]) return end case 4 % voltage threshold buslist = find(getkv_bus(Bus,0,0) >= EQUIV.bus_voltage); if isempty(buslist) disp(['There is no bus whose nominal voltage is >= ', ... num2str(EQUIV.bus_voltage)]) return end case 5 % custom bus list if isempty(EQUIV.custom_file) disp('Warning: No bus list file selected!') end [fid,msg] = fopen([EQUIV.custom_path,EQUIV.custom_file],'rt'); if fid == -1 disp(msg) disp('An empty bus list is returned.') return end % scanning bus list file buslist = []; while ~feof(fid) busname = deblank(fgetl(fid)); buslist = [buslist; strmatch(busname,Bus.names,'exact')]; end if isempty(buslist) disp('There is no bus whose name matches the given bus list.') return end otherwise disp('Unkonwn bus selection type. Empty bus list is returned.') end % removing repetitions buslist = unique(buslist); % bus depth nd = EQUIV.bus_depth; % line indexes busfr = Line.fr; busto = Line.to; idxLd = [busfr; busto]; idxLq = [busto; busfr]; % bus search newbus = []; for i = 1:length(buslist) busi = buslist(i); newbus = [newbus; searchbus(nd,busi,idxLd,idxLq)]; end % removing repetions again if ~isempty(newbus) buslist = unique([buslist; newbus]); end % check equivalent network connectivity Bn = length(buslist); Busint(buslist,1) = [1:Bn]; busmax = length(Busint); idxL = find(ismember(busfr,buslist).*ismember(busto,buslist)); Lfr = Busint(busfr(idxL)); Lto = Busint(busto(idxL)); u = Line.u(idxL); % connectivity matrix connect_mat = ... sparse(Lfr,Lfr,1,Bn,Bn) + ... sparse(Lfr,Lto,u,Bn,Bn) + ... sparse(Lto,Lto,u,Bn,Bn) + ... sparse(Lto,Lfr,1,Bn,Bn); % find network islands using QR factorization [Q,R] = qr(connect_mat); idx = find(abs(sum(R,2)-diag(R)) < 1e-5); nisland = length(idx); if nisland > 1 disp(['There are ',num2str(nisland),' islanded networks.']) EQUIV.island = nisland; else disp(['The equivalent network is interconnected.']) end EQUIV.buslist = buslist; % ------------------------------------------------------------------------- % recursive bus search up to the desired depth % ------------------------------------------------------------------------- function newbus = searchbus(nd,busi,idxLd,idxLq) newbus = []; if ~nd, return, end idx = find(idxLd == busi); if ~isempty(idx) newbus = idxLq(idx); for i = 1:length(newbus) newbus = [newbus; searchbus(nd-1,newbus(i),idxLd,idxLq)]; end end % ------------------------------------------------------------------------- % compute the voltage and power at the recieving end of external lines % ------------------------------------------------------------------------- function [v,a,p,q] = veq(zth,peq,qeq,idx) global DAE Bus if isempty(zth), return, end v1 = DAE.y(Bus.n+idx)*exp(i*DAE.y(idx)); i21 = (peq-i*qeq)/conj(v1); v2 = v1 + zth*i21; s = v2*conj(i21); p = real(s); q = imag(s); v = abs(v2); a = angle(v2);
github
Sinan81/PSAT-master
fm_omib.m
.m
PSAT-master/psat-oct/psat/fm_omib.m
4,194
utf_8
1348cdbb3b301d810cbdf9f800d9081c
function fm_omib %FM_OMIB computes the equivalent OMIB for a multimachine network and its % transient stability margin. % % see also FM_INT and FM_CONNECTIVITY % %Author: Sergio Mora & Federico Milano %Date: July 2006 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2006 Segio Mora & Federico Milano global OMIB Line Bus Syn DAE jay % ------------------------------------------------------------------------- % initial conditions % ------------------------------------------------------------------------- [gen,ib] = setdiff(getbus_syn(Syn),Bus.island); Pm = getvar_syn(Syn,ib,'pm'); ang = getvar_syn(Syn,ib,'delta'); omega = getvar_syn(Syn,ib,'omega'); M = getvar_syn(Syn,ib,'M'); to = 0; do = sum(M.*ang)/sum(M); wo = sum(M.*omega)/sum(M)-1; E = getvar_syn(Syn,ib,'e1q'); dt = 0.005; ngen = length(ib); ygen = -jay./getvar_syn(Syn,ib,'xd1'); bgen = getbus_syn(Syn,ib); bus0 = [1:ngen]'; nbus = Bus.n + ngen; Y11 = sparse(bus0, bus0, ygen, ngen, ngen); Y21 = sparse(bgen, bus0, -ygen, Bus.n, ngen); Y12 = sparse(bus0, bgen, -ygen, ngen, Bus.n); Yint = Y11 - Y12*[Line.Y\Y21]; % ------------------------------------------------------------------------- % sorting of rotor angles % ------------------------------------------------------------------------- [delta,pos] = sort(ang); difangle = delta(2:ngen) - delta(1:ngen-1); [difmax,idxmax] = sort(difangle,1,'descend'); m = 1; i = 1; while (m <= 5) && (m <= fix(ngen/2)) % select the m-th critical machine candidate cm = pos((idxmax(m)+1):ngen); ncm = pos(1:idxmax(m)); if ~isempty(cm) % compute the m-th equivalent OMIB data = equiv_omib(M,Pm,cm,ncm,Yint,E); % compute the critical clearing time [du,tu,margen] = critical_time(data,dt,to,do,wo); CMvec{i} = cm; NCMvec{i} = ncm; MT(i) = data(1); Pmax(i) = data(2); sig(i) = data(3); PM(i) = data(4); Pc(i) = data(5); dif(i) = difmax(m); DU(:,i) = du; TU(:,i) = tu; MAR(:,i) = margen; i = i + 1; end m = m + 1; end [mcri,i] = min(MAR); OMIB.cm = CMvec{i}; OMIB.ncm = NCMvec{i}; OMIB.mt = MT(i); OMIB.pmax = Pmax(i); OMIB.pc = Pc(i); OMIB.sig = sig(i); OMIB.du = DU(i); OMIB.tu = TU(i); OMIB.margin = MAR(i); % ------------------------------------------------------------------------- function data = equiv_omib(M,Pm,cm,ncm,Y,E) Mc = sum(M(cm)); Mn = sum(M(ncm)); Pc = (Mn*([E(cm)]'*[real(Y(cm,cm))*E(cm)]) - ... Mc*([E(ncm)]'*[real(Y(ncm,ncm))*E(ncm)]))/(Mc+Mn); PM = (Mn*sum(Pm(cm))-Mc*sum(Pm(ncm)))/(Mc+Mn); M = (Mc*Mn)/(Mc+Mn); EE = [E(cm)]'*[Y(cm,ncm)*E(ncm)]; V = ((Mc-Mn)*real(EE))/(Mc+Mn)+j*imag(EE); sig = -angle(V); Pmax = abs(V); data = [M,Pmax,sig,PM,Pc]; disp(data) % ------------------------------------------------------------------------- function [deltau,omegau,margin] = critical_time(data,dt,to,delta0,omega0) global Settings Wb = 2*pi*Settings.freq; iter_max = Settings.dynmit; tol = Settings.dyntol; %Pgen = inline('d(5)+d(2)*sin(delta-d(3))','d','delta'); t = 0; tu = inf; deltau = inf; omegau = inf; Mt = data(1); Pmax = data(2); d0 = data(3); Pm = data(4); Pc = data(5); Pe_old = Pc + Pmax*sin(delta0-d0); Pa_old = Pm - Pe_old; f = zeros(2,1); f(1) = Wb*omega0; f(2) = Pa_old/Mt; fn = f; x = [delta0; omega0]; xa = x; inc = ones(2,1); k = 0; while k < 200 inc(1) = 1; h = 0; while max(abs(inc)) > tol if (h > iter_max), break, end f(1) = Wb*x(2); f(2) = (Pm - Pc - Pmax*sin(x(1)-d0))/Mt; tn = x - xa - 0.5*dt*(f+fn); inc(1) = tn(2)/(Pmax*cos(x(1)-d0)); inc(2) = -tn(1)/Wb; x = x + inc; h = h + 1; disp([h, x(1), x(2), inc(1), inc(2), f(1), f(2)]) pause end Pe = Pc + Pmax*sin(x(1)-d0); Pa = Pm - Pe; if (Pe_old > Pm) && (Pe < Pm) && ((Pa-Pa_old) > 0) deltau = 0.5*(x(1) + xa(1)); % instability condition omegau = 0.5*(x(2) + xa(2)); tu = t - dt/2; break end if (Pa < 0) && (xa(2) > 0) && (x(2) < 0) deltau = 0.5*(x(1) + xa(1)); % stability condition omegau = 0.5*(x(2) + xa(2)); tu = t - dt/2; break end xa = x; fn = f; k = k + 1; t = t + dt; end margin = -0.5*Mt*omegau*omegau;
github
Sinan81/PSAT-master
psed.m
.m
PSAT-master/psat-oct/psat/psed.m
5,198
utf_8
28f1dea3f0f86d9d7bc4f5e2e3f96903
function psed(expression,string1,string2,type) %PSED change strings within files % %PSED(EXPRESSION,STRING1,STRING2,TYPE) % EXPRESSION: regular expression % STRING1: the string to be changed. % STRING2: the new string % TYPE: 1 - change all the occurrence % 2 - change only Matlab variable type % 3 - as 2 but no file modifications % 4 - as 1 but span all subdirectories % %see also PGREP % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 18-Feb-2003 %Update: 30-Mar-2004 %Version: 1.0.2 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano if nargin < 4, disp('Check synthax ...') disp(' ') help psed, return, end if ~ischar(expression) disp('First argument (EXPRESSION) has to be a string.') return end if ~ischar(string1) || isempty(string1), disp('Second argument (STRING1) has to be a string.') return end if ~ischar(string2) disp('Third argument (STRING2) has to be a string.') return end if isempty(string2) string2 = ''; end if ~isnumeric(type) || length(type) > 1 || rem(type,1) || type > 4 || ... type <= 0 disp('Fourth argument has to be a scalar integer [1-4]') return end a = dir(expression); if isempty(a) disp('No file name matches the given expression.') return end file = {a.name}'; a = dir(pwd); names = {a.name}'; isdir = [a.isdir]'; if type == 4, disp(' ') disp('Spanning directories ...') disp(' ') disp(pwd) file = deepdir(expression,names,file,isdir,pwd); type = 1; else disp(' ') disp(pwd) end n_file = length(file); if ~n_file, disp('No matches.'), return, end tipo = type; if tipo == 3, tipo = 2; end trova = 0; try, if exist('strfind'); trova = 1; end catch % nothing to do % this is for Octave compatibility end disp(' ') disp('Scanning files ...') disp(' ') for i = 1:n_file fid = fopen(file{i}, 'rt'); n_row = 0; match = 0; while 1 && fid > 0 sline = fgetl(fid); if ~isempty(sline), if sline == -1, break; end end n_row = n_row + 1; if trova vec = strfind(sline,string1); else vec = findstr(sline,string1); end slinenew = sline; if ~isempty(vec) switch tipo case 1 match = 1; slinenew = strrep(sline,string1,string2); disp([fvar(file{i},14),' row ',fvar(int2str(n_row),5), ... ' >> ',slinenew(1:end)]) disp([' ',sline]) case 2 ok = 0; okdisp = 0; okdispl = 0; okdispr = 0; count = 0; for j = 1:length(vec) if vec(j) > 1, ch_l = double(sline(vec(j)-1)); if ch_l ~= 34 && ch_l ~= 39 && ch_l ~= 95 && ... ch_l ~= 46 && (ch_l < 48 || (ch_l > 57 && ch_l < 65) || ... (ch_l > 90 && ch_l < 97) || ch_l > 122) okdispl = 1; end else okdispl = 1; end if vec(j) + length(string1) < length(sline), ch_r = double(sline(vec(j)+length(string1))); if ch_r ~= 34 && ch_r ~= 95 && ... (ch_r < 48 || (ch_r > 57 && ch_r < 65) || ... (ch_r > 90 && ch_r < 97) || ch_r > 122) okdispr = 1; end else okdispr = 1; end if okdispl && okdispr, okdisp = 1; end okdispl = 0; okdispr = 0; if okdisp count = count + 1; iniz = vec(j)-1+(count-1)*(length(string2)-length(string1)); slinenew = [slinenew(1:iniz),string2, ... sline(vec(j)+length(string1):end)]; ok = 1; end okdisp = 0; end if ok, disp([fvar(file{i},14),' row ',fvar(int2str(n_row),5), ... ' >> ',slinenew(1:end)]) disp([' ',sline]) match = 1; end end end newfile{n_row,1} = slinenew; end if fid > 0, count = fclose(fid); end if match && type ~= 3 fid = fopen(file{i}, 'wt'); if fid > 0 for i = 1:n_row-1, count = fprintf(fid,'%s\n',deblank(newfile{i})); end count = fprintf(fid,'%s',deblank(newfile{n_row})); count = fclose(fid); end end end % --------------------------------------------------------------------- % find subdirectories % --------------------------------------------------------------------- function file = deepdir(expression,names,file,isdir,folder) idx = find(isdir); for i = 3:length(idx) disp([folder,filesep,names{idx(i)}]) newfolder = [folder,filesep,names{idx(i)}]; b = dir([newfolder,filesep,expression]); if ~isempty({b.name}), bnames = {b.name}; n = length(bnames); newfiles = cell(n,1); for k = 1:n newfiles{k} = [folder,filesep,names{idx(i)},filesep,bnames{k}]; end file = [file; newfiles]; end b = dir([newfolder]); newdir = [b.isdir]'; newnames = {b.name}'; file = deepdir(expression,newnames,file,newdir,newfolder); end
github
Sinan81/PSAT-master
pgrep.m
.m
PSAT-master/psat-oct/psat/pgrep.m
4,302
utf_8
103545a4c4eba39f7a95a16bdbdf9512
function pgrep(expression,string,options) %PGREP change strings within files % %PGREP(EXPRESSION,STRING,TYPE) % EXPRESSION: regular expression % STRING: the string to be searched. % TYPE: 1 - list file names, row number and line text % 2 - list file names and line text % 3 - list file names % 4 - as 1, but look for Matlab variables only % 5 - as 1, but span all subdirectories % %see also PSED % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 18-Feb-2003 %Update: 30-Mar-2004 %Version: 1.0.2 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano if nargin < 3, disp('Check synthax ...') disp(' ') help pgrep, return, end if ~ischar(expression) disp('First argument has to be a not empty string.') return end if ~ischar(string) || isempty(string) disp('Second argument has to be a not empty string.') return end if ~isnumeric(options) || length(options) > 1 || rem(options,1) || ... options > 5 || options <= 0 disp('Third argument has to be a scalar integer within [1-5]') return end a = dir(expression); if isempty(a) disp('No file name matches the given expression.') return end file = {a.name}'; a = dir(pwd); names = {a.name}'; isdir = [a.isdir]'; if options == 5, disp(' ') disp('Spanning directories ...') disp(' ') disp(pwd) file = deepdir(expression,names,file,isdir,pwd); options = 1; else disp(' ') disp(pwd) end n_file = length(file); if ~n_file, disp('No matches.'), return, end check = 0; try, if exist('strfind'); check = 1; end catch % nothing to do % this for Octave compatibility end disp(' ') disp('Scanning files ...') disp(' ') for i = 1:n_file fid = fopen(file{i}, 'rt'); n_row = 0; while 1 && fid > 0 sline = fgets(fid); if ~isempty(sline), if sline == -1, break; end end n_row = n_row + 1; if check vec = strfind(sline,string); else vec = findstr(sline,string); end if ~isempty(vec) switch options case 1 disp([fvar(file{i},14),' row ',fvar(int2str(n_row),5), ... ' >> ',sline(1:end-1)]) case 3 disp(file{i}) break case 2 disp([fvar(file{i},14),' >> ',sline(1:end-1)]) case 4 okdisp = 0; okdispl = 0; okdispr = 0; for j = 1:length(vec) if vec(j) > 1, ch_l = double(sline(vec(j)-1)); if ch_l ~= 34 && ch_l ~= 39 && ch_l ~= 95 && ch_l ~= 46 && ... (ch_l < 48 || (ch_l > 57 && ch_l < 65) || ... (ch_l > 90 && ch_l < 97) || ch_l > 122) okdispl = 1; end end if vec(j) + length(string) < length(sline), ch_r = double(sline(vec(j)+length(string))); if ch_r ~= 34 && ch_r ~= 95 && ... (ch_r < 48 || (ch_r > 57 && ch_r < 65) || ... (ch_r > 90 && ch_r < 97) || ch_r > 122) okdispr = 1; end else okdispr = 1; end if okdispl && okdispr, okdisp = 1; break end okdispl = 0; okdispr = 0; end if okdisp, disp([fvar(file{i},14),' row ',fvar(int2str(n_row),5), ... ' >> ',sline(1:end-1)]), end end end end if fid > 0, count = fclose(fid); end end % ---------------------------------------------------------------------- % find subdirectories % ---------------------------------------------------------------------- function file = deepdir(expression,names,file,isdir,folder) idx = find(isdir); for i = 3:length(idx) disp([folder,filesep,names{idx(i)}]) newfolder = [folder,filesep,names{idx(i)}]; b = dir([newfolder,filesep,expression]); if ~isempty({b.name}) bnames = {b.name}; n = length(bnames); newfiles = cell(n,1); for k = 1:n newfiles{k} = [folder,filesep,names{idx(i)},filesep,bnames{k}]; end file = [file; newfiles]; end b = dir([newfolder]); newdir = [b.isdir]'; newnames = {b.name}'; file = deepdir(expression,newnames,file,newdir,newfolder); end
github
Sinan81/PSAT-master
fm_wcall.m
.m
PSAT-master/psat-oct/psat/fm_wcall.m
11,692
utf_8
eb62bbc13514e68d2e735f51afdf750f
function fm_wcall %FM_WCALL writes the function FM_CALL for the component calls. % and uses the information in Comp.prop for setting % the right calls. Comp.prop is organized as follows: % comp(i,:) = [x1 x2 x3 x4 x5 xi x0 xt] % % if x1 -> call for algebraic equations % if x2 -> call for algebraic Jacobians % if x3 -> call for state equations % if x4 -> call for state Jacobians % if x5 -> call for non-windup limits % if xi -> component used in power flow computations % if x0 -> call for initializations % if xt -> call for current simulation time % (-1 is used for static analysis) % % Comp.prop is stored in the "comp.ini" file. % %FM_WCALL % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 22-Aug-2003 %Update: 03-Nov-2005 %Version: 1.2.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Settings fm_var % ------------------------------------------------------------------------- % Opening file "fm_call.m" for writing % ------------------------------------------------------------------------- if Settings.local fid = fopen([Path.local,'fm_call.m'], 'wt'); else [fid,msg] = fopen([Path.psat,'fm_call.m'], 'wt'); if fid == -1 fm_disp(msg) fid = fopen([Path.local,'fm_call.m'], 'wt'); end end count = fprintf(fid,'function fm_call(flag)\n\n'); count = fprintf(fid,'\n%%FM_CALL calls component equations'); count = fprintf(fid,'\n%%'); count = fprintf(fid,'\n%%FM_CALL(CASE)'); count = fprintf(fid,'\n%% CASE ''1'' algebraic equations'); count = fprintf(fid,'\n%% CASE ''pq'' load algebraic equations'); count = fprintf(fid,'\n%% CASE ''3'' differential equations'); count = fprintf(fid,'\n%% CASE ''1r'' algebraic equations for Rosenbrock method'); count = fprintf(fid,'\n%% CASE ''4'' state Jacobians'); count = fprintf(fid,'\n%% CASE ''0'' initialization'); count = fprintf(fid,'\n%% CASE ''l'' full set of equations and Jacobians'); count = fprintf(fid,'\n%% CASE ''kg'' as "L" option but for distributed slack bus'); count = fprintf(fid,'\n%% CASE ''n'' algebraic equations and Jacobians'); count = fprintf(fid,'\n%% CASE ''i'' set initial point'); count = fprintf(fid,'\n%% CASE ''5'' non-windup limits'); count = fprintf(fid,'\n%%'); count = fprintf(fid,'\n%%see also FM_WCALL\n\n'); count = fprintf(fid,'fm_var\n\n'); count = fprintf(fid,'switch flag\n\n'); % ------------------------------------------------------------------------- % look for loaded components % ------------------------------------------------------------------------- Comp.prop(:,10) = 0; for i = 1:Comp.n ncompi = eval([Comp.names{i},'.n']); if ncompi, Comp.prop(i,10) = 1; end end cidx1 = find(Comp.prop(:,10)); prop1 = Comp.prop(cidx1,1:9); s11 = buildcell(cidx1,prop1(:,1),'gcall'); s12 = buildcell(cidx1,prop1(:,2),'Gycall'); s13 = buildcell(cidx1,prop1(:,3),'fcall'); s14 = buildcell(cidx1,prop1(:,4),'Fxcall'); s15 = buildcell(cidx1,prop1(:,5),'windup'); cidx2 = find(Comp.prop(1:end-2,10)); prop2 = Comp.prop(cidx2,1:9); s20 = buildcell(cidx2,prop2(:,7),'setx0'); s21 = buildcell(cidx2,prop2(:,1),'gcall'); s22 = buildcell(cidx2,prop2(:,2),'Gycall'); s23 = buildcell(cidx2,prop2(:,3),'fcall'); s24 = buildcell(cidx2,prop2(:,4),'Fxcall'); gisland = ' gisland_bus(Bus)\n'; gyisland = ' Gyisland_bus(Bus)\n'; % ------------------------------------------------------------------------- % call algebraic equations % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''gen''\n\n'); idx = find(sum(prop2(:,[8 9]),2)); count = fprintf(fid,' %s\n',s21{idx}); % ------------------------------------------------------------------------- % call algebraic equations of shunt components % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''load''\n\n'); idx = find(prod(prop2(:,[1 8]),2)); count = fprintf(fid,' %s\n',s21{idx}); count = fprintf(fid,gisland); % ------------------------------------------------------------------------- % call algebraic equations % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''gen0''\n\n'); idx = find(sum(prop2(:,[8 9]),2) & prop2(:,6)); count = fprintf(fid,' %s\n',s21{idx}); % ------------------------------------------------------------------------- % call algebraic equations of shunt components % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''load0''\n\n'); idx = find(prod(prop2(:,[1 6 8]),2)); count = fprintf(fid,' %s\n',s21{idx}); count = fprintf(fid,gisland); % ------------------------------------------------------------------------- % call differential equations % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''3''\n\n'); idx = find(prop2(:,3)); count = fprintf(fid,' %s\n',s23{idx}); % ------------------------------------------------------------------------- % call algebraic equations for Rosenbrock method % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''1r''\n\n'); idx = find(prop1(:,1)); count = fprintf(fid,' %s\n',s11{idx}); count = fprintf(fid,gisland); % ------------------------------------------------------------------------- % call algebraic equations of series component % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''series''\n\n'); idx = find(prop1(:,9)); count = fprintf(fid,' %s\n',s11{idx}); count = fprintf(fid,gisland); % ------------------------------------------------------------------------- % call DAE Jacobians % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''4''\n'); writejacs(fid) idx = find(prop2(:,4)); count = fprintf(fid,' %s\n',s24{idx}); % ------------------------------------------------------------------------- % call initialization functions % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''0''\n\n'); idx = find(prop2(:,7)); count = fprintf(fid,' %s\n',s20{idx}); % ------------------------------------------------------------------------- % call the complete set of algebraic equations % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''fdpf''\n\n'); idx = find(prod(prop1(:,[1 6]),2)); count = fprintf(fid,' %s\n',s11{idx}); count = fprintf(fid,gisland); % ------------------------------------------------------------------------- % call the complete set of equations and Jacobians % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''l''\n\n'); idx = find(prod(prop1(:,[1 6]),2)); count = fprintf(fid,' %s\n',s11{idx}); count = fprintf(fid,gisland); idx = find(prod(prop1(:,[2 6]),2)); count = fprintf(fid,' %s\n',s12{idx}); count = fprintf(fid,gyisland); count = fprintf(fid,'\n\n'); idx = find(prod(prop1(:,[3 6]),2)); count = fprintf(fid,' %s\n',s13{idx}); writejacs(fid) idx = find(prod(prop1(:,[4 6]),2)); count = fprintf(fid,' %s\n',s14{idx}); % ------------------------------------------------------------------------- % call the complete set of eqns and Jacs for distributed slack bus % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''kg''\n\n'); idx = find(prop2(:,1)); count = fprintf(fid,' %s\n',s21{idx}); count = fprintf(fid,gisland); idx = find(prop2(:,2)); count = fprintf(fid,' %s\n',s22{idx}); count = fprintf(fid,gyisland); count = fprintf(fid,'\n\n'); idx = find(prop2(:,3)); count = fprintf(fid,' %s\n',s23{idx}); writejacs(fid) idx = find(prop2(:,4)); count = fprintf(fid,' %s\n',s24{idx}); % ------------------------------------------------------------------------- % call the complete set of eqns and Jacs for distributed slack bus % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''kgpf''\n\n'); count = fprintf(fid,' global PV SW\n'); idx = find(prod(prop2(:,[1 6]),2)); count = fprintf(fid,' %s\n',s21{idx}); count = fprintf(fid,' PV = gcall_pv(PV);\n'); count = fprintf(fid,' greactive_sw(SW)\n'); count = fprintf(fid,' glambda_sw(SW,1,DAE.kg)\n'); count = fprintf(fid,gisland); idx = find(prod(prop2(:,[2 6]),2)); count = fprintf(fid,' %s\n',s22{idx}); count = fprintf(fid,' Gycall_pv(PV)\n'); count = fprintf(fid,' Gyreactive_sw(SW)\n'); count = fprintf(fid,gyisland); count = fprintf(fid,'\n\n'); idx = find(prod(prop2(:,[3 6]),2)); count = fprintf(fid,' %s\n',s23{idx}); writejacs(fid) idx = find(prod(prop2(:,[4 6]),2)); count = fprintf(fid,' %s\n',s24{idx}); % ------------------------------------------------------------------------- % calling algebraic equations and Jacobians % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''n''\n\n'); idx = find(prop1(:,1)); count = fprintf(fid,' %s\n',s11{idx}); count = fprintf(fid,gisland); idx = find(prop1(:,2)); count = fprintf(fid,' %s\n',s12{idx}); count = fprintf(fid,gyisland); count = fprintf(fid,'\n'); % ------------------------------------------------------------------------- % call all the functions for setting initial point % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''i''\n\n'); idx = find(prop1(:,1)); count = fprintf(fid,' %s\n',s11{idx}); count = fprintf(fid,gisland); idx = find(prop1(:,2)); count = fprintf(fid,' %s\n',s12{idx}); count = fprintf(fid,gyisland); count = fprintf(fid,'\n\n'); idx = find(prop1(:,3)); count = fprintf(fid,' %s\n',s13{idx}); count = fprintf(fid,'\n if DAE.n > 0'); writejacs(fid) count = fprintf(fid,' end \n\n'); idx = find(prop1(:,4)); count = fprintf(fid,' %s\n',s14{idx}); % ------------------------------------------------------------------------- % call saturation functions % ------------------------------------------------------------------------- count = fprintf(fid,'\n case ''5''\n\n'); idx = find(prop1(:,5)); count = fprintf(fid,' %s\n',s15{idx}); % ------------------------------------------------------------------------- % close "fm_call.m" % ------------------------------------------------------------------------- count = fprintf(fid,'\nend\n'); count = fclose(fid); cd(Path.local); % ------------------------------------------------------------------------- % function for writing Jacobian initialization % ------------------------------------------------------------------------- function writejacs(fid) count = fprintf(fid,'\n DAE.Fx = sparse(DAE.n,DAE.n);'); count = fprintf(fid,'\n DAE.Fy = sparse(DAE.n,DAE.m);'); count = fprintf(fid,'\n DAE.Gx = sparse(DAE.m,DAE.n);\n'); % ------------------------------------------------------------------------- % function for building component call function cells % ------------------------------------------------------------------------- function out = buildcell(j,idx,type) global Comp Settings out = cell(length(idx),1); h = find(idx <= 1); k = j(h); if Settings.octave c = Comp.names(k); out(h) = fm_strjoin(type,'_',lower(c),'(',c,')'); else out(h) = fm_strjoin(type,'(',{Comp.names{k}}',')'); end h = find(idx == 2); k = j(h); if Settings.octave c = Comp.names(k); out(h) = fm_strjoin(c,' = ',type,'_',lower(c),'(',c,');'); else str = [' = ',type,'(']; out(h) = fm_strjoin({Comp.names{k}}',str,{Comp.names{k}}',');'); end
github
Sinan81/PSAT-master
fm_linedlg.m
.m
PSAT-master/psat-oct/psat/fm_linedlg.m
18,525
utf_8
bc5ff2655dcc848e320ac75686ab208f
function fm_linedlg(varargin) %SCRIBELINEDLG Line property dialog helper function for Plot Editor % % Copyright 1984-2001 The MathWorks, Inc. % $Revision: 1.19 $ $Date: 2001/04/15 12:00:41 $ % %Modified by: Federico Milano %Date: 11-Nov-2002 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano persistent localData; global Theme switch nargin case 1 arg1 = varargin{1}; if isempty(arg1) || ishandle(arg1(1)) || isa(arg1(1), 'scribehandle') localData = LInitFig(arg1,localData); return elseif ischar(arg1(1)) action = arg1; parameter = []; end case 2 action = varargin{1}; parameter = varargin{2}; end if strcmp(parameter,'me') parameter = gcbo; end localData = feval(action,parameter,localData); %%%%%% function localData = LInitFig(objectV,localData) global Theme if isempty(objectV) LNoLineError; return end try if ishandle(objectV) fig = get(get(objectV(1),'Parent'),'Parent'); else % might be any selected object fig = get(objectV(1),'Figure'); end catch fm_disp(['Unable to edit line properties: invalid line handles']); return end oldPointer = get(fig,'Pointer'); set(fig,'Pointer','watch'); try if ishandle(objectV) LineVector = []; ArrowVector = []; for aHG = objectV if strcmp(get(aHG,'Type'),'line') LineVector(end+1) = aHG; end end else % pick out the line objects from the list LineVector = scribehandle([]); ArrowVector = scribehandle([]); for aObj = objectV if isa(aObj,'editline'), LineVector = [LineVector aObj]; % LineVector(end+1) = aObj; elseif isa(aObj,'arrowline') ArrowVector = [ArrowVector aObj]; % ArrowVector(end+1) = aObj; end end end if isempty(LineVector) IndLine = []; else IndLine = [1:length(LineVector)]; end HG = [LineVector ArrowVector]; catch set(fig,'Pointer',oldPointer); fm_disp(['Unable to open line properties dialog. ' ... 'Selection list is invalid:' ... 10 lasterr],2); return end if isempty(HG) LNoLineError; set(fig,'Pointer',oldPointer); return end %--temporary: redirect to Property Editor %propedit(get(HG,'MyHGHandle')); %set(fig,'Pointer',oldPointer); %return %---Set enable flag for marker boxes if isequal(length(ArrowVector),length(HG)), MarkerEnable='off'; else MarkerEnable='on'; end %---Get all object data for ctHG = 1:length(HG) GetData(ctHG) = struct('Selected',get(HG(ctHG),'Selected'), ... 'Parent',get(HG(ctHG),'Parent'), ... 'LineStyle',get(HG(ctHG),'LineStyle'), ... 'LineWidth',get(HG(ctHG),'LineWidth'), ... 'Marker',get(HG(ctHG),'Marker'), ... 'MarkerSize',get(HG(ctHG),'MarkerSize'), ... 'Color',get(HG(ctHG),'Color')); % turn off selection so we can see changes in marker style set(HG(ctHG),'Selected','off'); end % for ctHG localData = struct('CommonWidth',1,'CommonStyle',1,'CommonSize',1, ... 'CommonMarker',1,'CommonColor',1); localData.Selected = {GetData(:).Selected}; try % adjustment factors for character units % work in character units. fx = 5; fy = 13; figWidth = 360/fx; figHeight = 220/fy; callerPosition = get(fig,'Position'); callerUnits = get(fig,'Units'); bgcolor = get(0,'DefaultUIControlBackgroundColor'); if bgcolor==[0 0 0] fgcolor = [1 1 1]; else fgcolor = get(0,'DefaultUIControlForegroundColor'); end fProps = struct(... 'Units', callerUnits,... 'Color', Theme.color01,... 'NumberTitle', 'off',... 'IntegerHandle', 'off',... 'Pointer','watch', ... 'Resize', 'on',... 'Visible', 'off',... 'KeyPressFcn', 'fm_linedlg keypress',... 'HandleVisibility', 'callback',... 'WindowStyle', 'modal',... 'CloseRequestFcn', 'fm_linedlg button close',... 'Name', 'Edit Line Properties',... 'Position', callerPosition); f = figure(fProps); set(f,'Units','character'); figPos = get(f,'Position'); figPos(1:2) = figPos(1:2) + (figPos(3:4)-[figWidth, figHeight])/2; figPos(3:4) = [figWidth, figHeight]; set(f,'Position',figPos); ut = uicontrol('Style' , 'text',... 'Units' , 'character',... 'Parent' , f,... 'Visible' , 'off',... 'String' , 'Title'); charSize = get(ut,'Extent'); charH = charSize(4); delete(ut); % geometry LMarginW = 25/fx; RMarginW = 25/fx; ColPadW = 10/fx; RowLabelW = 65/fx; ColW = (figPos(3)-2*RowLabelW-LMarginW-RMarginW-3*ColPadW)/2; TopMarginH = 20/fy; BotMarginH = 20/fy; RowH = 30/fy; RowPadH = 8/fy; uiH = RowH-RowPadH; buttonW = 72/fx; buttonH = RowH-RowPadH; buttonPad = 7/fx; charOffset = uiH-charH; % property defaults editProps = struct(... 'Style', 'edit',... 'Parent' , f,... 'Units', 'character',... 'BackgroundColor', Theme.color04,... 'ForegroundColor', Theme.color05,... 'FontName',Theme.font01, ... 'HorizontalAlignment', 'left'); tProps = struct(... 'Style','text',... 'Parent' , f,... 'Units', 'character',... 'HorizontalAlignment', 'right',... 'BackgroundColor', Theme.color01,... 'ForegroundColor', fgcolor); prompt = {... 'Line Width:' 'Line Style:' '' 'Color:' 'Marker Size:' 'Marker:' }; properties = {... 'edit' 'fm_linedlg verifyposnumber me' 'LineWidth' 'popupmenu' '' 'LineStyle' '' '' '' 'frame' '' '' 'edit' 'fm_linedlg verifyposnumber me' 'MarkerSize' 'popupmenu' '' 'Marker' }; linestyles = {'-' '--' ':' '-.' 'none'}; markers = {'none' '+' 'o' '*' '.' 'x' 'square' 'diamond' ... 'v' '^' '>' '<' 'pentagram' 'hexagram'}; % Find common LineWidth and MarkerSize CommonWidth = unique([GetData(:).LineWidth]); if length(CommonWidth)>1, widthStr = ''; localData.CommonWidth = 0; else, widthStr = num2str(CommonWidth); end CommonSize = unique([GetData(IndLine).MarkerSize]); if length(CommonSize)>1, sizeStr = ''; localData.CommonSize = 0; else, sizeStr = num2str(CommonSize); end % Find Common LineStyle CommonStyle = unique({GetData(:).LineStyle}); if length(CommonStyle)==1, styleVal = find(strcmp(CommonStyle{1},linestyles)); linestr = {'solid (-)' 'dash (--)' 'dot (:)' 'dash-dot (-.)' 'none'}; else styleVal = 1; localData.CommonStyle = 0; linestyles = [{'Current'},linestyles]; linestr = {'Current' 'solid (-)' 'dash (--)' 'dot (:)' 'dash-dot (-.)' 'none'}; end % Find Common Marker markerVal = 1; if ~isempty(IndLine), CommonMarker = unique({GetData(IndLine).Marker}); if length(CommonMarker)==1, markerVal = find(strcmp(CommonMarker{1},markers)); else localData.CommonMarker = 0; markers = [{'Current'},markers]; end end strings = {... widthStr linestr '' '' sizeStr markers }; values = {... 0 styleVal 0 0 0 markerVal }; enables = {... 'on' 'on' 'on' 'on' MarkerEnable MarkerEnable }; data = {... '' linestyles '' '' '' markers }; nRows = length(prompt); % lay down prompts Y = figPos(4)-TopMarginH-charOffset; headingPosition = [LMarginW Y RowLabelW uiH]; for iRow=1:nRows if iRow==5 % start new column Y = figPos(4)-TopMarginH-charOffset; headingPosition = [LMarginW+RowLabelW+ColW+2*ColPadW Y RowLabelW uiH]; end Y = Y-RowH; if ~isempty(prompt{iRow}) headingPosition(2) = Y; uicontrol(tProps,... 'String', prompt{iRow,1},... 'Tag', prompt{iRow,1},... 'Enable',enables{iRow}, ... 'Position', headingPosition); end end iGroup = 1; Y = figPos(4)-TopMarginH; headingPosition = [LMarginW+RowLabelW+ColPadW Y ColW uiH]; for iRow=1:nRows if iRow ==5 % start new column Y = figPos(4)-TopMarginH; headingPosition = [LMarginW+2*RowLabelW+ColW+3*ColPadW Y ColW uiH]; end Y = Y-RowH; if ~isempty(prompt{iRow}) headingPosition(2) = Y; uic = uicontrol(editProps,... 'Style', properties{iRow,1},... 'Callback', properties{iRow,2},... 'Tag', properties{iRow,3},... 'ToolTip', properties{iRow,3},... 'String', strings{iRow},... 'Value', values{iRow},... 'UserData', data{iRow},... 'Enable',enables{iRow}, ... 'Position', headingPosition); localData.LimCheck(iGroup) = uic; localData.Prop{iGroup} = properties{iRow,3}; if strcmp(properties{iRow,1},'edit') % edit text box localData.OldVal{iGroup} = str2double(strings{iRow}); end iGroup = iGroup + 1; end end % set color on color button % Check for common color, otherwise use white col = cat(1,GetData(:).Color); col = unique(col,'rows'); if size(col,1)>1, BGC = [1 1 1]; localData.CommonColor = 0; ColVis='off'; else, BGC = col; ColVis='on'; end Y = figPos(4)-TopMarginH-4*RowH; headingPosition = [LMarginW+RowLabelW+ColPadW+(.1067*ColW) Y+(.164*uiH) ... ColW-(.205*ColW) uiH-(.3*uiH)]; colorSwatch = uicontrol(editProps,... 'BackgroundColor',BGC, ... 'Style','frame', ... 'Tag','Color', ... 'ToolTip', 'Color', ... 'Visible',ColVis, ... 'Position', headingPosition); headingPosition = [LMarginW+RowLabelW+ColW+2*ColPadW Y RowLabelW uiH]; uicontrol(editProps,... 'Style', 'pushbutton',... 'Callback', 'fm_linedlg getcolor me',... 'Tag', '',... 'BackgroundColor',Theme.color01,... 'ForegroundColor',fgcolor,... 'FontName',Theme.font01, ... 'Horiz','center', ... 'String', 'Select...',... 'UserData', colorSwatch,... 'Position', headingPosition); % OK, Apply, Cancel, Help buttonX(1) = (figPos(3)-3*1.5*buttonW-2*buttonPad)/2; for ib = 2:3 buttonX(ib) = buttonX(ib-1) + 1.5*buttonW + buttonPad; end buttonProps = struct(... 'Parent', f,... 'Units','character',... 'BackgroundColor', Theme.color01,... 'ForegroundColor', fgcolor,... 'Position', [0 BotMarginH 1.5*buttonW 1.5*buttonH],... 'Style', 'pushbutton'); buttonProps.Position(1) = buttonX(1); uicontrol(buttonProps,... 'Interruptible', 'off',... 'String', 'OK',... 'Callback', 'fm_linedlg button ok', ... 'ForegroundColor',Theme.color04, ... 'FontWeight','bold', ... 'BackgroundColor',Theme.color03); buttonProps.Position(1) = buttonX(2); uicontrol(buttonProps,... 'Interruptible', 'off',... 'String', 'Cancel',... 'Callback', 'fm_linedlg button cancel'); buttonProps.Position(1) = buttonX(3); uicontrol(buttonProps,... 'Interruptible', 'on',... 'String', 'Apply',... 'Callback', 'fm_linedlg button apply'); set(fig,'Pointer',oldPointer); set(f,'Visible','on','Pointer','arrow'); localData.HG = HG; catch if exist('f') delete(f); end set(fig,'Pointer',oldPointer); for ct=1:length(HG), set(HG,'Selected',localData.Selected{ct}); end lasterr end function localData = keypress(selection, localData) key = double(get(gcbf,'CurrentCharacter')); switch key case 13, localData = button('ok',localData); case 27, localData = button('cancel',localData); end function localData = showhelp(selection, localData) try helpview([docroot '/mapfiles/plotedit.map'], ... 'pe_line_change_props', 'PlotEditPlain'); catch fm_disp(['Unable to display help for Line Properties:' ... sprintf('\n') lasterr ],2); end function localData = button(selection, localData); switch selection case 'close' for ct=1:length(localData.HG) set(localData.HG(ct),'Selected',localData.Selected{ct}); end delete(gcbf); localData = []; case 'cancel' close(gcbf); case 'ok' set(gcbf,'Pointer','watch'); localData = LApplySettings(gcbf,localData); close(gcbf); case 'apply' set(gcbf,'Pointer','watch'); localData = LApplySettings(gcbf,localData); set(gcbf,'Pointer','arrow'); end function val = getval(f,tag) uic = findobj(f,'Tag',tag); switch get(uic,'Style') case 'edit' val = get(uic, 'String'); case {'checkbox' 'radiobutton'} val = get(uic, 'Value'); case 'popupmenu' choices = get(uic, 'UserData'); val = choices{get(uic,'Value')}; case 'frame' val = get(uic, 'BackgroundColor'); end function val = setval(f,tag,val) uic = findobj(f,'Tag',tag); switch get(uic,'Style') case 'edit' set(uic, 'String',val); case {'checkbox' 'radiobutton' 'popupmenu'} set(uic, 'Value',val); end function localData = verifyposnumber(uic, localData) iGroup = find(uic==localData.LimCheck); val = str2double(get(uic,'String')); if ~isnan(val) if length(val)==1 && val>0 % if it's a single number greater than zero, then it's fine localData.OldVal{iGroup} = val; return end end % trap errors set(uic,'String',num2str(localData.OldVal{iGroup})); fieldName = get(uic,'ToolTip'); fm_disp([fieldName ' field requires a single positive numeric input'],2) function localData = getcolor(uic, localData) colorSwatch = get(uic,'UserData'); currentColor = get(colorSwatch,'BackgroundColor'); c = uisetcolor(currentColor); %---Trap when cancel is pressed. if ~isequal(c,currentColor) set(colorSwatch,'BackgroundColor',c,'Visible','on'); end function localData = LApplySettings(f, localData) global Fig hdl_line = get(Fig.line,'UserData'); hdl_line = hdl_line(end:-1:1); Hdl_legend = findobj(Fig.plot,'Tag','Checkbox2'); Hdl_listplot = findobj(Fig.plot,'Tag','Listbox2'); Hdl_tipoplot = findobj(Fig.plot,'Tag','PopupMenu1'); allbaby = get(Fig.plot,'Children'); hdlfig = allbaby(end-1); HG = localData.HG; try %---Only change LineWidth if not set to Current LW = str2double(getval(f,'LineWidth')); if ~isnan(LW), lineSettings.LineWidth = LW; localData.CommonWidth = 1; end % if strcmp(Marker...'Current') %---Only change Linestyle if not set to Current if ~strcmp(getval(f,'LineStyle'),'Current'), lineSettings.LineStyle = getval(f,'LineStyle'); if ~localData.CommonStyle, StylePopup = findobj(f,'Tag','LineStyle'); StyleVal = get(StylePopup,'Value'); ud=get(StylePopup,'UserData'); str = get(StylePopup,'String'); set(StylePopup,'UserData',ud(2:end),'String',str(2:end), ... 'Value',StyleVal-1); localData.CommonStyle= 1; end end % if strcmp(Linestyle...'Current') %---Only change the color if the colorswatch is visible colorSwatch = findobj(f,'Tag','Color'); if strcmp(get(colorSwatch,'Visible'),'on'); lineSettings.Color = getval(f,'Color'); end % if colorswatch is visible %---Store subset for arrows arrowSettings = lineSettings; %---Only change the MarkerSize if on is actually entered MS = str2double(getval(f,'MarkerSize')); if ~isnan(MS), lineSettings.MarkerSize = MS; end % if strcmp(Marker...'Current') %---Only change Marker if not set to Current if ~strcmp(getval(f,'Marker'),'Current'), lineSettings.Marker= getval(f,'Marker'); if ~localData.CommonMarker, StylePopup = findobj(f,'Tag','Marker'); StyleVal = get(StylePopup,'Value'); ud=get(StylePopup,'UserData'); str = get(StylePopup,'String'); set(StylePopup,'UserData',ud(2:end),'String',str(2:end), ... 'Value',StyleVal-1); localData.CommonMarker = 1; end end % if strcmp(Marker...'Current') for ctHG=1:length(HG) if ishandle(HG(ctHG)) set(HG(ctHG), lineSettings); else if isa(HG(ctHG),'editline'), settings = lineSettings; elseif isa(HG(ctHG),'arrowline'), settings = arrowSettings; end % if/else isa(HG... props = fieldnames(settings)'; for i = props i=i{1}; set(HG(ctHG),i,getfield(settings,i)); end % for i end hdl = legend(get(HG(ctHG),'Parent')); end if get(Hdl_legend,'Value') n_var = length(get(Hdl_listplot,'String')); tipoplot = get(Hdl_tipoplot,'Value'); if tipoplot == 4 || tipoplot == 5 h = findobj(hdl,'Type','line'); for i = 0:n_var-1 marker = get(hdl_line(n_var+i+1),'Marker'); markersize = get(hdl_line(n_var+i+1),'MarkerSize'); markercolor = get(hdl_line(n_var+i+1),'MarkerEdgeColor'); %xdata = get(h(-i*2+3*n_var),'XData'); %ydata = get(h(-i*2+3*n_var),'YData'); %hmarker = plot((xdata(2)-xdata(1))/1.2,ydata(1)); set(h(i+1),'Marker',marker,'MarkerEdgeColor',markercolor,'MarkerSize',markersize); end end end catch fm_disp(lasterr,2) fm_disp('Unable to set line properties.',2); end function LNoLineError fm_disp(['No lines are selected. Click on an line to select it.'],2);
github
Sinan81/PSAT-master
autorun.m
.m
PSAT-master/psat-oct/psat/autorun.m
4,902
utf_8
20741ef2a2583acd393c076a1e0dc065
function check = autorun(msg,type) % AUTORUN properly launch PSAT routine checking for data % files and previous power flow solutions % % CHECK = AUTORUN(MSG) % MSG message to be displayed % TYPE 0 for static analysis, 1 for dynamic analysis % CHECK 1 if everything goes fine, 0 otherwise % %Author: Federico Milano %Date: 29-Oct-2003 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Settings File Bus global DAE LIB SNB OPF CPF clpsat Comp check = 0; % check for data file if isempty(File.data), fm_disp(['Set a data file before running ',msg,'.'],2) return end % check for initial power flow solution if ~Settings.init solvepf if ~Settings.init, return, end end % check for dynamic components if running a static analysis if ~type && DAE.n && ~clpsat.init dynlf = sum(prod(Comp.prop(:,[3 6 9]),2)); iscpf = strcmp(msg,'Continuation Power Flow'); if ~Settings.static && ~dynlf Settings.ok = 0; uiwait(fm_choice('Dynamic components will be discarded. Continue?')) if Settings.ok Settings.static = 1; solvepf Settings.static = 0; % reset initial condition else return end elseif ~Settings.static && ~dynlf && iscpf Settings.ok = 0; uiwait(fm_choice(['Dynamic components can lead to numerical ' ... 'problems, discard?'])) if Settings.ok Settings.static = 1; solvepf Settings.static = 0; % reset initial condition end elseif iscpf Settings.ok = 1; %uiwait(fm_choice(['Dynamic components can lead to numerical ' ... % 'problems, continue?'])) %if ~Settings.ok, return, end else uiwait(fm_choice(['Dynamic components are not supported for ' ... 'static analysis'],2)) return end end % check for previous CPF & ATC solutions if strcmp(msg,'SNB Direct Method') one = 1; else one = 0; end if CPF.init && ~(one && CPF.init == 1) switch CPF.init case 1, met = 'CPF'; case 2, met = 'ATC'; case 3, met = 'N-1 Cont. An.'; case 4, met = 'Continuation OPF (PSAT-GAMS)'; end Settings.ok = 0; if clpsat.init Settings.ok = clpsat.refresh; else uiwait(fm_choice([met,' has been run last. Do you want to' ... ' restore initial PF solution?'])) end if Settings.ok solvepf fm_disp(['Initial PF solution will be used as ', ... 'base case solution.']) else fm_disp(['Last ',met,' solution will be used as ', ... 'base case solution.']) end CPF.init = 0; end % check for previous time domain simulations if Settings.init == 2 Settings.ok = 0; if clpsat.init Settings.ok = clpsat.refresh; else uiwait(fm_choice(['TD has been run last. Do you want to' ... ' restore initial PF solution?'])) end if Settings.ok solvepf fm_disp(['Initial PF solution will be used as ', ... 'base case solution.']) else fm_disp('Last TD point will be used as base case solution.') end Settings.init = 1; end % check for SNB direct method if SNB.init Settings.ok = 0; if clpsat.init Settings.ok = clpsat.refresh; else uiwait(fm_choice(['SNB direct method has been run last. Do you want to' ... ' restore initial PF solution?'])) end if Settings.ok solvepf fm_disp(['Initial PF solution will be used as ', ... 'base case solution.']) else fm_disp('SNB solution will be used as base case solution.') end SNB.init = 0; end % check for LIB direct method if LIB.init Settings.ok = 0; if clpsat.init Settings.ok = clpsat.refresh; else uiwait(fm_choice(['LIB direct method has been run last. Do you want to' ... ' restore initial PF solution?'])) end if Settings.ok solvepf fm_disp('Initial PF solution will be used as base case solution.') else fm_disp('LIB solution will be used as base case solution.') end LIB.init = 0; end % check for OPF solution if strcmp(msg,'Optimal Power Flow') one = 0; else one = 1; end if OPF.init && one Settings.ok = 0; if clpsat.init Settings.ok = clpsat.refresh; else uiwait(fm_choice(['OPF has been run last. Do you want to' ... ' restore initial PF solution?'])) end if Settings.ok solvepf fm_disp(['Initial PF solution will be used as ', ... 'base case solution.']) else fm_disp('OPF solution will be used as base case solution.') end OPF.init = 0; end check = 1; % --------------------------------------------------- function solvepf global Settings Varname fm_disp('Solve base case power flow...') varname_old = Varname.idx; Settings.show = 0; fm_set('lf') Settings.show = 1; if ~isempty(varname_old) Varname.idx = varname_old; end
github
Sinan81/PSAT-master
fm_plotsel.m
.m
PSAT-master/psat-oct/psat/fm_plotsel.m
16,976
utf_8
835ea3c5df4a248947daa36694e2f9d8
function fig = fm_plotsel(varargin) % FM_PLOTSEL create GUI to select plotting variables % % HDL = FM_PLOTSEL() % %Author: Federico Milano %Date: 21-Dec-2005 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Fig Theme Varname Settings File Path % check for data file if isempty(File.data) fm_disp('Set a data file before selecting plot variables.',2) return end % check for initial power flow solution if ~Settings.init fm_disp('Solve base case power flow...') Settings.show = 0; fm_set lf Settings.show = 1; if ~Settings.init, return, end end if nargin switch varargin{1} case 'area' values = get(gcbo,'Value')-1; if ~values(1) values = 0; set(gcbo,'Value',1) end Varname.areas = values; setidx case 'region' values = get(gcbo,'Value')-1; if ~values(1) values = 0; set(gcbo,'Value',1) end Varname.regions = values; setidx case 'selvars' values = get(gcbo,'Value'); hdl = findobj(gcf,'Tag','listbox2'); Varname.idx = values; setidx case 'selection' if isempty(Varname.idx) set(gcbo,'String','<Empty>','Value',1) elseif Varname.idx(end) > Varname.nvars set(gcbo,'String','<Empty>','Value',1) Varname.idx = []; else set(gcbo,'String',Varname.uvars(Varname.idx),'Value',1) end case 'remove' hdl = findobj(gcf,'Tag','listbox2'); values = get(hdl,'Value'); Varname.idx(values) = []; if isempty(Varname.idx) set(hdl,'String','<Empty>') else nidx = length(Varname.idx); toplist = max(1,nidx-8); set(hdl,'String',Varname.uvars(Varname.idx), ... 'Value',min(max(values),nidx), ... 'ListboxTop',toplist) end case 'create_custom' setarea(0,1,'on','off') case 'creates_fixed' setarea(1,0,'off','on') case 'custom' setarea(0,1,'on','off') setidx case 'fixed' setarea(1,0,'off','on') setidx case 'setx' Varname.x = get(gcbo,'Value'); setidx case 'sety' Varname.y = get(gcbo,'Value'); setidx case 'setP' Varname.P = get(gcbo,'Value'); setidx case 'setQ' Varname.Q = get(gcbo,'Value'); setidx case 'setPij' Varname.Pij = get(gcbo,'Value'); setidx case 'setQij' Varname.Qij = get(gcbo,'Value'); setidx case 'setIij' Varname.Iij = get(gcbo,'Value'); setidx case 'setSij' Varname.Sij = get(gcbo,'Value'); setidx case 'appendidx' if isempty(File.data), fm_disp('No data file loaded.',2), return, end filedata = strrep(File.data,'@ ',''); if Settings.init == 0, fm_disp('Run power flow before saving plot variable indexes.',2), return, end if isempty(strfind(filedata,'(mdl)')) fid = fopen([Path.data,filedata,'.m'],'r+'); count = fseek(fid,0,1); count = fprintf(fid, '\n\nVarname.idx = [...\n'); nidx = length(Varname.idx); count = fprintf(fid,'%5d; %5d; %5d; %5d; %5d; %5d; %5d;\n',Varname.idx); if rem(nidx,7) ~= 0, count = fprintf(fid,'\n'); end count = fprintf(fid,' ];\n'); count = fprintf(fid, '\nVarname.areas = [...\n'); nidx = length(Varname.areas); count = fprintf(fid,'%5d; %5d; %5d; %5d; %5d; %5d; %5d;\n',Varname.areas); if rem(nidx,7) ~= 0, count = fprintf(fid,'\n'); end count = fprintf(fid,' ];\n'); count = fprintf(fid, '\nVarname.regions = [...\n'); nidx = length(Varname.regions); count = fprintf(fid,'%5d; %5d; %5d; %5d; %5d; %5d; %5d;\n',Varname.regions); if rem(nidx,7) ~= 0, count = fprintf(fid,'\n'); end count = fprintf(fid,' ];\n'); fclose(fid); fm_disp(['Plot variable indexes appended to file "',Path.data,File.data,'"']) else % load Simulink Library and add Varname block load_system('fm_lib'); cd(Path.data); filedata = filedata(1:end-5); open_sys = find_system('type','block_diagram'); if ~sum(strcmp(open_sys,filedata)) open_system(filedata); end cur_sys = get_param(filedata,'Handle'); blocks = find_system(cur_sys,'MaskType','Varname'); if ~isempty(blocks) if iscell(blocks) varblock = blocks{1}; % remove duplicate 'Varname' blocks for i = 2:length(blocks) delete_block(blocks{i}); end else varblock = blocks; end vec = Varname.idx; if size(vec,1) > 1, vec = vec'; end set_param( ... varblock, 'pxq', ... ['[',regexprep(num2str(vec),'\s*',' '),']']) else vec = Varname.idx; if size(vec,1) > 1, vec = vec'; end add_block( ... 'fm_lib/Connections/Varname',[filedata,'/Varname'], 'pxq', ... ['[',regexprep(num2str(vec),'\s*',' '),']'], ... 'Position',[20,20,105,57]) end cd(Path.local); end end return end if ishandle(Fig.plotsel), figure(Fig.plotsel), return, end h0 = figure(... 'Units','normalized',... 'Color',Theme.color01,... 'Colormap',[], ... 'MenuBar','none',... 'Name','Select Plot Variables',... 'NumberTitle','off',... 'Position',sizefig(0.75,0.69), ... 'FileName','fm_plotsel', ... 'HandleVisibility','callback',... 'Tag','figure1',... 'CreateFcn','Fig.plotsel = gcf;', ... 'DeleteFcn','Fig.plotsel = -1;', ... 'UserData',[],... 'Visible','on'); % Menu File h1 = uimenu('Parent',h0, ... 'Label','File', ... 'Tag','MenuFile'); h2 = uimenu('Parent',h1, ... 'Callback','close(gcf)', ... 'Label','Exit', ... 'Tag','PlotSelExit', ... 'Accelerator','x'); h1 = uipanel(... 'Parent',h0, ... 'Title','Variables', ... 'BackgroundColor',Theme.color02, ... 'Units','normalized',... 'Tag','uipanel1',... 'Clipping','on',... 'Position',[0.0611 0.2717 0.2506 0.6359]); idx = Varname.idx; if isempty(idx), idx = 1; end h1 = uicontrol(... 'Parent',h1, ... 'BackgroundColor',Theme.color03, ... 'Callback','fm_plotsel selvars', ... 'FontName',Theme.font01, ... 'Max',20, ... 'ForegroundColor',Theme.color06, ... 'Units','normalized',... 'Position',[0.1015 0.0597 0.8071 0.8985],... 'String',Varname.uvars,... 'Style','listbox',... 'Value',idx,... 'Tag','listbox1'); h1 = uipanel(... 'Parent',h0, ... 'Title','Selection', ... 'BackgroundColor',Theme.color02, ... 'Units','normalized',... 'Tag','uipanel2',... 'Clipping','on',... 'Position',[0.6833 0.2717 0.2506 0.6359]); h5 = uicontrol(... 'Parent',h1, ... 'Units','normalized',... 'BackgroundColor',Theme.color03, ... 'CreateFcn','fm_plotsel selection', ... 'Max',20, ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color06, ... 'Position',[0.1015 0.0597 0.8071 0.9015],... 'String',{ '<Empty>' },... 'Style','listbox',... 'Value',1,... 'Tag','listbox2'); set(h5,'Value',max(1,length(Varname.idx)-8)) h4 = uipanel(... 'Parent',h0,... 'Title','Region',... 'BackgroundColor',Theme.color02, ... 'Tag','uipanel2',... 'Clipping','on',... 'Position',[0.3728 0.6341 0.2506 0.2736]); h5 = uicontrol(... 'Parent',h4,... 'BackgroundColor',Theme.color03, ... 'ForegroundColor',Theme.color06, ... 'CreateFcn','set(gcbo,''String'',[{''<all>''};Regions.names])', ... 'Callback','fm_plotsel region', ... 'Max',20, ... 'FontName',Theme.font01, ... 'Units','normalized',... 'Position',[0.1015 0.1333 0.8020 0.7630],... 'String',{ '<empty>' },... 'Style','listbox',... 'Value',1,... 'Tag','listbox3'); if ~Varname.regions(1) Varname.regions = 0; set(h5,'Value',1) else set(h5,'Value',Varname.regions+1); end h6 = uipanel(... 'Parent',h0,... 'Title','Area',... 'BackgroundColor',Theme.color02, ... 'Tag','uipanel3',... 'Clipping','on',... 'Position',[0.3716 0.2736 0.2506 0.2736]); h7 = uicontrol(... 'Parent',h6,... 'BackgroundColor',Theme.color03, ... 'ForegroundColor',Theme.color06, ... 'CreateFcn','set(gcbo,''String'',[{''<all>''};Areas.names])', ... 'Callback','fm_plotsel area', ... 'Max',20, ... 'FontName',Theme.font01, ... 'Units','normalized',... 'Position',[0.1066 0.1185 0.8020 0.7852],... 'String',{ '<Empty>' },... 'Style','listbox',... 'Value',1,... 'Tag','listbox4'); if ~Varname.areas(1) Varname.areas = 0; set(h7,'Value',1) else set(h7,'Value',Varname.areas+1); end h8 = uicontrol(... 'Parent',h0, ... 'Units','normalized',... 'BackgroundColor',Theme.color03, ... 'FontWeight','bold', ... 'ForegroundColor',Theme.color09, ... 'Callback','close(gcf);', ... 'Position',[0.8092 0.1087 0.1259 0.0580],... 'String','Close',... 'Tag','Pushbutton1'); h8 = uicontrol(... 'Parent',h0, ... 'Callback','fm_plotsel appendidx', ... 'Units','normalized',... 'BackgroundColor',Theme.color02, ... 'Position',[0.6222 0.1087 0.1259 0.0598],... 'String','Save',... 'Tag','Pushbutton2'); h10 = uicontrol(... 'CData',fm_mat('plotsel_pij'), ... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel setPij', ... 'HorizontalAlignment','center', ... 'Position',[0.0611 0.0453 0.0623 0.0924],... 'String','',... 'Value',Varname.Pij,... 'Style','togglebutton',... 'Tag','radiobutton1'); h11 = uicontrol(... 'CData',fm_mat('plotsel_qij'), ... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel setQij', ... 'HorizontalAlignment','center', ... 'Position',[0.1297 0.0453 0.0623 0.0924],... 'String','',... 'Value',Varname.Qij,... 'Style','togglebutton',... 'Tag','radiobutton2'); h12 = uicontrol(... 'CData',fm_mat('plotsel_iij'), ... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel setIij', ... 'Position',[0.1983 0.0453 0.0623 0.0924],... 'HorizontalAlignment','center', ... 'String','',... 'Value',Varname.Iij,... 'Style','togglebutton',... 'Tag','radiobutton3'); h13 = uicontrol(... 'CData',fm_mat('plotsel_sij'), ... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel setSij', ... 'Position',[0.2668 0.0453 0.0623 0.0924],... 'HorizontalAlignment','center', ... 'String','',... 'Style','togglebutton',... 'Value',Varname.Sij,... 'Tag','radiobutton4'); h10 = uicontrol(... 'CData',fm_mat('plotsel_x'), ... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel setx', ... 'HorizontalAlignment','center', ... 'Position',[0.0611 0.1467 0.0623 0.0924],... 'String','',... 'Value',Varname.x,... 'Style','togglebutton',... 'Tag','radiobutton5'); h11 = uicontrol(... 'CData',fm_mat('plotsel_y'), ... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel sety', ... 'HorizontalAlignment','center', ... 'Position',[0.1297 0.1467 0.0623 0.0924],... 'String','',... 'Value',Varname.y,... 'Style','togglebutton',... 'Tag','radiobutton6'); h12 = uicontrol(... 'CData',fm_mat('plotsel_p'), ... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel setP', ... 'Position',[0.1983 0.1467 0.0623 0.0924],... 'HorizontalAlignment','center', ... 'String','',... 'Value',Varname.P,... 'Style','togglebutton',... 'Tag','radiobutton7'); h13 = uicontrol(... 'CData',fm_mat('plotsel_q'), ... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel setQ', ... 'Position',[0.2668 0.1467 0.0623 0.0924],... 'HorizontalAlignment','center', ... 'String','',... 'Style','togglebutton',... 'Value',Varname.Q,... 'Tag','radiobutton8'); h6 = uicontrol(... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel fixed', ... 'CreateFcn','fm_plotsel create_fixed', ... 'Position',[0.3728 0.1594 0.1870 0.0453],... 'HorizontalAlignment','left', ... 'String','Fixed Selection',... 'Value',Varname.fixed,... 'Style','checkbox',... 'Tag','checkbox_fixed'); h7 = uicontrol(... 'Parent',h0, ... 'Units','normalized',... 'Callback','fm_plotsel custom', ... 'CreateFcn','fm_plotsel create_custom', ... 'Position',[0.3728 0.0688 0.1870 0.0453],... 'HorizontalAlignment','left', ... 'String','Manual Selection',... 'Value',Varname.custom,... 'Style','checkbox',... 'Tag','checkbox_custom'); h1 = uicontrol( ... 'Parent',h0, ... 'CData',fm_mat('main_exit'), ... 'Units','normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_plotsel remove', ... 'Position',[0.885 0.9 0.05 0.05], ... 'Tag','PushRemove'); if nargout > 0, fig = h0; end % =============================================== function setarea(s1,s2,s3,s4) % =============================================== global Varname value = get(gcbo,'Value'); hdl_fix = findobj(gcf,'Tag','checkbox_fixed'); hdl_cus = findobj(gcf,'Tag','checkbox_custom'); hdl_list1 = findobj(gcf,'Tag','listbox1'); hdl_list2 = findobj(gcf,'Tag','listbox2'); hdl_tog = findobj(gcf,'Style','togglebutton'); hdl_text1 = findobj(gcf,'Tag','StaticText1'); hdl_text2 = findobj(gcf,'Tag','StaticText2'); hdl_text3 = findobj(gcf,'Tag','StaticText3'); if value set(hdl_fix,'Value',s1); set(hdl_cus,'Value',s2); set(hdl_list1,'Enable',s3) set(hdl_tog,'Enable',s4) set(hdl_text1,'Enable',s3) set(hdl_text3,'Enable',s4) Varname.custom = s2; Varname.fixed = s1; else set(hdl_fix,'Value',s2); set(hdl_cus,'Value',s1); set(hdl_list1,'Enable',s4) set(hdl_tog,'Enable',s3) set(hdl_text1,'Enable',s4) set(hdl_text3,'Enable',s3) Varname.custom = s1; Varname.fixed = s2; end % =============================================== function setidx % =============================================== global Varname Bus DAE Settings Fig Areas Regions if Varname.fixed Varname.idx = []; n1 = DAE.n+DAE.m; n2 = n1 + 2*Bus.n; n3 = 2*Settings.nseries; jdx = [1:(2*Settings.nseries)]'; if Varname.x Varname.idx = [1:DAE.n]'; end if Varname.y idx0 = DAE.n; Varname.idx = [Varname.idx; idx0+[1:DAE.m]']; end if Varname.P idx0 = n1; Varname.idx = [Varname.idx; idx0+Bus.a]; end if Varname.Q idx0 = n1; Varname.idx = [Varname.idx; idx0+Bus.v]; end if Varname.Pij idx0 = n2; Varname.idx = [Varname.idx; idx0+jdx]; end if Varname.Qij idx0 = n2 + n3; Varname.idx = [Varname.idx; idx0+jdx]; end if Varname.Iij idx0 = n2 + 2*n3; Varname.idx = [Varname.idx; idx0+jdx]; end if Varname.Sij idx0 = n2 + 3*n3; Varname.idx = [Varname.idx; idx0+jdx]; end elseif Varname.custom Varname.idx = get(findobj(gcf,'Tag','listbox1'),'Value'); end % take into account area selection if Varname.areas(1), setzone('area'), end % take into account region selection if Varname.regions(1), setzone('region'), end hdl_list2 = findobj(gcf,'Tag','listbox2'); if isempty(Varname.idx) set(hdl_list2,'String','<Empty>','Value',1) else set(hdl_list2,'String',Varname.uvars(Varname.idx), ... 'Value',1, ... 'ListboxTop',1) end % =============================================== function setzone(type) % =============================================== global DAE Areas Bus Regions Settings Varname n1 = DAE.n+DAE.m; n2 = n1 + 2*Bus.n; n3 = Settings.nseries; n4 = 2*n3; switch type case 'area' zdx = getidx_areas(Areas,Varname.areas); buses = getarea_bus(Bus,0,0); case 'region' zdx = getidx_areas(Regions,Varname.regions); buses = getregion_bus(Bus,0,0); end % find buses within selected zones bdx = find(ismember(buses,zdx)); idx = getint_bus(Bus,getidx_bus(Bus,bdx)); % find series components within selected zones [fr,to] = fm_flows('onlyidx'); series1 = ismember(fr,idx); series2 = ismember(to,idx); ldx = find(series1+series2); % find state and algebraic variables within selected zones [x,y] = fm_getxy(idx); values = []; if Varname.x || (Varname.y && ~isempty(y)) values = [x; DAE.n+y]; end if Varname.y values = [values; DAE.n+[bdx; Bus.n+bdx]]; end if Varname.P values = [values; n1+bdx]; end if Varname.Q values = [values; n1+Bus.n+bdx]; end if Varname.Pij values = [values; n2+ldx]; values = [values; n2+n3+ldx]; end if Varname.Qij values = [values; n2+n4+ldx]; values = [values; n2+n3+n4+ldx]; end if Varname.Iij values = [values; n2+2*n4+ldx]; values = [values; n2+2*n4+n3+ldx]; end if Varname.Sij values = [values; n2+3*n4+ldx]; values = [values; n2+3*n4+n3+ldx]; end values = sort(values); Varname.idx = intersect(Varname.idx,values);
github
Sinan81/PSAT-master
fm_axesdlg.m
.m
PSAT-master/psat-oct/psat/fm_axesdlg.m
39,209
utf_8
86e49074fe6ba75e24c2cc7863f15124
function fm_axesdlg(varargin) %SCRIBEAXESDLG Axes property dialog helper function for Plot Editor % SCRIBEAXESDLG(A) opens axes property dialog for axes A % % If the plot editor is active, the SCRIBEAXESDLG edits all % currently selected axes. Alternatively, SCRIBEAXESDLG(S) % explicitly passes a selection list S, a row vector % of scribehandle objects, to SCRIBEAXESDLG for editing. % % Copyright 1984-2001 The MathWorks, Inc. % $Revision: 1.27 $ $Date: 2001/04/15 12:01:20 $ % j. H. Roh % %Modified by: Federico Milano %Date: 11-Nov-2002 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html persistent localData; switch nargin case 1 arg1 = varargin{1}; if isempty(arg1) || ishandle(arg1) || isa(arg1(1),'scribehandle') localData = LInitFig(arg1,localData); return elseif ischar(arg1) action = arg1; parameter = []; end case 2 action = varargin{1}; parameter = varargin{2}; end if strcmp(parameter,'me') parameter = gcbo; end localData = feval(action,parameter,localData); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function localData = showhelp(selection, localData) try helpview([docroot '/mapfiles/plotedit.map'], ... 'pe_ax_props', 'PlotEditPlain'); catch errordlg(['Unable to display help for Axes Properties:' ... sprintf('\n') lasterr ]); end function localData = button(selection, localData); switch selection case 'cancel' close(gcbf); case 'ok' set(gcbf,'Pointer','watch'); localData = LApplySettings(gcbf,localData); close(gcbf); case 'apply' set(gcbf,'Pointer','watch'); localData = LApplySettings(gcbf,localData); set(gcbf,'Pointer','arrow'); end function localData = verifynumber(uic, localData) iGroup = find(uic==localData.LimCheck); val = str2double(get(uic,'String')); if ~isnan(val) if length(val)==1 localData.OldVal{iGroup} = val; return end end % trap errors set(uic,'String',num2str(localData.OldVal{iGroup})); fieldName = get(uic,'ToolTip'); errordlg([fieldName ' field requires a single numeric input'],'Error','modal'); function localData = key(fig,localData); theKey = get(fig,'CurrentCharacter'); if isempty(theKey), return, end switch theKey case 13 % return fm_axesdlg button ok; case 27 % escape fm_axesdlg button cancel; case 9 % tab % next field end % manage state of controls function localData = toggle(uic,localData); iGroup = find(uic==localData.LimCheck); Sibling = get(uic,'UserData'); enable = {'off' 'on'}; if isempty(Sibling), % Perform as before value = get(uic,'Value'); if ~isempty(iGroup), set(localData.LimGroup{iGroup},'Enable',enable{value+1}); end else % See if the extra checkbox was pressed if isempty(get(uic,'String')), Sibling=uic; % Reset the Sibling as the current UIcontrol end SibUd = get(Sibling,'UserData'); % Toggle the extra check box state if strcmp(get(Sibling,'enable'),'off'); set(Sibling,'enable','inactive'); value = get(Sibling,'Value'); elseif isequal(SibUd.Value,get(Sibling,'Value')), set(Sibling,'value',~get(Sibling,'Value')) value = get(Sibling,'Value'); else set(Sibling,'enable','off','Value',SibUd.Value); value = 0; end if ~isempty(iGroup), set(localData.LimGroup{iGroup},'Enable',enable{value+1}); end end % if/else isempty(Sibling) function localData = radio(uic,localData); iGroup = find(uic==localData.LimCheck); Sibling = get(uic,'UserData'); enableflag = 1; if isempty(Sibling), % Perform as before set(uic,'Value',1); set(localData.LimGroup{iGroup},'Value',0); else if ~isempty(get(uic,'String')), iGroup = iGroup+2; ActiveButton = localData.LimCheck(iGroup); value = ~get(ActiveButton,'Value'); else ActiveButton = uic; value = get(ActiveButton,'Value'); end udAB = get(ActiveButton,'UserData'); udLimGroup = get(localData.LimGroup{iGroup},'UserData'); udLimGroup.Value = 0; % Toggle the active radio button's state if strcmp(get(ActiveButton,'enable'),'off'); udAB.Value = 1; set(ActiveButton,'enable','on','Value',1,'UserData',udAB); set(localData.LimGroup{iGroup},'Enable','on'); elseif udAB.Value, udAB.Value = 0; set(ActiveButton,'Value',0, ... 'Enable','off','UserData',udAB) set(localData.LimGroup{iGroup},'Value',0, ... 'Enable','off','UserData',udLimGroup) % Store the checkbox state, if ~isempty(localData.Enable{iGroup}), localData.Disable{iGroup-1}.CheckValue = get(localData.Enable{iGroup}(1),'Value'); end enableflag = 0; else udAB.Value = 1; set(ActiveButton,'Value',1,'UserData',udAB); set(localData.LimGroup{iGroup},'Value',0,'UserData',udLimGroup) end % if/else strcmp(Sibling,'enable'...) end % if/else length(localData.axes... % for the linear/log switches disableGroup = localData.Disable{iGroup}; if ~isempty(disableGroup) && enableflag, if any(strcmp(get(disableGroup.Controls,'Enable'),'on')) , set(disableGroup.Controls,'Enable','off'); % Save the checkbox value localData.Disable{iGroup}.CheckValue = get(disableGroup.Controls(1),'Value'); end set(disableGroup.Controls(1),'Value',0); % uncheck Sibling = get(disableGroup.Controls(1),'UserData'); if ~isempty(Sibling), set(Sibling,'Value',0,'Enable','off','HitTest','off'); end end enableGroup = localData.Enable{iGroup}; if ~isempty(enableGroup) && enableflag, Sibling = get(enableGroup(1),'UserData'); if ~isempty(Sibling), value = get(Sibling,'Value'); else value = get(enableGroup(1),'Value'); end if ~value set(enableGroup(1),'Enable','on',... 'Value',localData.Disable{iGroup-1}.CheckValue); % enable checkbox else set(enableGroup,'Enable','on'); % enable both set(enableGroup(1),'Value',localData.Disable{iGroup-1}.CheckValue); end % if/else value if ~isempty(Sibling), set(Sibling,'HitTest','on','Value',localData.Disable{iGroup-1}.CheckValue); end else set(enableGroup,'Enable','off'); % disable both end function localData = LInitFig(ax,localData) if isempty(ax) LNoAxesError; return end try if ishandle(ax) fig = get(ax(1),'Parent'); else % might be any selected object fig = get(ax(1),'Figure'); end catch errordlg(['Unable to edit axes properties: invalid axes' ... ' handles.']); return end oldPointer = get(fig,'Pointer'); set(fig,'Pointer','watch'); try % look for a list of selected objects HG = []; if ~plotedit(fig,'isactive') % plotedit has not been activated and we have a list of HG handles HG = ax; % take the original handle list else % call from the Figure Tools menu or from context menu % ax is a selection list for aObj = ax aHG = get(aObj,'MyHGHandle'); if strcmp('axes',get(aHG,'Type')) HG(end+1) = aHG; end end end catch set(fig,'Pointer',oldPointer); errordlg(['Unable to open Axes Properties dialog. ' ... 'Selection list is invalid:' ... 10 lasterr]); return end if isempty(HG) LNoAxesError; set(fig,'Pointer',oldPointer); return end %--temporary: redirect to Property Editor %propedit(HG); %set(fig,'Pointer',oldPointer); %return ax = HG; try % Property constants White = [1 1 1]; Black = [0 0 0]; % Check each axes, if one is 3D allViews = get(ax,{'view'}); f2D = isequal(allViews{:},[0 90]); bgcolor = get(0,'DefaultUIControlBackgroundColor'); if bgcolor==Black fgcolor = White; else fgcolor = get(0,'DefaultUIControlForegroundColor'); end % adjustment factors for character units % work in character units. fx = 5; fy = 13; fProps = struct(... 'Units', get(fig,'Units'),... 'NumberTitle', 'off',... 'IntegerHandle', 'off',... 'Pointer','watch', ... 'Resize', 'on',... 'Color', bgcolor,... 'Visible', 'off',... 'KeyPressFcn', 'fm_axesdlg key me',... 'WindowStyle', 'modal',... 'Name', 'Edit Axes Properties', ... 'Position', get(fig,'Position')); f = figure(fProps); set(f,'Units','character'); figPos = get(f,'Position'); figWidth = 550/fx; figHeight = 325/fy; % center dialog over the calling window figPos(1:2) = figPos(1:2) + (figPos(3:4)-[figWidth, figHeight])/2; figPos(3:4) = [figWidth, figHeight]; set(f,'Position',figPos); enable = {'off' 'on'}; % geometry LMarginW = 15/fx; RMarginW = 25/fx; ColPadW = 20/fx; RowPadH = 9/fy; RowLabelW = 70/fx; if f2D nCols = 2; else nCols = 3; end data.nCols = nCols; setappdata(f,'ScribeAxesDialogData',data); ColW = (figPos(3)-RowLabelW-LMarginW-RMarginW-nCols*ColPadW)/nCols; TopMarginH = 20/fy; BotMarginH = 20/fy; TitleH = 25/fy; HeaderH = 30/fy; RowH = 30/fy; buttonW = 72/fx; buttonH = RowH-RowPadH; buttonPad = 7/fx; XCol(1) = LMarginW; XCol(2) = XCol(1) + RowLabelW + ColPadW; XCol(3) = XCol(2) + ColW + ColPadW; XCol(4) = XCol(3) + ColW + ColPadW; % defaults for each style editProps = struct(... 'Parent', f,... 'Style', 'edit',... 'Units', 'character',... 'BackgroundColor', White,... 'ForegroundColor', Black,... 'HorizontalAlignment', 'left',... 'Callback', 'fm_axesdlg verifynumber me'); checkProps = struct(... 'Parent', f,... 'Style', 'checkbox',... 'Units', 'character',... 'HorizontalAlignment', 'left',... 'BackgroundColor', bgcolor,... 'ForegroundColor', fgcolor,... 'Callback', 'fm_axesdlg toggle me'); radioProps = struct(... 'Parent', f,... 'Style', 'radio',... 'Units', 'character',... 'HorizontalAlignment', 'left',... 'BackgroundColor', bgcolor,... 'ForegroundColor', fgcolor,... 'Callback', 'fm_axesdlg radio me'); tProps = struct(... 'Parent', f,... 'Style', 'text',... 'Units', 'character',... 'HorizontalAlignment', 'right',... 'BackgroundColor', bgcolor,... 'ForegroundColor', fgcolor); % get text size ut = uicontrol(tProps,... 'Visible','off',... 'String','Title'); charSize = get(ut,'Extent'); charH = charSize(4); delete(ut); % charOffset = (RowH-charH)/2; editH = charH + 4/fy; uiH = RowH-RowPadH; YTitleRow = figPos(4)-TitleH-TopMarginH-uiH; % Title row charOffset = uiH-charH; uicontrol(tProps,... 'FontWeight','bold',... 'String', 'Title:',... 'Position', ... [ LMarginW YTitleRow + uiH + uiH - charH ... RowLabelW charH]); % Check for similar titles titleHandle = get(ax,{'Title'}); titleString = get([titleHandle{:}],{'String'}); if isempty(titleString{1}) || ... (length(titleString) > 1 && ~isequal(titleString{:})), % use a cell array, so spaces aren't padded out. CommonFlag = 0; titleString = {}; else CommonFlag = 1; titleString=titleString{1}; end titleU = uicontrol(editProps,... 'Tag', 'Title',... 'UserData',CommonFlag, ... 'Callback', '',... 'HorizontalAlignment','center',... 'Max', 2, ... % allow multi line titles 'String', titleString,... 'Position', ... [ XCol(2) YTitleRow ... nCols*ColW+(nCols-1)*ColPadW uiH + uiH]); iGroup=1; localData.LimCheck(iGroup)=titleU; localData.Prop{iGroup} = 'Title'; % put down the row headings rowLabelStrings = {... '','left', 'Label:','right', 'Limits:','right', 'Tick Step:','right', 'Scale:','right', '','right', 'Grid:','right', '','right', }; nRows = size(rowLabelStrings,1); Y = YTitleRow - HeaderH + RowPadH; headingPosition = [LMarginW Y RowLabelW charH]; for iRow = 1:nRows, if ~isempty(rowLabelStrings{iRow,1}) headingPosition(2) = Y; uicontrol(tProps,... 'FontWeight', 'bold',... 'String', rowLabelStrings{iRow,1},... 'HorizontalAlignment', rowLabelStrings{iRow,2},... 'Position', headingPosition); end Y = Y-RowH; end % fill each column cCol = ' XYZ'; for iCol = 2:nCols+1, X = XCol(iCol); col = cCol(iCol); % heading Y = YTitleRow - HeaderH + RowPadH; uicontrol(tProps,... 'Style', 'text',... 'FontWeight', 'bold',... 'HorizontalAlignment', 'center',... 'Position', [X Y-charOffset ColW charH],... 'String', col); % label Y = Y-RowH; % Check for similar labels labelHandle = get(ax,{[col 'Label']}); labelString = get([labelHandle{:}],{'String'}); if isempty(labelString{1}) || ... (length(labelString)>1 && ~isequal(labelString{:})), % use a cell array, so spaces aren't padded out. CommonFlag = 0; labelString = {}; else labelString=labelString{1}; CommonFlag = 1; end if size(labelString,1)>1 % multiline label multiline = 2; else multiline = 1; end labelU = uicontrol(editProps,... 'Enable', 'on',... 'Tag', [col 'Label'],... 'ToolTip', [col 'Label'],... 'UserData',CommonFlag, ... 'Position', [X Y ColW uiH ],... 'String', labelString,... 'Max', multiline,... 'Callback', ''); iGroup = iGroup+1; localData.LimCheck(iGroup) = labelU; localData.Prop{iGroup} = 'Title'; % range Y = Y-RowH; % Check if all axes are manual or auto AllMods = strcmp(get(ax, [col 'LimMode']),'manual'); MultMods = 0; if all(~AllMods) checkProps.Value = 0; elseif all(AllMods) checkProps.Value = 1; else MultMods = 1; checkProps.Value = length(find(AllMods))>=length(find(~AllMods)); end CheckVal = checkProps.Value; clim = uicontrol(checkProps,... 'String', 'Manual',... 'Tag', [col 'LimMode'],... 'ToolTip', [col 'LimMode'],... 'Position', [X Y ColW/2 uiH]); % Add a second checkbox when editing multiple axes if MultMods, % Overwrite the other checkbox, since it's callback will never % be invoked clim2 = uicontrol(checkProps,... 'ButtonDownFcn','fm_axesdlg toggle me', ... 'Enable','off', ... 'Tag', [col 'LimMode'],... 'ToolTip', [col 'LimMode'],... 'UserData',struct('Value',checkProps.Value,'Sibling',clim), ... 'Position', [X Y 3 uiH]); checkProps.Value = 0; set(clim,'UserData',clim2,'Tag','') end % Check for common limits lim = get(ax,{[col 'Lim']}); lim = cat(1,lim{:}); Umin = unique(lim(:,1)); Umax = unique(lim(:,2)); if length(Umin)>1, uminStr = ''; else, uminStr = num2str(Umin); end if length(Umax)>1, umaxStr = ''; else, umaxStr = num2str(Umax); end umin = uicontrol(editProps,... 'Tag', [col 'LimMin'],... 'ToolTip', [col ' Min'],... 'Enable', enable{checkProps.Value+1},... 'String', uminStr,... 'Position', [X+ColW/2 Y ColW/4 uiH]); iGroup=iGroup+1; localData.LimCheck(iGroup) = umin; localData.OldVal{iGroup} = min(lim); umax = uicontrol(editProps,... 'Tag', [col 'LimMax'],... 'Enable', enable{checkProps.Value+1},... 'String', umaxStr,... 'Position', [X+ColW*3/4 Y ColW/4 uiH],... 'ToolTip', [col ' Max']); iGroup = iGroup+1; localData.LimCheck(iGroup) = umax; localData.OldVal{iGroup} = max(lim); iGroup = iGroup+1; localData.LimGroup{iGroup} = [umin umax]; localData.LimCheck(iGroup) = clim; localData.Prop{iGroup} = [col 'LimMode']; if MultMods iGroup = iGroup+1; localData.LimGroup{iGroup} = [umin umax]; localData.LimCheck(iGroup) = clim2; localData.Prop{iGroup} = [col 'LimMode']; end % Check if all axes use a linear scale AllScales = strcmp(get(ax,[col 'Scale']),'linear'); MultScales = 0; if all(~AllScales) linearScale = 0; elseif all(AllScales) linearScale = 1; else MultScales = 1; linearScale=0; end % tickstep Y = Y-RowH; % Check if all TickModes are manual or auto AllMods = strcmp(get(ax, [col 'TickMode']),'manual'); MultMods = 0; if all(~AllMods) checkProps.Value = 0; elseif all(AllMods) checkProps.Value = 1; else MultMods = 1; checkProps.Value = length(find(AllMods))>=length(find(~AllMods)); end CheckVal = checkProps.Value; clim = uicontrol(checkProps,... 'String', 'Manual',... 'Tag', [col 'TickMode'],... 'Enable', enable{linearScale+1},... 'ToolTip', [col 'TickMode'],... 'Position', [X Y ColW/2 uiH]); % Add a second checkbox when editing multiple axes if MultMods, % Overwrite the other checkbox, since it's callback will never % be invoked clim2 = uicontrol(checkProps,... 'ButtonDownFcn','fm_axesdlg toggle me', ... 'Enable','off', ... 'Tag', [col 'TickMode'],... 'ToolTip', [col 'TickMode'],... 'UserData',struct('Value',checkProps.Value,'Sibling',clim), ... 'Position', [X Y 3 uiH]); checkProps.Value = 0; set(clim,'UserData',clim2,'Tag','') end if linearScale editProps.Enable = enable{checkProps.Value+1}; % Check for common tick marks tick = get(ax,{[col 'Tick']}); if (length(tick)>1 && ~isequal(tick{:})) || isempty(tick{1}) || length(tick{1})<2 tickstep = []; else tickstep = tick{1}(2)-tick{1}(1); end else editProps.Enable = enable{0+1}; tickstep = []; end utick = uicontrol(editProps,... 'Tag', [col 'TickStep'],... 'ToolTip', [col ' Tick step size'],... 'HorizontalAlignment','center',... 'String', num2str(min(tickstep)),... 'Position', [X+ColW/2 Y ColW/2 uiH]); iGroup = iGroup+1; localData.LimCheck(iGroup) = utick; localData.OldVal{iGroup} = tickstep; iGroup = iGroup+1; localData.LimGroup{iGroup} = utick; localData.LimCheck(iGroup) = clim; if MultMods, iGroup = iGroup+1; localData.LimGroup{iGroup} = utick; localData.LimCheck(iGroup) = clim2; end % Scale Y = Y-RowH; radioProps.Value = linearScale; rlin = uicontrol(radioProps,... 'Position', [X Y ColW/2 uiH],... 'String', 'Linear',... 'Tag', [col 'ScaleLinear'],... 'ToolTip',[col 'Scale=''linear''']); % Add a second set of radio buttons when editing multiple axes if MultScales, rlin2 = uicontrol(radioProps,... 'ButtonDownFcn','fm_axesdlg radio me', ... 'Enable','off', ... 'Position', [X Y 3 uiH],... 'String', '',... 'Tag', [col 'ScaleLinear'],... 'ToolTip',[col 'Scale=''linear'''], ... 'Value',0); set(rlin,'UserData',rlin2,'Tag',''); end Y = Y-RowH*2/3; rlog = uicontrol(radioProps,... 'Position', [X Y ColW/2 uiH],... 'String', 'Log',... 'Value', ~radioProps.Value,... 'Tag', [col 'ScaleLog'],... 'ToolTip',[col 'Scale=''log''']); % Add a second set of radio buttons when editing multiple axes if MultScales, rlog2 = uicontrol(radioProps,... 'Enable','off', ... 'Position', [X Y 3 uiH],... 'String', '',... 'Value', ~radioProps.Value,... 'Tag', [col 'ScaleLog'],... 'ToolTip',[col 'Scale=''log'''], ... 'Value',0); set(rlog,'UserData',rlog2,'Tag',''); set(rlin2,'UserData',... struct('Value',0,'Sibling',rlin,'OtherRadio',rlog2)); set(rlog2,'UserData',... struct('Value',0,'Sibling',rlog,'OtherRadio',rlin2)); end Y = Y-RowH*1/3; iGroup = iGroup+1; localData.LimGroup{iGroup} = [rlin]; localData.LimCheck(iGroup) = rlog; localData.Enable{iGroup} = []; localData.Disable{iGroup} = struct('Controls',[clim utick], ... 'CheckValue',CheckVal); iGroup = iGroup+1; localData.LimGroup{iGroup} = [rlog]; localData.LimCheck(iGroup) = rlin; localData.Enable{iGroup} = [clim utick]; % checkbox then % other control localData.Disable{iGroup} = []; if MultScales iGroup = iGroup+1; localData.LimGroup{iGroup} = [rlin2]; localData.LimCheck(iGroup) = rlog2; localData.Enable{iGroup} = []; localData.Disable{iGroup} = struct('Controls',[clim utick], ... 'CheckValue',CheckVal); iGroup = iGroup+1; localData.LimGroup{iGroup} = [rlog2]; localData.LimCheck(iGroup) = rlin2; localData.Enable{iGroup} = [clim utick]; % checkbox then % other control localData.Disable{iGroup} = []; end % Direction Y = Y+RowH; % Check if all axes use a normal dirction AllDirs = strcmp(get(ax, [col 'Dir']),'normal'); MultDirs = 0; if all(~AllDirs) radioProps.Value = 0; elseif all(AllDirs) radioProps.Value = 1; else MultDirs= 1; radioProps.Value = 0; end rnormal = uicontrol(radioProps,... 'Position', [X+ColW/2 Y ColW/2 uiH],... 'String', 'Normal',... 'Tag', [col 'DirNormal'],... 'ToolTip',[col 'Dir=''normal''']); if MultDirs rnormal2 = uicontrol(radioProps,... 'ButtonDownFcn','fm_axesdlg radio me', ... 'Enable','off', ... 'Position', [X+ColW/2 Y 3 uiH],... 'String', '',... 'Tag', [col 'DirNormal'],... 'ToolTip',[col 'Dir=''normal''']); set(rnormal,'UserData',rnormal2,'Tag',''); end Y = Y-RowH*2/3; rreverse = uicontrol(radioProps,... 'Position', [X+ColW/2 Y ColW/2 uiH],... 'String', 'Reverse',... 'Value', ~radioProps.Value,... 'Tag', [col 'DirReverse'],... 'ToolTip',[col 'Dir=''reverse''']); if MultDirs rreverse2 = uicontrol(radioProps,... 'ButtonDownFcn','fm_axesdlg radio me', ... 'Enable','off', ... 'Position', [X+ColW/2 Y 3 uiH],... 'String', '',... 'Tag', [col 'DirReverse'],... 'ToolTip',[col 'Dir=''reverse''']); set(rreverse,'UserData',rreverse2,'Tag',''); set(rreverse2,'UserData',... struct('Value',0,'Sibling',rreverse,'OtherRadio',rnormal2)); set(rnormal2,'UserData',... struct('Value',0,'Sibling',rnormal,'OtherRadio',rreverse2)); end Y = Y-RowH*1/3; iGroup = iGroup+1; localData.LimGroup{iGroup} = [rnormal]; localData.LimCheck(iGroup) = rreverse; localData.Enable{iGroup} = []; localData.Disable{iGroup} = []; iGroup = iGroup+1; localData.LimGroup{iGroup} = [rreverse]; localData.LimCheck(iGroup) = rnormal; localData.Enable{iGroup} = []; localData.Disable{iGroup} = []; if MultDirs iGroup = iGroup+1; localData.LimGroup{iGroup} = [rnormal2]; localData.LimCheck(iGroup) = rreverse2; localData.Enable{iGroup} = []; localData.Disable{iGroup} = []; iGroup = iGroup+1; localData.LimGroup{iGroup} = [rreverse2]; localData.LimCheck(iGroup) = rnormal2; localData.Enable{iGroup} = []; localData.Disable{iGroup} = []; end % grid % Check if all axes grids are on AllGrids = strcmpi(get(ax,[col 'Grid']),'on'); MultGrids = 0; if all(~AllGrids) checkProps.Value = 0; elseif all(AllGrids) checkProps.Value = 1; else MultGrids = 1; checkProps.Value = length(find(AllGrids))>=length(find(~AllGrids)); end Y = Y-RowH; g = uicontrol(checkProps,... 'String', 'On',... 'Tag', [col 'Grid'],... 'ToolTip', [col 'Grid'],... 'Position', [X Y ColW/3 uiH],... 'Callback', 'fm_axesdlg toggle me'); iGroup = iGroup+1; localData.LimGroup{iGroup} = []; localData.LimCheck(iGroup) = g; localData.Enable{iGroup} = []; localData.Disable{iGroup} = []; if MultGrids g2 = uicontrol(checkProps,... 'ButtonDownFcn','fm_axesdlg toggle me', ... 'Enable','off', ... 'String', '',... 'Tag', [col 'Grid'],... 'ToolTip', [col 'Grid'],... 'UserData',struct('Value',checkProps.Value,'Sibling',g), ... 'Position', [X Y 3 uiH],... 'Callback', 'fm_axesdlg toggle me'); set(g,'UserData',g2,'Tag',''); iGroup = iGroup+1; localData.LimGroup{iGroup} = []; localData.LimCheck(iGroup) = g2; localData.Enable{iGroup} = []; localData.Disable{iGroup} = []; end iGroup = iGroup+1; end buttonX(1) = (figPos(3)-4*buttonW-3*buttonPad)/2; for ib = 2:4 buttonX(ib) = buttonX(ib-1) + buttonW + buttonPad; end buttonProps = struct(... 'Parent',f,... 'Units','character',... 'BackgroundColor', bgcolor,... 'ForegroundColor', fgcolor,... 'Position', [0 BotMarginH buttonW buttonH],... 'Style', 'pushbutton'); buttonProps.Position(1) = buttonX(1); u = uicontrol(buttonProps,... 'Interruptible', 'off',... 'String', 'OK',... 'Callback', 'fm_axesdlg button ok'); buttonProps.Position(1) = buttonX(2); uicontrol(buttonProps,... 'Interruptible', 'off',... 'String', 'Cancel',... 'Callback', 'fm_axesdlg button cancel'); buttonProps.Position(1) = buttonX(3); uicontrol(buttonProps,... 'Interruptible', 'off',... 'String', 'Help',... 'Callback', 'fm_axesdlg showhelp me'); buttonProps.Position(1) = buttonX(4); uicontrol(buttonProps,... 'Interruptible', 'on',... 'String', 'Apply',... 'Callback', 'fm_axesdlg button apply'); % finish opening axes dialog box set(fig,'Pointer',oldPointer); set(f,'Visible','on','Pointer','arrow'); localData.axes = ax; catch set(fig,'Pointer',oldPointer); if exist('f') delete(f); end errordlg({'Couldn''t open axes properties dialog:' ... lasterr},... 'Error',... 'modal'); end function [val,setflag] = getval(f,tag) uic = findobj(f,'Tag',tag); setflag = 1; % Flag for setting properties on multiple axes switch get(uic,'Style') case 'edit' val = get(uic, 'String'); if isempty(val) setflag = 0; end case {'checkbox' 'radiobutton'} val = get(uic, 'Value'); setflag = ~strcmp(get(uic,'Enable'),'off'); if setflag && isstruct(get(uic,'UserData')); %---Making a previously non-common property, common LdeleteControl(uic) end end function val = setval(f,tag,val) uic = findobj(f,'Tag',tag); switch get(uic,'Style') case 'edit' set(uic, 'String',val); case {'checkbox' 'radiobutton'} set(uic, 'Value',val); end function localData = LApplySettings(f, localData) % get the values and set props: ax = localData.axes; iProp = 0; try % title val = getval(f,'Title'); switch class(val) case 'char' if ~isempty(val) && size(val,1)>1 % title returns as a string matrix % check for blank line at end of multiline title nTitleLines = size(val,1); if val(nTitleLines,:)==32 % true if all spaces val(nTitleLines,:) = []; setval(f,'Title',val); end end case 'cell' if length(val)>1 nTitleLines = length(val); if isempty(val{nTitleLines}) || val{nTitleLines}==32 val(nTitleLines) = []; end end end CommonTitle = get(findobj(f,'Tag','Title'),'UserData'); if ~(isempty(val) && length(ax)>1) || CommonTitle || length(ax)==1, t = get(ax,{'Title'}); set([t{:}],'String',val); if ~CommonTitle, % They are common, now set(findobj(f,'Tag','Title'),'UserData',1) end end data = getappdata(f,'ScribeAxesDialogData'); cols = 'XYZ'; for i = 1:data.nCols col = cols(i); %label CommonLabel = get(findobj(f,'Tag',[col 'Label']),'UserData'); val = getval(f,[col 'Label']); if ~(isempty(val) && length(ax)>1) || CommonLabel || length(ax)==1, t = get(ax,{[col 'Label']}); set([t{:}],'String',val) if ~CommonLabel, % They are common, now set(findobj(f,'Tag',[col 'Label']),'UserData',1) end end % scale [mode,setflag] = getval(f,[col 'ScaleLinear']); if setflag, iProp = iProp+1; axProps{iProp} = [col 'Scale']; modeswitch = {'log' 'linear'}; axVals{iProp} = modeswitch{mode+1}; % update immediately so that we get updated limits and ticks set(ax,axProps(iProp),axVals(iProp)); end % if setflag linearScale = mode; %limitmode [manual,setflag] = getval(f,[col 'LimMode']); valMax=[]; valMin=[]; limits=[]; if setflag iProp = iProp+1; axProps{iProp} = [col 'LimMode']; modeswitch = {'auto' 'manual'}; axVals{iProp} = modeswitch{manual+1}; if manual %limits valMin = str2double(getval(f,[col 'LimMin'])); valMax = str2double(getval(f,[col 'LimMax'])); % ranges checked on callbacks if ~(isnan(valMax) || isnan(valMin)), iProp = iProp+1; axProps{iProp} = [col 'Lim']; limits = [valMin valMax]; axVals{iProp} = limits; end else % auto set(ax,[col 'LimMode'],'auto'); % Check for common limits lim = get(ax,{[col 'Lim']}); lim = cat(1,lim{:}); Umin = unique(lim(:,1)); Umax = unique(lim(:,2)); if length(Umin)>1, uminStr = ''; else, uminStr = num2str(Umin); end if length(Umax)>1, umaxStr = ''; else, umaxStr = num2str(Umax); end setval(f, [col 'LimMin'], uminStr); setval(f, [col 'LimMax'], umaxStr); end % if manual end % if setflag %tickmode TickInd=[]; [manual,setflag] = getval(f,[col 'TickMode']); if setflag, iProp = iProp+1; axProps{iProp} = [col 'TickMode']; modeswitch = {'auto' 'manual'}; axVals{iProp} = modeswitch{manual+1}; if linearScale if manual tickstep = str2double(getval(f,[col 'TickStep'])); if ~isempty(tickstep), % Make sure something is there if ~isempty(limits), % Only preset ticks when everything is the same iProp = iProp+1; axProps{iProp} = [col 'Tick']; ticks = limits(1):tickstep:limits(2); % ranges checked on callbacks axVals{iProp} = ticks; else TickInd = iProp; end end else % auto set(ax,[col 'TickMode'],'auto'); if length(ax)==1 ticks = get(ax,[col 'Tick']); setval(f, [col 'TickStep'], ticks(2)-ticks(1)); end end % if manual else % log scale % manual mode disabled for log scale set(ax,[col 'TickMode'],'auto'); setval(f, [col 'TickStep'], ''); end end % if setflag % scale direction [mode,setflag] = getval(f,[col 'DirNormal']); if setflag, iProp = iProp+1; axProps{iProp} = [col 'Dir']; modeswitch = {'reverse' 'normal'}; axVals{iProp} = modeswitch{mode+1}; end % grid [mode,setflag] = getval(f,[col 'Grid']); if setflag, iProp = iProp+1; axProps{iProp} = [col 'Grid']; modeswitch = {'off' 'on'}; axVals{iProp} = modeswitch{mode+1}; end % if setflag if ~isempty(TickInd) || isnan(valMax) || isnan(valMin) % Going to have to loop thru to set limits/ticks individually for ct = 1:length(ax) limits = get(ax(ct),[col 'Lim']); axPropsCustom{1} = [col 'Lim']; if ~isnan(valMax), limits(2) = valMax; end if ~isnan(valMin), limits(1) = valMin; end axValsCustom{1} = limits; if ~isempty(TickInd); axPropsCustom{2} = [col 'Tick']; ticks = limits(1):tickstep:limits(2); % ranges checked on callbacks axValsCustom{2} = ticks; end % if ~isempty(TickInd) set(ax(ct),axPropsCustom,axValsCustom); end % for ct end end % for col set(ax,axProps,axVals) catch % error somewhere in there... end % try/catch function LdeleteControl(OldControl) ud = get(OldControl,'UserData'); set(ud.Sibling,'Value',get(OldControl,'Value'), ... 'Tag',get(OldControl,'Tag'),'UserData',[]) if isfield(ud,'OtherRadio'), ud2 = get(ud.OtherRadio,'UserData'); set(ud2.Sibling,'Value',get(ud.OtherRadio,'Value'), ... 'Tag',get(ud.OtherRadio,'Tag'),'UserData',[]) delete(ud.OtherRadio) end delete(OldControl) function LNoAxesError errordlg(['No axes are selected. Click on an axis to select it.']);
github
Sinan81/PSAT-master
runpsat.m
.m
PSAT-master/psat-oct/psat/runpsat.m
10,545
utf_8
6d79193e3e1dfd944a1732b17a3c9d9d
function runpsat(varargin) % RUNPSAT run PSAT routine for power system analysis % % RUNPSAT([FILE,[PATH]],[PERTFILE,[PERTPATH]],ROUTINE) % % FILE: string containing the PSAT data file (can be a % simulink model) % PATH: string containing the absolute path of the data % file (default path is "pwd") % PERTFILE: string containing the PSAT perturbation file % (default is the empty string) % PERTPATH: string containing the absolute path of the % perturbation file (default is the empty string) % ROUTINE: name of the routine to be launched: % % General options: % % 'data' => set data file % 'pert' => set perturbation file % 'opensys' => open saved system % 'savsys' => save currenst system % 'pfrep' => write power flow solution % 'eigrep' => write eigenvalue report file % 'pmurep' => write PMU placement report file % 'plot' => plot TD results (Octave only) % % Routines: % % 'pf' => power flow % 'cpf' => continuation power flow % 'snb' => SNB computation (direct method) % 'limit' => LIB computation % 'n1cont' => N-1 contingency analysis % 'opf' => optimal power flow % 'cpfatc' => ATC computation through CPF analysis % 'sensatc' => ATC computation through sensitivity % analysis % 'td' => time domain simulation % 'sssa' => small signal stability analysis % 'pmu' => PMU placement % 'gams' => OPF through PSAT-GAMS interface % 'uw' => CPF through PSAT-UWPFLOW interface % %Author: Federico Milano %Date: 23-Feb-2004 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Settings fm_var % last input is the routine type if nargin == 0 disp('Error: runpsat needs at least one argument.') return end routine = varargin{nargin}; if isnumeric(routine) fm_disp('Routine specifier must be a string.') return end % Simulink models are not supported on GNU/Octave if Settings.octave && strcmp(routine,'data') && ... ~isempty(findstr(varargin{1},'.mdl')) fm_disp('Simulink models are not supported on GNU/Octave') return end % check if the data file has been changed changedata = strcmp(routine,'data'); if nargin > 1 changedata = changedata || ~strcmp(varargin{1},File.data); end if changedata, Settings.init = 0; end % check inputs switch nargin case 5 File.data = varargin{1}; Path.data = checksep(varargin{2}); File.pert = varargin{3}; Path.pert = checksep(varargin{4}); case 4 File.data = varargin{1}; Path.data = checksep(varargin{2}); File.pert = varargin{3}; Path.pert = [pwd,filesep]; case 3 switch routine case 'data' File.data = varargin{1}; Path.data = checksep(varargin{2}); case 'pert' File.pert = varargin{1}; Path.pert = checksep(varargin{2}); case 'opensys' datafile = varargin{1}; datapath = checksep(varargin{2}); otherwise File.data = varargin{1}; Path.data = checksep(varargin{2}); File.pert = ''; Path.pert = ''; end case 2 switch routine case 'data' File.data = varargin{1}; Path.data = [pwd,filesep]; case 'pert' File.pert = varargin{1}; Path.pert = [pwd,filesep]; case 'opensys' datafile = varargin{1}; datapath = [pwd,filesep]; case 'plot' % nothing to do... otherwise File.data = varargin{1}; Path.data = [pwd,filesep]; File.pert = ''; Path.pert = ''; end case 1 % nothing to do... otherwise fm_disp('Invalid number of arguments: check synthax...') return end % remove extension from data file (only Matlab files) if length(File.data) >= 2 && strcmp(routine,'data') if strcmp(File.data(end-1:end),'.m') File.data = File.data(1:end-2); end end % remove extension from perturbation file (only Matlab files) if length(File.pert) >= 2 && strcmp(routine,'pert') if strcmp(File.pert(end-1:end),'.m') File.pert = File.pert(1:end-2); end end % set local path as data path to prevent undesired change % of path within user defined functions Path.local = Path.data; % check if the data file is a Simulink model File.data = strrep(File.data,'.mdl','(mdl)'); if ~isempty(findstr(File.data,'(mdl)')) filedata = deblank(strrep(File.data,'(mdl)','_mdl')); if exist(filedata) ~= 2 || clpsat.refreshsim || strcmp(routine,'data') check = sim2psat; if ~check, return, end File.data = filedata; end end % launch PSAT computations switch routine case 'data' % set data file % checking the consistency of the data file localpath = pwd; cd(Path.data) check = exist(File.data); cd(localpath) if check ~= 2 && check ~= 4 fm_disp(['Warning: The selected file is not valid or not in the ' ... 'current folder!']) else Settings.init = 0; end case 'pert' % set perturbation file localpath = pwd; cd(Path.pert) check = exist(File.pert); cd(localpath) % checking the consistency of the pert file if check ~= 2 fm_disp(['Warning: The selected file is not valid or not in the ' ... 'current folder!']) else localpath = pwd; cd(Path.pert) if Settings.hostver >= 6 Hdl.pert = str2func(File.pert); else Hdl.pert = File.pert; end cd(localpath) end case 'opensys' fm_set('opensys',datafile,datapath) Settings.init = 0; case 'savesys' fm_set('savesys') case 'log' fm_text(1) case 'pfrep' fm_report case 'eigrep' fm_eigen('report') case 'pf' % solve power flow if isempty(File.data) fm_disp('Set a data file before running Power Flow.',2) return end if clpsat.readfile || Settings.init == 0 fm_inilf filedata = [File.data,' ']; filedata = strrep(filedata,'@ ',''); if ~isempty(findstr(filedata,'(mdl)')) && clpsat.refreshsim filedata1 = File.data(1:end-5); open_sys = find_system('type','block_diagram'); OpenModel = sum(strcmp(open_sys,filedata1)); if OpenModel if strcmp(get_param(filedata1,'Dirty'),'on') || ... str2num(get_param(filedata1,'ModelVersion')) > Settings.mv check = sim2psat; if ~check, return, end end end end cd(Path.data) filedata = deblank(strrep(filedata,'(mdl)','_mdl')); a = exist(filedata); clear(filedata) if a == 2, b = dir([filedata,'.m']); lasterr(''); %if ~strcmp(File.modify,b.date) try fm_disp('Load data from file...') eval(filedata); File.modify = b.date; catch fm_disp(lasterr), fm_disp(['Something wrong with the data file "',filedata,'"']), return end %end else fm_disp(['File "',filedata,'" not found or not an m-file'],2) end cd(Path.local) Settings.init = 0; end if Settings.init fm_restore if Settings.conv, fm_base, end Line = build_y_line(Line); fm_wcall; fm_dynlf; end filedata = deblank(strrep(File.data,'(mdl)','_mdl')); if Settings.static % do not use dynamic components for i = 1:Comp.n comp_name = [Comp.names{i},'.con']; comp_con = eval(['~isempty(',comp_name,')']); if comp_con && ~Comp.prop(i,6) eval([comp_name,' = [];']); end end end % the following code is needed for compatibility with older PSAT versions if isfield(Varname,'bus') if ~isempty(Varname.bus) Bus.names = Varname.bus; Varname = rmfield(Varname,'bus'); end end if exist('Mot') if isfield(Mot,'con') Ind.con = Mot.con; clear Mot end end fm_spf SNB.init = 0; LIB.init = 0; CPF.init = 0; OPF.init = 0; case 'opf' % solve optimal power flow fm_set('opf') case 'cpf' % solve continuation power flow fm_cpf('main'); case 'cpfatc' % find ATC of the current system opftype = OPF.type; OPF.type = 4; fm_atc OPF.type = opftype; case 'sensatc' opftype = OPF.type; OPF.type = 5; fm_atc OPF.type = opftype; case 'n1cont' fm_n1cont; case 'td' % solve time domain simulation fm_int case 'sssa' % solve small signal stability analyisis fm_eigen('runsssa') case 'snb' fm_snb case 'lib' fm_limit case 'pmu' fm_pmuloc; case 'pmurep' fm_pmurep; case 'gams' % solve OPF using the PSAT-GAMS interface fm_gams case 'uw' % solve CPF using the PSAT-UWPFLOW interface fm_uwpflow('init') fm_uwpflow('uwrun') case 'plot' if ~Settings.octave fm_disp('This option is supported only on GNU/Octave') return end if isempty(Varout.t) fm_disp('No data is available for plotting') return end if nargin == 2 value = varargin{1}; else value = menu('Plot variables:','States','Voltage Magnitudes', ... 'Voltage Angles','Active Powers','Reactive Powers', ... 'Generator Speeds','Generator Angles'); end switch value case 1 if ~DAE.n fm_disp('No dynamic component is loaded') return end case {2,3,4,5} if ~Bus.n fm_disp('No bus is present in the current network') return end case {6,7} if ~Syn.n fm_disp('No synchronous generator is loaded') return end end switch value case 1 idx = intersect([1:DAE.n],Varname.idx); case 2 idx0 = DAE.n+Bus.n; idx = intersect([idx0+1:idx0+Bus.n],Varname.idx); case 3 idx0 = DAE.n; idx = intersect([idx0+1:idx0+Bus.n],Varname.idx); case 4 idx0 = DAE.n+DAE.m; idx = intersect([idx0+1:idx0+Bus.n],Varname.idx); case 5 idx0 = DAE.n+DAE.m+Bus.n; idx = intersect([idx0+1:idx0+Bus.n],Varname.idx); case 6 idx = intersect(Syn.omega,Varname.idx); case 7 idx = intersect(Syn.delta,Varname.idx); end if isempty(idx) fm_disp('The selected data have not been stored.') return end n = length(idx); y = Varout.vars(:,idx); s = Varname.uvars(idx); plot(Varout.t,y(:,1),['1;',strrep(s{1},'_',' '),';']) hold on for i = 2:n FMT = [num2str(rem(i-1,6)+1),';',strrep(s{i},'_',' '),';']; plot(Varout.t,y(:,i),FMT) end xlabel(Settings.xlabel) hold off otherwise % give an error message and exit fm_disp(['"',routine,'" is an invalid routine identifier.']) return end % ---------------------------------------------------------------- function string = checksep(string) if ~strcmp(string(end),filesep) string = [string,filesep]; end
github
Sinan81/PSAT-master
fm_dump.m
.m
PSAT-master/psat-oct/psat/fm_dump.m
1,579
utf_8
e82f5e57ff859c7a2cc916e8f07ee9d9
function fm_dump % FM_DUMP dump the current data file to a file % %Author: Federico Milano %Date: 28-Nov-2008 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano fm_var filename = [fm_filenum('m'), '.m']; [fid,msg] = fopen([Path.data,filename], 'wt'); if fid == -1 fm_disp(msg) return end dump_data(fid, Bus, 'Bus') dump_data(fid, SW, 'SW') dump_data(fid, PV, 'PV') for i = 1:(length(Comp.names)-2) dump_data(fid, eval(Comp.names{i}), Comp.names{i}) end dump_data(fid, Areas, 'Areas') dump_data(fid, Regions, 'Regions') dump_name(fid, Bus.names, 'Bus') dump_name(fid, Areas.names, 'Areas') dump_name(fid, Regions.names, 'Regions') fclose(fid); fm_disp(['Data dumped to file <', filename ,'>']) function dump_data(fid, var, name) if ~var.n, return, end fprintf(fid, '%s.con = [ ...\n', name); fprintf(fid, [var.format, ';\n'], var.store.'); fprintf(fid, ' ];\n\n'); function dump_name(fid, var, name) if isempty(var), return, end n = length(var); count = fprintf(fid, [name,'.names = {... \n ']); for i = 1:n-1 names = strrep(var{i,1},char(10),' '); names = strrep(var{i,1},'''',''''''); count = fprintf(fid, ['''',names,'''; ']); if rem(i,5) == 0; count = fprintf(fid,'\n '); end end if iscell(var) names = strrep(var{n,1},char(10),' '); names = strrep(var{n,1},'''',''''''); count = fprintf(fid, ['''',names,'''};\n\n']); else names = strrep(var,char(10),' '); names = strrep(var,'''',''''''); count = fprintf(fid, ['''',names,'''};\n\n']); end
github
Sinan81/PSAT-master
fm_laprint.m
.m
PSAT-master/psat-oct/psat/fm_laprint.m
67,335
utf_8
9f22107ad64af26a59a85b5285887c81
function fm_laprint(figno,filename,varargin) %FM_LAPRINT prints a figure for inclusion in LaTeX documents. % It creates an eps-file and a tex-file. The tex-file contains the % annotation of the figure such as titles, labels and texts. The % eps-file contains the non-text part of the figure as well as the % position of the text-objects. The packages 'epsfig' and 'psfrag' are % required for the LaTeX run. A postscript driver like 'dvips' is % required for printing. % % Usage: fm_laprint % % This opens a graphical user interface window, to control the % various options. It is self-explainatory. Just try it. % % Example: Suppose you have created a MATLAB Figure. Saving the figure % with LaPrint (using default values everywhere), creates the two % files unnamed.eps and unnamed.tex. The tex-file calls the % eps-file and can be included into a LaTeX document as follows: % .. \usepackage{epsfig,psfrag} .. % .. \input{unnamed} .. % This will create a figure of width 12cm in the LaTeX document. % Its texts (labels,title, etc) are set in LaTeX and have 80% of the % font size of the surrounding text. Figure widths, text font % sizes, file names and various other issues can be freely % adjusted using the interface window. % % Alternatively, you can control the behaviour of LaPrint using various % extra input arguments. This is recommended for advanced users only. % Help on advanced usage is obtained by typing fm_laprint({'AdvancedHelp'}). % % The document 'MATLAB graphics in LaTeX documents: Some tips and % a tool' contains more help on LaPrint and various examples. % It can be obtained along with the most recent version of LaPrint % from http://www.uni-kassel.de/~linne/matlab/. % known problems and limitations, things to do, ... % -- The matlab functions copyobj and plotedit have bugs. % If this is a problem, use option 'nofigcopy'. % -- multi-line text is not supported % -- cm is the only unit used (inches not supported) % -- a small preview would be nice % (c) Arno Linnemann. All rights reserved. % The author of this program assumes no responsibility for any errors % or omissions. In no event shall he be liable for damages arising out of % any use of the software. Redistribution of the unchanged file is allowed. % Distribution of changed versions is allowed provided the file is renamed % and the source and authorship of the original version is acknowledged in % the modified file. % Please report bugs, suggestions and comments to: % Arno Linnemann % Control and Systems Theory % Department of Electrical Engineering % University of Kassel % 34109 Kassel % Germany % mailto:[email protected] % http://www.uni-kassel.de/~linne/ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% Initialize %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% global LAPRINTOPT global LAPRINTHAN global Theme Fig laprintident = '2.03 (19.1.2000)'; vers=version; vers=eval(vers(1:3)); if vers < 5.0 fm_disp('LaPrint Error: Matlab 5.0 or above is required.',2) return end % no output if nargout fm_disp('La Print Error: No output argument is required.',2) return end if nargin==0 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% GUI %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ishandle(Fig.laprint), return, end %--------------------------------- % default values %--------------------------------- LAPRINTOPT.figno=gcf; LAPRINTOPT.filename='unnamed'; LAPRINTOPT.verbose=0; LAPRINTOPT.asonscreen=0; LAPRINTOPT.keepticklabels=0; LAPRINTOPT.mathticklabels=0; LAPRINTOPT.keepfontprops=0; LAPRINTOPT.extrapicture=1; LAPRINTOPT.loose=0; LAPRINTOPT.nofigcopy=0; LAPRINTOPT.nohead=0; LAPRINTOPT.noscalefonts=0; LAPRINTOPT.caption=0; LAPRINTOPT.commenttext=['Figure No. ' int2str(LAPRINTOPT.figno)]; LAPRINTOPT.width=12; LAPRINTOPT.factor=0.8; LAPRINTOPT.viewfile=0; LAPRINTOPT.viewfilename='unnamed_'; LAPRINTOPT.HELP=1; %--------------------------------- % open window %--------------------------------- hf = figure; Fig.laprint = hf; clf reset; set(hf,'NumberTitle','off') %set(hf,'CreateFcn','Fig.laprint = hf;') set(hf,'FileName','fm_laprint') set(hf,'DeleteFcn','fm_laprint({''quit''})') set(hf,'MenuBar','none') set(hf,'Color',Theme.color01) set(hf,'Name','LaPrint (LaTeX Print)') set(hf,'Units','points') set(hf,'Resize','off') h=uicontrol(hf); set(h,'Units','points') fsize=get(h,'Fontsize'); delete(h) posf=get(hf,'Position'); figheight=30*fsize; posf= [ posf(1) posf(2)+posf(4)-figheight ... 31*fsize figheight]; set(hf,'Position',posf) curh=figheight-0*fsize; %--------------------------------- % LaTeX logo %--------------------------------- h1 = axes('Parent',hf, ... 'Units','points', ... 'Box','on', ... 'CameraUpVector',[0 1 0], ... 'CameraUpVectorMode','manual', ... 'Color',Theme.color04, ... 'HandleVisibility','on', ... 'HitTest','off', ... 'Layer','top', ... 'Position',[23*fsize 20.5*fsize 7*fsize 7*fsize], ... 'Tag','Axes1', ... 'XColor',Theme.color03, ... 'XLim',[0.5 128.5], ... 'XLimMode','manual', ... 'XTickLabelMode','manual', ... 'XTickMode','manual', ... 'YColor',Theme.color03, ... 'YDir','reverse', ... 'YLim',[0.5 128.5], ... 'YLimMode','manual', ... 'YTickLabelMode','manual', ... 'YTickMode','manual', ... 'ZColor',[0 0 0]); h2 = image('Parent',h1, ... 'CData',fm_mat('misc_laprint'), ... 'Tag','Axes1Image1', ... 'XData',[1 128], ... 'YData',[1 128]); %--------------------------------- % figure no. %--------------------------------- loch=1.7*fsize; curh=curh-loch-1*fsize; h = uicontrol; set(h,'Parent',hf) set(h,'BackgroundColor',Theme.color01) set(h,'style','text') set(h,'Units','points') set(h,'Position',[1*fsize curh 8*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'string','Figure No.:') h = uicontrol; set(h,'Parent',hf) set(h,'Parent',hf) set(h,'style','edit') set(h,'FontName',Theme.font01) set(h,'BackgroundColor',Theme.color04) set(h,'ForegroundColor',Theme.color05) set(h,'Units','points') set(h,'Position',[10*fsize curh 3*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'String',int2str(LAPRINTOPT.figno)) set(h,'Callback','fm_laprint({''figno''});') LAPRINTHAN.figno=h; %--------------------------------- % filename %--------------------------------- loch=1.7*fsize; curh=curh-loch; h = uicontrol; set(h,'Parent',hf) set(h,'style','text') set(h,'BackgroundColor',Theme.color01) set(h,'Units','points') set(h,'Position',[1*fsize curh 8*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'string','filename (base):') h = uicontrol; set(h,'Parent',hf) set(h,'Parent',hf) set(h,'style','edit') set(h,'FontName',Theme.font01) set(h,'BackgroundColor',Theme.color04) set(h,'ForegroundColor',Theme.color05) set(h,'Units','points') set(h,'Position',[10*fsize curh 12*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'String',LAPRINTOPT.filename) set(h,'Callback','fm_laprint({''filename''});') LAPRINTHAN.filename=h; %--------------------------------- % width %--------------------------------- loch=1.7*fsize; curh=curh-loch-1*fsize; h = uicontrol; set(h,'Parent',hf) set(h,'style','text') set(h,'BackgroundColor',Theme.color01) set(h,'Units','points') set(h,'Position',[1*fsize curh 17*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'string','Width in LaTeX document [cm]:') h = uicontrol; set(h,'Parent',hf) set(h,'Parent',hf) set(h,'style','edit') set(h,'FontName',Theme.font01) set(h,'BackgroundColor',Theme.color04) set(h,'ForegroundColor',Theme.color05) set(h,'Units','points') set(h,'Position',[19*fsize curh 3*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'String',num2str(LAPRINTOPT.width)) set(h,'Callback','fm_laprint({''width''});') LAPRINTHAN.width=h; %--------------------------------- % factor %--------------------------------- loch=1.7*fsize; curh=curh-loch; h = uicontrol; set(h,'Parent',hf) set(h,'style','text') set(h,'BackgroundColor',Theme.color01) set(h,'Units','points') set(h,'Position',[1*fsize curh 17*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'string','Factor to scale fonts and eps figure:') h = uicontrol; set(h,'Parent',hf) set(h,'Parent',hf) set(h,'style','edit') set(h,'FontName',Theme.font01) set(h,'BackgroundColor',Theme.color04) set(h,'ForegroundColor',Theme.color05) set(h,'Units','points') set(h,'Position',[19*fsize curh 3*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'String',num2str(LAPRINTOPT.factor)) set(h,'Callback','fm_laprint({''factor''});') LAPRINTHAN.factor=h; %--------------------------------- % show sizes %--------------------------------- loch=1.7*fsize; curh=curh-loch; h = uicontrol; set(h,'Parent',hf) set(h,'style','text') set(h,'BackgroundColor',Theme.color01) set(h,'Units','points') set(h,'Position',[1*fsize curh 22*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'string',[ 'latex figure size: ' ]) LAPRINTHAN.texsize=h; loch=1.7*fsize; curh=curh-loch; h = uicontrol; set(h,'Parent',hf) set(h,'style','text') set(h,'BackgroundColor',Theme.color01) set(h,'Units','points') set(h,'Position',[1*fsize curh 22*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'string',[ 'postscript figure size: ' ]) LAPRINTHAN.epssize=h; %--------------------------------- % comment/caption text %--------------------------------- loch=1.7*fsize; curh=curh-loch-fsize; h = uicontrol; set(h,'Parent',hf) set(h,'style','text') set(h,'BackgroundColor',Theme.color01) set(h,'Units','points') set(h,'Position',[1*fsize curh 12*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'string','Comment/Caption text:') h = uicontrol; set(h,'Parent',hf) set(h,'style','edit') set(h,'FontName',Theme.font01) set(h,'BackgroundColor',Theme.color04) set(h,'ForegroundColor',Theme.color05) set(h,'Units','points') set(h,'Position',[14*fsize curh 16*fsize loch]) set(h,'HorizontalAlignment','left') set(h,'String',LAPRINTOPT.commenttext) set(h,'Callback','fm_laprint({''commenttext''});') LAPRINTHAN.commenttext=h; %--------------------------------- % text %--------------------------------- loch=10*fsize; curh=curh-loch-fsize; h = uicontrol; set(h,'Parent',hf) set(h,'style','text') set(h,'FontName',Theme.font01) set(h,'BackgroundColor',Theme.color04) set(h,'ForegroundColor',Theme.color05) set(h,'Units','points') set(h,'Position',[1*fsize curh 29*fsize loch]) set(h,'HorizontalAlignment','left') %set(h,'BackgroundColor',[1 1 1]) LAPRINTHAN.helptext=h; if (isempty(get(LAPRINTOPT.figno,'children'))) txt=['Warning: Figure ' int2str(LAPRINTOPT.figno) ... ' is empty. There is nothing to do yet.' ]; else txt=''; end showtext({['This is LaPrint, Version ', laprintident, ... ', by Arno Linnemann. ', ... 'The present version was slightly modified by ', ... 'Federico Milano (17.12.2003) and can be used only from within ', ... 'PSAT. To get started, press ''Help'' below.', txt]}) showsizes; %--------------------------------- % save, quit, help %--------------------------------- loch=2*fsize; curh=curh-loch-fsize; h=uicontrol; set(h,'Parent',hf) set(h,'Style','pushbutton') set(h,'BackgroundColor',Theme.color01) set(h,'Units','Points') set(h,'Position',[23*fsize curh 5*fsize loch]) set(h,'HorizontalAlignment','center') set(h,'String','Quit') set(h,'Callback','fm_laprint({''quit''});') h=uicontrol; set(h,'Parent',hf) set(h,'Style','pushbutton') set(h,'BackgroundColor',Theme.color01) set(h,'Units','Points') set(h,'Position',[13*fsize curh 5*fsize loch]) set(h,'HorizontalAlignment','center') set(h,'String','Help') set(h,'Callback','fm_laprint({''help''});') h=uicontrol; set(h,'Parent',hf) set(h,'BackgroundColor',Theme.color03) set(h,'FontWeight','bold') set(h,'ForegroundColor',Theme.color09) set(h,'Style','pushbutton') set(h,'Units','Points') set(h,'Position',[3*fsize curh 5*fsize loch]) set(h,'HorizontalAlignment','center') set(h,'String','Export') set(h,'Callback','fm_laprint({''save''});') %--------------------------------- % options uimenue %--------------------------------- % Menu File h1 = uimenu('Parent',hf, ... 'Label','File', ... 'Tag','MenuFile'); h2 = uimenu('Parent',h1, ... 'Label', 'Export figure', ... 'Callback','fm_laprint({''save''});', ... 'Accelerator','s', ... 'Tag','file_save'); h2 = uimenu('Parent',h1, ... 'Label', 'Quit LaPrint', ... 'Callback','fm_laprint({''quit''});', ... 'Accelerator','x', ... 'Separator','on', ... 'Tag','file_quit'); hm=uimenu('label','Options'); LAPRINTHAN.asonscreen=uimenu(hm,... 'label','as on screen',... 'callback','fm_laprint({''asonscreen''})',... 'checked','off'); LAPRINTHAN.keepticklabels=uimenu(hm,... 'label','keep tick labels',... 'callback','fm_laprint({''keepticklabels''})',... 'checked','off'); LAPRINTHAN.mathticklabels=uimenu(hm,... 'label','math tick labels',... 'callback','fm_laprint({''mathticklabels''})',... 'checked','off'); LAPRINTHAN.keepfontprops=uimenu(hm,... 'label','keep font props',... 'callback','fm_laprint({''keepfontprops''})',... 'checked','off'); LAPRINTHAN.extrapicture=uimenu(hm,... 'label','extra picture',... 'callback','fm_laprint({''extrapicture''})',... 'checked','on'); LAPRINTHAN.loose=uimenu(hm,... 'label','print loose',... 'callback','fm_laprint({''loose''})',... 'checked','off'); LAPRINTHAN.nofigcopy=uimenu(hm,... 'label','figure copy',... 'callback','fm_laprint({''nofigcopy''})',... 'checked','on'); LAPRINTHAN.nohead=uimenu(hm,... 'label','file head',... 'callback','fm_laprint({''nohead''})',... 'checked','on'); LAPRINTHAN.noscalefonts=uimenu(hm,... 'label','scale fonts',... 'callback','fm_laprint({''noscalefonts''})',... 'checked','on'); LAPRINTHAN.caption=uimenu(hm,... 'label','caption',... 'callback','fm_laprint({''caption''})',... 'checked','off'); LAPRINTHAN.viewfile=uimenu(hm,... 'label','viewfile',... 'callback','fm_laprint({''viewfile''})',... 'checked','off'); uimenu(hm,... 'label','Defaults',... 'callback','laprint({''defaults''})',... 'separator','on'); % Menu Help h1 = uimenu('Parent',hf, ... 'Label','Help', ... 'Tag','MenuFile'); h2 = uimenu('Parent',h1, ... 'Label', 'LaPrint help', ... 'Callback','fm_laprint({''help''});', ... 'Accelerator','h', ... 'Tag','file_help'); h2 = uimenu('Parent',h1, ... 'label','About',... 'callback','fm_laprint({''whois''})'); %--------------------------------- % make hf invisible %--------------------------------- set(hf,'HandleVisibility','callback') return end % if nargin==0 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% callback calls %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isa(figno,'cell') switch lower(figno{1}) %%% figno %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'figno' global LAPRINTOPT global LAPRINTHAN LAPRINTOPT.figno=eval(get(LAPRINTHAN.figno,'string')); figure(LAPRINTOPT.figno) figure(Fig.laprint) txt=[ 'Pushing ''Export'' will save the contents of Figure No. '... int2str(LAPRINTOPT.figno) '.' ]; showtext({txt}); %%% filename %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'filename' global LAPRINTOPT global LAPRINTHAN LAPRINTOPT.filename=get(LAPRINTHAN.filename,'string'); LAPRINTOPT.viewfilename=[ LAPRINTOPT.filename '_']; [texfullnameext,texbasenameext,texbasename,texdirname] = ... getfilenames(LAPRINTOPT.filename,'tex',0); [epsfullnameext,epsbasenameext,epsbasename,epsdirname] = ... getfilenames(LAPRINTOPT.filename,'eps',0); txt0=[ 'Pushing ''save'' will create the following files:' ]; txt1=[ texfullnameext ' (LaTeX file)' ]; txt2=[ epsfullnameext ' (Postscript file)']; if exist(texfullnameext,'file') txt5=[ 'Warning: LaTeX file exists an will be overwritten.']; else txt5=''; end if exist(epsfullnameext,'file') txt6=[ 'Warning: Postscript file exists an will be overwritten.']; else txt6=''; end if LAPRINTOPT.viewfile [viewfullnameext,viewbasenameext,viewbasename,viewdirname] = ... getfilenames(LAPRINTOPT.viewfilename,'tex',0); txt3=[ viewfullnameext ' (View file)']; if exist(viewfullnameext,'file') txt7=[ 'Warning: View file exists an will be overwritten.']; else txt7=''; end else txt3=''; txt7=''; end showtext({txt0,txt1,txt2,txt3,txt5,txt6,txt7}); %%% width %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'width' global LAPRINTOPT global LAPRINTHAN LAPRINTOPT.width=eval(get(LAPRINTHAN.width,'string')); txt1=[ 'The width of the figure in the LaTeX document is set to '... int2str(LAPRINTOPT.width) ' cm. Its height is determined '... 'by the aspect ratio of the figure on screen '... '(i.e. the figure ''position'' property).']; showtext({txt1}); showsizes; %%% factor %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'factor' global LAPRINTOPT global LAPRINTHAN LAPRINTOPT.factor=eval(get(LAPRINTHAN.factor,'string')); txt1=[ 'The factor to scale the fonts and the eps figure is set to '... num2str(LAPRINTOPT.factor) '.']; if LAPRINTOPT.factor < 1 txt2=[ 'Thus the (bounding box of the) eps figure is ' ... 'larger than the figure in the LaTeX document ' ... 'and the text fonts of the figure are ' ... 'by the factor ' num2str(LAPRINTOPT.factor) ' smaller ' ... 'than the fonts of the surrounding text.']; elseif LAPRINTOPT.factor > 1 txt2=[ 'Thus the (bounding box of the) eps figure ' ... 'is smaller than the figure in the LaTeX document. ' ... 'Especially, the text fonts of the figure are ' ... 'by the factor ' num2str(LAPRINTOPT.factor) ' larger ' ... 'than the fonts of the surrounding text.']; else txt2=[ 'Thus the eps figure is displayed 1:1.'... 'Especially, the text fonts of the figure are of ' ... 'the same size as the fonts of the surrounding text.']; end showtext({txt1,txt2}); showsizes; case 'commenttext' global LAPRINTOPT global LAPRINTHAN LAPRINTOPT.commenttext=get(LAPRINTHAN.commenttext,'string'); txt=[ 'The comment text is displayed in the commenting header '... 'of the tex file. This is for bookkeeping only.' ... 'If the option ''caption'' is set to ''on'', then '... 'this text is also displayed in the caption of the figure.']; showtext({txt}); %%% options %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'asonscreen' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', the ticks, ticklabels '... 'and lims are printed ''as on screen''. Note that the '... 'aspect ratio of the printed figure is always equal '... 'to the aspect ratio on screen.']; if LAPRINTOPT.asonscreen==1 LAPRINTOPT.asonscreen=0; set(LAPRINTHAN.asonscreen,'check','off') txt2= 'Current setting is: off'; else LAPRINTOPT.asonscreen=1; set(LAPRINTHAN.asonscreen,'check','on') txt2='Current setting is: on'; end showtext({txt1, txt2}); case 'keepticklabels' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', the tick labels '... 'are kept within the eps-file and are therefore not set '... 'in LaTeX. This option is useful for some rotated 3D plots.']; if LAPRINTOPT.keepticklabels==1 LAPRINTOPT.keepticklabels=0; set(LAPRINTHAN.keepticklabels,'check','off') txt2= 'Current setting is: off'; else LAPRINTOPT.keepticklabels=1; set(LAPRINTHAN.keepticklabels,'check','on') txt2='Current setting is: on'; end showtext({txt1, txt2}); case 'mathticklabels' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', the tick labels '... 'are set in LaTeX math mode.']; if LAPRINTOPT.mathticklabels==1 LAPRINTOPT.mathticklabels=0; set(LAPRINTHAN.mathticklabels,'check','off') txt2= 'Current setting is: off'; else LAPRINTOPT.mathticklabels=1; set(LAPRINTHAN.mathticklabels,'check','on') txt2='Current setting is: on'; end showtext({txt1, txt2}); case 'keepfontprops' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', LaPrint tries to ',... 'translate the MATLAB font properties (size, width, ',... 'angle) into similar LaTeX font properties. Set to ''off'', ',... 'LaPrint does not introduce any LaTeX font selection commands.']; if LAPRINTOPT.keepfontprops==1 LAPRINTOPT.keepfontprops=0; set(LAPRINTHAN.keepfontprops,'check','off') txt2= 'Current setting is: off'; else LAPRINTOPT.keepfontprops=1; set(LAPRINTHAN.keepfontprops,'check','on') txt2='Current setting is: on'; end showtext({txt1, txt2}); case 'loose' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', LaPrint uses the ',... '''-loose'' option in the Matlab print command. ']; if LAPRINTOPT.loose==1 LAPRINTOPT.loose=0; set(LAPRINTHAN.loose,'check','off') txt2= 'Current setting is: off'; else LAPRINTOPT.loose=1; set(LAPRINTHAN.loose,'check','on') txt2='Current setting is: on'; end showtext({txt1, txt2}); case 'extrapicture' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', LaPrint adds an ',... 'extra picture environment to each axis correponding to a '... '2D plot. The picture ',... 'is empty, but alows to place LaTeX objects in arbitrary ',... 'positions by editing the tex file. ']; if LAPRINTOPT.extrapicture==1 LAPRINTOPT.extrapicture=0; set(LAPRINTHAN.extrapicture,'check','off') txt2= 'Current setting is: off'; else LAPRINTOPT.extrapicture=1; set(LAPRINTHAN.extrapicture,'check','on') txt2='Current setting is: on'; end showtext({txt1, txt2}); case 'nofigcopy' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', LaPrint creates a temporary ',... 'figure to introduce the tags. If set to ''off'', it directly ',... 'modifies the original figure. ' ... 'There are some bugs in the Matlab copyobj '... 'command. If you encounter these cases, set this '... 'option to ''off''.']; if LAPRINTOPT.nofigcopy==1 LAPRINTOPT.nofigcopy=0; set(LAPRINTHAN.nofigcopy,'check','on') txt2= 'Current setting is: on'; else LAPRINTOPT.nofigcopy=1; set(LAPRINTHAN.nofigcopy,'check','off') txt2='Current setting is: off'; end showtext({txt1, txt2}); case 'nohead' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', LaPrint ',... 'adds a commenting head to the tex-file. To save disk '... 'space, out can turn this option ''off''.']; if LAPRINTOPT.nohead==1 LAPRINTOPT.nohead=0; set(LAPRINTHAN.nohead,'check','on') txt2= 'Current setting is: on'; else LAPRINTOPT.nohead=1; set(LAPRINTHAN.nohead,'check','off') txt2='Current setting is: off'; end showtext({txt1, txt2}); case 'noscalefonts' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', LaPrint scales the ',... 'fonts with the figure. With this option set to '... '''off'', the font size in the figure is equal to the '... 'size of the surrounding text.']; if LAPRINTOPT.noscalefonts==1 LAPRINTOPT.noscalefonts=0; set(LAPRINTHAN.noscalefonts,'check','on') txt2= 'Current setting is: on'; else LAPRINTOPT.noscalefonts=1; set(LAPRINTHAN.noscalefonts,'check','off') txt2='Current setting is: off'; end showtext({txt1, txt2}); case 'caption' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', LaPrint adds ',... '\caption{' LAPRINTOPT.commenttext ,... '} and \label{fig:' LAPRINTOPT.filename '} entries ',... 'to the tex-file.']; if LAPRINTOPT.caption==1 LAPRINTOPT.caption=0; set(LAPRINTHAN.caption,'check','off') txt2= 'Current setting is: off'; else LAPRINTOPT.caption=1; set(LAPRINTHAN.caption,'check','on') txt2='Current setting is: on'; end showtext({txt1, txt2}); case 'viewfile' global LAPRINTOPT global LAPRINTHAN txt1=[ 'With this option set to ''on'', LaPrint creates an ',... 'additional file ' LAPRINTOPT.viewfilename ... '.tex containing a LaTeX document ',... 'which calls the tex-file.']; if LAPRINTOPT.viewfile==1 LAPRINTOPT.viewfile=0; set(LAPRINTHAN.viewfile,'check','off') txt2= 'Current setting is: off'; else LAPRINTOPT.viewfile=1; set(LAPRINTHAN.viewfile,'check','on') txt2='Current setting is: on'; end showtext({txt1, txt2}); case 'defaults' global LAPRINTOPT global LAPRINTHAN LAPRINTOPT.asonscreen=0; LAPRINTOPT.keepticklabels=0; LAPRINTOPT.mathticklabels=0; LAPRINTOPT.keepfontprops=0; LAPRINTOPT.extrapicture=1; LAPRINTOPT.loose=0; LAPRINTOPT.nofigcopy=0; LAPRINTOPT.nohead=0; LAPRINTOPT.noscalefonts=0; LAPRINTOPT.caption=0; LAPRINTOPT.viewfile=0; set(LAPRINTHAN.asonscreen,'check','off') set(LAPRINTHAN.keepticklabels,'check','off') set(LAPRINTHAN.mathticklabels,'check','off') set(LAPRINTHAN.keepfontprops,'check','off') set(LAPRINTHAN.extrapicture,'check','off') set(LAPRINTHAN.loose,'check','off') set(LAPRINTHAN.nofigcopy,'check','on') set(LAPRINTHAN.nohead,'check','on') set(LAPRINTHAN.noscalefonts,'check','on') set(LAPRINTHAN.caption,'check','off') set(LAPRINTHAN.viewfile,'check','off') showtext({[ 'All options availabe through the menu bar '... 'are set to their default values.']}); case 'whois' showtext({'To blame for LaPrint:',... 'Arno Linnemann','Control and Systems Theory',... 'Department of Electrical Engineering',... 'University of Kassel',... '34109 Kassel | mailto:[email protected]'... 'Germany | http://www.uni-kassel.de/~linne/'}) %%% help %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'help' global LAPRINTOPT global LAPRINTHAN txt0='...Press ''Help'' again to continue....'; if LAPRINTOPT.HELP==1 txt=[ 'LAPRINT prints a figure for inclusion in LaTeX documents. ',... 'It creates an eps-file and a tex-file. The tex-file contains the ',... 'annotation of the figure such as titles, labels and texts. The ',... 'eps-file contains the non-text part of the figure as well as the ',... 'position of the text-objects.']; txt={txt,txt0}; elseif LAPRINTOPT.HELP==2 txt1= [ 'The packages epsfig and psfrag are ',... 'required for the LaTeX run. A postscript driver like dvips is ',... 'required for printing. ' ]; txt2=' '; txt3= ['It is recommended to switch off the Matlab TeX ' ... 'interpreter before using LaPrint:']; txt4= ' >> set(0,''DefaultTextInterpreter'',''none'')'; txt={txt1,txt2,txt3,txt4,txt0}; elseif LAPRINTOPT.HELP==3 txt1= [ 'EXAMPLE: Suppose you have created a MATLAB Figure.']; txt2= [ 'Saving the figure with LaPrint (using default '... 'values everywhere), creates the two files unnamed.eps '... 'and unnamed.tex. The tex-file calls the eps-file '... 'and can be included into a LaTeX document as follows:']; txt={txt1,txt2,txt0}; elseif LAPRINTOPT.HELP==4 txt1=' ..'; txt2=' \usepackage{epsfig,psfrag}'; txt3=' ..'; txt4=' \input{unnamed}'; txt5=' ..'; txt={txt1,txt2,txt3,txt4,txt5,txt0}; elseif LAPRINTOPT.HELP==5 txt1=[ 'This will create a figure of width 12cm in the LaTeX '... 'document. Its texts (labels,title, etc) are set in '... 'LaTeX and have 80% of the font size of the '... 'surrounding text.']; txt={txt1,txt0}; elseif LAPRINTOPT.HELP==6 txt1=[ 'The LaTeX figure width, the scaling factor and the '... 'file names can be adjusted using '... 'this interface window.']; txt2=[ 'More options are available through the menu bar above. '... 'Associated help is displayed as you change the options.']; txt={txt1,txt2,txt0}; elseif LAPRINTOPT.HELP==7 txt1=[ 'The document ''MATLAB graphics in LaTeX documents: '... 'Some tips and a tool'' contains more help on LaPrint '... 'and various examples. It can be obtained along '... 'with the most recent version of LaPrint from '... 'http://www.uni-kassel.de/~linne/matlab/.']; txt2=[ 'Please report bugs, suggestions '... 'and comments to [email protected].']; txt={txt1,txt2,txt0}; else txt={'Have fun!'}; LAPRINTOPT.HELP=0; end LAPRINTOPT.HELP=LAPRINTOPT.HELP+1; showtext(txt); %%% quit %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'quit' LAPRINTHAN=[]; LAPRINTOPT=[]; delete(Fig.laprint) Fig.laprint = -1; %%% Advanced Help %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'advancedhelp' disp(' ') disp('Advanced usage: fm_laprint(figno,filename,opt1,opt2,..)') disp('where ') disp(' figno : integer, figure to be printed') disp(' filename : string, basename of files to be created') disp(' opt1,.. : strings, describing optional inputs as follows') disp('') disp(' ''width=xx'' : xx is the width of the figure in the tex') disp(' file (in cm).') disp(' ''factor=xx'' : xx is the factor by which the figure in ') disp(' the LaTeX document is smaller than the figure') disp(' in the postscript file.') disp(' A non-positive number for xx lets the factor') disp(' be computed such that the figure in the') disp(' postscript file has the same size as the') disp(' figure on screen.') disp(' ''asonscreen'' : prints a graphics ''as on screen'',') disp(' retaining ticks, ticklabels and lims.') disp(' ''verbose'' : verbose mode; asks before overwriting') disp(' files and issues some more messages.') disp(' ''keepticklabels'': keeps the tick labels within the eps-file') disp(' ''mathticklabels'': tick labels are set in LaTeX math mode') disp(' ''keepfontprops'' : tries to translate the MATLAB font') disp(' properties (size, width, angle) into') disp(' similar LaTeX font properties.') disp(' ''noscalefonts'' : does not scale the fonts with the figure.') disp(' ''noextrapicture'': does not add extra picture environments.') disp(' ''loose'' : uses ''-loose'' in the Matlab print command.') disp(' ''nofigcopy'' : directly modifies the figure figno.') disp(' ''nohead'' : does not place a commenting head in ') disp(' the tex-file. ') disp(' ''caption=xx'' : adds \caption{xx} and \label{fig:filename}') disp(' entries to the tex-file.') disp(' ''comment=xx'' : places the comment xx into the header') disp(' of the tex-file') disp(' ''viewfile=xx'' : creates an additional file xx.tex') disp(' containing a LaTeX document which calls') disp(' the tex-file.') disp(' ') %%% save %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'save' global LAPRINTOPT global LAPRINTHAN global Fig psatfigs = fieldnames(Fig); for hhh = 1:length(psatfigs) psatfigno = getfield(Fig,psatfigs{hhh}); if psatfigno == LAPRINTOPT.figno fm_choice('Exporting PSAT GUIs using LaPrint is not allowed.',2) return end end lapcmd = [ 'fm_laprint(' int2str(LAPRINTOPT.figno) ... ', ''' LAPRINTOPT.filename ''''... ', ''width=' num2str(LAPRINTOPT.width) '''' ... ', ''factor=' num2str(LAPRINTOPT.factor) '''' ]; if LAPRINTOPT.verbose lapcmd = [ lapcmd ,', ''verbose''' ]; end if LAPRINTOPT.asonscreen lapcmd = [ lapcmd ,', ''asonscreen''' ]; end if LAPRINTOPT.keepticklabels lapcmd = [ lapcmd ,', ''keepticklabels''' ]; end if LAPRINTOPT.mathticklabels lapcmd = [ lapcmd ,', ''mathticklabels''' ]; end if LAPRINTOPT.keepfontprops lapcmd = [ lapcmd ,', ''keepfontprops''' ]; end if ~LAPRINTOPT.extrapicture lapcmd = [ lapcmd ,', ''noextrapicture''' ]; end if LAPRINTOPT.loose lapcmd = [ lapcmd ,', ''loose''' ]; end if LAPRINTOPT.nofigcopy lapcmd = [ lapcmd ,', ''nofigcopy''' ]; end if LAPRINTOPT.nohead lapcmd = [ lapcmd ,', ''nohead''' ]; end if LAPRINTOPT.noscalefonts lapcmd = [ lapcmd ,', ''noscalefonts''' ]; end if LAPRINTOPT.caption lapcmd = [ lapcmd ,', ''caption=' LAPRINTOPT.commenttext '''' ]; end if length(LAPRINTOPT.commenttext) lapcmd = [ lapcmd ,', ''comment=' LAPRINTOPT.commenttext '''' ]; end if LAPRINTOPT.viewfile lapcmd = [ lapcmd ,', ''viewfile=' LAPRINTOPT.viewfilename '''' ]; end lapcmd = [ lapcmd ')']; showtext({'Saving using:', lapcmd }); eval(lapcmd) otherwise fm_disp('LaPrint Error: unknown callback option!',2) end return end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% PART 1 of advanced usage: %%%% Check inputs and initialize %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % called directly or via gui? directcall=1; iswarning=0; if exist('LAPRINTHAN','var') if ~isempty(LAPRINTHAN) directcall=0; end end if nargin==1 if ~isa(figno,'char') filename='unnamed'; else filename=figno; figno=gcf; end end if ~isa(figno,'double') fm_disp(['LaPrint Error: "',num2str(figno),'" is not a figure handle.'],2) return end if ~any(get(0,'children')==figno) fm_disp(['LaPrint Error: "',num2str(figno),'" is not a figure handle.'],2) return end if ~isa(filename,'char') filename fm_disp(['La Print Error: file name is not valid.'],2) return end % default values furtheroptions=''; verbose=0; asonscreen=0; keepticklabels=0; mathticklabels=0; keepfontprops=0; extrapicture=1; loose=0; nofigcopy=0; nohead=0; noscalefonts=0; caption=0; commenttext=''; captiontext=''; width=12; factor=0.8; viewfile=0; % read and check options if nargin>2 for i=1:nargin-2 if ~isa(varargin{i},'char') fm_disp('LaPrint Error: Options must be character arrays.',2) return end oriopt=varargin{i}(:)'; opt=[ lower(strrep(oriopt,' ','')) ' ' ]; if strcmp(opt(1:7),'verbose') verbose=1; furtheroptions=[ furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:10),'asonscreen') asonscreen=1; furtheroptions=[furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:14),'keepticklabels') keepticklabels=1; furtheroptions=[furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:14),'mathticklabels') mathticklabels=1; furtheroptions=[furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:13),'keepfontprops') keepfontprops=1; furtheroptions=[furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:14),'noextrapicture') extrapicture=0; furtheroptions=[furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:5),'loose') loose=1; furtheroptions=[furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:9),'nofigcopy') nofigcopy=1; furtheroptions=[furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:12),'noscalefonts') noscalefonts=1; furtheroptions=[furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:6),'nohead') nohead=1; furtheroptions=[furtheroptions ' / ' deblank(opt) ]; elseif strcmp(opt(1:7),'caption') caption=1; eqpos=findstr(oriopt,'='); if isempty(eqpos) furtheroptions=[furtheroptions ' / ' deblank(opt) ]; captiontext=[]; else furtheroptions=[furtheroptions ' / ' oriopt ]; captiontext=oriopt(eqpos+1:length(oriopt)); end elseif strcmp(opt(1:8),'comment=') eqpos=findstr(oriopt,'='); furtheroptions=[furtheroptions ' / ' oriopt ]; commenttext=oriopt(eqpos(1)+1:length(oriopt)); elseif strcmp(opt(1:9),'viewfile=') viewfile=1; eqpos=findstr(oriopt,'='); furtheroptions=[furtheroptions ' / ' oriopt ]; viewfilename=oriopt(eqpos(1)+1:length(oriopt)); elseif strcmp(opt(1:6),'width=') eval([ opt ';' ]); elseif strcmp(opt(1:7),'factor=') eval([ opt ';' ]); else fm_disp(['LaPrint Error: Option ' varargin{i} ' not recognized.'],2) return end end end furtheroptions=strrep(strrep(furtheroptions,'\','\\'),'%','%%'); captiontext=strrep(strrep(captiontext,'\','\\'),'%','%%'); commenttext=strrep(strrep(commenttext,'\','\\'),'%','%%'); if verbose, fm_disp(['This is LaPrint, version ',laprintident,'.']); end if mathticklabels Do='$'; else Do=''; end % eps- and tex- filenames [epsfullnameext,epsbasenameext,epsbasename,epsdirname]= ... getfilenames(filename,'eps',verbose); [texfullnameext,texbasenameext,texbasename,texdirname]= ... getfilenames(filename,'tex',verbose); if ~strcmp(texdirname,epsdirname) fm_disp(['LaPrint Warning: eps-file and tex-file are placed in ' ... 'different directories.']) iswarning=1; end if viewfile [viewfullnameext,viewbasenameext,viewbasename,viewdirname]= ... getfilenames(viewfilename,'tex',verbose); if strcmp(texfullnameext,viewfullnameext) fm_disp(['LaPrint Error: The tex- and view-file coincide. Use ' ... 'different names.'],2) return end if ~strcmp(texdirname,viewdirname) fm_disp(['LaPrint Warning: eps-file and view-file are placed '... 'in different directories.']) iswarning=1; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% PART 2 of advanced usage: %%%% Create new figure, insert tags, and bookkeep original text %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % open new figure (if required) and set properties if ~nofigcopy figno=copyobj(figno,0); set(figno,'Numbertitle','off') set(figno,'MenuBar','none') pause(0.5) end if asonscreen xlimmodeauto=findobj(figno,'xlimmode','auto'); xtickmodeauto=findobj(figno,'xtickmode','auto'); xticklabelmodeauto=findobj(figno,'xticklabelmode','auto'); ylimmodeauto=findobj(figno,'ylimmode','auto'); ytickmodeauto=findobj(figno,'ytickmode','auto'); yticklabelmodeauto=findobj(figno,'yticklabelmode','auto'); zlimmodeauto=findobj(figno,'zlimmode','auto'); ztickmodeauto=findobj(figno,'ztickmode','auto'); zticklabelmodeauto=findobj(figno,'zticklabelmode','auto'); set(xlimmodeauto,'xlimmode','manual') set(xtickmodeauto,'xtickmode','manual') set(xticklabelmodeauto,'xticklabelmode','manual') set(ylimmodeauto,'ylimmode','manual') set(ytickmodeauto,'ytickmode','manual') set(yticklabelmodeauto,'yticklabelmode','manual') set(zlimmodeauto,'ylimmode','manual') set(ztickmodeauto,'ytickmode','manual') set(zticklabelmodeauto,'yticklabelmode','manual') end set(figno,'paperunits','centimeters'); set(figno,'units','centimeters'); %oripp=get(figno,'PaperPosition'); orip=get(figno,'Position'); if factor <= 0 factor=width/orip(3); end latexwidth=width; epswidth=latexwidth/factor; epsheight = epswidth*orip(4)/orip(3); set(figno,'PaperPosition',[1 1 epswidth epsheight ]) set(figno,'Position',[orip(1)+0.5 orip(2)-0.5 epswidth epsheight ]) set(figno,'Name',[ 'To be printed; size: ' num2str(factor,3) ... ' x (' num2str(epswidth,3) 'cm x ' num2str(epsheight,3) 'cm)' ]) asonscreen_dummy=0; if asonscreen_dummy set(xlimmodeauto,'xlimmode','auto') set(xtickmodeauto,'xtickmode','auto') set(xticklabelmodeauto,'xticklabelmode','auto') set(ylimmodeauto,'ylimmode','auto') set(ytickmodeauto,'ytickmode','auto') set(yticklabelmodeauto,'yticklabelmode','auto') set(zlimmodeauto,'ylimmode','auto') set(ztickmodeauto,'ytickmode','auto') set(zticklabelmodeauto,'yticklabelmode','auto') end % some warnings if directcall if (epswidth<13) || (epsheight<13*0.75) disp('warning: The size of the eps-figure is quite small.') disp(' The text objects might not be properly set.') disp(' Reducing ''factor'' might help.') end if latexwidth/epswidth<0.5 disp([ 'warning: The size of the eps-figure is large compared ' ... 'to the latex figure.' ]) disp(' The text size might be too small.') disp(' Increasing ''factor'' might help.') end if (orip(3)-epswidth)/orip(3) > 0.1 disp(['warning: The size of the eps-figure is much smaller '... 'than the original']) disp(' figure on screen. Matlab might save different ticks and') disp([ ' ticklabels than in the original figure. See option ' ... '''asonsceen''. ' ]) end end if verbose disp('Strike any key to continue.'); pause end % % TEXT OBJECTS: modify new figure % % find all text objects hxl=get(findobj(figno,'type','axes'),'xlabel'); hyl=get(findobj(figno,'type','axes'),'ylabel'); hzl=get(findobj(figno,'type','axes'),'zlabel'); hti=get(findobj(figno,'type','axes'),'title'); hte=findobj(figno,'type','text'); % array of all text handles htext=unique([ celltoarray(hxl) celltoarray(hyl) celltoarray(hzl) ... celltoarray(hti) celltoarray(hte)]); nt=length(htext); % generate new strings and store old ones oldstr=get(htext,'string'); newstr=cell(nt,1); basestr='str00'; for i=1:nt if isa(oldstr{i},'cell') if length(oldstr{i})>1 disp('LaPrint warning: Annotation in form of a cell is currently') disp(' not supported. Ignoring all but first component.') iswarning=1; end % To do: place a parbox here. oldstr{i}=oldstr{i}{1}; end if size(oldstr{i},1)>1 disp([ 'LaPrint warning: Annotation in form of string matrices ' ... 'is currently not supported.' ]) disp(' Ignoring all but first row.') iswarning=1; % To do: place a parbox here. oldstr{i}=oldstr{i}(1,:); end if length(oldstr{i}) oldstr{i}=strrep(strrep(oldstr{i},'\','\\'),'%','%%'); newstr{i} = overwritetail(basestr,i); else newstr{i}=''; end end % replace strings in figure for i=1:nt set(htext(i),'string',newstr{i}); %set(htext(i),'visible','on'); end % get alignments hora=get(htext,'HorizontalAlignment'); vera=get(htext,'VerticalAlignment'); align=cell(nt,1); for i=1:nt align{i}=hora{i}(1); if strcmp(vera{i},'top') align{i}=[align{i} 't']; elseif strcmp(vera{i},'cap') align{i}=[align{i} 't']; elseif strcmp(vera{i},'middle') align{i}=[align{i} 'c']; elseif strcmp(vera{i},'baseline') align{i}=[align{i} 'B']; elseif strcmp(vera{i},'bottom') align{i}=[align{i} 'b']; end end % get font properties and create commands if nt > 0 [fontsizecmd{1:nt}] = deal(''); [fontanglecmd{1:nt}] = deal(''); [fontweightcmd{1:nt}] = deal(''); end selectfontcmd=''; if keepfontprops % fontsize set(htext,'fontunits','points'); fontsize=get(htext,'fontsize'); for i=1:nt fontsizecmd{i}=[ '\\fontsize{' num2str(fontsize{i}) '}{' ... num2str(fontsize{i}*1.5) '}' ]; end % fontweight fontweight=get(htext,'fontweight'); for i=1:nt if strcmp(fontweight{i},'light') fontweightcmd{i}=[ '\\fontseries{l}\\mathversion{normal}' ]; elseif strcmp(fontweight{i},'normal') fontweightcmd{i}=[ '\\fontseries{m}\\mathversion{normal}' ]; elseif strcmp(fontweight{i},'demi') fontweightcmd{i}=[ '\\fontseries{sb}\\mathversion{bold}' ]; elseif strcmp(fontweight{i},'bold') fontweightcmd{i}=[ '\\fontseries{bx}\\mathversion{bold}' ]; else disp([ ' LaPrint warning: unknown fontweight:' fontweight{i} ]) iswarning=1; fontweightcmd{i}=[ '\\fontseries{m}\\mathversion{normal}' ]; end end % fontangle fontangle=get(htext,'fontangle'); for i=1:nt if strcmp(fontangle{i},'normal') fontanglecmd{i}=[ '\\fontshape{n}' ]; elseif strcmp(fontangle{i},'italic') fontanglecmd{i}=[ '\\fontshape{it}' ]; elseif strcmp(fontangle{i},'oblique') fontangle{i}=[ '\\fontshape{it}' ]; else disp([ ' LaPrint warning: unknown fontangle:' fontangle{i} ]) iswarning=1; fontanglecmd{i}=[ '\\fontshape{n}' ]; end end selectfontcmd= '\\selectfont '; end % % LABELS: modify new figure % if ~keepticklabels % all axes hax=celltoarray(findobj(figno,'type','axes')); na=length(hax); if directcall % try to figure out if we have 3D axes an warn issuewarning=0; for i=1:na issuewarning=max(issuewarning,is3d(hax(i))); end if issuewarning disp('LaPrint warning: There seems to be a 3D plot. The LaTeX labels are') disp(' possibly incorrect. The option ''keepticklabels'' might') disp(' help. The option ''nofigcopy'' might be wise, too.') end end % try to figure out if we linear scale with extra factor % and determine powers of 10 powers=NaN*zeros(na,3); % matrix with powers of 10 for i=1:na % all axes allxyz={ 'x', 'y', 'z' }; for ixyz=1:3 % x,y,z xyz=allxyz{ixyz}; ticklabelmode=get(hax(i),[ xyz 'ticklabelmode']); if strcmp(ticklabelmode,'auto') tick=get(hax(i),[ xyz 'tick']); ticklabel=get(hax(i),[ xyz 'ticklabel']); nticks=size(ticklabel,1); if nticks==0, powers(i,ixyz)=0; end for k=1:nticks % all ticks label=str2num(ticklabel(k,:)); if length(label)==0, powers(i,ixyz)=0; break; end if ( label==0 ) && ( abs(tick(k))>1e-10 ) powers(i,ixyz)=0; break; end if label~=0 expon=log10(tick(k)/label); rexpon=round(expon); if abs(rexpon-expon)>1e-10 powers(i,ixyz)=0; break; end if isnan(powers(i,ixyz)) powers(i,ixyz)=rexpon; else if powers(i,ixyz)~=rexpon powers(i,ixyz)=0; break; end end end end % k else % if 'auto' powers(i,ixyz)=0; end % if 'auto' end % ixyz end % i % replace all ticklabels and bookkeep nxlabel=zeros(1,na); nylabel=zeros(1,na); nzlabel=zeros(1,na); allxyz={ 'x', 'y', 'z' }; for ixyz=1:3 xyz=allxyz{ixyz}; k=1; basestr=[ xyz '00' ]; if strcmp(xyz,'y') % 'y' is not horizontally centered! basestr='v00'; end oldtl=cell(na,1); newtl=cell(na,1); nlabel=zeros(1,na); for i=1:na % set(hax(i),[ xyz 'tickmode' ],'manual') % set(hax(i),[ xyz 'ticklabelmode' ],'manual') oldtl{i}=chartocell(get(hax(i),[ xyz 'ticklabel' ])); nlabel(i)=length(oldtl{i}); newtl{i}=cell(1,nlabel(i)); for j=1:nlabel(i) newtl{i}{j} = overwritetail(basestr,k); k=k+1; oldtl{i}{j}=deblank(strrep(strrep(oldtl{i}{j},'\','\\'),'%','%%')); end set(hax(i),[ xyz 'ticklabel' ],newtl{i}); end eval([ 'old' xyz 'tl=oldtl;' ]); eval([ 'new' xyz 'tl=newtl;' ]); eval([ 'n' xyz 'label=nlabel;' ]); end % determine latex commands for font properties if keepfontprops % font size afsize=zeros(na,1); for i=1:na afsize(i)=get(hax(i),'fontsize'); end if (any(afsize ~= afsize(1) )) disp('LaPrint warning: Different font sizes for axes not supported.') disp([ ' All axses will have font size ' ... num2str(afsize(1)) '.' ] ) iswarning=1; end afsizecmd = [ '\\fontsize{' num2str(afsize(1)) '}{' ... num2str(afsize(1)*1.5) '}' ]; % font weight afweight=cell(na,1); for i=1:na afweight{i}=get(hax(i),'fontweight'); end if strcmp(afweight{1},'light') afweightcmd=[ '\\fontseries{l}\\mathversion{normal}' ]; elseif strcmp(afweight{1},'normal') afweightcmd=[ '\\fontseries{m}\\mathversion{normal}' ]; elseif strcmp(afweight{1},'demi') afweightcmd=[ '\\fontseries{sb}\\mathversion{bold}' ]; elseif strcmp(afweight{1},'bold') afweightcmd=[ '\\fontseries{bx}\\mathversion{bold}' ]; else disp([ ' LaPrint warning: unknown fontweight:' afweight{1} ]) iswarning=1; afweightcmd=[ '\\fontseries{m}\\mathversion{normal}' ]; end for i=1:na if ~strcmp(afweight{i},afweight{1}) disp(' LaPrint warning: Different font weights for axes not') disp([ ' supported. All axes will have font weight ' afweightcmd]) iswarning=1; end end % font angle afangle=cell(na,1); for i=1:na afangle{i}=get(hax(i),'fontangle'); end if strcmp(afangle{1},'normal') afanglecmd=[ '\\fontshape{n}' ]; elseif strcmp(afangle{1},'italic') afanglecmd=[ '\\fontshape{it}' ]; elseif strcmp(afangle{1},'oblique') afanglecmd=[ '\\fontshape{it}' ]; else disp([ ' LaPrint warning: unknown fontangle:' afangle{1} ]) iswarning=1; afanglecmd=[ '\\fontshape{n}' ]; end for i=1:na if ~strcmp(afangle{i},afangle{1}) disp('LaPrint warning: Different font angles for axes not supported.') disp([ ' All axes will have font angle ' afanglecmd ] ) iswarning=1; end end end end % % extra picture environment % if extrapicture unitlength=zeros(na,1); ybound=zeros(na,1); for i=1:na if ~is3d(hax(i)) xlim=get(hax(i),'xlim'); ylim=get(hax(i),'ylim'); axes(hax(i)); hori=text(ylim(1),ylim(1),[ 'origin' int2str(i) ]); set(hori,'VerticalAlignment','bottom'); set(hori,'Fontsize',2); pos=get(hax(i),'Position'); unitlength(i)=pos(3)*epswidth; ybound(i)=(pos(4)*epsheight)/(pos(3)*epswidth); else if directcall disp('LaPrint warning: Option ''extrapicture'' for 3D axes not supported.') end end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% PART 3 of advanced usage: %%%% save eps and tex files %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % save eps file % if ~loose cmd=[ 'print(''-deps'',''-f' int2str(figno) ''',''' epsfullnameext ''')' ]; else cmd=[ 'print(''-deps'',''-loose'',''-f' int2str(figno) ... ''',''' epsfullnameext ''')' ]; end if verbose disp([ 'executing: '' ' cmd ' ''' ]); end eval(cmd); % % create latex file % if verbose disp([ 'writing to: '' ' texfullnameext ' ''' ]) end fid=fopen(texfullnameext,'w'); % head if ~nohead fprintf(fid,[ '%% This file is generated by the MATLAB m-file fm_laprint.m.' ... ' It can be included\n']); fprintf(fid,[ '%% into LaTeX documents using the packages epsfig and ' ... 'psfrag. It is accompanied\n' ]); fprintf(fid, '%% by a postscript file. A sample LaTeX file is:\n'); fprintf(fid, '%% \\documentclass{article} \\usepackage{epsfig,psfrag}\n'); fprintf(fid,[ '%% \\begin{document}\\begin{figure}\\input{' ... texbasename '}\\end{figure}\\end{document}\n' ]); fprintf(fid, [ '%% See http://www.uni-kassel.de/~linne/ for recent ' ... 'versions of fm_laprint.m.\n' ]); fprintf(fid, '%%\n'); fprintf(fid,[ '%% created by: ' 'LaPrint version ' ... laprintident '\n' ]); fprintf(fid,[ '%% created on: ' datestr(now) '\n' ]); fprintf(fid,[ '%% options used: ' furtheroptions '\n' ]); fprintf(fid,[ '%% latex width: ' num2str(latexwidth) ' cm\n' ]); fprintf(fid,[ '%% factor: ' num2str(factor) '\n' ]); fprintf(fid,[ '%% eps file name: ' epsbasenameext '\n' ]); fprintf(fid,[ '%% eps bounding box: ' num2str(epswidth) ... ' cm x ' num2str(epsheight) ' cm\n' ]); fprintf(fid,[ '%% comment: ' commenttext '\n' ]); fprintf(fid,'%%\n'); else fprintf(fid,[ '%% generated by fm_laprint.m\n' ]); fprintf(fid,'%%\n'); end % go on fprintf(fid,'\\begin{psfrags}%%\n'); %fprintf(fid,'\\fontsize{10}{12}\\selectfont%%\n'); fprintf(fid,'\\psfragscanon%%\n'); % text strings numbertext=0; for i=1:nt numbertext=numbertext+length(newstr{i}); end if numbertext>0, fprintf(fid,'%%\n'); fprintf(fid,'%% text strings:\n'); for i=1:nt if length(newstr{i}) alig=strrep(align{i},'c',''); fprintf(fid,[ '\\psfrag{' newstr{i} '}[' alig '][' alig ']{' ... fontsizecmd{i} fontweightcmd{i} fontanglecmd{i} selectfontcmd ... oldstr{i} '}%%\n' ]); end end end % labels if ~keepticklabels if keepfontprops fprintf(fid,'%%\n'); fprintf(fid,'%% axes font properties:\n'); fprintf(fid,[ afsizecmd afweightcmd '%%\n' ]); fprintf(fid,[ afanglecmd '\\selectfont%%\n' ]); end nxlabel=zeros(1,na); nylabel=zeros(1,na); nzlabel=zeros(1,na); for i=1:na nxlabel(i)=length(newxtl{i}); nylabel(i)=length(newytl{i}); nzlabel(i)=length(newztl{i}); end allxyz={ 'x', 'y', 'z' }; for ixyz=1:3 xyz=allxyz{ixyz}; eval([ 'oldtl=old' xyz 'tl;' ]); eval([ 'newtl=new' xyz 'tl;' ]); eval([ 'nlabel=n' xyz 'label;' ]); if sum(nlabel) > 0 fprintf(fid,'%%\n'); fprintf(fid,[ '%% ' xyz 'ticklabels:\n']); if xyz=='x' poss='[t][t]'; else poss='[r][r]'; end for i=1:na if nlabel(i) if strcmp(get(hax(i),[ xyz 'scale']),'linear') % lin scale % all but last for j=1:nlabel(i)-1 fprintf(fid,[ '\\psfrag{' newtl{i}{j} '}' poss '{' ... Do oldtl{i}{j} Do '}%%\n' ]); end % last rexpon=powers(i,ixyz); if rexpon if xyz=='x' fprintf(fid,[ '\\psfrag{' newtl{i}{nlabel(i)} ... '}' poss '{\\shortstack{' ... Do oldtl{i}{nlabel(i)} Do '\\\\$\\times 10^{'... int2str(rexpon) '}\\ $}}%%\n' ]); else fprintf(fid,[ '\\psfrag{' newtl{i}{nlabel(i)} ... '}' poss '{' Do oldtl{i}{nlabel(i)} Do ... '\\setlength{\\unitlength}{1ex}%%\n' ... '\\begin{picture}(0,0)\\put(0.5,1.5){$\\times 10^{' ... int2str(rexpon) '}$}\\end{picture}}%%\n' ]); end else fprintf(fid,[ '\\psfrag{' newtl{i}{nlabel(i)} '}' poss '{' ... Do oldtl{i}{nlabel(i)} Do '}%%\n' ]); end else % log scale for j=1:nlabel fprintf(fid,[ '\\psfrag{' newtl{i}{j} '}' poss '{$10^{' ... oldtl{i}{j} '}$}%%\n' ]); end end end end end end end % extra picture if extrapicture fprintf(fid,'%%\n'); fprintf(fid,'%% extra picture(s):\n'); for i=1:na fprintf(fid,[ '\\psfrag{origin' int2str(i) '}[lb][lb]{' ... '\\setlength{\\unitlength}{' ... num2str(unitlength(i),'%5.5f') 'cm}%%\n' ]); fprintf(fid,[ '\\begin{picture}(1,' ... num2str(ybound(i),'%5.5f') ')%%\n' ]); %fprintf(fid,'\\put(0,0){}%% lower left corner\n'); %fprintf(fid,[ '\\put(1,' num2str(ybound(i),'%5.5f') ... % '){}%% upper right corner\n' ]); fprintf(fid,'\\end{picture}%%\n'); fprintf(fid,'}%%\n'); end end % figure fprintf(fid,'%%\n'); fprintf(fid,'%% Figure:\n'); if caption fprintf(fid,[ '\\parbox{' num2str(latexwidth) 'cm}{\\centering%%\n' ]); end if noscalefonts fprintf(fid,[ '\\epsfig{file=' epsbasenameext ',width=' ... num2str(latexwidth) 'cm}}%%\n' ]); else fprintf(fid,[ '\\resizebox{' num2str(latexwidth) 'cm}{!}' ... '{\\epsfig{file=' epsbasenameext '}}%%\n' ]); end if caption if isempty(captiontext) captiontext=[ texbasenameext ', ' epsbasenameext ]; end fprintf(fid,[ '\\caption{' captiontext '}%%\n' ]); fprintf(fid,[ '\\label{fig:' texbasename '}%%\n' ]); fprintf(fid,[ '}%%\n' ]); end fprintf(fid,'\\end{psfrags}%%\n'); fprintf(fid,'%%\n'); fprintf(fid,[ '%% End ' texbasenameext '\n' ]); fclose(fid); set(figno,'Name','Printed by LaPrint') if ~nofigcopy if verbose disp('Strike any key to continue.'); pause end close(figno) end % % create view file % if viewfile if verbose disp([ 'writing to: '' ' viewfullnameext ' ''' ]) end fid=fopen(viewfullnameext,'w'); if ~nohead fprintf(fid,[ '%% This file is generated by fm_laprint.m.\n' ]); fprintf(fid,[ '%% It calls ' texbasenameext ... ', which in turn calls ' epsbasenameext '.\n' ]); fprintf(fid,[ '%% Process this file using\n' ]); fprintf(fid,[ '%% latex ' viewbasenameext '\n' ]); fprintf(fid,[ '%% dvips -o' viewbasename '.ps ' viewbasename '.dvi' ... '\n']); fprintf(fid,[ '%% ghostview ' viewbasename '.ps&\n' ]); else fprintf(fid,[ '%% generated by fm_laprint.m\n' ]); end fprintf(fid,[ '\\documentclass{article}\n' ]); fprintf(fid,[ '\\usepackage{epsfig,psfrag,a4}\n' ]); fprintf(fid,[ '\\usepackage[latin1]{inputenc}\n' ]); if ~strcmp(epsdirname,viewdirname) %disp([ 'warning: The view-file has to be supplemented by '... % 'path information.' ]) fprintf(fid,[ '\\graphicspath{{' epsdirname '}}\n' ]); end fprintf(fid,[ '\\begin{document}\n' ]); fprintf(fid,[ '\\pagestyle{empty}\n' ]); fprintf(fid,[ '\\begin{figure}[ht]\n' ]); fprintf(fid,[ ' \\begin{center}\n' ]); if strcmp(texdirname,viewdirname) %fprintf(fid,[ ' \\fbox{\\input{' texbasenameext '}}\n' ]); fprintf(fid,[ ' \\input{' texbasenameext '}\n' ]); else %fprintf(fid,[ ' \\fbox{\\input{' texdirname texbasenameext '}}\n' ]); fprintf(fid,[ ' \\input{' texdirname texbasenameext '}\n' ]); end fprintf(fid,[ ' %% \\caption{A LaPrint figure}\n' ]); fprintf(fid,[ ' %% \\label{fig:' texbasename '}\n' ]); fprintf(fid,[ ' \\end{center}\n' ]); fprintf(fid,[ '\\end{figure}\n' ]); fprintf(fid,[ '\\vfill\n' ]); fprintf(fid,[ '\\begin{flushright}\n' ]); fprintf(fid,[ '\\tiny printed with LaPrint on ' ... datestr(now) '\\\\\n' ]); fprintf(fid,[ '\\verb+' viewdirname viewbasenameext '+\\\\\n' ]); fprintf(fid,[ '\\verb+( ' texdirname texbasenameext ' )+\\\\\n' ]); fprintf(fid,[ '\\verb+( ' epsdirname epsbasenameext ' )+\n' ]); fprintf(fid,[ '\\end{flushright}\n' ]); fprintf(fid,[ '\\end{document}\n' ]); fclose(fid); if verbose yn=input([ 'Perform LaTeX run on ' viewbasenameext '? (y/n) '],'s'); if strcmp(yn,'y') cmd=[ '!latex ' viewbasenameext ]; disp([ 'executing: '' ' cmd ' ''' ]); eval(cmd); yn=input([ 'Perform dvips run on ' viewbasename '.dvi? (y/n) '],'s'); if strcmp(yn,'y') cmd=[ '!dvips -o' viewbasename '.ps ' viewbasename '.dvi' ]; disp([ 'executing: '' ' cmd ' ''' ]); eval(cmd); yn=input([ 'Call ghostview on ' viewbasename '.ps? (y/n) '],'s'); if strcmp(yn,'y') cmd=[ '!ghostview ' viewbasename '.ps&' ]; disp([ 'executing: '' ' cmd ' ''' ]); eval(cmd); end end end end end if ~directcall && iswarning showtext({'Watch the LaPrint messages in the command window!'},'add') end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% functions used %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function showtext(txt,add) global LAPRINTHAN txt=textwrap(LAPRINTHAN.helptext,txt); if nargin==1 set(LAPRINTHAN.helptext,'string','') set(LAPRINTHAN.helptext,'string',txt) else txt0=get(LAPRINTHAN.helptext,'string'); set(LAPRINTHAN.helptext,'string','') set(LAPRINTHAN.helptext,'string',{txt0{:},txt{:}}) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function showsizes() global LAPRINTOPT global LAPRINTHAN figpos=get(LAPRINTOPT.figno,'position'); latexwidth=LAPRINTOPT.width; latexheight=latexwidth*figpos(4)/figpos(3); epswidth=latexwidth/LAPRINTOPT.factor; epsheight=latexheight/LAPRINTOPT.factor; set(LAPRINTHAN.texsize,'string',[ 'latex figure size: ' num2str(latexwidth) ... 'cm x ' num2str(latexheight) 'cm' ]) set(LAPRINTHAN.epssize,'string',[ 'postscript figure size: ' ... num2str(epswidth) ... 'cm x ' num2str(epsheight) 'cm' ]) % some warnings txt1=' '; txt2=' '; txt3=' '; if (epswidth<13) || (epsheight<13*0.75) txt1=['Warning: The size of the eps-figure is quite small. '... 'Text objects might not be properly set. ']; showtext({txt1},'add') end if LAPRINTOPT.factor<0.5 txt2=['Warning: The ''factor'' is quite small. ' ... 'The text size might be too small.']; showtext({txt2},'add') end if ((figpos(3)-epswidth)/figpos(3)>0.1) && ~LAPRINTOPT.asonscreen txt3=['Warning: The size of the eps-figure is much smaller '... 'than the figure on screen. '... 'Consider using option ''as on sceen''.' ]; showtext({txt3},'add') end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fullnameext,basenameext,basename,dirname]= getfilenames(... filename,extension,verbose); % appends an extension to a filename (as '/home/tom/tt') and determines % fullnameext: filename with extension with dirname, as '/home/tom/tt.tex' % basenameext: filename with extension without dirname, as 'tt.tex' % basename : filename without extension without dirname, as 'tt' % dirname : dirname without filename, as '/home/tom/' % In verbose mode, it asks if to overwrite or to modify. % [dirname, basename] = splitfilename(filename); fullnameext = [ dirname basename '.' extension ]; basenameext = [ basename '.' extension ]; if verbose quest = (exist(fullnameext)==2); while quest yn=input([ fullnameext ' exists. Overwrite? (y/n) '],'s'); if strcmp(yn,'y') quest=0; else filename=input( ... [ 'Please enter new filename (without extension .' ... extension '): ' ],'s'); [dirname, basename] = splitfilename(filename); fullnameext = [ dirname basename '.' extension ]; basenameext = [ basename '.' extension ]; quest = (exist(fullnameext)==2); end end end if ( exist(dirname)~=7 && ~strcmp(dirname,[ '.' filesep ]) ... && ~strcmp(dirname,filesep) ) fm_disp(['LaPrint Error: Directory ',dirname,' does not exist.'],2) return end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [dirname,basename]=splitfilename(filename); % splits filename into dir and base slashpos=findstr(filename,filesep); nslash=length(slashpos); nfilename=length(filename); if nslash dirname = filename(1:slashpos(nslash)); basename = filename(slashpos(nslash)+1:nfilename); else dirname = pwd; nn=length(dirname); if ~strcmp(dirname(nn),filesep) dirname = [ dirname filesep ]; end basename = filename; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function yesno=is3d(haxes); % tries to figure out if axes is 3D yesno=0; CameraPosition=get(haxes,'CameraPosition'); CameraTarget=get(haxes,'CameraTarget'); CameraUpVector=get(haxes,'CameraUpVector'); if CameraPosition(1)~=CameraTarget(1) yesno=1; end if CameraPosition(2)~=CameraTarget(2) yesno=1; end if any(CameraUpVector~=[0 1 0]) yesno=1; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function b=celltoarray(a); % converts a cell of doubles to an array if iscell(a), b=[]; for i=1:length(a), b=[b a{i}]; end else, b=a(:)'; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function b=chartocell(a) % converts a character array into a cell array of characters % convert to cell if isa(a,'char') n=size(a,1); b=cell(1,n); for j=1:n b{j}=a(j,:); end else b=a; end % convert to char n=length(b); for j=1:n if isa(b{j},'double') b{j}=num2str(b{j}); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function b=overwritetail(a,k) % overwrites tail of a by k % a,b: strings % k: integer ks=int2str(k); b = [ a(1:(length(a)-length(ks))) ks ]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
Sinan81/PSAT-master
fm_writexls.m
.m
PSAT-master/psat-oct/psat/fm_writexls.m
6,451
utf_8
d360fea56202b900aa531d108d3cf13d
function fm_writexls(Matrix,Header,Cols,Rows,File) % FM_WRITEXLS export PSAT results to an Microsoft Excel % spreadsheet using Matlab ActiveX interface. % Microsoft Excel is required. % % This function is based on xlswrite.m by Scott Hirsch % % FM_WRITEXLS(MATRIX,HEDAER,COLNAMES,ROWNAMES,FILENAME) % % MATRIX Matrix to write to file % Cell array for multiple matrices. % HEADER String of header information. % Cell array for multiple header. % COLNAMES (Cell array of strings) Column headers. % One cell element per column. % ROWNAMES (Cell array of strings) Row headers. % One cell element per row. % FILENAME (string) Name of Excel file. % If not specified, contents will be % opened in Excel. % %Author: Federico Milano %Date: 13-Sep-2003 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Path if ~iscell(Matrix) Matrix{1,1} = Matrix; Header{1,1} = Header; Cols{1,1} = Cols; Rows{1,1} = Rows; end % Open Excel, add workbook, change active worksheet, % get/put array, save. % First, open an Excel Server. Excel = actxserver('Excel.Application'); % If the user does not specify a filename, we'll make Excel % visible if they do, we'll just save the file and quit Excel % without ever making it visible %if nargin < 5 set(Excel, 'Visible', 1); %end; % Insert a new workbook. Workbooks = Excel.Workbooks; Workbook = invoke(Workbooks, 'Add'); % Make the first sheet active. Sheets = Excel.ActiveWorkBook.Sheets; sheet1 = get(Sheets, 'Item', 1); invoke(sheet1, 'Activate'); % Get a handle to the active sheet. Activesheet = Excel.Activesheet; % -------------------------------------------------------------------- % writing data % -------------------------------------------------------------------- nhr = 0; for i_matrix = 1:length(Matrix) m = Matrix{i_matrix}; colnames = Cols{i_matrix}; rownames = Rows{i_matrix}; header = Header{i_matrix}; [nr,nc] = size(m); if nc > 256 fm_disp(['Matrix is too large. Excel only supports 256' ... ' columns'],2) delete(Excel) return end % Write header % ----------------------------------------------------------------- if ~isempty(header) if iscell(header) % Number header rows for ii=1:length(header) jj = nhr + ii; ActivesheetRange = get(Activesheet, ... 'Range', ... ['A',num2str(jj)], ... ['A',num2str(jj)]); set(ActivesheetRange, 'Value', header{ii}); end nhr = nhr + length(header); else % Number header rows nhr = nhr + 1; hcol = ['A',num2str(nhr)]; ActivesheetRange = get(Activesheet,'Range',hcol,hcol); set(ActivesheetRange, 'Value', header); end end %Add column names % ----------------------------------------------------------------- if nargin > 2 && ~isempty(colnames) [nrows,ncolnames] = size(colnames); for hh = 1:nrows nhr = nhr + 1; for ii = 1:ncolnames colname = localComputLastCol('A',ii); cellname = [colname,num2str(nhr)]; ActivesheetRange = get(Activesheet,'Range',cellname,cellname); set(ActivesheetRange, 'Value', colnames{hh,ii}); end end end % Put a MATLAB array into Excel. % ----------------------------------------------------------------- % Data start right after the headers FirstRow = nhr + 1; LastRow = FirstRow + nr - 1; % First column depends on the dimension of rownames [nrownames,ncols] = size(rownames); if nargin < 3 || isempty(rownames) FirstCol = 'A'; elseif isempty(colnames) FirstCol = 'D'; else switch ncols case 1, FirstCol = 'B'; case 2, FirstCol = 'C'; case 3, FirstCol = 'D'; case 4, FirstCol = 'E'; case 5, FirstCol = 'F'; otherwise, FirstCol = 'G'; end end if ~isempty(m) LastCol = localComputLastCol(FirstCol,nc); ActivesheetRange = get(Activesheet,'Range', ... [FirstCol,num2str(FirstRow)], ... [LastCol,num2str(LastRow)]); set(ActivesheetRange,'Value',full(m)); end %Add row names % ----------------------------------------------------------------- if nargin > 3 && ~isempty(rownames) %nrownames = length(rownames); for ii = 1:nrownames for jj = 1:ncols switch jj case 1, Col = 'A'; case 2, Col = 'B'; case 3, Col = 'C'; case 4, Col = 'D'; case 5, Col = 'E'; otherwise, Col = 'F'; end %rowname = localComputLastCol('A',FirstRow+ii-1); cellname = [Col,num2str(FirstRow + ii - 1)]; ActivesheetRange = get(Activesheet,'Range',cellname,cellname); set(ActivesheetRange, 'Value', rownames{ii,jj}); end end end % add a blank row in between data % ----------------------------------------------------------------- nhr = LastRow + 1; end % If user specified a filename, save the file and quit Excel % ------------------------------------------------------------------- if nargin == 5 invoke(Workbook, 'SaveAs', [Path.data,File]); %invoke(Excel, 'Quit'); fm_disp(['Excel file ',Path.data,File,' has been created.']); end %Delete the ActiveX object % ------------------------------------------------------------------- delete(Excel) % Local functions % ------------------------------------------------------------------- function LastCol = localComputLastCol(FirstCol,nc); % Compute the name of the last column where we will place data % Input: % FirstCol (string) name of first column % nc total number of columns to write % Excel's columns are named: % A B C ... A AA AB AC AD .... BA BB BC ... % Offset from column A FirstColOffset = double(FirstCol) - double('A'); % Easy if single letter % Just convert to ASCII code, add the number of needed columns, % and convert back to a string if nc<=26-FirstColOffset LastCol = char(double(FirstCol)+nc-1); else % Number of groups (of 26) ng = ceil(nc/26); % How many extra in this group beyond A rm = rem(nc,26)+FirstColOffset; LastColFirstLetter = char(double('A') + ng-2); LastColSecondLetter = char(double('A') + rm-1); LastCol = [LastColFirstLetter LastColSecondLetter]; end;
github
Sinan81/PSAT-master
fm_stat.m
.m
PSAT-master/psat-oct/psat/fm_stat.m
25,747
utf_8
61c73c2b4a3210fe8b88a7ba2641f1ba
function fig = fm_stat(varargin) % FM_STAT create GUI for power flow reports % % HDL = FM_STAT(VARARGIN) % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 24-Aug-2003 %Version: 2.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Bus DAE Varname Settings Fig Path OPF Theme global Oxl File abus = DAE.y(Bus.a); vbus = DAE.y(Bus.v); if nargin && ischar(varargin{1}) switch varargin{1} case 'report' if OPF.init == 1 || OPF.init == 2 fm_opfrep else fm_report end case 'toplist' value = get(gcbo,'Value'); set(gcbo,'Value',value(end)) set(get(gcf,'UserData'), ... 'Value',value(end), ... 'ListboxTop',get(gcbo,'ListboxTop')); case 'checkabs' hdl = findobj(Fig.stat,'Tag','CheckABS'); switch get(gcbo,'Checked') case 'on' set(gcbo,'Checked','off') Settings.absvalues = 'off'; set(hdl,'Value',0); case 'off' set(gcbo,'Checked','on') Settings.absvalues = 'on'; set(hdl,'Value',1); end case 'report_type' switch get(gcbo,'Checked') case 'on' set(gcbo,'Checked','off') Settings.report = 0; case 'off' set(gcbo,'Checked','on') Settings.report = 1; end case 'violation' hdl = findobj(Fig.stat,'Tag','CheckVIOL'); switch get(gcbo,'Checked') case 'on' set(gcbo,'Checked','off') Settings.violations = 'off'; set(hdl,'Value',0); case 'off' set(gcbo,'Checked','on') Settings.violations = 'on'; set(hdl,'Value',1); end case 'abscheck' hdl = findobj(Fig.stat,'Tag','absvalues'); switch get(gcbo,'Value') case 1 Settings.absvalues = 'on'; set(hdl,'Checked','on'); case 0 Settings.absvalues = 'off'; set(hdl,'Checked','off'); end case 'violcheck' hdl = findobj(Fig.stat,'Tag','violations'); switch get(gcbo,'Value') case 1 Settings.violations = 'on'; set(hdl,'Checked','on'); case 0 Settings.violations = 'off'; set(hdl,'Checked','off'); end case 'sort' hdl = findobj(gcf,'Tag','PushSort'); maxn = 150; switch get(hdl,'UserData') case 'az' [a,ordbus] = sortbus_bus(Bus,maxn); [a,ordbus] = sort(getidx_bus(Bus,ordbus)); h = get(gcf,'UserData'); for i = 1:length(h) String = get(h(i),'String'); set(h(i),'String',String(ordbus)) end set(hdl,'UserData','1n','CData',fm_mat('stat_sort12')) case '1n' [a,ordbus] = sortbus_bus(Bus,maxn); h = get(gcf,'UserData'); for i = 1:length(h) String = get(h(i),'String'); set(h(i),'String',String(ordbus)) end set(hdl,'UserData','az','CData',fm_mat('stat_sortaz')) end case 'kvpu' hdl = findobj(gcf,'Tag','PushVoltage'); switch get(hdl,'UserData') case 'pu' set(findobj(Fig.stat,'Tag','ListboxV'),'String',setvar(vbus.*getkv_bus(Bus,0,0))); set(hdl,'UserData','kv','CData',fm_mat('stat_kv')) case 'kv' set(findobj(Fig.stat,'Tag','ListboxV'),'String',setvar(vbus)); set(hdl,'UserData','pu','CData',fm_mat('stat_pu')) end case 'plotv' hdl = findobj(gcf,'Tag','PushVoltage'); figure switch get(hdl,'UserData') case 'pu' bar(vbus) ylabel('V [p.u.]') case 'kv' bar(vbus.*getkv_bus(Bus,0,0)) ylabel('V [kV]') end title('Voltage Magnitude Profile') xlabel('Bus #') case 'raddeg' hdl = findobj(gcf,'Tag','PushAngle'); switch get(hdl,'UserData') case 'deg' set(findobj(Fig.stat,'Tag','ListboxAng'),'String',setvar(abus)); set(hdl,'UserData','rad','CData',fm_mat('stat_rad')) case 'rad' set(findobj(Fig.stat,'Tag','ListboxAng'),'String',setvar(abus*180/pi)); set(hdl,'UserData','deg','CData',fm_mat('stat_deg')) end case 'plota' hdl = findobj(gcf,'Tag','PushAngle'); figure switch get(hdl,'UserData') case 'rad' bar(abus) ylabel('\theta [rad]') case 'deg' bar(abus*180/pi) ylabel('\theta [deg]') end title('Voltage Phase Profile') xlabel('Bus #') case 'realpower' hdl1 = findobj(gcf,'Tag','PushPGL'); switch get(hdl1,'UserData') case 'I', set(hdl1,'UserData','L') case 'G', set(hdl1,'UserData','I') case 'L', set(hdl1,'UserData','G') end hdl2 = findobj(gcf,'Tag','PushP'); switch get(hdl2,'UserData') case 'mw' set(hdl2,'UserData','pu','CData',fm_mat('stat_pu')) case 'pu' set(hdl2,'UserData','mw','CData',fm_mat('stat_mw')) end fm_stat pgl case 'pgl' hdl1 = findobj(gcf,'Tag','PushPGL'); hdl2 = findobj(gcf,'Tag','PushP'); switch get(hdl2,'UserData') case 'pu', mva = 1; case 'mw', mva = Settings.mva; end switch get(hdl1,'UserData') case 'I' pgl = Bus.Pg; set(hdl1,'UserData','G','CData',fm_mat('stat_pqg')) case 'G' pgl = Bus.Pl; set(hdl1,'UserData','L','CData',fm_mat('stat_pql')) case 'L' pgl = Bus.Pg - Bus.Pl; set(hdl1,'UserData','I','CData',fm_mat('stat_pqi')) end set(findobj(Fig.stat,'Tag','ListboxP'),'String',setvar(pgl*mva)); case 'qgl' hdl1 = findobj(gcf,'Tag','PushQGL'); hdl2 = findobj(gcf,'Tag','PushQ'); switch get(hdl2,'UserData') case 'pu', mva = 1; case 'mvar', mva = Settings.mva; end switch get(hdl1,'UserData') case 'I' qgl = Bus.Qg; set(hdl1,'UserData','G','CData',fm_mat('stat_pqg')) case 'G' qgl = Bus.Ql; set(hdl1,'UserData','L','CData',fm_mat('stat_pql')) case 'L' qgl = Bus.Qg - Bus.Ql; set(hdl1,'UserData','I','CData',fm_mat('stat_pqi')) end set(findobj(Fig.stat,'Tag','ListboxQ'),'String',setvar(qgl*mva)); case 'plotp' switch get(findobj(Fig.stat,'Tag','PushP'),'UserData') case 'pu', mva = 1; unit = 'p.u.'; case 'mw', mva = Settings.mva; unit = 'MW'; end switch get(findobj(Fig.stat,'Tag','PushPGL'),'UserData') case 'I' pgl = Bus.Pg - Bus.Pl; tag = 'P_G - P_L'; case 'G' pgl = Bus.Pg; tag = 'P_G'; case 'L' pgl = Bus.Pl; tag = 'P_L'; end figure bar(pgl*mva) ylabel([tag,' [',unit,']']) title('Real Power Profile') xlabel('Bus #') case 'reactivepower' hdl1 = findobj(gcf,'Tag','PushQGL'); switch get(hdl1,'UserData') case 'I', set(hdl1,'UserData','L') case 'G', set(hdl1,'UserData','I') case 'L', set(hdl1,'UserData','G') end hdl2 = findobj(gcf,'Tag','PushQ'); switch get(hdl2,'UserData') case 'mvar' set(hdl2,'UserData','pu','CData',fm_mat('stat_pu')) case 'pu' set(hdl2,'UserData','mvar','CData',fm_mat('stat_mvar')) end fm_stat qgl case 'plotq' switch get(findobj(Fig.stat,'Tag','PushQ'),'UserData') case 'pu', mva = 1; unit = 'p.u.'; case 'mvar', mva = Settings.mva; unit = 'MVar'; end switch get(findobj(Fig.stat,'Tag','PushQGL'),'UserData') case 'I' qgl = Bus.Qg-Bus.Ql; tag = 'Q_G - Q_L'; case 'G' qgl = Bus.Qg; tag = 'Q_G'; case 'L' qgl = Bus.Ql; tag = 'Q_L'; end figure bar(qgl*mva) ylabel([tag,' [',unit,']']) title('Reactive Power Profile') xlabel('Bus #') end return end % check for data file if isempty(File.data) fm_disp('Set a data file for viewing static report.',2) return end % check for initial power flow solution if ~Settings.init fm_disp('Solve base case power flow...') Settings.show = 0; fm_set('lf') Settings.show = 1; if ~Settings.init, return, end end if ishandle(Fig.stat) figure(Fig.stat) set(findobj(Fig.stat,'Tag','ListboxBus'),'String',setbus); if strcmp(get(findobj(Fig.stat,'Tag','PushAngle'),'UserData'),'rad') set(findobj(Fig.stat,'Tag','ListboxAng'),'String',setvar(abus)); else set(findobj(Fig.stat,'Tag','ListboxAng'),'String',setvar(abus*180/pi)); end if strcmp(get(findobj(Fig.stat,'Tag','PushVoltage'),'UserData'),'pu') set(findobj(Fig.stat,'Tag','ListboxV'),'String',setvar(vbus)); else set(findobj(Fig.stat,'Tag','ListboxV'),'String',setvar(vbus.*getkv_bus(Bus,0,0))); end switch get(findobj(Fig.stat,'Tag','PushP'),'UserData') case 'pu', mva = 1; case 'mw', mva = Settings.mva; end switch get(findobj(Fig.stat,'Tag','PushPGL'),'UserData') case 'I', pgl = Bus.Pg-Bus.Pl; case 'G', pgl = Bus.Pg; case 'L', pgl = Bus.Pl; end set(findobj(Fig.stat,'Tag','ListboxP'),'String',setvar(pgl*mva)); switch get(findobj(Fig.stat,'Tag','PushQ'),'UserData') case 'pu', mva = 1; case 'mvar', mva = Settings.mva; end switch get(findobj(Fig.stat,'Tag','PushQGL'),'UserData') case 'I', qgl = Bus.Qg-Bus.Ql; case 'G', qgl = Bus.Qg; case 'L', qgl = Bus.Ql; end set(findobj(Fig.stat,'Tag','ListboxQ'),'String',setvar(qgl*mva)); set(findobj(Fig.stat,'Tag','ListboxState'),'String',setx); hdl = findobj(Fig.stat,'Tag','ListboxServ'); if nargin > 0 set(hdl,'String',varargin{1}); setyvars(hdl,1); elseif OPF.init set(hdl,'String',OPF.report); else setyvars(hdl,0); end return end if Bus.n > 150, fm_disp(['Only the first 150 buses are reported in the Static', ... ' Report GUI']) end if DAE.n > 100, fm_disp(['Only the first 100 state variables are reported in the Static', ... ' Report GUI']) end h0 = figure('Color',Theme.color01, ... 'Units', 'normalized', ... 'Colormap',[], ... 'CreateFcn','Fig.stat = gcf;', ... 'DeleteFcn','Fig.stat = -1;', ... 'FileName','fm_stat', ... 'MenuBar','none', ... 'Name','Static Report', ... 'NumberTitle','off', ... 'PaperPosition',[18 180 576 432], ... 'PaperUnits','points', ... 'Position',sizefig(0.6984,0.6377), ... 'Resize','on', ... 'ToolBar','none'); % Menu File h1 = uimenu('Parent',h0, ... 'Label','File', ... 'Tag','MenuFile'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat report', ... 'Label','Create report', ... 'Tag','OTV', ... 'Accelerator','r'); h2 = uimenu('Parent',h1, ... 'Callback','close(gcf)', ... 'Label','Exit', ... 'Tag','NetSett', ... 'Accelerator','x', ... 'Separator','on'); % Menu View h1 = uimenu('Parent',h0, ... 'Label','View', ... 'Tag','MenuView'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat plotv', ... 'Label','Voltage Profile', ... 'Tag','v_prof', ... 'Accelerator','v'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat plota', ... 'Label','Angle Profile', ... 'Tag','a_prof', ... 'Accelerator','a'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat plotp', ... 'Label','Real Power Profile', ... 'Tag','v_prof', ... 'Accelerator','p'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat plotq', ... 'Label','Reactive Power Profile', ... 'Tag','a_prof', ... 'Accelerator','q'); % Menu Preferences h1 = uimenu('Parent',h0, ... 'Label','Preferences', ... 'Tag','MenuPref'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat kvpu', ... 'Label','Switch voltage units', ... 'Tag','tvopt', ... 'Accelerator','k'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat raddeg', ... 'Label','Switch radiant/degree', ... 'Tag','tvopt', ... 'Accelerator','d'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat realpower', ... 'Label','Switch real power units', ... 'Tag','tvopt', ... 'Accelerator','w'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat reactivepower', ... 'Label','Switch reactive power units', ... 'Tag','tvopt', ... 'Accelerator','u'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat pgl', ... 'Label','Switch real power type', ... 'Tag','tvopt', ... 'Accelerator','e'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat qgl', ... 'Label','Switch reactive power type', ... 'Tag','tvopt', ... 'Accelerator','f'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat checkabs', ... 'Label','Use absolute values in report files', ... 'Tag','absvalues', ... 'Checked',Settings.absvalues, ... 'Separator','on', ... 'Accelerator','b'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat violation', ... 'Label','Include limit violation checks', ... 'Tag','violations', ... 'Checked',Settings.violations, ... 'Accelerator','l'); h2 = uimenu('Parent',h1, ... 'Callback','fm_stat report_type', ... 'Label','Embed line flows in bus report', ... 'Tag','report_type', ... 'Checked','off', ... 'Accelerator','1'); if Settings.report, set(h2,'Checked','on'), end h2 = uimenu('Parent',h1, ... 'Callback','fm_tviewer', ... 'Label','Select Text Viewer', ... 'Tag','tvopt', ... 'Separator','on', ... 'Accelerator','t'); h1 = uicontrol( ... 'Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'ForegroundColor',Theme.color03, ... 'Position',[0.040268 0.48392 0.91499 0.475], ... 'Style','frame', ... 'Tag','Frame1'); hP = uicontrol( ... 'Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color03, ... 'Callback','fm_stat toplist', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color10, ... 'Max',100, ... 'Position',[0.60235 0.51149 0.14094 0.36547], ... 'String',setvar(Bus.Pg-Bus.Pl), ... 'Style','listbox', ... 'Tag','ListboxP', ... 'Value',1); hQ = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color03, ... 'Callback','fm_stat toplist', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color10, ... 'Max',100, ... 'Position',[0.7774 0.51149 0.14094 0.36547], ... 'String',setvar(Bus.Qg-Bus.Ql), ... 'Style','listbox', ... 'Tag','ListboxQ', ... 'Value',1); hB = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color03, ... 'Callback','fm_stat toplist', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color06, ... 'Max',100, ... 'Position',[0.077181 0.51149 0.14094 0.36547], ... 'String',setbus, ... 'Style','listbox', ... 'Tag','ListboxBus', ... 'Value',1); hV = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color03, ... 'Callback','fm_stat toplist', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color10, ... 'Max',100, ... 'Position',[0.25224 0.51149 0.14094 0.36547], ... 'String',setvar(vbus), ... 'Style','listbox', ... 'Tag','ListboxV', ... 'Value',1); hA = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color03, ... 'Callback','fm_stat toplist', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color10, ... 'Max',100, ... 'Position',[0.42729 0.51149 0.14094 0.36547], ... 'String',setvar(abus), ... 'Style','listbox', ... 'Tag','ListboxAng', ... 'Value',1); % Static texts h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[0.7774 0.89227 0.12975 0.030628], ... 'String','Q', ... 'Style','text', ... 'Tag','StaticText1'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[0.60235 0.89227 0.12975 0.030628], ... 'String','P', ... 'Style','text', ... 'Tag','StaticText1'); hT = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HitTest','off', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.42729 0.89227 0.12975 0.030628], ... 'String','Va', ... 'Style','text', ... 'Tag','StaticTextAng'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[0.25224 0.89227 0.12975 0.030628], ... 'String','Vm', ... 'Style','text', ... 'Tag','StaticText1'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[0.077181 0.89227 0.12975 0.030628], ... 'String','Bus', ... 'Style','text', ... 'Tag','StaticText1'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'ForegroundColor',Theme.color03, ... 'Position',[0.040268 0.049005 0.32662 0.41041], ... 'Style','frame', ... 'Tag','Frame2'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[0.072707 0.41348 0.12975 0.030628], ... 'String','State Variables', ... 'Style','text', ... 'Tag','StaticText1'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color03, ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color10, ... 'Max',100, ... 'Position',[0.072707 0.084227 0.26286 0.317], ... 'String',setx, ... 'Style','listbox', ... 'Tag','ListboxState', ... 'Value',1); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'ForegroundColor',Theme.color03, ... 'Position',[0.41051 0.049005 0.32662 0.41041], ... 'Style','frame', ... 'Tag','Frame2'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color03, ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color10, ... 'Max',100, ... 'Position',[0.44295 0.084227 0.26286 0.317], ... 'String',' ', ... 'Style','listbox', ... 'Tag','ListboxServ', ... 'Value',1); if nargin > 0 set(h1,'String',varargin{1}); setyvars(h1,1) elseif ~isempty(OPF.report) set(h1,'String',OPF.report); else setyvars(h1,0) end h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[0.44295 0.41348 0.12975 0.030628], ... 'String','Other Variables', ... 'Style','text', ... 'Tag','StaticText1'); h1 = axes('Parent',h0, ... 'Box','on', ... 'CameraUpVector',[0 1 0], ... 'CameraUpVectorMode','manual', ... 'Color',Theme.color04, ... 'ColorOrder',Settings.color, ... 'Layer','top', ... 'Position',[0.77964 0.050394 0.17785 0.176378], ... 'Tag','Axes1', ... 'XColor',Theme.color03, ... 'XLim',[0.5 190.5], ... 'XLimMode','manual', ... 'XTickLabelMode','manual', ... 'XTickMode','manual', ... 'YColor',Theme.color03, ... 'YDir','reverse', ... 'YLim',[0.5 115.5], ... 'YLimMode','manual', ... 'YTickLabelMode','manual', ... 'YTickMode','manual', ... 'ZColor',[0 0 0]); if Settings.hostver < 8.04 h2 = image('Parent',h1, ... 'CData',imread([Path.images,'stat_fig.jpg'],'jpg'), ... 'Tag','Axes1Image1', ... 'XData',[1 190], ... 'YData',[1 115]); else h2 = image('Parent',h1, ... 'CData',flipud(fliplr(imread([Path.images,'stat_fig.jpg'],'jpg'))), ... 'Tag','Axes1Image1', ... 'XData',[1 190], ... 'YData',[1 115]); end h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat abscheck', ... 'Position',[0.77964 0.050394+0.176378+0.03 0.17785 0.05], ... 'String','Use absolute values', ... 'Style','checkbox', ... 'Tag','CheckABS', ... 'Value',onoff(Settings.absvalues)); % 'Position',[0.77964 0.050394+0.176378+0.01 0.17785 0.05], ... %h1 = uicontrol('Parent',h0, ... % 'Units', 'normalized', ... % 'BackgroundColor',Theme.color02, ... % 'Callback','fm_stat xxx', ... % 'Position',[0.77964 0.1108+0.176378-0.005 0.17785 0.05], ... % 'String','xxx', ... % 'Style','checkbox', ... % 'Tag','CheckSHUNT', ... % 'Value',onoff(xxx)); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat violcheck', ... 'Position',[0.77964 0.1712+0.176378-0.04 0.17785 0.05], ... 'String','Check limit violations', ... 'Style','checkbox', ... 'Tag','CheckVIOL', ... 'Value',onoff(Settings.violations)); % 'Position',[0.77964 0.1712+0.176378-0.02 0.17785 0.05], ... % Push buttons h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color03, ... 'Callback','fm_stat report', ... 'FontWeight','bold', ... 'ForegroundColor',Theme.color09, ... 'Position',[0.77964 0.39051 0.0839 0.061256], ... 'String','Report', ... 'Tag','Pushbutton1'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback','close(gcf)', ... 'Position',[0.8685 0.39051 0.0839 0.061256], ... 'String','Close', ... 'Tag','Pushbutton1'); % 'Position',[0.80425 0.39051 0.12864 0.061256], ... % 'Position',[0.80425 0.317 0.12864 0.061256], ... if isunix, dy = 0.0025; else dy = 0; end h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_profile'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat plotv', ... 'Position',[0.34899 0.89686 0.045861 0.030628+dy], ... 'Tag','Pushbutton3'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_pu'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat kvpu', ... 'UserData','pu', ... 'Position',[0.3 0.89686 0.045861 0.030628+dy], ... 'Tag','PushVoltage'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_profile'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat plota', ... 'Position',[0.52349 0.89686 0.045861 0.030628+dy], ... 'Tag','Pushbutton3'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_rad'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat raddeg', ... 'UserData','rad', ... 'Position',[0.4745 0.89686 0.045861 0.030628+dy], ... 'Tag','PushAngle'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_sortaz'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat sort', ... 'Position',[0.1740 0.89686 0.045861 0.030628+dy], ... 'UserData','az', ... 'Tag','PushSort'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_profile'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat plotp', ... 'Position',[0.6974 0.89686 0.045861 0.030628+dy], ... 'Tag','Pushbutton3'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_pu'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat realpower', ... 'UserData','pu', ... 'Position',[0.6484 0.89686 0.045861 0.030628+dy], ... 'Tag','PushP'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_pqi'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat pgl', ... 'UserData','I', ... 'Position',[0.6224 0.89686 0.0229 0.030628+dy], ... 'Tag','PushPGL'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_profile'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat plotq', ... 'Position',[0.8725 0.89686 0.045861 0.030628+dy], ... 'Tag','Pushbutton3'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_pu'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat reactivepower', ... 'UserData','pu', ... 'Position',[0.8235 0.89686 0.045861 0.030628+dy], ... 'Tag','PushQ'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'CData', fm_mat('stat_pqi'), ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_stat qgl', ... 'UserData','I', ... 'Position',[0.7975 0.89686 0.0229 0.030628+dy], ... 'Tag','PushQGL'); set(h0,'UserData',[hB; hV; hA; hP; hQ]); if nargout > 0, fig = h0; end %============================================================== function stringa = setvar(input) global Bus busn = min(150,Bus.n); [buss, ordbus] = sortbus_bus(Bus,busn); hdl = findobj(gcf,'Tag','PushSort'); if ~isempty(hdl) if strcmp(get(hdl,'UserData'),'1n') [a,ordbus] = sort(getidx_bus(Bus,0)); end end stringa = cell(busn,1); for i = 1:busn, stringa{i,1} = fvar(input(ordbus(i)),10); end %============================================================== function stringa = setx global DAE Varname daen = min(100,DAE.n); stringa = cell(daen,1); for i = 1:daen, stringa{i,1} = [fvar(Varname.uvars{i,1},19), fvar(DAE.x(i),10)]; end %============================================================== function stringa = setbus global Bus [stringa, ord] = sortbus_bus(Bus,150); stringa = fm_strjoin('[',int2str(getidx_bus(Bus,ord)),']-',stringa); hdl = findobj(gcf,'Tag','PushSort'); if ~isempty(hdl) if strcmp(get(hdl,'UserData'),'1n') [a,ord] = sort(getidx_bus(Bus,ord)); stringa = stringa(ord); end end %============================================================== function value = onoff(string) switch string case 'on' value = 1; otherwise value = 0; end %============================================================== function setyvars(h1,type) global DAE Bus Varname if DAE.m > 2*Bus.n idx = [2*Bus.n+1:DAE.m]; if type string = get(h1,'String'); if ~iscell(string) string = cellstr(a); end else string = cell(0,0); end string = [string; fm_strjoin(Varname.uvars(DAE.n+idx),' = ',num2str(DAE.y(idx)))]; set(h1,'String',string); end
github
Sinan81/PSAT-master
fm_save.m
.m
PSAT-master/psat-oct/psat/fm_save.m
2,769
utf_8
a1510ea9eb17a263a21ac823d3a4bd19
function fm_save(Comp) % FM_SAVE save UDM to file % % FM_SAVE uses the component name COMP.NAME as file name % and creates a Matlab script. % The file is saved in the folder ./psat/build % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 15-Sep-2003 %Version: 2.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Settings Path Fig global Algeb Buses Initl Param Servc State % check for component name if isempty(Comp.name) fm_disp('No component name set.',2) return end % check for older versions a = dir([Path.build,'*.m']); b = {a.name}; older = strmatch([Comp.name,'.m'],b,'exact'); if ~isempty(older) uiwait(fm_choice(['Overwrite Existing File "',Comp.name,'.m" ?'])) if ~Settings.ok, return, end end % save data if isempty(Comp.init) Comp.init = 0; end if isempty(Comp.descr) Comp.descr = ['DAE function ', Comp.name, '.m']; end [fid,msg] = fopen([Path.build,Comp.name,'.m'],'wt'); if fid == -1 fm_disp(msg,2) fm_disp(['UDM File ',Comp.name,'.m couldn''t be saved.'],2) return end count = fprintf(fid,'%% User Defined Component %s\n',Comp.name); count = fprintf(fid,'%% Created with PSAT v%s\n',Settings.version); count = fprintf(fid,'%% \n'); count = fprintf(fid,'%% Date: %s\n',datestr(now,0)); Comp = rmfield(Comp,{'names','prop','n'}); savestruct(fid,Comp) savestruct(fid,Buses) savestruct(fid,Algeb) savestruct(fid,State) savestruct(fid,Servc) savestruct(fid,Param) savestruct(fid,Initl) count = fprintf(fid,'\n'); fclose(fid); fm_disp(['UDM File ',Comp.name,'.m saved in folder ./build']) % update list in the component browser GUI if ishandle(Fig.comp) fm_comp clist end % ------------------------------------------------------------------- function savestruct(fid,structdata) if isempty(structdata) return end if ~isstruct(structdata) return end fields = fieldnames(structdata); namestruct = inputname(2); count = fprintf(fid,'\n%% Struct: %s\n',namestruct); for i = 1:length(fields) field = getfield(structdata,fields{i}); if isempty(field) count = fprintf(fid,'\n%s.%s = [];',namestruct,fields{i}); end [m,n] = size(field); if isnumeric(field) for mi = 1:m for ni = 1:n count = fprintf(fid,['\n%s.%s(%d,%d) = %d;'], ... namestruct,fields{i},mi,ni,field(mi,ni)); end end elseif iscell(field) for mi = 1:m for ni = 1:n count = fprintf(fid,['\n%s.%s{%d,%d} = ''%s'';'], ... namestruct,fields{i},mi,ni, ... strrep(field{mi,ni},'''','''''')); end end elseif ischar(field) count = fprintf(fid,'\n%s.%s = ''%s'';', ... namestruct,fields{i},strrep(field,'''','''''')); end count = fprintf(fid,'\n'); end
github
Sinan81/PSAT-master
fm_eigen.m
.m
PSAT-master/psat-oct/psat/fm_eigen.m
16,954
utf_8
aa0ebcea776cfef3638414003a5d7782
function fm_eigen(type) % FM_EIGEN compute eigenvalues of static and dynamic Jacobian % matrices % % FM_EIGEN(TYPE,REPORT) % TYPE 1 -> Jlfd eigenvalues % 2 -> Jlfv eigenvalues % 3 -> Jlf eigenvalues % 4 -> As eigenvalues % REPORT 1 -> create report file % 0 -> no report file % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 05-Mar-2004 %Version: 1.1.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global DAE Bus Settings Varname File Path global PQ PV SW Fig Theme SSSA Line clpsat switch type case 'matrix' % set matrix type mat = zeros(4,1); mat(1) = findobj(gcf,'Tag','Checkbox1'); mat(2) = findobj(gcf,'Tag','Checkbox2'); mat(3) = findobj(gcf,'Tag','Checkbox3'); mat(4) = findobj(gcf,'Tag','Checkbox4'); tplot = zeros(3,1); tplot(1) = findobj(gcf,'Tag','Radiobutton1'); tplot(2) = findobj(gcf,'Tag','Radiobutton2'); tplot(3) = findobj(gcf,'Tag','Radiobutton3'); ca = find(mat == gcbo); vals = zeros(4,1); vals(ca) = 1; for i = 1:4 set(mat(i),'Value',vals(i)) end a = get(tplot(3),'Value'); if ca == 4 set(tplot(3),'Enable','on') else if a set(tplot(3),'Value',0) set(tplot(1),'Value',1) SSSA.map = 1; end set(tplot(3),'Enable','off') end if ca == 4 && SSSA.neig > DAE.n-1, set(findobj(Fig.eigen,'Tag','EditText1'),'String','1') SSSA.neig = 1; elseif ca < 4 && SSSA.neig > Bus.n-1, set(findobj(Fig.eigen,'Tag','EditText1'),'String','1') SSSA.neig = 1; end SSSA.matrix = ca; SSSA.report = []; case 'map' % set eigenvalue map type tplot = zeros(3,1); tplot(1) = findobj(gcf,'Tag','Radiobutton1'); tplot(2) = findobj(gcf,'Tag','Radiobutton2'); tplot(3) = findobj(gcf,'Tag','Radiobutton3'); ca = find(tplot == gcbo); vals = zeros(3,1); vals(ca) = 1; for i = 1:3 set(tplot(i),'Value',vals(i)) end SSSA.map = find(vals); SSSA.report = []; case 'neig' % Set number of eigs to be computed if SSSA.matrix == 4 amax = DAE.n; else amax = Bus.n; end number = get(gcbo,'String'); try a = round(str2num(number)); if a > 0 && a < amax SSSA.neig = a; SSSA.report = []; else set(gcbo,'String',num2str(SSSA.neig)); end catch set(gcbo,'String',num2str(SSSA.neig)); end case 'method' % Set method for eigenvalue computation t1 = findobj(Fig.eigen,'Tag','Radiobutton1'); t3 = findobj(Fig.eigen,'Tag','Radiobutton2'); a = get(gcbo,'Value'); hedit = findobj(Fig.eigen,'Tag','EditText1'); if a == 1 set(hedit,'Enable','off') set(t3,'Enable','on') else set(hedit,'Enable','on') if get(t3,'Value') set(t3,'Value',0) set(t1,'Value',1) SSSA.map = 1; end set(t3,'Enable','off') end SSSA.method = a; SSSA.report = []; case 'runsssa' % check for data file if isempty(File.data) fm_disp('Set a data file before running eigenvalue analysis.',2) return end % check for initial power flow solution if ~Settings.init fm_disp('Solve base case power flow...') Settings.show = 0; fm_set('lf') Settings.show = 1; if ~Settings.init, return, end end if PQ.n && Settings.pq2z pq2z = 0; if clpsat.init pq2z = clpsat.pq2z; elseif Settings.donotask pq2z = Settings.pq2z; else uiwait(fm_choice(['Convert PQ loads to constant impedances?'])) pq2z = Settings.ok; end if pq2z % convert PQ loads to shunt admittances PQ = pqshunt_pq(PQ); % update Jacobian matrices fm_call('i'); else % reset PQ loads to constant powers PQ = noshunt_pq(PQ); % update Jacobian matrices fm_call('i'); Settings.pq2z = 0; if ishandle(Fig.setting) set(findobj(Fig.setting,'Tag','CheckboxPQ2Z'),'Value',0) end end end uno = 0; tipo_mat = SSSA.matrix; tipo_plot = SSSA.map; SSSA.report = []; if isempty(Bus.n) fm_disp('No loaded system. Eigenvalue computation cannot be run.',2) return end % build eigenvalue names if (Settings.vs == 0), fm_idx(2), end % initialize report structures Header{1,1}{1,1} = 'EIGENVALUE REPORT'; Header{1,1}{2,1} = ' '; Header{1,1}{3,1} = ['P S A T ',Settings.version]; Header{1,1}{4,1} = ' '; Header{1,1}{5,1} = 'Author: Federico Milano, (c) 2002-2019'; Header{1,1}{6,1} = 'e-mail: [email protected]'; Header{1,1}{7,1} = 'website: faraday1.ucd.ie/psat.html'; Header{1,1}{8,1} = ' '; Header{1,1}{9,1} = ['File: ', Path.data,strrep(File.data,'(mdl)','.mdl')]; Header{1,1}{10,1} = ['Date: ',datestr(now,0)]; Matrix{1,1} = []; Cols{1,1} = ''; Rows{1,1} = ''; if tipo_mat == 4 if DAE.n == 0 fm_disp('No dynamic component loaded. State matrix is not defined',2) return end As = DAE.Fx - DAE.Fy*(DAE.Gy\DAE.Gx) - 1e-6*speye(DAE.n); if tipo_plot == 3 As = (As+8*speye(DAE.n))/(As-8*speye(DAE.n)); end [auto,autor,autoi,num_auto,pf] = compute_eigs(As); names = cellstr(fm_strjoin('Eig As #',num2str([1:num_auto]'))); Header{2,1} = 'STATE MATRIX EIGENVALUES'; Cols{2,1} = {'Eigevalue', 'Most Associated States', ... 'Real part','Imag. Part','Pseudo-Freq.','Frequency'}; Matrix{2,1} = zeros(num_auto,4); Matrix{2,1}(:,[1 2]) = [autor, autoi]; for i = 1:num_auto; if autoi(i) == 0 [part, idxs] = max(pf(i,:)); stat = Varname.uvars{idxs}; pfrec = 0; frec = 0; else [part, idxs] = sort(pf(i,:)); stat = [Varname.uvars{idxs(end)},', ',Varname.uvars{idxs(end-1)}]; pfrec = abs(imag(auto(i))/2/3.1416); frec = abs(auto(i))/2/3.1416; end Rows{2,1}{i,1} = names{i}; Rows{2,1}{i,2} = stat; Matrix{2,1}(i,3) = pfrec; Matrix{2,1}(i,4) = frec; end [uno,Header,Cols,Rows,Matrix] = ... write_pf(pf,DAE.n,Varname.uvars,names,Header,Cols,Rows,Matrix); elseif tipo_mat == 3 Jlf = build_gy_line(Line); if DAE.m > 2*Bus.n x3 = 1:2*Bus.n; Jlf = Jlf(x3,x3); end x1 = Bus.a; x2 = Bus.v; vbus = [getbus_sw(SW,'a');getbus_sw(SW,'v');getbus_pv(PV,'v')]; Jlf(vbus,:) = 0; Jlf(:,vbus) = 0; Jlf = Jlf + sparse(vbus,vbus,999,2*Bus.n,2*Bus.n); Jlfptheta = Jlf(x1,x1)+1e-5*speye(Bus.n,Bus.n); elementinulli = find(diag(Jlfptheta == 0)); if ~isempty(elementinulli) for i = 1:length(elementinulli) Jlfptheta(elementinulli(i),elementinulli(i)) = 1; end end Jlfr = Jlf(x2,x2) - Jlf(x2,x1)*(Jlfptheta\Jlf(x1,x2)); [auto,autor,autoi,num_auto,pf] = compute_eigs(Jlfr); names = cellstr(fm_strjoin('Eig Jlfr #',num2str([1:num_auto]'))); Header{2,1} = 'EIGENVALUES OF THE STANDARD POWER JACOBIAN MATRIX'; Cols{2,1} = {'Eigevalue', 'Most Associated Bus', 'Real part', ... 'Imaginary Part'}; Rows{2,1} = names; Matrix{2,1} = [autor, autoi]; for i = 1:num_auto; if autoi(i) == 0 [part, idxs] = max(pf(i,:)); stat = Bus.names{idxs}; else [part, idxs] = sort(pf(i,:)); stat = [Bus.names{idxs(end)},', ',Bus.names{idxs(end-1)}]; end Rows{2,1}{i,1} = names{i}; Rows{2,1}{i,2} = stat; end [uno,Header,Cols,Rows,Matrix] = ... write_pf(pf,Bus.n,Bus.names,names,Header,Cols,Rows,Matrix); elseif tipo_mat == 2 x1 = Bus.a; x2 = Bus.v; if DAE.m > 2*Bus.n x3 = 1:2*Bus.n; x4 = 2*Bus.n+1:DAE.m; Gy = DAE.Gy(x3,x3)-DAE.Gy(x3,x4)*(DAE.Gy(x4,x4)\DAE.Gy(x4,x3)); else Gy = DAE.Gy; end Jlfvr = Gy(x2,x2)-Gy(x2,x1)*(Gy(x1,x1)\Gy(x1,x2)); vbus = [getbus_sw(SW);getbus_pv(PV)]; Jlfvr = Jlfvr + sparse(vbus,vbus,998,Bus.n,Bus.n); [auto,autor,autoi,num_auto,pf] = compute_eigs(Jlfvr); names = cellstr(fm_strjoin('Eig Jlfv #',num2str([1:num_auto]'))); Header{2,1} = 'EIGENVALUES OF THE COMPLETE POWER JACOBIAN MATRIX'; Cols{2,1} = {'Eigevalue', 'Most Associated Bus', 'Real part', ... 'Imaginary Part'}; Rows{2,1} = names; Matrix{2,1} = [autor, autoi]; for i = 1:num_auto; if autoi(i) == 0 [part, idxs] = max(pf(i,:)); stat = Bus.names{idxs}; else [part, idxs] = sort(pf(i,:)); stat = [Bus.names{idxs(end)},', ',Bus.names{idxs(end-1)}]; end Rows{2,1}{i,1} = names{i}; Rows{2,1}{i,2} = stat; end [uno,Header,Cols,Rows,Matrix] = ... write_pf(pf,Bus.n,Bus.names,names,Header,Cols,Rows,Matrix); elseif tipo_mat == 1 if DAE.n == 0 fm_disp('Since no dynamic component is loaded, Jlfd = Jlfv.',2) end if DAE.m > 2*Bus.n x3 = 1:2*Bus.n; x4 = 2*Bus.n+1:DAE.m; x5 = 1:DAE.n; Gy = DAE.Gy(x3,x3)-DAE.Gy(x3,x4)*(DAE.Gy(x4,x4)\DAE.Gy(x4,x3)); Gx = DAE.Gx(x3,x5)-DAE.Gy(x3,x4)*(DAE.Gy(x4,x4)\DAE.Gx(x4,x5)); Fx = DAE.Fx(x5,x5)-DAE.Fy(x5,x4)*(DAE.Gy(x4,x4)\DAE.Gx(x4,x5)); Fy = DAE.Fy(x5,x3)-DAE.Fy(x5,x4)*(DAE.Gy(x4,x4)\DAE.Gy(x4,x3)); else Gy = DAE.Gy; Gx = DAE.Gx; Fx = DAE.Fx; Fy = DAE.Fy; end Fx = Fx-1e-5*speye(DAE.n,DAE.n); Jlfd = Gy-Gx*(Fx\Fy); x1 = Bus.a; x2 = Bus.v; Jlfdr = Jlfd(x2,x2)-Jlfd(x2,x1)*(Jlfd(x1,x1)\Jlfd(x1,x2)); vbus = [getbus_sw(SW);getbus_pv(PV)]; Jlfdr = Jlfdr + sparse(vbus,vbus,998,Bus.n,Bus.n); [auto,autor,autoi,num_auto,pf] = compute_eigs(Jlfdr); names = cellstr(fm_strjoin('Eig Jlfd #',num2str([1:num_auto]'))); Header{2,1} = 'EIGENVALUES OF THE DYNAMIC POWER JACOBIAN MATRIX'; Cols{2,1} = {'Eigevalue', 'Most Associated Bus', 'Real part', ... 'Imaginary Part'}; Rows{2,1} = names; Matrix{2,1} = [autor, autoi]; for i = 1:num_auto; if autoi(i) == 0 [part, idxs] = max(pf(i,:)); stat = Bus.names{idxs}; else [part, idxs] = sort(pf(i,:)); stat = [Bus.names{idxs(end)},', ',Bus.names{idxs(end-1)}]; end Rows{2,1}{i,1} = names{i}; Rows{2,1}{i,2} = stat; end [uno,Header,Cols,Rows,Matrix] = ... write_pf(pf,Bus.n,Bus.names,names,Header,Cols,Rows,Matrix); end auto_neg = find(autor < 0); auto_pos = find(autor > 0); auto_real = find(autoi == 0); auto_comp = find(autoi < 0); auto_zero = find(autor == 0); num_neg = length(auto_neg); num_pos = length(auto_pos); num_real = length(auto_real); num_comp=length(auto_comp); num_zero = length(auto_zero); if ishandle(Fig.eigen) hdl = zeros(8,1); hdl(1) = findobj(Fig.eigen,'Tag','Text3'); hdl(2) = findobj(Fig.eigen,'Tag','Text4'); hdl(3) = findobj(Fig.eigen,'Tag','Text5'); hdl(4) = findobj(Fig.eigen,'Tag','Text6'); hdl(5) = findobj(Fig.eigen,'Tag','Axes1'); hdl(6) = findobj(Fig.eigen,'Tag','Listbox1'); hdl(7) = findobj(Fig.eigen,'Tag','Text1'); hdl(8) = findobj(Fig.eigen,'Tag','Text2'); set(hdl(1),'String',num2str(num_pos)); set(hdl(2),'String',num2str(num_neg)); set(hdl(3),'String',num2str(num_comp)); set(hdl(4),'String',num2str(num_zero)); set(hdl(7),'String',num2str(DAE.n)); set(hdl(8),'String',num2str(Bus.n)); autovalori = cell(length(autor),1); if num_auto < 10 d = ''; e = ''; elseif num_auto < 100 d = ' '; e = ''; elseif num_auto < 1000 d = ' '; e = ' '; else d = ' '; e = ' '; end for i = 1:length(autor) if autor(i)>=0 a = ' '; else a = ''; end if autoi(i)>=0 c = '+'; else c = '-'; end if i < 10 f1 = [d,e]; elseif i < 100 f1 = e; else f1 = ''; end if tipo_plot == 3 autovalori{i,1} = ['|',char(181),'(A)| #',num2str(i), ... f1, ' ', fvar(abs(auto(i)),9)]; else autovalori{i,1} = [char(181),'(A) #',num2str(i),f1, ... ' ',a,num2str(autor(i)),' ',c, ... ' j',num2str(abs(autoi(i)))]; end end set(hdl(6),'String',autovalori,'Value',1) end Header{3+uno,1} = 'STATISTICS'; Cols{3+uno} = ''; Rows{3+uno} = ''; Matrix{3+uno,1} = []; if tipo_mat < 4 Rows{3+uno}{1,1} = 'NUMBER OF BUSES'; Matrix{3+uno,1}(1,1) = Bus.n; else Rows{3+uno}{1,1} = 'DYNAMIC ORDER'; Matrix{3+uno,1}(1,1) = DAE.n; end Rows{3+uno}{2,1} = '# OF EIGS WITH Re(mu) < 0'; Matrix{3+uno,1}(2,1) = num_neg; Rows{3+uno}{3,1} = '# OF EIGS WITH Re(mu) > 0'; Matrix{3+uno,1}(3,1) = num_pos; Rows{3+uno}{4,1} = '# OF REAL EIGS'; Matrix{3+uno,1}(4,1) = num_real; Rows{3+uno}{5,1} = '# OF COMPLEX PAIRS'; Matrix{3+uno,1}(5,1) = num_comp; Rows{3+uno}{6,1} = '# OF ZERO EIGS'; Matrix{3+uno,1}(6,1) = num_zero; % save eigenvalues and participation factors in SSSA structure SSSA.eigs = auto; SSSA.pf = pf; if ishandle(Fig.eigen), axes(hdl(5)); fm_eigen('graph') end SSSA.report.Matrix = Matrix; SSSA.report.Header = Header; SSSA.report.Cols = Cols; SSSA.report.Rows = Rows; case 'report' if SSSA.matrix == 4 && DAE.n == 0 fm_disp('No dynamic component loaded. State matrix is not defined',2) return end if isempty(SSSA.report), fm_eigen('runsssa'), end % writing data... fm_write(SSSA.report.Matrix,SSSA.report.Header, ... SSSA.report.Cols,SSSA.report.Rows) case 'graph' hgca = gca; if isempty(SSSA.eigs) fm_eigen('runsssa') end axes(hgca) autor = real(SSSA.eigs); autoi = imag(SSSA.eigs); num_auto = length(SSSA.eigs); idx = find(autor > -990); if ~isempty(idx) autor = autor(idx); autoi = autoi(idx); end if ishandle(Fig.eigen) switch SSSA.map case 1 idxn = find(autor < 0); idxz = find(autor == 0); idxp = find(autor > 0); if SSSA.matrix == 4 hdle = plot(autor(idxn), autoi(idxn),'bx', ... autor(idxz), autoi(idxz),'go', ... autor(idxp), autoi(idxp),'rx'); else hdle = plot(autor(idxn), autoi(idxn),'rx', ... autor(idxz), autoi(idxz),'go', ... autor(idxp), autoi(idxp),'bx'); end hold on plot([0,0],ylim,':k'); plot(xlim,[0,0],':k'); zeta = [0.05, 0.1, 0.15]; colo = {'r:', 'g:', 'b:'}; for i = 1:3 mu = sqrt((1 - zeta(i)^2)/zeta(i)^2); ylimits = ylim; plot([0, -ylimits(2)/mu], [0, ylimits(2)], colo{i}) plot([0, ylimits(1)/mu], [0, ylimits(1)], colo{i}) end set(hdle,'MarkerSize',8); xlabel('Real'); ylabel('Imag'); hold off set(hgca,'Tag','Axes1') case 2 surf(real(SSSA.pf)) set(hgca,'XLim',[1 num_auto],'YLim',[1 num_auto]); view(0,90); box('on') ylabel('Eigenvalues'); if SSSA.matrix == 4 xlabel('State Variables'); else xlabel('Buses'); end shading('interp') colormap('summer'); title('Participation Factors') set(hgca,'Tag','Axes1'); case 3 t = 0:0.01:2*pi+0.01; x = cos(t); y = sin(t); plot(x,y,'k:') hold on idxn = find(autor < 1); idxz = find(autor == 1); idxp = find(autor > 1); hdle = plot(autor(idxn), autoi(idxn),'bx', ... autor(idxz), autoi(idxz),'go', ... autor(idxp), autoi(idxp),'rx'); set(hdle,'MarkerSize',8); xlabel('Real'); ylabel('Imag'); xlim(1.1*xlim); ylim(1.1*ylim); plot([0,0],1.1*ylim,':k'); plot(1.1*xlim,[0,0],':k'); hold off set(hgca,'Tag','Axes1'); end set(hgca,'Color',Theme.color11) end end % ======================================================= function [auto,autor,autoi,num_auto,pf] = compute_eigs(A) global Settings SSSA meth = {'LM';'SM';'LR';'SR';'LI';'SI'}; neig = SSSA.neig; opts = SSSA.method-1; opt.disp = 0; if opts [V, auto] = eigs(A,neig,meth{opts},opt); [W, dummy] = eigs(A',neig,meth{opts},opt); else [V, auto] = eig(full(A)); W = [pinv(V)]'; end auto = diag(auto); auto = round(auto/Settings.lftol)*Settings.lftol; num_auto = length(auto); autor = real(auto); autoi = imag(auto); WtV = sum(abs(W).*abs(V)); pf = [abs(W).*abs(V)]'; %pf = [W.*V].'; % for getting p.f. with their signs for i = 1:length(auto), pf(i,:) = pf(i,:)/WtV(i); end % ======================================================= function [uno,Header,Cols,Rows,Matrix] = write_pf(pf,n,name1,name2,Header,Cols,Rows,Matrix) uno = fix(n/5); due = rem(n,5); if due > 0, uno = uno + 1; end for k = 1:uno Header{2+k,1} = 'PARTICIPATION FACTORS (Euclidean norm)'; Cols{2+k} = {' ',name1{5*(k-1)+1:min(5*k,n)}}; Rows{2+k} = name2; Matrix{2+k,1} = pf(:,5*(k-1)+1:min(5*k,n)); end
github
Sinan81/PSAT-master
fm_simrep.m
.m
PSAT-master/psat-oct/psat/fm_simrep.m
23,494
utf_8
366e4a9529c94d9e4a3f77afe3de53db
function fm_simrep(varargin) % FM_SIMREP generate data report in Simulink models % % FM_SIMREP(FLAG,FONTSIZE,FONTNAME) % FLAG: 1 - set up voltage report on current loaded network % 2 - wipe voltage report on current loaded network % 3 - set up power flows on current loaded network % 4 - wipe power flows on current loaded network % 5 - hide component names except for buses % 6 - show component names % 7 - hide bus names % 8 - show bus names % 9 - set font name % 10 - set font size % 11 - save model diagram to eps file % FONTSIZE: font size (integer) % FONTNAME: font name (string) % %see also FM_LIB, FM_SIMSET % %Author: Federico Milano %Date: 11-Nov-2002 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano fm_var global Settings type = 1; switch nargin case 1 flag = varargin{1}; case 3 flag = varargin{1}; fontsize = varargin{2}; fontname = varargin{3}; case 4 flag = varargin{1}; maptype = varargin{2}; type = varargin{3}; method = varargin{4}; end if isempty(File.data) && type, fm_disp('No loaded system is present at the moment.',2), return end if isempty(strfind(File.data,'(mdl)')) && type fm_disp('The actual data file is not generated from a Simulink model.',2), return end if ~Settings.init && ~strcmp(flag,{'mdl2eps','ViewModel','DrawModel'}) & type fm_disp('Perform Power Flow before using this utility.',2), return end lasterr(''); % load Simulink model cd(Path.data); filedata = File.data(1:end-5); open_sys = find_system('type','block_diagram'); if ~sum(strcmp(open_sys,filedata)) try if nargin > 3 load_system(filedata) else open_system(filedata); end catch fm_disp(lasterr,2) return end end cur_sys = get_param(filedata,'Handle'); if ~strcmp(flag,'DrawModel'), set_param(cur_sys,'Open','on'), end blocks = find_system(cur_sys,'Type','block'); lines = find_system(cur_sys, ... 'FindAll','on', ... 'type','line'); masks = get_param(blocks,'Masktype'); nblock = length(blocks); switch flag case 'ViewModel' % view the current Simulink model. hilite_system(cur_sys,'none') case 'DrawModel' maps = {'jet';'hot';'gray';'bone';'copper';'pink'; 'hsv';'cool';'autumn';'spring';'winter';'summer'}; if ~method switch type case 0 % only one-line diagram zlevel = 0; case 1 % voltage magnitudes zlevel = 1.025*max(DAE.y(Bus.v)); case 2 % voltage phases zmax = max(180*DAE.y(Bus.a)/pi); if zmax >= 0 zlevel = 1.1*zmax; else zlevel = 0.9*zmax; end case 3 % line flows [sij,sji] = flows_line(Line,3); zlevel = 1.1*max(sij); case 4 % generator rotor angles if ~Syn.n if Settings.static fm_disp('Currently, synchronous machines are not loaded.') fm_disp('Uncheck the option "Discard dynamic data" and try again.') else fm_disp('There are no synchronous machines in the current system.',2) end return end zmax = max(180*DAE.x(Syn.delta)/pi); if zmax >= 0 zlevel = 1.1*zmax; else zlevel = 0.9*zmax; end case 5 % generator rotor speeds if ~Syn.n if Settings.static fm_disp('Currently, synchronous machines are not loaded.') fm_disp('Uncheck the option "Discard dynamic data" and try again.') else fm_disp('There are no synchronous machines in the current system.',2) end return end zlevel = 1.05*max(DAE.x(Syn.omega)); case 6 % locational marginal prices if ~OPF.init fm_disp(['Run OPF before displaying Locational Marginal ' ... 'Prices'],2) return end LMP = OPF.LMP; zlevel = 1.025*max(LMP); case 7 % nodal congestion prices if ~OPF.init fm_disp(['Run OPF before displaying Nodal Congestion Prices'], ... 2) return end NCP = OPF.NCP(1:Bus.n); zlevel = 1.025*max(NCP); otherwise zlevel = 0; end Varout.zlevel = zlevel; end if ishandle(Fig.threed) && type figure(Fig.threed) elseif ishandle(Fig.dir) && ~type figure(Fig.dir) hdla = findobj(Fig.dir,'Tag','Axes1'); cla(hdla) else figure end hold on if ~method if type, colorbar, end if ishandle(Fig.threed), cla(get(Fig.threed,'UserData')), end lines = get_param(cur_sys,'Lines'); end pos = get_param(cur_sys,'Location'); xl = []; yl = []; for i = 1:length(lines)*(~method) z = zlevel*ones(length(lines(i).Points(:,1)),1); plot3(lines(i).Points(:,1),lines(i).Points(:,2),z,'k') xl = [xl; lines(i).Points([1 end],1)]; yl = [yl; lines(i).Points([1 end],2)]; end xb = []; yb = []; zb = []; x_max = 0; x_min = 2000; y_max = 0; y_min = 2000; idx = 0; idx_line = 0; idx_gen = 0; Compnames = cell(0,0); Compidx = []; ncomp = 0; if ~method switch type case 3 Varout.hdl = zeros(Line.n,1); case {4,5} Varout.hdl = zeros(Syn.n,1); otherwise Varout.hdl = zeros(Bus.n,1); end end for i = 1:length(blocks)*(~method) bmask = get_param(blocks(i),'MaskType'); jdx = strmatch(bmask,Compnames,'exact'); if isempty(jdx) ncomp = ncomp + 1; Compnames{ncomp,1} = bmask; Compidx(ncomp,1) = 0; jdx = ncomp; end Compidx(jdx) = Compidx(jdx)+1; bpos = get_param(blocks(i),'Position'); bidx = Compidx(jdx); %str2double(get_param(blocks(i),'UserData')); borien = get_param(blocks(i),'Orientation'); bports = get_param(blocks(i),'Ports'); bvalues = get_param(blocks(i),'MaskValues'); bin = sum(bports([1 6])); bou = sum(bports([2 7])); switch bmask case 'Varname' % nothing to do! x = cell(1,1); y = cell(1,1); s = cell(1,1); x{1} = 0; y{1} = 0; s{1} = 'k'; case 'Ltc' bname = get_param(blocks(i),'NamePlacement'); [x,y,s] = mask(eval(bmask),bidx,{borien;bname},bvalues); case 'Line' bdescr = get_param(blocks(i),'MaskDescription'); [x,y,s] = mask(eval(bmask),bidx,borien,bdescr); case 'PQ' [x,y,s] = mask(eval(bmask),bidx,borien,'PQ'); case 'PQgen' [x,y,s] = mask(eval(bmask),bidx,borien,'PQgen'); case 'Link' rot = strcmp(get_param(blocks(i),'NamePlacement'),'normal'); x = cell(6,1); y = cell(6,1); s = cell(6,1); x{1} = [0.45 0]; y{1} = [0.5 0.5]; s{1} = 'k'; x{2} = [1 0.55]; y{2} = [0.5 0.5]; s{2} = 'k'; x{3} = [0.45 0.55 0.55 0.45 0.45]; y{3} = [0.45 0.45 0.55 0.55 0.45]; s{3} = 'g'; x{4} = [0.5 0.5]; y{4} = rot*0.45+[0.1 0.45]; s{4} = 'g'; x{5} = [0.45 0.55 0.55 0.45 0.45]; y{5} = rot*0.9+[0 0 0.1 0.1 0]; s{5} = 'g'; x{6} = 1-rot; y{6} = 1-rot; s{6} = 'w'; [x,y] = fm_maskrotate(x,y,borien); case 'Link2' x = cell(10,1); y = cell(10,1); s = cell(10,1); x{1} = [0 0.45]; y{1} = [0.5 0.5]; s{1} = 'k'; x{2} = [0.5 0.5]; y{2} = [0 0.4]; s{2} = 'k'; x{3} = [0.5 0.5]; y{3} = [0 0.4]; s{3} = 'k'; x{4} = [0.5 1]; y{4} = [0 0]; s{4} = 'k'; x{5} = [0.5 0.5]; y{5} = [0.6 1]; s{5} = 'g'; x{6} = [0.5 0.9]; y{6} = [1 1]; s{6} = 'g'; x{7} = [0.9 0.985 0.985 0.9 0.9]; y{7} = [0.1 0.1 -0.1 -0.1 0.1]+1; s{7} = 'g'; x{8} = [0.45 0.55 0.55 0.45 0.45]; y{8} = [0.6 0.6 0.4 0.4 0.6]; s{8} = 'g'; x{9} = 0; y{9} = -0.5; s{9} = 'w'; x{10} = 0; y{10} = 1.5; s{10} = 'w'; [x,y] = fm_maskrotate(x,y,borien); otherwise [x,y,s] = mask(eval(bmask),bidx,borien,bvalues); end xt = []; yt = []; for j = 1:length(x) xt = [xt, x{j}]; yt = [yt, y{j}]; end xmin = min(xt); xmax = max(xt); if xmax == xmin, xmax = xmin+1; end ymin = min(yt); ymax = max(yt); if ymax == ymin, ymax = ymin+1; end dx = bpos(3)-bpos(1); dy = bpos(4)-bpos(2); xscale = dx/(xmax-xmin); yscale = dy/(ymax-ymin); xcorr = -xscale*(xmax+xmin)/2 + 0.5*dx; ycorr = -yscale*(ymax+ymin)/2 + 0.5*dy; xmean = bpos(1)+xcorr+xscale*(xmax+xmin)/2; ymean = bpos(4)-ycorr-yscale*(ymax+ymin)/2; if strcmp(bmask,'Bus') idx = idx + 1; if type == 1 || type == 2 || type == 6 || type == 7 xb = [xb; bpos(1)+xcorr+xscale*xmax; xmean]; yb = [yb; bpos(4)-yscale*ymax-ycorr; ymean]; xb = [xb; bpos(1)+xcorr+xscale*xmin]; yb = [yb; bpos(4)-yscale*ymin-ycorr]; end %bcolor = get_param(blocks(i),'BackgroundColor'); bname = get_param(blocks(i),'Name'); switch borien case {'right','left'} switch get_param(blocks(i),'NamePlacement') case 'normal' xtext = xmean; ytext = bpos(4)-ycorr-yscale*ymin+7; bha = 'center'; bva = 'top'; case 'alternate' xtext = xmean; ytext = bpos(4)-ycorr-yscale*ymax-7; bha = 'center'; bva = 'bottom'; end case {'up','down'} switch get_param(blocks(i),'NamePlacement') case 'normal' xtext = bpos(1)+xcorr+xscale*xmax+7; ytext = ymean; bha = 'left'; bva = 'middle'; case 'alternate' xtext = bpos(1)+xcorr+xscale*xmin-7; ytext = ymean; bha = 'right'; bva = 'middle'; end end % write bus names if type h = text(xtext,ytext,zlevel,bname); set(h,'HorizontalAlignment',bha,'VerticalAlignment',bva, ... 'FontSize',8) end if type == 1 || type == 2 || type == 6 || type == 7 switch type case 1, zpeak = DAE.y(Bus.v(idx)); case 2, zpeak = 180*DAE.y(Bus.a(idx))/pi; case 6, zpeak = LMP(idx); case 7, zpeak = NCP(idx); end Varout.hdl(idx) = plot3([xmean xmean],[ymean ymean], ... [zlevel,zpeak],'k:'); end end if strcmp(bmask,'Line') && type == 3 idx_line = idx_line + 1; xb = [xb; bpos(1)+xcorr+xscale*xmax; xmean]; yb = [yb; bpos(4)-yscale*ymax-ycorr; ymean]; xb = [xb; bpos(1)+xcorr+xscale*xmin]; yb = [yb; bpos(4)-yscale*ymin-ycorr]; Varout.hdl(idx_line) = plot3([xmean xmean],[ymean ymean],[zlevel,sij(idx_line)],'k:'); elseif strcmp(bmask,'Syn') && (type == 4 || type == 5) idx_gen = idx_gen + 1; xb = [xb; bpos(1)+xcorr+xscale*xmax; xmean]; yb = [yb; bpos(4)-yscale*ymax-ycorr; ymean]; xb = [xb; bpos(1)+xcorr+xscale*xmin]; yb = [yb; bpos(4)-yscale*ymin-ycorr]; switch type case 4 zpeak = 180*DAE.x(Syn.delta(idx_gen))/pi; case 5 zpeak = DAE.x(Syn.omega(idx_gen)); end Varout.hdl(idx_gen) = plot3([xmean xmean],[ymean ymean], ... [zlevel,zpeak],'k:'); end switch borien case 'right' len = yscale*(ymax-ymin); if bin, in_off = len/bin; end if bou, ou_off = len/bou; end for j = 1:bin yi = bpos(4)-ycorr-yscale*ymin-in_off/2-in_off*(j-1); xi = bpos(1)+xcorr+xscale*xmin; [yf,xf] = closerline(yi,xi-5,yl,xl); plot3([xi, xf],[yf, yf],[zlevel, zlevel],'k') end for j = 1:bou yi = bpos(4)-ycorr-yscale*ymin-ou_off/2-ou_off*(j-1); xi = bpos(1)+xcorr+xscale*xmax; [yf,xf] = closerline(yi,xi+5,yl,xl); plot3([xi, xf],[yf, yf],[zlevel, zlevel],'k') end case 'left' len = yscale*(ymax-ymin); if bin, in_off = len/bin; end if bou, ou_off = len/bou; end for j = 1:bin yi = bpos(4)-ycorr-yscale*ymin-in_off/2-in_off*(j-1); xi = bpos(1)+xcorr+xscale*xmax; [yf,xf] = closerline(yi,xi+5,yl,xl); plot3([xi, xf],[yf, yf],[zlevel, zlevel],'k') end for j = 1:bou yi = bpos(4)-ycorr-yscale*ymin-ou_off/2-ou_off*(j-1); xi = bpos(1)+xcorr+xscale*xmin; [yf,xf] = closerline(yi,xi-5,yl,xl); plot3([xi, xf],[yf, yf],[zlevel, zlevel],'k') end case 'up' len = xscale*(xmax-xmin); if bin, in_off = len/bin; end if bou, ou_off = len/bou; end for j = 1:bin yi = bpos(4)-ycorr-yscale*ymin; xi = bpos(1)+xcorr+xscale*xmin+in_off/2+in_off*(j-1); [xf,yf] = closerline(xi,yi+5,xl,yl); plot3([xf, xf],[yi, yf],[zlevel, zlevel],'k') end for j = 1:bou yi = bpos(4)-ycorr-yscale*ymax; xi = bpos(1)+xcorr+xscale*xmin+ou_off/2+ou_off*(j-1); [xf,yf] = closerline(xi,yi-5,xl,yl); plot3([xf, xf],[yi, yf],[zlevel, zlevel],'k') end case 'down' len = xscale*(xmax-xmin); if bin, in_off = len/bin; end if bou, ou_off = len/bou; end for j = 1:bin yi = bpos(4)-ycorr-yscale*ymax; xi = bpos(1)+xcorr+xscale*xmin+in_off/2+in_off*(j-1); [xf,yf] = closerline(xi,yi-5,xl,yl); plot3([xf, xf],[yi, yf],[zlevel, zlevel],'k') end for j = 1:bou yi = bpos(4)-ycorr-yscale*ymin; xi = bpos(1)+xcorr+xscale*xmin+ou_off/2+ou_off*(j-1); [xf,yf] = closerline(xi,yi+5,xl,yl); plot3([xf, xf],[yi, yf],[zlevel, zlevel],'k') end end for j = 1:length(x) z = zlevel*ones(length(x{j}),1); xx = bpos(1)+xcorr+xscale*(x{j}); yy = bpos(4)-yscale*(y{j})-ycorr; if ~type if ~isempty(xx) x_max = max(x_max,max(xx)); x_min = min(x_min,min(xx)); end if ~isempty(yy) y_max = max(y_max,max(yy)); y_min = min(y_min,min(yy)); end end plot3(xx,yy,z,s{j}) end x1 = [xlim]'; x2 = [ylim]'; x1mean = 0.5*(x1(1)+x1(2)); x2mean = 0.5*(x2(1)+x2(2)); xba = [xb;x1(1);x1(1);x1(2);x1(2);x1mean;x1mean;x1(1);x1(2)]; yba = [yb;x2(1);x2(2);x2(1);x2(2);x2(1);x2(2);x2mean;x2mean]; Varout.xb = xba; Varout.yb = yba; end if ~type % draw only one-line diagram xframe = 0.05*(x_max-x_min); yframe = 0.05*(y_max-y_min); set(hdla,'XLim',[x_min-xframe, x_max+xframe],'YLim',[y_min-yframe, y_max+yframe]) hold off return end x1 = [xlim]'; x2 = [ylim]'; switch type case 1 zb = formz(DAE.y(Bus.v),Bus.n); if abs(mean(DAE.y(Bus.v))-1) < 1e-3 zba = [zb; 0.9999*ones(8,1)]; else zba = [zb; ones(8,1)]; end case 2 zb = formz(180*DAE.y(Bus.a)/pi,Bus.n); zba = [zb; mean(180*DAE.y(Bus.a)/pi)*ones(8,1)]; case 3 [sij,sji] = flows_line(Line,3); zb = formz(sij,Line.n); zba = [zb; mean(sij)*ones(8,1)]; case 4 zb = formz(180*DAE.x(Syn.delta)/pi,Syn.n); zba = [zb; mean(180*DAE.x(Syn.delta)/pi)*ones(8,1)]; case 5 zb = formz(DAE.x(Syn.omega),Syn.n); zba = [zb; 0.999*ones(8,1)]; case 6 zb = formz(LMP,Bus.n); zba = [zb; mean(LMP)*ones(8,1)]; case 7 zb = formz(NCP,Bus.n); zba = [zb; mean(NCP)*ones(8,1)]; end [XX,YY] = meshgrid(x1(1):5:x1(2),x2(1):5:x2(2)); if length(zba) > length(Varout.xb) zba = zba(1:length(Varout.xb)); elseif length(zba) < length(Varout.xb) zba = [zba, ones(1, length(Varout.xb)-length(zba))]; end ZZ = griddata(Varout.xb,Varout.yb,zba,XX,YY,'cubic'); if method zlevel = Varout.zlevel; switch type case 1 for i = 1:Bus.n set(Varout.hdl(i),'ZData',[zlevel,DAE.y(Bus.v(i))]); end case 2 for i = 1:Bus.n set(Varout.hdl(i),'ZData',[zlevel,180*DAE.y(Bus.a(i))/pi]); end case 3 [sij,sji] = flows_line(Line,3); for i = 1:Line.n set(Varout.hdl(i),'ZData',[zlevel,sij(i)]); end case 4 for i = 1:Syn.n set(Varout.hdl(i),'ZData',[zlevel,180*DAE.x(Syn.delta(i))/pi]); end case 5 for i = 1:Syn.n set(Varout.hdl(i),'ZData',[zlevel,zlevel,DAE.x(Syn.omega(i))]); end case 6 for i = 1:Bus.n set(Varout.hdl(i),'ZData',[zlevel,zlevel,LMP(i)]); end case 7 for i = 1:Bus.n set(Varout.hdl(i),'ZData',[zlevel,zlevel,NCP(i)]); end end delete(Varout.surf) if strcmp(Settings.xlabel,'Loading Parameter \lambda (p.u.)') xlabel([Settings.xlabel,' = ',sprintf('%8.4f',DAE.lambda)]) else xlabel([Settings.xlabel,' = ',sprintf('%8.4f',DAE.t)]) end Varout.surf = surf(XX,YY,ZZ); alpha(Varout.alpha) shading interp axis manual Varout.movie(end+1) = getframe(findobj(Fig.threed,'Tag','Axes1')); %Varout.movie(end+1) = getframe(Fig.threed); else if type == 1 && Varout.caxis caxis([0.9 1.1]) else caxis('auto') end Varout.surf = surf(XX,YY,ZZ); axis auto shading interp alpha(Varout.alpha) xlabel('') % if Settings.hostver < 8.04 % set(gca,'YDir','reverse') % end set(gca,'YDir','reverse') % set(gca,'XDir','reverse') % set(gca) set(gca,'XTickLabel',[]) set(gca,'YTickLabel',[]) set(gca,'XTick',[]) set(gca,'YTick',[]) switch type case 1 zlabel('Voltage Magnitudes [p.u.]') case 2 zlabel('Voltage Angles [deg]') case 3 zlabel('Line Flows [p.u.]') case 4 zlabel('Gen. Rotor Angles [deg]') case 5 zlabel('Gen. Rotor Speeds [p.u.]') case 6 zlabel('Locational Marginal Prices [$/MWh]') case 7 zlabel('Nodal Congestion Prices [$/MWh]') end colormap(maps{maptype}) colorbar('EastOutside') xlim(x1) box on end hold off case 'VoltageReport' busidx = find(strcmp(masks,'Bus')); for i = 1:Bus.n valore = ['|V| = ', ... fvar(DAE.y(i+Bus.n),7), ... ' p.u.\n<V = ', ... fvar(DAE.y(i),7), ... ' rad ']; set_param(blocks(busidx(i)),'AttributesFormatString',valore); end case 'WipeVoltageReport' busidx = find(strcmp(masks,'Bus')); for i = 1:Bus.n, set_param(blocks(busidx(i)),'AttributesFormatString',''); end case 'PowerFlowReport' simrep_line(Line, blocks, masks, lines) simrep_hvdc(Hvdc, blocks, masks, lines) simrep_ltc(Ltc, blocks, masks, lines) simrep_phs(Phs, blocks, masks, lines) simrep_lines(Lines, blocks, masks, lines) simrep_tg(Tg, blocks, masks, lines) simrep_exc(Exc, blocks, masks, lines) simrep_oxl(Oxl, blocks, masks, lines) simrep_pss(Pss, blocks, masks, lines) simrep_syn(Syn, blocks, masks, lines) simrep_pq(PQ, blocks, masks, lines) simrep_pv(PV, blocks, masks, lines) simrep_sw(SW, blocks, masks, lines) %for i = 1:Comp.n % simrep(eval(Comp.names{i},blocks,masks,lines) %end case 'WipePowerFlowReport' for i = 1:length(lines) set_param(lines(i),'Name','') end case 'HideNames' nobusidx = find(~strcmp(masks,'Bus')); for i = 1:length(nobusidx) set_param(blocks(nobusidx(i)),'ShowName','off') end nobusidx = find(strcmp(masks,'')); for i = 1:length(nobusidx) set_param(blocks(nobusidx(i)),'ShowName','on') end case 'ShowNames' for i = 1:nblock set_param(blocks(i),'ShowName','on') end case 'HideBusNames' busidx = find(strcmp(masks,'Bus')); for i = 1:Bus.n set_param(blocks(busidx(i)),'ShowName','off') end case 'ShowBusNames' busidx = find(strcmp(masks,'Bus')); for i = 1:Bus.n set_param(blocks(busidx(i)),'ShowName','on') end case 'FontType' for i = 1:nblock set_param(blocks(i),'FontName',fontname) end for i = 1:length(lines) set_param(lines(i),'FontName',fontname) end case 'FontSize' for i = 1:nblock, set_param(blocks(i),'FontSize',fontsize); end for i = 1:length(lines), set_param(lines(i),'FontSize',fontsize); end case 'mdl2eps' % fontsize == 0: export to color eps % fontsize == 1: export to grey-scale eps grey_eps = fontsize; pat = '^/c\d+\s\{.* sr\} bdef'; cd(Path.data) fileeps = [filedata,'.eps']; a = dir(fileeps); Settings.ok = 1; if ~isempty(a) uiwait(fm_choice(['Overwrite "',fileeps,'" ?'])) end if ~Settings.ok, return, end orient portrait print('-s','-depsc',fileeps) if ~Settings.noarrows cd(Path.local) fm_disp(['PSAT model saved in ',Path.data,fileeps]) return end file = textread(fileeps,'%s','delimiter','\n'); idx = []; d2 = zeros(1,4); for i = 1:length(file) if grey_eps && ~isempty(regexp(file{i},pat)) matchexp = regexp(file{i},'^/c\d+\s\{','match'); colors = strrep(file{i},matchexp{1},'['); colors = regexprep(colors,' sr\} bdef',']'); rgb = sum(str2num(colors)); colors = num2str([rgb rgb rgb]/3); file{i} = [matchexp{1},colors,' sr} bdef']; end if strcmp(file{i},'PP') if strcmp(file{i-1}(end-1:end),'MP') d1 = str2num(strrep(file{i-1},'MP','')); if length(d1) >= 6 if ~d1(3) d2(2) = d1(6)-d1(2); d2(4) = d1(6)-d1(2); d2(1) = d1(5)-d1(2); d2(3) = d1(5)+d1(1); else d2(2) = d1(6)+d1(2); d2(4) = d1(6)-d1(1); d2(1) = d1(5)-d1(1); d2(3) = d1(5)-d1(1); end file{i-1} = sprintf('%4d %4d mt %4d %4d L',d2); idx = [idx, i]; end end end if ~isempty(findstr(file{i}(max(1,end-1):end),'PO')) d1 = str2num(strrep(file{i},'PO','')); if ~isempty(findstr(file{i+1},'L')) nextline = strrep(file{i+1},'L',''); d2 = str2num(strrep(nextline,'mt','')); if d1(4) == d2(2) if d2(1) > d1(3); d2(1) = d1(3)-d1(1); else d2(1) = d2(1)+d1(1)+abs(d1(3)-d2(1)); end else if d2(2) > d1(4) d2(2) = d1(4)-d1(2); else d2(2) = d2(2)+d1(2)+abs(d1(4)-d2(2)); end end file{i+1} = sprintf('%4d %4d mt %4d %4d L',d2); elseif ~isempty(findstr(file{i+2},'MP stroke')) d2 = str2num(strrep(file{i+2},'MP stroke','')); if d2(1) d2(3) = d2(3)-d2(1); if d2(1) < 0 d2(3) = d2(3) - 4; end end if d2(2) d2(4) = d2(4)-d2(2); if d2(2) < 0 d2(4) = d2(4) - 4; end end file{i+1} = sprintf('%4d %4d %4d %4d %4d MP stroke',d2); end idx = [idx, i]; end end file(idx) = []; fid = fopen(fileeps,'wt+'); for i = 1:length(file) fprintf(fid,'%s\n',file{i}); end fclose(fid); cd(Path.local) fm_disp(['PSAT model saved in ',Path.data,fileeps]) otherwise fm_disp('Unknown command for Simulink Settings GUI...',2) end cd(Path.local) % ------------------------------------------------------------------------- function [xa,ya] = closerline(xa,ya,xl,yl) [err,idx] = min(abs(sqrt((xl-xa).^2+(yl-ya).^2))); if err < 15 xa = xl(idx); ya = yl(idx); end % ------------------------------------------------------------------------- function zb = formz(vec,n) zb = zeros(3*n,1); zb(1:3:3*n) = vec; zb(2:3:3*n) = vec; zb(3:3:3*n) = vec;
github
Sinan81/PSAT-master
fm_view.m
.m
PSAT-master/psat-oct/psat/fm_view.m
2,820
utf_8
c358f5ce2a57ece7f7b1352a891545bc
function fm_view(flag) % FM_VIEW functions for matrix visualizations % % FM_VIEW(FLAG) % FLAG matrix visualization type % %see also FM_MATRX % %Author: Federico Milano %Date: 11-Nov-2002 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global DAE Bus Theme Line if isempty(Bus.con) fm_disp('No loaded system. Matrix visualization cannot be run.',2) return end switch flag case 1 if DAE.n > 0 matrice = [DAE.Fx, DAE.Fy; DAE.Gx, DAE.Gy]; else fm_disp('Since no dynamic component is loaded, AC coincides with Jlfv.',2) matrice = DAE.Gy; end titolo = 'Complete System Matrix A_c'; visual(matrice,titolo) case 2 if DAE.n > 0 matrice = DAE.Fx - DAE.Fy*inv(DAE.Gy)*DAE.Gx; else fm_disp('No dynamic component loaded.',2); return end titolo = 'State jacobian matrix A_s'; visual(matrice,titolo) case 3 matrice = build_gy_line(Line); titolo = 'Jacobian matrix J_l_f'; visual(matrice,titolo) case 4 matrice = DAE.Gy; titolo = 'Jacobian matrix J_l_f_v'; visual(matrice,titolo) case 5 if DAE.n > 0 Fx_mod = DAE.Fx+diag(-1e-5*ones(DAE.n,1)); matrice = DAE.Gy - DAE.Gx*inv(Fx_mod)*DAE.Fy; else fm_disp(['Since no dynamic component is loaded, ', ... 'Jlfd coincides with Jlfv.'],2) matrice = DAE.Gy; end titolo = 'Jacobian matrix J_l_f_d'; visual(matrice,titolo) case 6 ch(1) = findobj(gcf,'Tag','toggle1'); ch(2) = findobj(gcf,'Tag','toggle2'); ch(3) = findobj(gcf,'Tag','toggle3'); ch(4) = findobj(gcf,'Tag','toggle4'); ca = find(ch == gcbo); vals = zeros(4,1); vals(ca) = 1; for i = 1:4, set(ch(i),'Value',vals(i)); end hdl = findobj(gcf,'Tag','toggle5'); if ca == 3 set(hdl,'Enable','off'); else set(hdl,'Enable','on'); end end %====================================================================== function visual(matrice,titolo) global DAE Theme ch(1) = findobj(gcf,'Tag','toggle1'); ch(2) = findobj(gcf,'Tag','toggle2'); ch(3) = findobj(gcf,'Tag','toggle3'); ch(4) = findobj(gcf,'Tag','toggle4'); vals = get(ch,'Value'); for i = 1:4, valn(i) = vals{i}; end tre_d = find(valn); switch tre_d case 1 surf(full(matrice)); shading('interp') case 2 mesh(full(matrice)); case 3 rotate3d off hdl = findobj(gcf,'Tag','toggle5'); set(hdl,'Value',0); spy(matrice); if flag == 1 hold on plot([0,DAE.n+DAE.m+2],[DAE.n+0.5,DAE.n+0.5],'k:'); plot([DAE.n+0.5,DAE.n+0.5],[0,DAE.n+DAE.m+2],'k:'); hold off end case 4 surf(full(matrice)); end hdl = findobj(gcf,'Tag','toggle6'); if get(hdl,'Value'), grid on, else grid off, end hdl = findobj(gcf,'Tag','toggle7'); if get(hdl,'Value'), zoom on, else zoom off, end set(gca,'Color',Theme.color11); title(titolo);
github
Sinan81/PSAT-master
fm_int.m
.m
PSAT-master/psat-oct/psat/fm_int.m
10,809
utf_8
443bd8a1f81900e735f551ea9393566f
function fm_int % FM_INT time domain integration routines: % 1 - Forward Euler % 2 - Trapezoidal Method % % FM_INT % %see also FM_TSTEP, FM_OUT and the Settings structure % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 16-Jan-2003 %Update: 27-Feb-2003 %Update: 01-Aug-2003 %Update: 11-Sep-2003 %Version: 1.0.4 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Fig Settings Snapshot Hdl global Bus File DAE Theme OMIB global SW PV PQ Fault Ind global Varout Breaker Line Path clpsat if ~autorun('Time Domain Simulation',1), return, end tic % initial messages % ----------------------------------------------------------------------- fm_disp if DAE.n == 0 && ~clpsat.init Settings.ok = 0; uiwait(fm_choice('No dynamic component is loaded. Continue anyway?',1)) if ~Settings.ok fm_disp('Time domain simulation aborted.',2) return end end fm_disp('Time domain simulation') switch Settings.method case 1, fm_disp('Implicit Euler integration method') case 2, fm_disp('Trapezoidal integration method') end fm_disp(['Data file "',Path.data,File.data,'"']) if ~isempty(Path.pert), fm_disp(['Perturbation file "',Path.pert,File.pert,'"']) end if (strcmp(File.pert,'pert') && strcmp(Path.pert,Path.psat)) || ... isempty(File.pert) fm_disp('No perturbation file set.',1) end if ishandle(Fig.main) hdl = findobj(Fig.main,'Tag','PushClose'); set(hdl,'String','Stop'); set(Fig.main,'UserData',1); end if Settings.plot if Settings.plottype == 1 && ~DAE.n Settings.plottype = 2; fm_disp('Cannot plot state variables (dynamic order = 0).') fm_disp('Bus voltages will be plotted during the TD simulation.') end maxlegend = min(Bus.n,7); switch Settings.plottype case 1 maxlegend = min(DAE.n,7); idx0 = 0; case 2 idx0 = DAE.n; case 3 idx0 = DAE.n+Bus.n; case 4 idx0 = DAE.n+DAE.m; case 5 idx0 = DAE.n+DAE.m+Bus.n; case 6 maxlegend = 3; idx0 = DAE.n+DAE.m+2*Bus.n; end end % check settings % ------------------------------------------------------------------ iter_max = Settings.dynmit; tol = Settings.dyntol; Dn = 1; if DAE.n, Dn = DAE.n; end identica = speye(max(Dn,1)); if (Fault.n || Breaker.n) && PQ.n && ~Settings.pq2z if clpsat.init if clpsat.pq2z Settings.pq2z = 1; else Settings.pq2z = 0; end elseif ~Settings.donotask uiwait(fm_choice(['Convert (recommended) PQ loads to constant impedances?'])) if Settings.ok Settings.pq2z = 1; else Settings.pq2z = 0; end end end % convert PQ loads to shunt admittances (if required) PQ = pqshunt_pq(PQ); % set up variables % ---------------------------------------------------------------- DAE.t = Settings.t0; fm_call('i'); DAE.tn = DAE.f; if isempty(DAE.tn), DAE.tn = 0; end % graphical settings % ---------------------------------------------------------------- plot_now = 0; if ~clpsat.init || ishandle(Fig.main) if Settings.plot if ishandle(Fig.plot) figure(Fig.plot); else fm_plotfig; end elseif Settings.status fm_bar('open') fm_simtd('init') idxo = 0; else fm_disp(['t = ',num2str(Settings.t0),' s'],3) perc = 0; perc_old = 0; end drawnow end % ---------------------------------------------------------------- % initializations % ---------------------------------------------------------------- t = Settings.t0; k = 1; h = fm_tstep(1,1,0,Settings.t0); inc = zeros(Dn+DAE.m,1); callpert = 1; % get initial network connectivity fm_flows('connectivity', 'verbose'); % output initialization fm_out(0,0,0); fm_out(2,Settings.t0,k); % time vector of snapshots, faults and breaker events fixed_times = []; n_snap = length(Snapshot); if n_snap > 1 && ~Settings.locksnap snap_times = zeros(n_snap-1,1); for i = 2:n_snap snap_times(i-1,1) = Snapshot(i).time; end fixed_times = [fixed_times; snap_times]; end fixed_times = [fixed_times; gettimes_fault(Fault); ... gettimes_breaker(Breaker); gettimes_ind(Ind)]; fixed_times = sort(fixed_times); % compute max rotor angle difference diff_max = anglediff; % ================================================================ % ---------------------------------------------------------------- % Main loop % ---------------------------------------------------------------- % ================================================================ inc = zeros(Dn+DAE.m,1); while (t < Settings.tf) && (t + h > t) && ~diff_max if ishandle(Fig.main) if ~get(Fig.main,'UserData'), break, end end if (t + h > Settings.tf), h = Settings.tf - t; end actual_time = t + h; % check not to jump disturbances index_times = find(fixed_times > t & fixed_times < t+h); if ~isempty(index_times); actual_time = min(fixed_times(index_times)); h = actual_time - t; end % set global time DAE.t = actual_time; % backup of actual variables if isempty(DAE.x), DAE.x = 0; end xa = DAE.x; ya = DAE.y; % initialize NR loop iterazione = 1; inc(1) = 1; if isempty(DAE.f), DAE.f = 0; end fn = DAE.f; % applying faults, breaker interventions and perturbations if ~isempty(fixed_times) if ~isempty(find(fixed_times == actual_time)) Fault = intervention_fault(Fault,actual_time); Breaker = intervention_breaker(Breaker,actual_time); end end if callpert try if Settings.hostver >= 6 feval(Hdl.pert,actual_time); else if ~isempty(Path.pert) cd(Path.pert) feval(Hdl.pert,actual_time); cd(Path.local) end end catch fm_disp('* * Something wrong in the perturbation file:') fm_disp(lasterr) fm_disp('* * The perturbation file will be discarded.') callpert = 0; end end % Newton-Raphson loop Settings.error = tol+1; while Settings.error > tol if (iterazione > iter_max), break, end drawnow if ishandle(Fig.main) if ~get(Fig.main,'UserData'), break, end end % DAE equations fm_call('i'); % complete Jacobian matrix DAE.Ac switch Settings.method case 1 % Forward Euler DAE.Ac = [identica - h*DAE.Fx, -h*DAE.Fy; DAE.Gx, DAE.Gy]; DAE.tn = DAE.x - xa - h*DAE.f; case 2 % Trapezoidal Method DAE.Ac = [identica - h*0.5*DAE.Fx, -h*0.5*DAE.Fy; DAE.Gx, DAE.Gy]; DAE.tn = DAE.x - xa - h*0.5*(DAE.f + fn); end % Non-windup limiters fm_call('5'); inc = -DAE.Ac\[DAE.tn; DAE.g]; %inc = -umfpack(DAE.Ac,'\',[DAE.tn; DAE.g]); DAE.x = DAE.x + inc(1:Dn); DAE.y = DAE.y + inc(1+Dn: DAE.m+Dn); iterazione = iterazione + 1; Settings.error = max(abs(inc)); end if (iterazione > iter_max) h = fm_tstep(2,0,iterazione,t); DAE.x = xa; DAE.y = ya; DAE.f = fn; else h = fm_tstep(2,1,iterazione,t); t = actual_time; k = k+1; % extend output stack if k > length(Varout.t), fm_out(1,t,k); end % ---------------------------------------------------------------- % ---------------------------------------------------------------- % update output variables, snapshots and network visualisation % ---------------------------------------------------------------- % ---------------------------------------------------------------- fm_out(2,t,k); % plot variables & display iteration status % ---------------------------------------------------------------- i_plot = 1+k-10*fix(k/10); perc = (t-Settings.t0)/(Settings.tf-Settings.t0); if i_plot == 10 fm_disp([' > Simulation time = ',num2str(DAE.t), ... ' s (',num2str(round(perc*100)),'%)']) end if ~clpsat.init || ishandle(Fig.main) if Settings.plot if i_plot == 10 plot(Varout.t(1:k),Varout.vars(1:k,idx0+[1:maxlegend])); set(gca,'Color',Theme.color11); xlabel('time (s)') drawnow end elseif Settings.status idx = (t-Settings.t0)/(Settings.tf-Settings.t0); fm_bar([idxo,idx]) if i_plot == 10, fm_simtd('update'), end idxo = idx; end end % fill up snapshots if n_snap > 1 && ~Settings.locksnap snap_i = find(snap_times == t)+1; fm_snap('assignsnap',snap_i); end end % compute max rotor angle difference diff_max = anglediff; end if Settings.status && ~Settings.plot fm_bar('close') fm_simtd('update') end if ~DAE.n, DAE.x = []; DAE.f =[]; end % final messages % ----------------------------------------------------------------------- if ishandle(Fig.main) if diff_max && get(Fig.main,'UserData') fm_disp(['Rotor angle max difference is > ', ... num2str(Settings.deltadelta), ... ' deg. Simulation stopped at t = ', ... num2str(t), ' s'],2); elseif (t < Settings.tf) && get(Fig.main,'UserData') fm_disp(['Singularity likely. Simulation stopped at t = ', ... num2str(t), ' s'],2); elseif ~get(Fig.main,'UserData') fm_disp(['Dynamic Simulation interrupted at t = ',num2str(t),' s'],2) else fm_disp(['Dynamic Simulation completed in ',num2str(toc),' s']); end else if diff_max fm_disp(['Rotor angle max difference is > ', ... num2str(Settings.deltadelta), ... ' deg. Simulation stopped at t = ', ... num2str(t), ' s'],2); elseif (t < Settings.tf) fm_disp(['Singularity likely. Simulation stopped at t = ', ... num2str(t), ' s'],2); else fm_disp(['Dynamic Simulation completed in ',num2str(toc),' s']); end end % resize output varibales & final settings % ----------------------------------------------------------------------- fm_out(3,t,k); if Settings.beep, beep, end Settings.xlabel = 'time (s)'; if ishandle(Fig.plot), fm_plotfig, end % future simulations do not need LF computation Settings.init = 2; SNB.init = 0; LIB.init = 0; CPF.init = 0; OPF.init = 0; if ishandle(Fig.main), set(hdl,'String','Close'); end DAE.t = -1; % reset global time % compute delta difference at each step % ----------------------------------------------------------------------- function diff_max = anglediff global Settings Syn Bus DAE SW OMIB diff_max = 0; if ~Settings.checkdelta, return, end if ~Syn.n, return, end delta = DAE.x(Syn.delta); [idx,ia,ib] = intersect(Bus.island,getbus_syn(Syn)); if ~isempty(idx), delta(ib) = []; end if isscalar(delta) delta = [delta; DAE.y(SW.refbus)]; end delta_diff = abs(delta-min(delta)); diff_max = (max(delta_diff)*180/pi) > Settings.deltadelta; if diff_max, return, end % check transient stability %fm_omib %if abs(OMIB.margin) > 1e-2 % fm_disp(['* * Transient stability margin: ',num2str(OMIB.margin)]) %end
github
Sinan81/PSAT-master
fm_writetex.m
.m
PSAT-master/psat-oct/psat/fm_writetex.m
5,097
utf_8
2a8467ad574f2e808e3e851821c9a981
function fm_writetex(Matrix,Header,Cols,Rows,File) % FM_WRITETEX export PSAT results in LaTeX2e format. % % FM_WRITETEX(MATRIX,HEDAER,COLNAMES,ROWNAMES,FILENAME) % % MATRIX Matrix to write to file % Cell array for multiple matrices. % HEADER String of header information. % Cell array for multiple header. % COLNAMES (Cell array of strings) Column headers. % One cell element per column. % ROWNAMES (Cell array of strings) Row headers. % One cell element per row. % FILENAME (string) Name of TeX file. % If not specified, contents will be % opened in the current selected text % viewer. % %Author: Federico Milano %Date: 15-Sep-2003 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Path if ~iscell(Matrix) Matrix{1,1} = Matrix; Header{1,1} = Header; Cols{1,1} = Cols; Rows{1,1} = Rows; end % -------------------------------------------------------------------- % opening text file % -------------------------------------------------------------------- fm_disp fm_disp('Writing the report LaTeX2e file...') [fid,msg] = fopen([Path.data,File], 'wt'); if fid == -1 fm_disp(msg) return end path_lf = strrep(Path.data,'\','\\'); % -------------------------------------------------------------------- % writing data % -------------------------------------------------------------------- nhr = 0; idx_table = 0; for i_matrix = 1:length(Matrix) m = Matrix{i_matrix}; colnames = Cols{i_matrix}; rownames = Rows{i_matrix}; header = Header{i_matrix}; if isempty(colnames) && isempty(rownames) && isempty(m) % treat header as comment if ~isempty(header) if iscell(header) for ii = 1:length(header) count = fprintf(fid,'%% %s\n',specialchar(header{ii})); end else count = fprintf(fid,'%% %s\n',specialchar(header)); end end else % create table idx_table = idx_table + 1; % print the preamble of the table % see Leslie Lamport's LATEX book for details. % open the table environment as a floating body fprintf(fid, '\\begin{table}[htbp] \n'); fprintf(fid, ' \\begin{center} \n'); % Write header % ------------------------------------------------------------------ caption = ''; if iscell(header) for ii = 1:length(header) caption = [caption,' ',header{ii}]; end else caption = [caption,header]; end caption = specialchar(caption); %% include the user-defined or default caption fprintf(fid, ' \\caption{%s} \n', caption); count = fprintf(fid,' \\vspace{0.1cm}\n'); % Write column names % ------------------------------------------------------------------ if nargin > 2 && ~isempty(colnames) [nrows,ncolnames] = size(colnames); tt = '|'; for ii = 1:ncolnames tt = [tt,'c|']; end fprintf(fid, ' \\begin{tabular}{%s} \n', tt); fprintf(fid, ' \\hline \n'); for jj = 1:nrows fprintf(fid, ' '); for ii = 1:ncolnames-1 count = fprintf(fid, '%s & ', specialchar(colnames{jj,ii})); end count = fprintf(fid, '%s \\\\\n', specialchar(colnames{jj,ncolnames})); end count = fprintf(fid,' \\hline \\hline \n'); end % Write data % ------------------------------------------------------------------ if nargin > 3 && ~isempty(rownames) [nrownames,ncols] = size(rownames); ndata = size(m,2); if isempty(colnames) tt = '|'; for ii = 1:(ncols+ndata) tt = [tt,'c|']; end fprintf(fid, ' \\begin{tabular}{%s} \n', tt); fprintf(fid, ' \\hline \n'); end for ii = 1:nrownames fprintf(fid, ' '); for jj = 1:ncols count = fprintf(fid, '%s & ', specialchar(rownames{ii,jj})); end for hh = 1:ndata-1 count = fprintf(fid, '$%8.5f$ & ', m(ii,hh)); end count = fprintf(fid, '$%8.5f$ \\\\ \\hline \n', m(ii,ndata)); end end %% print the footer of the table environment fprintf(fid, ' \\end{tabular} \n'); %% include the user-defined or default label fprintf(fid, ' \\label{%s} \n', ... ['tab:',strrep(File,'.tex',''),'_',num2str(idx_table)]); fprintf(fid, ' \\end{center} \n'); %% close the table environment and return fprintf(fid, '\\end{table} \n'); end count = fprintf(fid,'\n'); end fclose(fid); fm_disp(['Report of Static Results saved in ',File]) % view file fm_text(13,[Path.data,File]) % ------------------------------------------------------- % check for special LaTeX2e character % ------------------------------------------------------- function string = specialchar(string) string = [lower(strrep(string,'#','\#')),' ']; string = strrep(string,'&','\&'); string = strrep(string,'_','\_'); string = strrep(string,'$','\$'); string = strrep(string,'{','\{'); string = strrep(string,'}','\}'); string = strrep(string,'%','\%'); string = strrep(string,'~','$\sim$'); string(1) = upper(string(1));