MATPOWER Manual.pdf

140
Matpower 5.0b1 User’s Manual Ray D. Zimmerman Carlos E. Murillo-S´anchez July 1, 2014 © 2010, 2011, 2012, 2013, 2014 Power Systems Engineering Research Center (Pserc) All Rights Reserved

Transcript of MATPOWER Manual.pdf

Matpower 5.0b1Users ManualRayD.Zimmerman CarlosE.Murillo-SanchezJuly1,20142010,2011,2012,2013,2014PowerSystemsEngineeringResearchCenter(Pserc)AllRightsReservedContents1 Introduction 81.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.2 LicenseandTermsofUse . . . . . . . . . . . . . . . . . . . . . . . . 81.3 CitingMatpower . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 GettingStarted 102.1 SystemRequirements. . . . . . . . . . . . . . . . . . . . . . . . . . . 102.2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.3 RunningaSimulation . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.3.1 PreparingCaseInputData . . . . . . . . . . . . . . . . . . . . 122.3.2 SolvingtheCase . . . . . . . . . . . . . . . . . . . . . . . . . 122.3.3 AccessingtheResults. . . . . . . . . . . . . . . . . . . . . . . 132.3.4 SettingOptions . . . . . . . . . . . . . . . . . . . . . . . . . . 142.4 Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 Modeling 173.1 DataFormats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173.2 Branches. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173.3 Generators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193.4 Loads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193.5 ShuntElements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193.6 NetworkEquations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203.7 DCModeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204 PowerFlow 244.1 ACPowerFlow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244.2 DCPowerFlow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264.3 runpf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264.4 LinearShiftFactors. . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 ContinuationPowerFlow 305.1 Parameterization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315.2 Predictor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315.3 Corrector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325.4 Steplengthcontrol . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325.5 runcpf. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3326 OptimalPowerFlow 396.1 StandardACOPF . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396.2 StandardDCOPF . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406.3 ExtendedOPFFormulation . . . . . . . . . . . . . . . . . . . . . . . 416.3.1 User-denedCosts . . . . . . . . . . . . . . . . . . . . . . . . 416.3.2 User-denedConstraints . . . . . . . . . . . . . . . . . . . . . 436.3.3 User-denedVariables . . . . . . . . . . . . . . . . . . . . . . 436.4 StandardExtensions . . . . . . . . . . . . . . . . . . . . . . . . . . . 446.4.1 PiecewiseLinearCosts . . . . . . . . . . . . . . . . . . . . . . 446.4.2 DispatchableLoads . . . . . . . . . . . . . . . . . . . . . . . . 456.4.3 GeneratorCapabilityCurves. . . . . . . . . . . . . . . . . . . 476.4.4 BranchAngleDierenceLimits . . . . . . . . . . . . . . . . . 486.5 Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486.6 runopf. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497 ExtendingtheOPF 547.1 DirectSpecication. . . . . . . . . . . . . . . . . . . . . . . . . . . . 547.2 CallbackFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557.2.1 ext2intCallback. . . . . . . . . . . . . . . . . . . . . . . . . 567.2.2 formulationCallback . . . . . . . . . . . . . . . . . . . . . . 587.2.3 int2extCallback. . . . . . . . . . . . . . . . . . . . . . . . . 607.2.4 printpfCallback. . . . . . . . . . . . . . . . . . . . . . . . . 627.2.5 savecaseCallback . . . . . . . . . . . . . . . . . . . . . . . . 657.3 RegisteringtheCallbacks . . . . . . . . . . . . . . . . . . . . . . . . . 677.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697.5 ExampleExtensions . . . . . . . . . . . . . . . . . . . . . . . . . . . 697.5.1 FixedZonalReserves . . . . . . . . . . . . . . . . . . . . . . . 697.5.2 InterfaceFlowLimits. . . . . . . . . . . . . . . . . . . . . . . 707.5.3 DCTransmissionLines . . . . . . . . . . . . . . . . . . . . . . 718 UnitDe-commitmentAlgorithm 749 Acknowledgments 75AppendixAMIPSMatlabInteriorPointSolver 76A.1 Example1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79A.2 Example2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80A.3 QuadraticProgrammingSolver . . . . . . . . . . . . . . . . . . . . . 82A.4 Primal-DualInteriorPointAlgorithm. . . . . . . . . . . . . . . . . . 833A.4.1 Notation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83A.4.2 ProblemFormulationandLagrangian. . . . . . . . . . . . . . 84A.4.3 FirstOrderOptimalityConditions . . . . . . . . . . . . . . . 85A.4.4 NewtonStep . . . . . . . . . . . . . . . . . . . . . . . . . . . 85AppendixBDataFileFormat 88AppendixCMatpowerOptions 94C.1 MappingofOld-StyleOptionstoNew-StyleOptions . . . . . . . . . . 107AppendixDMatpowerFilesandFunctions 111D.1 DocumentationFiles . . . . . . . . . . . . . . . . . . . . . . . . . . . 111D.2 MatpowerFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . 111D.3 ExampleMatpowerCases . . . . . . . . . . . . . . . . . . . . . . . 119D.4 AutomatedTestSuite . . . . . . . . . . . . . . . . . . . . . . . . . . 120AppendixE ExtrasDirectory 123AppendixF SmartMarketCode 124F.1 HandlingSupplyShortfall . . . . . . . . . . . . . . . . . . . . . . . . 126F.2 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126F.3 SmartmarketFilesandFunctions . . . . . . . . . . . . . . . . . . . . 130AppendixGOptionalPackages 132G.1 BPMPDMEXMEXinterfaceforBPMPD. . . . . . . . . . . . . . 132G.2 CPLEXHigh-performanceLPandQPSolvers . . . . . . . . . . . . 132G.3 GLPKGNULinearProgrammingKit . . . . . . . . . . . . . . . . 133G.4 GurobiHigh-performanceLPandQPSolvers . . . . . . . . . . . . 134G.5 IpoptInteriorPointOptimizer . . . . . . . . . . . . . . . . . . . . 134G.6 KNITRONon-LinearProgrammingSolver . . . . . . . . . . . . . . 135G.7 MINOPFACOPFSolverBasedonMINOS . . . . . . . . . . . . . 136G.8 MOSEKHigh-performanceLPandQPSolvers . . . . . . . . . . . 136G.9 SDPPFApplicationsof aSemideniteProgrammingRelaxationofthePowerFlowEquations . . . . . . . . . . . . . . . . . . . . . . . . 136G.10 TSPOPFThreeACOPFSolversbyH.Wang . . . . . . . . . . . . 137References 1384ListofFigures3-1 BranchModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185-1 NoseCurveofVoltageMagnitudeatBus9. . . . . . . . . . . . . . . 376-1 Relationshipofwitorifordi= 1(linearoption) . . . . . . . . . . . . 426-2 Relationshipofwitorifordi= 2(quadraticoption) . . . . . . . . . 436-3 ConstrainedCostVariable . . . . . . . . . . . . . . . . . . . . . . . . 446-4 MarginalBenetorBidFunction . . . . . . . . . . . . . . . . . . . . 466-5 TotalCostFunctionforNegativeInjection . . . . . . . . . . . . . . . 466-6 GeneratorP-QCapabilityCurve . . . . . . . . . . . . . . . . . . . . 477-1 AddingConstraintsAcrossSubsetsofVariables . . . . . . . . . . . . 597-2 DCLineModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 727-3 EquivalentDummyGenerators . . . . . . . . . . . . . . . . . . . . 72ListofTables4-1 PowerFlowResults. . . . . . . . . . . . . . . . . . . . . . . . . . . . 274-2 PowerFlowOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . 274-3 PowerFlowOutputOptions . . . . . . . . . . . . . . . . . . . . . . . 285-1 ContinuationPowerFlowResults . . . . . . . . . . . . . . . . . . . . 335-2 ContinuationPowerFlowOptions. . . . . . . . . . . . . . . . . . . . 345-3 ContinuationPowerFlowCallbackArguments . . . . . . . . . . . . . 356-1 OptimalPowerFlowResults. . . . . . . . . . . . . . . . . . . . . . . 506-2 OptimalPowerFlowOptions . . . . . . . . . . . . . . . . . . . . . . 526-3 OPFOutputOptions. . . . . . . . . . . . . . . . . . . . . . . . . . . 537-1 NamesUsedbyImplementationofOPFwithReserves . . . . . . . . 577-2 ResultsforUser-DenedVariables,ConstraintsandCosts . . . . . . . 617-3 CallbackFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697-4 InputDataStructuresforInterfaceFlowLimits . . . . . . . . . . . . 717-5 OutputDataStructuresforInterfaceFlowLimits . . . . . . . . . . . 71A-1 InputArgumentsformips . . . . . . . . . . . . . . . . . . . . . . . . 77A-2 OutputArgumentsformips . . . . . . . . . . . . . . . . . . . . . . . 78B-1 BusData(mpc.bus) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89B-2 GeneratorData(mpc.gen) . . . . . . . . . . . . . . . . . . . . . . . . 90B-3 BranchData(mpc.branch) . . . . . . . . . . . . . . . . . . . . . . . . 91B-4 GeneratorCostData(mpc.gencost) . . . . . . . . . . . . . . . . . . . 92B-5 DCLineData(mpc.dcline) . . . . . . . . . . . . . . . . . . . . . . . 93C-1 Top-LevelOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 965C-2 PowerFlowOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . 97C-3 ContinuationPowerFlowOptions. . . . . . . . . . . . . . . . . . . . 98C-4 GeneralOPFOptions . . . . . . . . . . . . . . . . . . . . . . . . . . 99C-5 PowerFlowandOPFOutputOptions . . . . . . . . . . . . . . . . . 100C-6 OPFOptionsforMIPS. . . . . . . . . . . . . . . . . . . . . . . . . . 101C-7 OPFOptionsforCPLEX . . . . . . . . . . . . . . . . . . . . . . . . 101C-8 OPFOptionsforfmincon . . . . . . . . . . . . . . . . . . . . . . . . 102C-9 OPFOptionsforGLPK . . . . . . . . . . . . . . . . . . . . . . . . . 102C-10 OPFOptionsforGurobi . . . . . . . . . . . . . . . . . . . . . . . . . 103C-11 OPFOptionsforIpopt . . . . . . . . . . . . . . . . . . . . . . . . . 103C-12 OPFOptionsforKNITRO. . . . . . . . . . . . . . . . . . . . . . . . 104C-13 OPFOptionsforMINOPF. . . . . . . . . . . . . . . . . . . . . . . . 104C-14 OPFOptionsforMOSEK . . . . . . . . . . . . . . . . . . . . . . . . 105C-15 OPFOptionsforPDIPM . . . . . . . . . . . . . . . . . . . . . . . . . 106C-16 OPFOptionsforTRALM. . . . . . . . . . . . . . . . . . . . . . . . 106C-17 Old-StyletoNew-StyleOptionMapping . . . . . . . . . . . . . . . . 107D-1 MatpowerDocumentationFiles . . . . . . . . . . . . . . . . . . . . 111D-2 Top-LevelSimulationFunctions . . . . . . . . . . . . . . . . . . . . . 112D-3 Input/OutputFunctions . . . . . . . . . . . . . . . . . . . . . . . . . 112D-4 DataConversionFunctions. . . . . . . . . . . . . . . . . . . . . . . . 112D-5 PowerFlowFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . 113D-6 ContinuationPowerFlowFunctions. . . . . . . . . . . . . . . . . . . 113D-7 OPFandWrapperFunctions . . . . . . . . . . . . . . . . . . . . . . 113D-8 OPFModelObjects . . . . . . . . . . . . . . . . . . . . . . . . . . . 114D-9 OPFSolverFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . 114D-10 OtherOPFFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . 115D-11 OPFUserCallbackFunctions . . . . . . . . . . . . . . . . . . . . . . 115D-12 PowerFlowDerivativeFunctions . . . . . . . . . . . . . . . . . . . . 116D-13 NLP,LP&QPSolverFunctions . . . . . . . . . . . . . . . . . . . . 116D-14 MatrixBuildingFunctions . . . . . . . . . . . . . . . . . . . . . . . . 117D-15 UtilityFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118D-16 ExampleCases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119D-17 AutomatedTestUtilityFunctions . . . . . . . . . . . . . . . . . . . . 120D-18 TestData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120D-19 MiscellaneousMatpowerTests . . . . . . . . . . . . . . . . . . . . . 121D-20 MatpowerOPFTests . . . . . . . . . . . . . . . . . . . . . . . . . 122F-1 AuctionTypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125F-2 GeneratorOers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1276F-3 LoadBids . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127F-4 GeneratorSales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130F-5 LoadPurchases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130F-6 SmartmarketFilesandFunctions . . . . . . . . . . . . . . . . . . . . 13171 Introduction1.1 BackgroundMatpowerisapackageof MatlabM-lesforsolvingpowerowandoptimalpower ow problems. It is intended as a simulation tool for researchers and educatorsthat is easy to use and modify. Matpower is designed to give the best performancepossiblewhilekeepingthecodesimpletounderstandandmodify. TheMatpowerhomepagecanbefoundat:http://www.pserc.cornell.edu/matpower/MatpowerwasinitiallydevelopedbyRayD. Zimmerman, CarlosE. Murillo-S anchezandDeqiangGanofPSERC1atCornell UniversityunderthedirectionofRobert J. Thomas. The initial need for Matlab-based power ow and optimal powerow code was born out of the computational requirements of the PowerWeb project2.ManyothershavecontributedtoMatpowerovertheyearsanditcontinuestobedevelopedandmaintainedunderthedirectionofRayZimmerman.1.2 LicenseandTermsofUseBeginningwithversion4, thecodeinMatpowerisdistributedunder theGNUGeneral PublicLicense(GPL)[1] withanexceptionaddedtoclarifyourintentiontoallowMatpowertointerfacewithMatlabaswellasanyotherMatlabcodeorMEX-lesausermayhaveinstalled,regardlessoftheirlicensingterms. ThefulltextoftheGPLcanbefoundintheCOPYINGleatthetoplevelofthedistributionorathttp://www.gnu.org/licenses/gpl-3.0.txt.The text of the license notice that appears with the copyright in each of the codelesreads:1http://www.pserc.cornell.edu/2http://www.pserc.cornell.edu/powerweb/8MATPOWER is free software: you can redistribute it and/or modifyit under the terms of the GNU General Public License as publishedby the Free Software Foundation, either version 3 of the License,or (at your option) any later version.MATPOWER is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theGNU General Public License for more details.You should have received a copy of the GNU General Public Licensealong with MATPOWER. If not, see .Additional permission under GNU GPL version 3 section 7If you modify MATPOWER, or any covered work, to interface withother modules (such as MATLAB code and MEX-files) available in aMATLAB(R) or comparable environment containing parts coveredunder other licensing terms, the licensors of MATPOWER grantyou additional permission to convey the resulting work.Please note that the Matpower case les distributed with Matpower are notcovered by the GPL. In most cases, the data has either been included with permissionorhasbeenconvertedfromdataavailablefromapublicsource.1.3 CitingMatpowerWhile not required by the terms of the license, we do request that publications derivedfromtheuseofMatpowerexplicitlyacknowledgethatfactbycitingreference[2].R.D.Zimmerman,C.E.Murillo-Sanchez,andR.J.Thomas,Matpower: Steady-StateOperations,PlanningandAnalysisToolsforPowerSystemsResearchandEd-ucation, PowerSystems,IEEETransactionson, vol. 26, no. 1, pp. 1219, Feb. 2011.92 GettingStarted2.1 SystemRequirementsTouseMatpower5.0b1youwillneed: Matlabversion7orlater3,or GNUOctaveversion3.4orlater4Forthehardwarerequirements, pleaserefertothesystemrequirementsfortheversionof Matlab5orOctavethatyouareusing. If theMatlabOptimizationToolbox is installed as well, Matpower enables an option to use it to solve optimalpowerowproblems,thoughthisoptionisnotrecommendedformostapplications.In this manual, references to Matlab usually apply to Octave as well. However,due to lack of extensive testing, support for Octave should be considered experimen-tal. Atthetimeofwriting,noneoftheoptionalMEX-basedMatpowerpackageshavebeenbuiltforOctave.2.2 InstallationInstallationanduseofMatpowerrequiresfamiliaritywiththebasicoperationofMatlab,includingsettingupyourMatlabpath.Step1: Followthedownloadinstructions ontheMatpowerhomepage6. YoushouldendupwithalenamedmatpowerXXX.zip, whereXXXdependsontheversionofMatpower.Step2: Unzip the downloaded le. Move the resulting matpowerXXX directory to thelocationofyourchoice. Theselesshouldnotneedtobemodied,soitisrecommendedthattheybekeptseparatefromyourowncode. Wewilluse$MATPOWERtodenotethepathtothisdirectory.3Matlabis available fromThe MathWorks, Inc. (http://www.mathworks.com/). Mat-power4requiredMatlab6.5, Matpower3.2requiredMatlab6, Matpower3.0requiredMatlab5andMatpower2.0andearlier requiredonlyMatlab4. Matlabis aregisteredtrademarkofTheMathWorks,Inc.4GNUOctave is free software, available online at http://www.gnu.org/software/octave/.Some parts of Matpower 5.0b1 may work on earlier versions of Octave, but it has not been testedonversionspriorto3.4,andpsse2mcpcurrentlyrequires3.8ornewer.5http://www.mathworks.com/support/sysreq/previous_releases.html6http://www.pserc.cornell.edu/matpower/10Step3: AddthefollowingdirectoriestoyourMatlabpath:$MATPOWERcoreMatpowerfunctions$MATPOWER/ttestscriptsforMatpower (optional)sub-directoriesof$MATPOWER/extrasadditional function-alityandcontributedcode(seeAppendixEfordetails).Step4: At the Matlab prompt, type testmatpower to run the test suite and verifythatMatpowerisproperlyinstalledandfunctioning. Theresultshouldresemble the following, possiblyincludingextratests, dependingontheavailablilityofoptionalpackages,solversandextras.>> test_matpowert_nested_struct_copy....okt_mpoption..............okt_loadcase..............okt_ext2int2ext...........okt_jacobian..............okt_hessian...............okt_margcost..............okt_totcost...............okt_modcost...............okt_hasPQcap..............okt_mips..................okt_qps_matpower..........ok (252 of 324 skipped)t_pf....................okt_cpf...................okt_islands...............okt_opf_model.............okt_opf_mips..............okt_opf_mips_sc...........okt_opf_dc_mips...........okt_opf_dc_mips_sc........okt_opf_userfcns..........okt_runopf_w_res..........okt_dcline................okt_makePTDF..............okt_makeLODF..............okt_total_load............okt_scale_load............okt_psse..................okAll tests successful (2542 passed, 252 skipped of 2794)Elapsed time 7.32 seconds.11test_matpower function2.3 RunningaSimulationTheprimaryfunctionalityofMatpoweristosolvepowerowandoptimalpowerow(OPF)problems. Thisinvolves(1)preparingtheinputdatadeningtheallofthe relevant power system parameters, (2) invoking the function to run the simulationand (3) viewing and accessing the results that are printed to the screen and/or savedinoutputdatastructuresorles.2.3.1 PreparingCaseInputDataTheinputdataforthecasetobesimulatedarespeciedinasetofdatamatricespackaged as the elds of a Matlab struct, referred to as a Matpower case structandconventionallydenotedbythevariablempc. Thisstructistypicallydenedinacasele, eitherafunctionM-lewhosereturnvalueisthempcstructoraMAT-lethatdenesavariablenamedmpcwhenloaded7. Themainsimulationroutines,whosenames beginwithrun(e.g. runpf, runopf), accept either alenameor aMatpowercasestructasaninput.Useloadcasetoloadthedatafromacaseleintoastructifyouwanttomakemodicationstothedatabeforepassingittothesimulation.>> mpc = loadcase(casefilename);SeealsosavecaseforwritingaMatpowercasestructtoacasele.The structure of the Matpower case data is described a bit further in Section 3.1andthefulldetailsaredocumentedinAppendix Bandcanbeaccessedatanytimevia the command help caseformat. The Matpower distribution also includes manyexamplecaseleslistedinTableD-16.2.3.2 SolvingtheCaseThesolverisinvokedbycallingoneofthemainsimulationfunctions,suchasrunpfor runopf, passinginacaselenameoracasestructastherstargument. Forexample, to run a simple Newton power ow with default options on the 9-bus systemdenedincase9.m,attheMatlabprompt,type:>> runpf('case9');7Thisdescribesversion2of theMatpowercaseformat, whichisusedinternallyandisthedefault. The version 1 format,now deprecated,but still accessible via theloadcase andsavecasefunctions,denesthedatamatricesasindividualvariablesratherthaneldsofastruct,andsomedonotincludeallofthecolumnsdenedinversion2.12If, on the other hand, you wanted to load the 30-bus system data fromcase30.m,increaseitsrealpowerdemandatbus2to30MW,thenrunanACoptimalpowerowwithdefaultoptions,thiscouldbeaccomplishedasfollows:>> define_constants;>> mpc = loadcase('case30');>> mpc.bus(2, PD) = 30;>> runopf(mpc);Thedefineconstantsintherstlineissimplyaconveniencescriptthatdenesanumberofvariablestoserveasnamedcolumnindicesforthedatamatrices. Inthisexample, itallowsustoaccessthereal powerdemandcolumnofthebusmatrixusingthenamePDwithouthavingtorememberthatitisthe3rdcolumn.Other top-level simulationfunctions are available for runningDCversions ofpowerowandOPF,forrunninganOPFwiththeoptionforMatpowertoshutdown(decommit)expensivegenerators,etc. ThesefunctionsarelistedinTableD-2inAppendixD.2.3.3 AccessingtheResultsBydefault,theresultsofthesimulationarepretty-printedtothescreen,displayingasystemsummary, bus data, branchdataand, for the OPF, bindingconstraintinformation. The bus data includes the voltage, angle and total generation and loadateachbus. ItalsoincludesnodalpricesinthecaseoftheOPF.Thebranchdatashows the ows and losses in each branch. These pretty-printed results can be savedtoale byprovidingalename as the optional 3rdargument tothe simulationfunction.The solution is also stored in a results struct available as an optional return valuefromthesimulationfunctions. ThisresultsstructisasupersetoftheMatpowercasestructmpc, withadditional columnsaddedtosomeof theexistingdataeldsandadditionalelds. Thefollowingexampleshowshowsimpleitis,afterrunningaDCOPFonthe118-bussystemincase118.m,toaccessthenalobjectivefunctionvalue,therealpoweroutputofgenerator6andthepowerowinbranch51.>> define_constants;>> results = rundcopf('case118');>> final_objective = results.f;>> gen6_output = results.gen(6, PG);>> branch51_flow = results.branch(51, PF);13Full documentationforthecontentof theresultsstructcanbefoundinSec-tions4.3and6.6.2.3.4 SettingOptionsMatpower has many options for selecting among the available solution algorithms,controlling the behavior of the algorithms and determining the details of the pretty-printed output. These options are passed to the simulation routines as a Matpoweroptions struct. Theelds of thestruct havenames that canbeusedtoset thecorresponding value via thempoption function. Callingmpoption with no argumentsreturns the default options struct, the struct usedif none is explicitlysupplied.Callingitwithasetofnameandvaluepairsmodiesthedefaultvector.Forexample, thefollowingcoderunsapowerowonthe300-busexampleincase300.m using the fast-decoupled (XB version) algorithm, with verbose printing ofthealgorithmprogress,butsuppressingallofthepretty-printedoutput.>> mpopt = mpoption('pf.alg', 'FDXB', 'verbose', 2, 'out.all', 0);>> results = runpf('case300', mpopt);Tomodifyanexistingoptionsstruct,forexample,toturntheverboseoptionoandre-runwiththeremainingoptionsunchanged,simplypasstheexistingoptionsastherstargumenttompoption.>> mpopt = mpoption(mpopt, 'verbose', 0);>> results = runpf('case300', mpopt);SeeAppendixCortype:>> help mpoptionformoreinformationonMatpowersoptions.2.4 DocumentationTherearetwoprimarysourcesofdocumentationforMatpower. Therstisthismanual, whichgives anoverviewof Matpowers capabilities andstructure anddescribesthemodelingandformulationsbehindthecode. ItcanbefoundinyourMatpowerdistributionat $MATPOWER/docs/manual.pdf.Thesecondisthebuilt-inhelpcommand. AswithMatlabsbuilt-infunctionsandtoolboxroutines, youcantype helpfollowedbythenameof acommandor14Solution algorithms can be changed.Important Help CommandM-letogethelponthatparticularfunction. Nearlyall of MatpowersM-leshavesuchdocumentationandthisshouldbeconsideredthemainreferenceforthecalling options for each individual function. See Appendix D for a list of Matpowerfunctions.Asanexample,thehelpforrunopflookslike:15>> help runopfRUNOPF Runs an optimal power flow.[RESULTS, SUCCESS] = RUNOPF(CASEDATA, MPOPT, FNAME, SOLVEDCASE)Runs an optimal power flow (AC OPF by default), optionally returninga RESULTS struct and SUCCESS flag.Inputs (all are optional):CASEDATA : either a MATPOWER case struct or a string containingthe name of the file with the case data (default is 'case9')(see also CASEFORMAT and LOADCASE)MPOPT : MATPOWER options struct to override default optionscan be used to specify the solution algorithm, output optionstermination tolerances, and more (see also MPOPTION).FNAME : name of a file to which the pretty-printed output willbe appendedSOLVEDCASE : name of file to which the solved case will be savedin MATPOWER case format (M-file will be assumed unless thespecified name ends with '.mat')Outputs (all are optional):RESULTS : results struct, with the following fields:(all fields from the input MATPOWER case, i.e. bus, branch,gen, etc., but with solved voltages, power flows, etc.)order - info used in external internal data conversionet - elapsed time in secondssuccess - success flag, 1 = succeeded, 0 = failed(additional OPF fields, see OPF for details)SUCCESS : the success flag can additionally be returned asa second output argumentCalling syntax options:results = runopf;results = runopf(casedata);results = runopf(casedata, mpopt);results = runopf(casedata, mpopt, fname);results = runopf(casedata, mpopt, fname, solvedcase);[results, success] = runopf(...);Alternatively, for compatibility with previous versions of MATPOWER,some of the results can be returned as individual output arguments:[baseMVA, bus, gen, gencost, branch, f, success, et] = runopf(...);Example:results = runopf('case30');See also RUNDCOPF, RUNUOPF. 163 ModelingMatpower employs all of the standard steady-state models typically used for powerow analysis. The AC models are described rst, then the simplied DC models. In-ternally, the magnitudes of all values are expressed in per unit and angles of complexquantitiesareexpressedinradians. Internally, all o-linegeneratorsandbranchesare removed before forming the models used to solve the power ow or optimal powerowproblem. Allbusesarenumberedconsecutively,beginningat1,andgeneratorsare reordered by bus number. Conversions to and from this internal indexing is donebythefunctionsext2intandint2ext. Thenotationinthissection,aswellasSec-tions4and6,isbasedonthisinternalnumbering,withallgeneratorsandbranchesassumedtobein-service. Duetothestrengthsof theMatlabprogramminglan-guage in handling matrices and vectors, the models and equations are presented hereinmatrixandvectorform.3.1 DataFormatsThedatalesusedbyMatpowerareMatlabM-lesorMAT-leswhichdeneand return a single Matlab struct. The M-le format is plain text that can be editedusing any standard text editor. The elds of the struct arebaseMVA,bus,branch,genandoptionallygencost,wherebaseMVAisascalarandtherestarematrices. Inthematrices, eachrowcorrespondstoasinglebus, branch, orgenerator. Thecolumnsare similar to the columns in the standard IEEE CDF and PTI formats. The numberof rowsinbus, branchandgenarenb, nlandng, respectively. If present, gencosthaseitherngor2ngrows,dependingonwhetheritincludescostsforreactivepoweror just real power. Full details of the Matpowercase format are documentedinAppendixBandcanbe accessedfromthe Matlabcommandline bytypinghelp caseformat.3.2 BranchesAll transmissionlines8, transformers andphaseshifters aremodeledwithacom-monbranchmodel, consistingofastandardtransmissionlinemodel, withseriesimpedancezs=rs + jxsandtotal chargingcapacitancebc, inserieswithanidealphaseshiftingtransformer. Thetransformer,whosetapratiohasmagnitude and8ThisdoesnotincludeDCtransmissionlines. FormoreinformationthehandlingofDCtrans-missionlinesinMatpower,seeSection7.5.3.17phaseshiftangleshift, islocatedatthefromendof thebranch, asshowninFig-ure3-1. Theparametersrs,xs,bc,andshiftarespecieddirectlyincolumns3,4,5,9and10,respectively,ofthecorrespondingrowofthebranchmatrix.Thecomplexcurrentinjectionsifanditatthefromandtoendsofthebranch,respectively, canbeexpressedintermsof the22branchadmittancematrixYbrandtherespectiveterminalvoltagesvfandvt_ifit_ = Ybr_vfvt_. (3.1)With the series admittance element in the model denoted by ys= 1/zs, the branchadmittancematrixcanbewrittenYbr=_ _ys + jbc2_12ys1ejshiftys1ejshiftys + jbc2_. (3.2)Figure3-1: BranchModelIfthefourelementsofthismatrixforbranchiarelabeledasfollows:Yibr=_yiffyiftyitfyitt_(3.3)then four nl1 vectors Yff, Yft, Ytfand Ytt can be constructed, where the i-th elementof each comes from the corresponding element of Yibr. Furthermore, the nlnb sparseconnection matrices Cfand Ctused in building the system admittance matrices canbedenedasfollows. The(i, j)thelementof Cfandthe(i, k)thelementof Ctareequal to 1 for each branch i,where branch i connects from bus jto bus k. All otherelementsofCfandCtarezero.183.3 GeneratorsA generator is modeled as a complex power injection at a specic bus. For generator i,theinjectionissig= pig + jqig. (3.4)LetSg= Pg + jQgbetheng1vectorofthesegeneratorinjections. TheMWandMVAr equivalents (before conversion to p.u.) of pigand qigare specied in columns 2and 3, respectively of row i of thegen matrix. A sparse nbnggenerator connectionmatrixCgcanbedenedsuchthatits(i, j)thelementis1ifgeneratorjislocatedat bus i and 0 otherwise. The nb1 vector of all bus injections from generators canthenbeexpressedasSg,bus= Cg Sg. (3.5)3.4 LoadsConstant power loads are modeled as a specied quantity of real and reactive powerconsumedatabus. Forbusi,theloadissid= pid + jqid(3.6)andSd=Pd+ jQddenotesthenb1vectorof complexloadsatall buses. TheMWandMVArequivalents(beforeconversiontop.u.) ofpidandqidarespeciedincolumns3and4,respectivelyofrowiofthebusmatrix.Constant impedanceandconstant current loads arenot implementeddirectly,buttheconstantimpedanceportionscanbemodeledasashuntelementdescribedbelow. Dispatchable loads are modeled as negative generators and appear as negativevaluesinSg.3.5 ShuntElementsAshunt connectedelement suchasacapacitor or inductor is modeledas axedimpedance to ground at a bus. The admittance of the shunt element at bus i is givenasyish= gish + jbish(3.7)andYsh=Gsh + jBshdenotesthenb1vectorofshuntadmittancesatall buses.Theparametersgishandbisharespeciedincolumns5and6, respectively, ofrowiofthebusmatrixasequivalentMW(consumed)andMVAr(injected)atanominalvoltagemagnitudeof1.0p.uandangleofzero.193.6 NetworkEquationsFor anetworkwithnbbuses, all constant impedance elements of the model areincorporatedintoacomplexnbnbbus admittancematrixYbusthat relates thecomplexnodalcurrentinjectionsIbustothecomplexnodevoltagesV :Ibus= YbusV. (3.8)Similarly, for anetworkwithnlbranches, thenlnbsystembranchadmittancematricesYfandYtrelatethebusvoltagestothenl1vectorsIfandItofbranchcurrentsatthefromandtoendsofallbranches,respectively:If= YfV (3.9)It= YtV. (3.10)If [] is usedtodenote anoperator that takes ann 1vector andcreates thecorresponding nn diagonal matrix with the vector elements on the diagonal, thesesystemadmittancematricescanbeformedasfollows:Yf= [Yff] Cf+ [Yft] Ct(3.11)Yt= [Ytf] Cf+ [Ytt] Ct(3.12)Ybus= CfTYf+ CtTYt + [Ysh] . (3.13)Thecurrentinjectionsof (3.8)(3.10)canbeusedtocomputethecorrespondingcomplexpowerinjectionsasfunctionsofthecomplexbusvoltagesV :Sbus(V ) = [V ] Ibus= [V ] YbusV(3.14)Sf(V ) = [CfV ] If= [CfV ] Yf V(3.15)St(V ) = [CtV ] It= [CtV ] YtV. (3.16)The nodal bus injections are then matched to the injections from loads and generatorsto form the AC nodal power balance equations, expressed as a function of the complexbusvoltagesandgeneratorinjectionsincomplexmatrixformasgS(V, Sg) = Sbus(V ) + SdCgSg= 0. (3.17)3.7 DCModelingTheDCformulation[8] is basedonthesameparameters, but withthefollowingthreeadditionalsimplifyingassumptions.20 Branchescanbeconsideredlossless. Inparticular, branchresistancesrsandchargingcapacitancesbcarenegligible:ys=1rs + jxs1jxs, bc 0. (3.18) Allbusvoltagemagnitudesarecloseto1p.u.vi eji. (3.19) Voltageangledierencesacrossbranchesaresmallenoughthatsin(f tshift) f tshift. (3.20)Substituting the rst set of assumptions regarding branch parameters from (3.18),thebranchadmittancematrixin(3.2)approximatestoYbr 1jxs_121ejshift1ejshift1_. (3.21)Combiningthisandthesecondassumptionwith(3.1)yieldsthefollowingapproxi-mationforif:if 1jxs(12ejf1ejshiftejt)=1jxs(1ejfej(t+shift)). (3.22)The approximate real power ow is then derived as follows, rst applying (3.19) and(3.22),thenextractingtherealpartandapplying(3.20).pf= 1sf= 1_vfif_ 1_ejf

jxs(1ejfej(t+shift))_= 1_jxs_1 ej(ftshift)__= 1_1xs_sin(f tshift) + j_1 cos(f tshift)___1xs(f tshift) (3.23)21Asexpected,giventhelosslessassumption,asimilarderivationforthepowerinjec-tionatthetoendofthelineleadstoleadstopt= pf.The relationship between the real power ows and voltage angles for an individualbranchicanthenbesummarizedas_pfpt_ = Bibr_ft_+ Pishift(3.24)whereBibr= bi_1 11 1_,Pishift= ishiftbi_ 11_andbiisdenedintermsoftheseriesreactancexisandtapratioiforbranchiasbi=1xisi.Forashuntelementatbusi,theamountofcomplexpowerconsumedissish= vi(yishvi) eji(gishjbish)eji= gishjbish. (3.25)Sothevectorofrealpowerconsumedbyshuntelementsatallbusescanbeapprox-imatedbyPsh Gsh. (3.26)WithaDCmodel,thelinearnetworkequationsrelaterealpowertobusvoltageangles, versuscomplexcurrentstocomplexbusvoltagesintheACcase. Letthenl1vectorBffbeconstructedsimilartoYff,wherethei-thelementisbiandletPf,shiftbethenl1vectorwhosei-thelementisequalto ishiftbi. Thenthenodalrealpowerinjectionscanbeexpressedasalinearfunctionof,thenb1vectorofbusvoltageanglesPbus() = Bbus + Pbus,shift(3.27)wherePbus,shift= (Cf Ct)TPf,shift. (3.28)22Similarly, thebranchowsatthefromendsof eachbrancharelinearfunctionsofthebusvoltageanglesPf() = Bf + Pf,shift(3.29)and,due to the lossless assumption,the ows at the toends are given by Pt= Pf.Theconstructionof thesystemBmatricesisanalogoustothesystemY matricesfortheACmodel:Bf= [Bff] (Cf Ct) (3.30)Bbus= (Cf Ct)TBf. (3.31)The DC nodal power balance equations for the system can be expressed in matrixformasgP(, Pg) = Bbus + Pbus,shift + Pd + GshCgPg= 0 (3.32)234 PowerFlowThe standard power ow or loadow problem involves solving for the set of voltagesandowsinanetworkcorrespondingtoaspeciedpatternofloadandgeneration.Matpowerincludes solvers for bothACandDCpower owproblems, bothofwhichinvolvesolvingasetofequationsoftheformg(x) = 0, (4.1)constructed by expressing a subset of the nodal power balance equations as functionsofunknownvoltagequantities.All of Matpowerssolversexploitthesparsityof theproblemand, exceptforGauss-Seidel,scalewelltoverylargesystems. Currently,noneofthemincludeanyautomaticupdatingof transformer tapsor other techniquestoattempt tosatisfytypical optimal power owconstraints, suchas generator, voltageor branchowlimits.4.1 ACPowerFlowInMatpower,byconvention,asinglegeneratorbusistypicallychosenasarefer-encebustoservetherolesofbothavoltageanglereferenceandarealpowerslack.Thevoltageangleatthereferencebushasaknownvalue, butthereal powergen-erationattheslackbusistakenasunknowntoavoidoverspecifyingtheproblem.The remaining generator buses are classied as PV buses, with the values of voltagemagnitudeandgeneratorrealpowerinjectiongiven. SincetheloadsPdandQdarealsogiven, all non-generatorbusesarePQbuses, withreal andreactiveinjectionsfullyspecied. Let Jref, JPVand JPQdenotethesetsofbusindicesofthereferencebus,PVbusesandPQbuses,respectively.InthetraditionalformulationoftheACpowerowproblem,thepowerbalanceequation in (3.17) is split into its real and reactive components, expressed as functionsof the voltage angles and magnitudes Vm and generator injections Pg and Qg, wheretheloadinjectionsareassumedconstantandgiven:gP(, Vm, Pg) = Pbus(, Vm) + PdCgPg= 0 (4.2)gQ(, Vm, Qg) = Qbus(, Vm) + QdCgQg= 0. (4.3)For the AC power ow problem, the function g(x) from (4.1) is formed by takingtheleft-handsideof thereal powerbalanceequations(4.2)forall non-slackbuses24andthereactivepowerbalanceequations(4.3)forallPQbusesandplugginginthereference angle, the loads and the known generator injections and voltage magnitudes:g(x) =_g{i}P(, Vm, Pg)g{j}Q(, Vm, Qg)_i JPV JPQj JPQ.(4.4)The vector x consists of the remaining unknown voltage quantities, namely the volt-ageanglesatallnon-referencebusesandthevoltagemagnitudesatPQbuses:x =_{i}v{j}m_i/ Jrefj JPQ.(4.5)Thisyieldsasystemof nonlinearequationswithnpv+ 2npqequationsandun-knowns,wherenpvandnpqarethenumberofPVandPQbuses,respectively. Aftersolvingforx, theremainingreal powerbalanceequationcanbeusedtocomputethegeneratorrealpowerinjectionattheslackbus. Similarly,theremainingnpv + 1reactivepowerbalanceequationsyieldthegeneratorreactivepowerinjections.Matpowerincludes four dierent algorithms for solvingthe ACpower owproblem. ThedefaultsolverisbasedonastandardNewtonsmethod[4] usingapolar form and a full Jacobian updated at each iteration. Each Newton step involvescomputingthemismatchg(x), formingtheJacobianbasedonthesensitivities ofthese mismatches to changes in x and solving for an updated value of x by factorizingthisJacobian. Thismethodisdescribedindetailinmanytextbooks.Alsoincludedaresolversbasedonvariationsof thefast-decoupledmethod[5],specically, theXBandBXmethodsdescribedin[6]. Thesesolversgreatlyreducetheamountofcomputationperiteration, byupdatingthevoltagemagnitudesandanglesseparatelybasedonconstantapproximateJacobianswhicharefactoredonlyonceatthebeginningofthesolutionprocess. Theseper-iterationsavings,however,comeatthecostofmoreiterations.The fourthalgorithmis the standardGauss-Seidel methodfromGlimmandStagg[7]. It has numerous disadvantages relativetotheNewtonmethodandisincludedprimarilyforacademicinterest.By default, the AC power ow solvers simply solve the problem described above,ignoring any generator limits, branch ow limits, voltage magnitude limits, etc. How-ever, thereisanoption(pf.enforceqlims)thatallowsforthegeneratorreactivepowerlimitstoberespectedattheexpenseof thevoltagesetpoint. ThisisdoneinaratherbruteforcefashionbyaddinganouterlooparoundtheACpowerowsolution. If any generator has a violated reactive power limit, its reactive injection isxed at the limit, the corresponding bus is converted to a PQ bus and the power ow25issolvedagain. Thisprocedureisrepeateduntiltherearenomoreviolations. NotethatthisoptionisbasedsolelyontheQMINandQMAXparametersforthegeneratorand does not take into account the trapezoidal generator capability curves describedinSection6.4.3.4.2 DCPowerFlowFor the DC power ow problem [8],the vector x consists of the set of voltage anglesatnon-referencebusesx =_{i}, i/ Jref(4.6)and(4.1)takestheformBdcx Pdc= 0 (4.7)where Bdcis the (nb1) (nb1) matrix obtained by simply eliminating from Bbusthe row and column corresponding to the slack bus and reference angle, respectively.GiventhatthegeneratorinjectionsPgarespeciedatallbuttheslackbus,Pdccanbeformeddirectlyfromthenon-slackrowsofthelastfourtermsof (3.32).Thevoltageanglesinxarecomputedbyadirectsolutionof thesetof linearequations. Thebranchowsandslackbusgeneratorinjectionarethencalculateddirectlyfromthebusvoltageanglesvia(3.29)andtheappropriaterowin(3.32),respectively.4.3 runpfInMatpower,apowerowisexecutedbycallingrunpfwithacasestructorcaselenameastherstargument(casedata). Inadditiontoprintingoutputtothescreen,whichitdoesbydefault, runpfoptionallyreturnsthesolutioninaresultsstruct.>> results = runpf(casedata);Theresults struct is a superset of the input Matpower case structmpc, with someadditional eldsaswell asadditional columnsinsomeof theexistingdataelds.ThesolutionvaluesarestoredasshowninTable4-1.Additional optional input arguments canbe usedtoset options (mpopt) andprovidelenamesforsavingtheprettyprintedoutput(fname)orthesolvedcasedata(solvedcase).>> results = runpf(casedata, mpopt, fname, solvedcase);26Table4-1: PowerFlowResultsname descriptionresults.success successag,1=succeeded,0=failedresults.et computationtimerequiredforsolutionresults.order seeext2inthelpfordetailsonthiseldresults.bus(:, VM)busvoltagemagnitudesresults.bus(:, VA) busvoltageanglesresults.gen(:, PG) generatorrealpowerinjectionsresults.gen(:, QG)generatorreactivepowerinjectionsresults.branch(:, PF) realpowerinjectedintofromendofbranchresults.branch(:, PT) realpowerinjectedintotoendofbranchresults.branch(:, QF)reactivepowerinjectedintofromendofbranchresults.branch(:, QT)reactivepowerinjectedintotoendofbranchACpowerowonly.The options that control the power ow simulation are listed in Table 4-2 and thosecontrollingtheoutputprintedtothescreeninTable4-3.Bydefault, runpfsolvesanACpowerowproblemusingastandardNewtonsmethodsolver. TorunaDCpowerow,themodeloptionmustbesetto'DC'.Forconvenience, Matpowerprovides afunctionrundcpfwhichis simplyawrapperthatsetsthemodeloptionto 'DC'beforecallingrunpf.Table4-2: PowerFlowOptionsname default descriptionmodel 'AC' ACvs. DCmodelingforpowerowandOPFformulation'AC'useACformulationandcorrespondingalgoptions'DC'useDCformulationandcorrespondingalgoptionspf.alg 'NR' ACpowerowalgorithm:'NR' Newtonssmethod'FDXB'Fast-Decoupled(XBversion)'FDBX'Fast-Decouple(BXversion)'GS' Gauss-Seidelpf.tol 108terminationtoleranceonperunitPandQdispatchpf.nr.maxit 10 maximumnumberofiterationsforNewtonsmethodpf.fd.maxit 30 maximumnumberofiterationsforfastdecoupledmethodpf.gs.maxit 1000 maximumnumberofiterationsforGauss-Seidelmethodpf.enforceqlims 0 enforcegenreactivepowerlimitsatexpenseof [Vm[0donot enforcelimits1enforcelimits,simultaneousbustypeconversion2enforcelimits,one-at-a-timebustypeconversion27Table4-3: PowerFlowOutputOptionsname default descriptionverbose 1 amountofprogressinfotobeprinted0printnoprogressinfo1printalittleprogressinfo2printalotofprogressinfo3printallprogressinfoout.all -1 controlspretty-printingofresults-1individualagscontrolwhatisprinted0donot printanything1printeverythingout.syssum 1 printsystemsummary(0or1)out.areasum 0 printareasummaries(0or1)out.bus 1 printbusdetail,includesperbusgeninfo(0or1)out.branch 1 printbranchdetail(0or1)out.gen 0 printgeneratordetail(0or1)out.force 0 printresultsevenifsuccessag=0(0or1)Overridesindividualags.Internally,therunpffunctiondoesanumberofconversionstotheproblemdatabeforecallingtheappropriatesolverroutinefortheselectedpowerowalgorithm.Thisexternal-to-internal format conversionisperformedbytheext2intfunction,described in more detail in Section 7.2.1, and includes the elimination of out-of-serviceequipment, theconsecutiverenumberingof busesandthereorderingof generatorsbyincreasingbusnumber. All computationsaredoneusingthisinternal indexing.Whenthesimulationhascompleted, thedataisconvertedbacktoexternalformatbyint2extbeforetheresultsareprintedandreturned.4.4 LinearShiftFactorsTheDCpowerowmodel canalsobeusedtocomputethesensitivitiesof branchows to changes in nodal real power injections, sometimes called injection shift factors(ISF)orgenerationshiftfactors[8]. Thesenlnbsensitivitymatrices, alsocalledpowertransferdistributionfactorsorPTDFs, carryanimplicitassumptionabouttheslackdistribution. IfHisusedtodenoteaPTDFmatrix, thentheelementinrowi andcolumnj, hij, representsthechangeinthereal powerowinbranchigivenaunitincreaseinthepowerinjectedatbusj, withtheassumptionthattheadditionalunitofpowerisextractedaccordingtosomespeciedslackdistribution:Pf= HPbus. (4.8)28Thisslackdistributioncanbeexpressedasannb1vectorwof non-negativeweights whose elements sum to 1. Each element species the proportion of the slacktakenupateachbus. Forthespecialcaseofasingleslackbusk,wisequaltothevectorek. ThecorrespondingPTDFmatrixHkcanbeconstructedbyrstcreatingthenl(nb1)matrixHk= BfB1dc(4.9)then inserting a column of zeros at column k. Here Bfand Bdcare obtained from BfandBbus, respectively, byeliminatingtheirreferencebuscolumnsand, inthecaseofBdc,removingrowkcorrespondingtotheslackbus.ThePTDFmatrixHw, correspondingtoageneral slackdistributionw, canbeobtained from any other PTDF, such as Hk, by subtracting Hk w from each column,equivalenttothefollowingsimplematrixmultiplication:Hw= Hk(I w1T). (4.10)These same linear shift factors may also be used to compute sensitivities of branchows tobranchoutages, knownas lineoutagedistributionfactors or LODFs [9].GivenaPTDFmatrixHw, thecorrespondingnlnlLODFmatrixLcanbecon-structedasfollows,wherelijistheelementinrowiandcolumnj,representingthechange in ow in branch i (as a fraction of its initial ow) for an outage of branch j.First,letHrepresentthematrixofsensitivitiesofbranchowstobranchows,foundbymultplyingthePTDFmatrixbythenode-branchincidencematrix:H= Hw(Cf Ct)T. (4.11)Ifhijisthesensitivityofowinbranchiwithrespecttoowinbranchj,thenlijcanbeexpressedaslij=___hij1 hjji ,= j1 i = j.(4.12)MatpowerincludesfunctionsforcomputingboththeDCPTDFmatrixandthecorrespondingLODFmatrixforeitherasingleslackbuskorageneral slackdistributionvectorw. SeethehelpformakePTDFandmakeLODFfordetails.295 ContinuationPowerFlowContinuation methods or branch tracing methods are used to trace a curve given aninitial pointonthecurve. Thesearealsocalledpredictor-correctormethodssincetheyinvolvethepredictionofthenextsolutionpointandcorrectingthepredictiontogetthenextpointonthecurve.Consider asystemof nnonlinear equations g(x) =0, x Rn. Byaddingacontinuationparameterandonemoreequationtothesystem,xcanbetracedbyvarying. Theresultingsystemf(x, )=0hasn + 1dimensions. Theadditionalequationis aparameterizedequationwhichidenties the locationof the currentsolutionwithrespecttothepreviousornextsolution.Thecontinuationprocesscanbediagrammaticallyshownby(5.1)._xj, j_Predictor( xj+1,j+1)Corrector_xj+1, j+1_(5.1)where,(xj, j) represents the current solution,( xj+1,j+1) is the predictedsolution,and(xj+1, j+1)isthenextsolutiononthecurve.Continuationmethodsareemployedinpowersystemstodeterminesteadystatestabilitylimits[10] inwhatiscalledacontinuationpowerow9. Thelimitisde-terminedfromanosecurvewherethenoserepresentsthemaximumpowertransferthat the system can handle given a power transfer schedule. To determine the steadystateloadinglimit,thebasicpowerowequationsg(x) =_P(x) PinjQ(x) Qinj_ = 0, (5.2)arerestructuredasf(x, ) = g(x) b = 0 (5.3)wherex (, Vm)andbisavectorofpowertransfergivenbyb =_PinjtargetPinjbaseQinjtargetQinjbase_. (5.4)Theeectsof thevariationof loadingorgenerationcanbeinvestigatedusingthecontinuationmethodbycomposingthebvectorappropriately.9Thanks toShrirangAbhyankar, Rui Bo, andAlexander Flueckfor contributions toMat-powerscontinuationpowerowfeature.305.1 ParameterizationThe values of (x, ) along the solution curve can parameterized in a number of ways[11, 12]. Parameterization is a mathematical way of identifying each solution so thatthe next solution or previoussolution can be quantied. Matpower includes threeparameterization scheme options to quantify this relationship, detailed below, whereisthecontinuationstepsizeparameter. Natural parameterizationsimplyusesdirectlyastheparameter, sothenewissimplythepreviousvalueplusthestepsize.pj(x, ) = j= 0 (5.5) Arc lengthparameterizationresults inthefollowingrelationship, wherethestepsizeisequal tothe2-normof thedistancefromonesolutiontothenext.pj(x, ) =

i(xixji)2+ ( j)22= 0 (5.6) Pseudo arc length parameterization[14] is Matpowers default pa-rameterizationscheme, wherethenext point (x, ) onthesolutioncurveisconstrainedtolieinthehyperplanerunningthroughthepredictedsolution( xj+1,j+1) orthogonal to the tangent line from the previous corrected solution(xj, j). Thisrelationshipcanbequantiedbythefunctionpj(x, ) = zTj__x__xjj__= 0, (5.7)where zjisthenormalizedtangentvectorat (xj, j)andisthecontinuationstepsizeparameter.5.2 PredictorThepredictorisusedtoproduceanestimateforthenextsolution. Thebettertheprediction, thefasteristheconvergencetothesolutionpoint. Matpowerusesatangentpredictorforestimatingthecurvetothenextsolution. Thetangentvectorzj=_dx djTat the current solution(xj, j) is foundbysolvingthe linearsystem_fxfpj1xpj1_zj=_01_. (5.8)31The matrix on the left-hand side is simply the standard power ow Jacobian with anadditional column and row added. The extra column fis simply the negative of thepower transfer vector b and the extra row, required to make the system non-singularand dene the magnitude of zj, is the derivative of the the parameterization functionattheprevioussolutionpointpj1.Theresultingtangentvectoristhennormalized zj=zj[[zj[[2(5.9)andusedtocomputethepredictedapproximation( xj+1,j+1)tothenextsolution(xj+1, j+1)using_ xj+1j+1_ =_xjj_+ zj, (5.10)whereisthecontinuationstepsize.5.3 CorrectorThecorrectorstagendsthenextsolution(xj+1, j+1)bycorrectingtheapproxi-mationestimatedbythepredictor ( xj+1,j+1). Newtons methodis usedtondthenextsolutionbysolvingthen + 1dimensional systemin(5.11), whereoneof(5.5)(5.7)hasbeenaddedasanadditional constrainttotheparameterizedpowerowequationsof (5.3)._f(x, )pj(x, )_ = 0 (5.11)5.4 SteplengthcontrolStep length control is a key element aecting the computational eciency of a contin-uationmethod. Itaectsthecontinuationmethodwithtwoissues: (1)speedhowfastthecorrectorconvergestoaspeciedaccuracy, and(2)robustnesswhetherthecorrector convergestoatruesolutiongivenapredictedpoint. Matpowerscontinuationpowerowcanoptionallyuseadaptivesteps, wherethestepisvariedbased on an error estimation between the predicted and corrected solutions as givenin(5.12).n+1= n

cpf[[ (xj+1, j+1) _ xj+1,j+1_[[min n+1 max(5.12)325.5 runcpfInMatpower, acontinuationpowerowisexecutedbycallingruncpfwithtwoMatpowercases (case structs or case le names) as the rst two arguments,basecasedataandtargetcasedata, respectively. Therstcontainsthebaseload-ing/generationprolewhilethesecondcontainsthetargetloading/generationpro-le. Inadditiontoprintingoutputtothescreen, whichitdoesbydefault, runcpfoptionallyreturnsthesolutioninaresultsstruct.>> results = runcpf(basecasedata, targetcasedata);Additional optional input arguments canbe usedtoset options (mpopt) andprovidelenamesforsavingtheprettyprintedoutput(fname)orthesolvedcasedata(solvedcase).>> results = runcpf(basecasedata, targetcasedata, mpopt, fname, solvedcase);TheresultsstructisasupersetoftheinputMatpowercasestructmpc,withsomeadditional elds as well as additional columns insomeof theexistingdataelds. Inadditiontothesolutionvaluesincludedintheresultsforasimplepowerow,showninTable4-1inSection4.3,thefollowingadditionalcontinuationpowerowsolutionvaluesarestoredinthecpfeldasshowninTable5-1.Table5-1: ContinuationPowerFlowResultsname descriptionresults.cpf.iterations nsteps,numberofcontinuationstepsperformedresults.cpf.lamc 1 nvectorofvaluesfromcorrectionstepsresults.cpf.lamp 1 nvectorofvaluesfrompredictionstepsresults.cpf.maxlam maximumvalueoffoundinresults.cpf.lamcresults.cpf.Vc nbnmatrixofcomplexbusvoltagesfromcorrectionstepsresults.cpf.Vp nbnmatrixofcomplexbusvoltagesfrompredictionstepsnisonemorethanthenumberofcontinuationsteps,i.e. nsteps + 1.The options that control the continuationpower owsimulationare listedinTable5-2. All thepowerowoptionsforNewtonsmethod(tolerance, maximumiterations)andforcontrollingtheoutputonthescreen(seeTables4-2and4-3)arealsoavailablewiththecontinuationpowerow.Matpowers continuationpower owalsoprovides acallbackmechanismtogivetheuseraccesstotheiterationprocessforexecutingcustomcodeateachiter-ation, forexample, toimplementcustomincremental plottingof aPVnosecurve.33Table5-2: ContinuationPowerFlowOptionsname default descriptioncpf.parameterization 3 choiceofparameterization1natural2arclength3pseudoarclengthcpf.stopat 'NOSE' determinesstoppingcriterion'NOSE'stopwhennosepointisreached'FULL'tracefullnosecurvestopstopuponreachingtargetvaluestopcpf.step 0.05 continuationpowerowstepsizecpf.adaptstep 0 toggleadaptivestepsizefeature0adaptivestepsizedisabled1adaptivestepsizeenabledcpf.errortol 103tolerancefortheadaptivestepcontrollercpf.stepmin 104minimumallowedstepsizecpf.stepmax 0.2 maximumallowedstepsizecpf.plot.level 0 controlplottingofnosecurve0donotplotnosecurve1plotwhencompleted2plotincrementallyateachiteration3sameas2,withpauseateachiterationcpf.plot.bus empty indexofbuswhosevoltageistobeplottedcpf.usercallback empty string or cell array of strings with names of user callbackfunctionscpf.usercallbackargs empty structpassedtouser-denedcallbackfunctionsSeehelp cpfdefaultcallbackfordetails.Any user-dened callback takes the same input and output arguments as those usedbythe cpfdefaultcallbackfunction, whichis always calledandis usedtocol-lect theandV results fromeachpredictor andcorrector iteration. Toregisterusercallbackfunction(s)soit(they)will beexecuted, thefunctionname(s)is(are)suppliedasastring(cell arrayof strings)andassignedtothecpf.usercallbackoption. Ifyourcallbackrequiresadditionalarguments,theycanbeprovidedinthecpf.usercallbackargsoption.TheprototypeforaCPFusercallbackfunctionisfunction [cb_state, results] = cpf_user_callback(...k, V_c, lam_c, V_p, lam_p, cb_data, cb_state, cb_args, results)andtheinputandoutputargumentsaredescribedinTable5-3andinthehelpforcpfdefaultcallback. The CPF user callback functions are called in three dierent34Table5-3: ContinuationPowerFlowCallbackArgumentsname descriptionInputsk continuationstepiterationcountvc vectorofcomplexbusvoltagesafterk-thcorrectorsteplamc valueofafterk-thcorrectorstepvp vectorofcomplexbusvoltagesafterk-thpredictorsteplamp valueofafterk-thpredictorstepcbdata structcontainingpotentiallyuseful staticdata, withthefollowingelds(allbasedoninternalindexing):.mpcbase Matpowercasestructofbasestate.mpctarget Matpowercasestructoftargetstate.Sxfr powertransfervectorbfrom(5.4).Ybus busadmittancematrix.Yf branchadmittancematrix,fromendofbranches.Yt branchadmittancematrix,toendofbranches.pv listofindicesofPVbuses.pq listofindicesofPQbuses.ref listofindicesofreferencebuses.mpopt Matpoweroptionsstructcbstate user-dened struct containing any information the callback function wouldliketopassfromoneinvokationtothenextcbargs callbackargumentsstructspeciedincpf.usercallbackargsresults initial valueof outputstructtobeassignedtocpfeldof resultsstructreturnedbyruncpfOuputscbstate updatedversionofcbstateinputargumentresults updatedversionofresultsinputargumentcontexts,distinguishedasfollows:1. initial calledwithoutresultsoutputarg,withinputargumentk=0,afterbasepowerow,beforerstCPFstep.2. iterationscalledwithoutresultsoutputarg,withinputargumentk> 0,ateachiteration,afterpredictor-correctorstep3. nal calledwithresultsoutputarg, afterexitingpredictor-correctorloop,inputsidenticaltolastiterationcall35ExampleThefollowingisanexampleofrunningacontinuationpowerowusingaversionofthe9-bussystem, lookingatincreasingall loadsbyafactorof 2.5. ThisexampleplotsthenosecurveshowninFigure5-1.define_constants;mpopt = mpoption('out.all', 0, 'verbose', 2);mpopt = mpoption(mpopt, 'cpf.stop_at', 'FULL', 'cpf.step', 0.2);mpopt = mpoption(mpopt, 'cpf.plot.level', 2);mpcb = loadcase(t_case9_pfv2); % load base casempct = mpcb; % set up target case withmpct.gen(:, [PG QG]) = mpcb.gen(:, [PG QG]) * 2.5; % increased generationmpct.bus(:, [PD QD]) = mpcb.bus(:, [PD QD]) * 2.5; % and increased loadresults = runcpf(mpcb, mpct, mpopt);Thisshouldresultinsomethinglikethefollowingoutputtothescreen.MATPOWER Version 5.0b1, 01-Jul-2014 -- AC Continuation Power Flowstep 0 : lambda = 0.000, 4 Newton stepsstep 1 : lambda = 0.181, 2 corrector Newton stepsstep 2 : lambda = 0.359, 2 corrector Newton stepsstep 3 : lambda = 0.530, 2 corrector Newton stepsstep 4 : lambda = 0.693, 3 corrector Newton stepsstep 5 : lambda = 0.839, 3 corrector Newton stepsstep 6 : lambda = 0.952, 3 corrector Newton stepsstep 7 : lambda = 0.988, 3 corrector Newton stepsstep 8 : lambda = 0.899, 3 corrector Newton stepsstep 9 : lambda = 0.776, 3 corrector Newton stepsstep 10 : lambda = 0.654, 3 corrector Newton stepsstep 11 : lambda = 0.533, 2 corrector Newton stepsstep 12 : lambda = 0.413, 2 corrector Newton stepsstep 13 : lambda = 0.294, 2 corrector Newton stepsstep 14 : lambda = 0.176, 2 corrector Newton stepsstep 15 : lambda = 0.000, 3 corrector Newton stepsTraced full continuation curve in 15 continuation stepsTheresults of thecontinuationpower owarethenfoundinthe cpfeldof thereturnedresultsstruct.360 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 100.10.20.30.40.50.60.70.80.91Voltage at Bus 9Voltage MagnitudeFigure5-1: NoseCurveofVoltageMagnitudeatBus937>> results.cpfans =V_p: [9x16 double]lam_p: [1x16 double]V_c: [9x16 double]lam_c: [1x16 double]iterations: 15max_lam: 0.9876386 OptimalPowerFlowMatpowerincludescodetosolvebothACandDCversionsoftheoptimalpowerowproblem. Thestandardversionofeachtakesthefollowingform:minxf(x) (6.1)subjecttog(x) = 0 (6.2)h(x) 0 (6.3)xmin x xmax. (6.4)6.1 StandardACOPFTheoptimizationvectorxforthestandardACOPFproblemconsistsofthenb1vectorsofvoltageanglesandmagnitudesVmandtheng1vectorsofgeneratorrealandreactivepowerinjectionsPgandQg.x =__VmPgQg__(6.5)Theobjectivefunction(6.1)issimplyasummationof individual polynomial costfunctions fiPandfiQof real andreactive power injections, respectively, for eachgenerator:min,Vm,Pg,Qgng

i=1fiP(pig) + fiQ(qig). (6.6)Theequalityconstraintsin(6.2)aresimplythefull setof2nbnonlinearreal andreactivepowerbalanceequationsfrom(4.2)and(4.3). Theinequalityconstraints(6.3)consistof twosetsof nlbranchowlimitsasnonlinearfunctionsof thebusvoltageanglesandmagnitudes,oneforthefromendandoneforthetoendofeachbranch:hf(, Vm) = [Ff(, Vm)[ Fmax 0 (6.7)ht(, Vm) = [Ft(, Vm)[ Fmax 0. (6.8)39The ows are typically apparent power ows expressed in MVA, but can be real powerorcurrentows,yieldingthefollowingthreepossibleformsfortheowconstraints:Ff(, Vm) =___Sf(, Vm), apparentpowerPf(, Vm), realpowerIf(, Vm), current(6.9)whereIfisdenedin(3.9), Sfin(3.15),Pf= 1SfandthevectorofowlimitsFmaxhas the appropriate units for the type of constraint. It is likewise for Ft(, Vm).The variable limits (6.4) include an equality constraint on any reference bus angleandupper andlower limits onall bus voltage magnitudes andreal andreactivegeneratorinjections:refi i refi, i Jref(6.10)vi,minm vim vi,maxm, i = 1 . . . nb(6.11)pi,ming pig pi,maxg, i = 1 . . . ng(6.12)qi,ming qig qi,maxg, i = 1 . . . ng. (6.13)6.2 StandardDCOPFWhenusingDCnetworkmodelingassumptions andlimitingpolynomial costs tosecondorder, thestandardOPFproblemabovecanbesimpliedtoaquadraticprogram, withlinear constraints andaquadraticcost function. Inthis case, thevoltage magnitudes and reactive powers are eliminated from the problem completelyandreal power ows aremodeledas linear functions of thevoltageangles. Theoptimizationvariableisx =_Pg_(6.14)andtheoverallproblemreducestothefollowingform.min,Pgng

i=1fiP(pig) (6.15)subjecttogP(, Pg) = Bbus + Pbus,shift + Pd + GshCgPg= 0 (6.16)hf() = Bf + Pf,shiftFmax 0 (6.17)ht() = BfPf,shiftFmax 0 (6.18)40refi i refi, i Jref(6.19)pi,ming pig pi,maxg, i = 1 . . . ng(6.20)6.3 ExtendedOPFFormulationMatpoweremploysanextensibleOPFstructure[15] toallowtheusertomodifyoraugmenttheproblemformulationwithoutrewritingtheportionsthataresharedwiththestandardOPFformulation. Thisisdonethroughoptional inputparame-ters,preservingtheabilitytousepre-compiledsolvers. Thestandardformulationismodiedbyintroducingadditional optional user-denedcostsfu, constraints, andvariableszandcanbewritteninthefollowingform:minx,zf(x) + fu(x, z) (6.21)subjecttog(x) = 0 (6.22)h(x) 0 (6.23)xmin x xmax(6.24)l A_xz_ u (6.25)zmin z zmax. (6.26)Section7describesthemechanismsavailabletotheuserfortakingadvantageoftheextensibleformulationdescribedhere.6.3.1 User-denedCostsTheuser-denedcostfunctionfuisspeciedintermsofparametersH,C,N, r,k,dandm. All of theparametersarenw1vectorsexceptthesymmetricnwnwmatrixHandthenw(nx + nz)matrixN. Thecosttakestheformfu(x, z) =12wTHw + CTw (6.27)wherewisdenedinseveral stepsasfollows. First, anewvectoruiscreatedbyapplying a linear transformation Nand shift r to the full set of optimization variablesr = N_xz_, (6.28)41u = r r, (6.29)then a scaled function with a dead zone is applied to each element of u to producethecorrespondingelementofw.wi=___mifdi(ui + ki), ui< ki0, ki ui kimifdi(uiki), ui> ki(6.30)Herekispeciesthesizeof thedeadzone, miisasimplescalefactorandfdiisapre-denedscalar functionselectedbythevalueof di. Currently, Matpowerimplementsonlylinearandquadraticoptions:fdi() =_, ifdi= 12, ifdi= 2(6.31)asillustratedinFigure6-1andFigure6-2,respectively.wimiri rikikiFigure6-1: Relationshipofwitorifordi= 1(linearoption)Thisformforfuprovidestheexibilitytohandleawiderangeof costs, fromsimplelinear functions of theoptimizationvariables toscaledquadraticpenaltiesonquantities, suchasvoltages, lyingoutsideadesiredrange, tofunctionsoflinear42wiri rikikiFigure6-2: Relationshipofwitorifordi= 2(quadraticoption)combinationsofvariables, inspiredbytherequirementsofpricecoordinationtermsfound in the decomposition of large loosely coupled problems encountered in our ownresearch.Some limitations are imposed on the parameters in the case of the DC OPF sinceMatpower uses a generic quadratic programming (QP) solver for the optimization.Inparticular, ki=0anddi=1forall i, sothedeadzoneisnotconsideredandonly the linear option is available for fdi. As a result, for the DC case (6.30) simpliestowi= miui.6.3.2 User-denedConstraintsThe user-dened constraints (6.25) are general linear restrictions involving all of theoptimizationvariablesandarespeciedviamatrixAandlowerandupperboundvectors l and u. These parameters can be used to create equality constraints (li= ui)or inequality constraints that are bounded below (ui= ), bounded above (li= )orboundedonbothsides.6.3.3 User-denedVariablesThecreationof additional user-denedzvariablesisdoneimplicitlybasedonthedierencebetweenthenumberof columnsinAandthedimensionof x. Theop-tional vectorszminandzmaxareavailabletoimposelowerandupperboundsonz,respectively.436.4 StandardExtensionsInadditiontomakingthisextensibleOPFstructureavailabletoendusers, Mat-poweralsotakesadvantageof itinternallytoimplementseveral additional capa-bilities.6.4.1 PiecewiseLinearCostsThe standardOPFformulationin(6.1)(6.4) does not directlyhandle the non-smoothpiecewiselinear cost functions that typicallyarisefromdiscretebids andoersinelectricitymarkets. Whensuchcostfunctionsareconvex, however, theycan be modeled using a constrained cost variable (CCV) method. The piecewise lin-ear cost function c(x) is replaced by a helper variable y and a set of linear constraintsthat form a convex basin requiring the cost variable yto lie in the epigraph of thefunctionc(x).Figure6-3illustratesaconvexn-segmentpiecewiselinearcostfunctionc(x) =___m1(x x1) + c1, x x1m2(x x2) + c2, x1< x x2......mn(x xn) + cn, xn1< x(6.32)xx0x1x2cc0c1c2ycnxnFigure6-3: ConstrainedCostVariable44denedbyasequenceof points(xj, cj), j=0 . . . n, wheremjdenotestheslopeofthej-thsegmentmj=cj cj1xj xj1, j= 1 . . . n (6.33)andx0< x1 360. Ifbothparametersarezero,thevoltageangledierenceisunconstrained.11Availablefromhttps://projects.coin-or.org/Ipopt/.48MatlabMEXinterfacetoIpopt12. ItalsoincludestheoptiontouseCPLEX13orMOSEK14forDCOPFs. Matpower4.1addedtheoptiontouseKNITRO[29]15forACOPFsandtheGurobi Optimizer16forDCOPFsandMatpower5addedGLPK.SeeAppendixGformoredetailsontheseoptionalpackages.Beginnning with version 4, Matpower also includes its own primal-dual interiorpoint methodimplementedinpure-Matlabcode, derivedfromtheMEXimple-mentationofthealgorithmsdescribedin[17]. ThissolveriscalledMIPS(MatlabInteriorPointSolver)andisdescribedinmoredetailinAppendixA.Ifnooptionalpackages are installed, MIPS will be used by default for both the AC OPF and as theQP solver used by the DC OPF. The AC OPF solver also employs a unique techniqueforecientlyformingtherequiredHessiansviaafewsimplematrixoperations[23].This solver has applicationtogeneral nonlinear optimizationproblems outsideofMatpower and can be called directly asmips. There is also a convenience wrapperfunctioncalledqpsmipsmakingittrivialtosetupandsolveLPandQPproblems,withaninterfacesimilartoquadprogfromtheMatlabOptimizationToolbox.6.6 runopfInMatpower, anoptimal power owis executedbycallingrunopfwithacasestructorcaselenameastherstargument(casedata). Inadditiontoprintingoutputtothescreen,whichitdoesbydefault,runpfoptionallyreturnsthesolutioninaresultsstruct.>> results = runopf(casedata);The resultsstruct is asuperset of the input Matpowercase struct mpc, withsomeadditional elds as well as additional columns insomeof theexistingdataelds. Inadditiontothesolutionvaluesincludedintheresultsforasimplepowerow,showninTable4-1inSection4.3,thefollowingadditionaloptimalpowerowsolutionvaluesarestoredasshowninTable6-1.Additional optional input arguments canbe usedtoset options (mpopt) andprovidelenamesforsavingtheprettyprintedoutput(fname)orthesolvedcasedata(solvedcase).12Seehttps://projects.coin-or.org/Ipopt/wiki/MatlabInterface.13Seehttp://www.ibm.com/software/integration/optimization/cplex-optimizer/.14Seehttp://www.mosek.com/.15Seehttp://www.ziena.com/.16Seehttp://www.gurobi.com/.49Table6-1: OptimalPowerFlowResultsname descriptionresults.f nalobjectivefunctionvalueresults.x nalvalueofoptimizationvariables(internalorder)results.om OPFmodelobjectresults.bus(:, LAMP) Lagrangemultiplieronrealpowermismatchresults.bus(:, LAMQ) Lagrangemultiplieronreactivepowermismatchresults.bus(:, MUVMAX) Kuhn-Tuckermultiplieronuppervoltagelimitresults.bus(:, MUVMIN) Kuhn-Tuckermultiplieronlowervoltagelimitresults.gen(:, MUPMAX) Kuhn-TuckermultiplieronupperPglimitresults.gen(:, MUPMIN) Kuhn-TuckermultiplieronlowerPglimitresults.gen(:, MUQMAX) Kuhn-TuckermultiplieronupperQglimitresults.gen(:, MUQMIN) Kuhn-TuckermultiplieronlowerQglimitresults.branch(:, MUSF) Kuhn-Tuckermultiplieronowlimitatfrombusresults.branch(:, MUST) Kuhn-Tuckermultiplieronowlimitattobusresults.mu shadowpricesofconstraintsresults.g (optional)constraintvaluesresults.dg (optional)constraint1stderivativesresults.raw rawsolveroutputinformreturnedbyMINOS,andmoreresults.var.val nalvalueofoptimizationvariables,bynamedsubsetresults.var.mu shadowpricesonvariablebounds,bynamedsubsetresults.nln shadowpricesonnonlinearconstraints,bynamedsubsetresults.lin shadowpricesonlinearconstraints,bynamedsubsetresults.cost nalvalueofuser-denedcosts,bynamedsubsetSeehelpforopfmodelformoredetails.Seehelpforopfformoredetails.>> results = runopf(casedata, mpopt, fname, solvedcase);Some of the main options that control the optimal power ow simulation are listed inTable 6-2. There are many other options that can be used to control the terminationcriteria and other behavior of the individual solvers. See Appendix C or the mpoptionhelpfordetails. AswithrunpftheoutputprintedtothescreencanbecontrolledbytheoptionsinTable4-3, butthereareadditional outputoptionsfortheOPF,relatedtothedisplayof bindingconstraintsthatarelistedTable6-3, alongwithanoptionthatcanbeusedtoforcetheACOPFtoreturninformationabouttheconstraintvaluesandJacobianandtheobjectivefunctiongradientandHessian.By default,runopf solves an AC optimal power ow problem using a primal dualinterior point method. To run a DC OPF, themodel option must be set to 'DC'. Forconvenience, Matpowerprovidesafunctionrundcopfwhichissimplyawrapper50thatsetsthemodelto 'DC'beforecallingrunopf.Internally, the runopffunctiondoes anumber of conversions tothe problemdatabeforecallingtheappropriatesolverroutinefortheselectedOPFalgorithm.Thisexternal-to-internal format conversionisperformedbytheext2intfunction,described in more detail in Section 7.2.1, and includes the elimination of out-of-serviceequipment, theconsecutiverenumberingof busesandthereorderingof generatorsbyincreasingbusnumber. All computationsaredoneusingthisinternal indexing.Whenthesimulationhascompleted, thedataisconvertedbacktoexternalformatbyint2extbeforetheresultsareprintedandreturned. Inaddition, bothext2intandint2extcanbecustomizedviauser-suppliedcallbackroutinestoconvertdataneededbyuser-suppliedvariables,constraintsorcostsintointernalindexing.51Table6-2: OptimalPowerFlowOptionsname default descriptionopf.ac.solver 'DEFAULT' ACoptimalpowerowsolver:'DEFAULT'choose default solver based on availability inthefollowingorder: 'PDIPM', 'MIPS''MIPS' MIPS, MatlabInterior Point Solver, pri-mal/dualinteriorpointmethod'FMINCON'MatlabOptimizationToolbox,fmincon'IPOPT' Ipopt*'KNITRO' KNITRO*'MINOPF' MINOPF*,MINOS-basedsolver'PDIPM' PDIPM*,primal/dualinteriorpointmethod'SDPOPF' SDPOPF*, solver based on semidenite relax-ation'TRALM' TRALM*, trust region based augmented Lan-grangianmethodopf.dc.solver 'DEFAULT' DCoptimalpowerowsolver:'DEFAULT'choose default solver based on availabilityinthefollowingorder: 'CPLEX', 'GUROBI','MOSEK', 'BPMPD', 'OT', 'GLPK' (linearcostsonly), 'MIPS''MIPS' MIPS, MatlabInterior Point Solver, pri-mal/dualinteriorpointmethod'BPMPD' BPMPD*'CPLEX' CPLEX*'GLPK' GLPK*(noquadraticcosts)'GUROBI' Gurobi*'IPOPT' Ipopt*'MOSEK' MOSEK*'OT' MatlabOptToolbox,quadprog,linprogopf.violation 5 106constraintviolationtoleranceopf.flowlim 'S' quantitytolimitforbranchowconstraints'S'apparentpowerow(limitinMVA)'P'activepowerow(limitinMW)'I'currentmagnitude(limitinMVAat1p.u.voltage)opf.ignoreanglim 0 ignoreangledierencelimitsforbranches0includeangledierencelimits,ifspecied1ignoreangledierencelimitsevenifspeciedopf.returnrawder 0 for ACOPF, return constraint and derivative info inresults.raw(ineldsg,dg,df,d2f)*Requirestheinstallationofanoptionalpackage. SeeAppendixGfordetailsonthecorrespondingpackage.ForSC-PDIPM,thestep-controlledversionofthissolver,thepdipm.stepcontroloptionmustbesetto1.ForMIPS-sc,thestep-controlledversionofthissolver,themips.stepcontroloptionmustbesetto1.52Table6-3: OPFOutputOptionsname default descriptionout.lim.all -1 controlsconstraintinfooutput-1individualagscontrolwhatisprinted0donot printanyconstraintinfo1printonlybindingconstraintinfo2printallconstraintinfoout.lim.v 1 controloutputofvoltagelimitinfo0donot print1printbindingconstraintsonly2printallconstraintsout.lim.line 1 controloutputoflineowlimitinfoout.lim.pg 1 controloutputofgenactivepowerlimitinfoout.lim.qg 1 controloutputofgenreactivepowerlimitinfoOverridesindividualags.Takesvaluesof0,1or2asforout.lim.v.537 ExtendingtheOPFThe extended OPF formulation described in Section 6.3 allows the user to modify thestandardOPFformulationtoincludeadditionalvariables,costsand/orconstraints.There are two primary mechanisms available for the user to accomplish this. The rstisbydirectlyconstructingthefull parametersfortheaddional costsorconstraintsandsupplyingthemeitheraseldsinthecasestructordirectlyasargumentstotheopffunction. Thesecond, andmorepowerful, methodisviaasetof callbackfunctionsthatcustomizetheOPFatvariousstagesoftheexecution. Matpowerincludestwoexamplesofusingthelattermethod, onetoaddaxedzonal reserverequirementandanothertoimplementinterfaceowlimits.7.1 DirectSpecicationToaddcosts directly, the parameters H, C, N, r, k, dandmof (6.27)(6.31)describedinSection6.3.1arespeciedaseldsorarguments H, Cw, Nandfparm,repectively,wherefparmisthenw4matrixfparm=_d r k m. (7.1)Whenspecifyingadditional costs, NandCware required, while Handfparmareoptional. ThedefaultvalueforHisazeromatrix,andthedefaultforfparmissuchthatdandmareallonesand randkareallzeros, resultinginsimplelinearcost,withnoshiftordead-zone. NandHshouldbespeciedassparsematrices.Foradditional constraints, theA, l anduparametersof (6.25)arespeciedaseldsorargumentsofthesamenames,A,landu,respectively,whereAissparse.Additional variablesarecreatedimplicitlybasedonthedierencebetweenthenumberof columnsinAandthenumbernxof standardOPFvariables. If Ahasmore columns than x has elements, the extra columns are assumed to correspond toanewzvariable. Theinitial valueandlowerandupperboundsforzcanalsobespeciedintheoptionaleldsorarguments,z0,zlandzu,respectively.ForasimpleformulationextensiontobeusedforasmallnumberofOPFcases,thismethodhastheadvantageof beingdirectandstraightforward. WhileMat-power does include code to eliminate the columns of A and Ncorresponding to Vmand Qgwhen running a DC OPF17, as well as code to reorder and eliminate columnsappropriatelywhenconvertingfromexternal tointernal dataformats, thismecha-nismstill requirestheusertotakespecial careinpreparingtheAandNmatrices17Onlyiftheycontainallzeros.54toensurethatthecolumnsmatchtheorderingof theelementsof theopimizationvectorsxandz. All extraconstraintsandvariablesmust beincorporatedintoasingle set of parameters that are constructed before calling the OPF. The bookkeep-ingneededtoaccesstheresultingvariablesandshadowpricesonconstraintsandvariableboundsmustbehandledmanuallybytheuseroutsideof theOPF, alongwithanyprocessingof additional inputdataandprocessing, printingorsavingoftheadditional resultdata. Makingfurthermodicationstoaformulationthatal-readyincludesuser-suppliedcosts, constraintsorvariables, requiresthatbothsetsbeincorporatedintoanewsingleconsistentsetofparameters.7.2 CallbackFunctionsThe secondmethod, basedondeningaset of callbackfunctions, oers severaldistinctadvantages, especiallyformorecomplexscenariosorforaddingafeatureforotherstouse, suchasthezonal reserverequirementortheinterfaceowlimitsmentionedpreviously. Thisapproachmakesitpossibleto: deneandaccessvariable/constraintsetsasindividualnamedblocks deneconstraints,costsonlyintermsofvariablesdirectlyinvolved pre-processinputdataand/orpost-processresultdata printandsavenewresultdata simultaneouslyusemultiple, independentlydevelopedextensions(e.g. zonalreserverequirementsandinterfaceowlimits)Matpowerdenesvestagesintheexecutionof asimulationwherecustomcodecanbeinsertedtoalter thebehavior or databeforeproceedingtothenextstage. Thiscustomcodeisdenedasasetof callbackfunctionsthatareregis-tered viaadduserfcn for Matpower to call automatically at one of the ve stages.Each stage has a name and, by convention, the name of a user-dened callback func-tionendswiththenameof thecorrespondingstage. For example, acallbackfortheformulationstagethatmodiestheOPFproblemformulationtoaddreserverequirementscouldberegisteredwiththefollowinglineofcode.mpc = add_userfcn(mpc, 'formulation', @userfcn_reserves_formulation);55The sections below willdescribe eachstage andthe input andoutput argumentsfor thecorrespondingcallbackfunction, whichvarydependingonthestage. Anexamplethat employs additional variables, constraints andcosts will beusedforillustration.Consider the problemof jointlyoptimizingthe allocationof bothenergyandreserves,wherethereserverequirementsaredenedasasetofnrzxedzonalMWquantities. LetZkbethesetof generatorsinzonekandRkbetheMWreserverequirementforzonek. Anewsetof variablesrareintroducedrepresentingthereservesprovidedbyeachgenerator. Thevalueri, for generator i, must benon-negativeandislimitedabovebyauser-providedupperboundrmaxi(e.g. areserveoerquantity)aswellasthephysicalrampratei.0 ri min(rmaxi, i), i = 1 . . . ng(7.2)Ifthevectorccontainsthemarginalcostofreservesforeachgenerator,theuserdenedcosttermfrom(6.21)issimplyfu(x, z) = cTr. (7.3)Therearetwoadditional setsof constraintsneeded. Therstensuresthat, foreach generator, the total amount of energy plus reserve provided does not exceed thecapacityoftheunit.pig + ri pi,maxg, i = 1 . . . ng(7.4)Thesecondrequiresthatthesumofthereserveallocatedwithineachzonekmeetsthestatedrequirements.

iZkri Rk, k = 1 . . . nrz(7.5)Table 7-1 describes some of the variables and names that are used in the examplecallbackfunctionlistingsinthesectionsbelow.7.2.1 ext2intCallbackBeforedoinganysimulationofacase, Matpowerperformssomedataconversiononthecasestructinordertoachieveaconsistentinternalstructure,bycallingthefollowing.mpc = ext2int(mpc);56Table7-1: NamesUsedbyImplementationofOPFwithReservesname descriptionmpc Matpowercasestructreserves additional eldinmpccontaininginputparametersforzonal reservesinthefollowingsub-elds:cost ng 1vectorofreservecosts,cfrom(7.3)qty ng 1vectorofreservequantityupperbounds,ithelementisrmaxizones nrz ngmatrixofreservezonedenitionszones(k,j)=_1 if genjbelongstoreservezonek (j Zk)0 otherwise (j / Zk)req nrz 1vectorofzonalreserverequirements,kthelementisRkfrom(7.5)om OPFmodelobject,alreadyincludesstandardOPFsetupresults OPFresultsstruct,supersetofmpcwithadditionaleldsforoutputdatang ng,numberofgeneratorsR namefornewreservevariableblock,ithelementisriPgplusR namefornewcapacitylimitconstraintset(7.4)Rreq namefornewreserverequirementconstraintset(7.5)All isolatedbuses, out-of-servicegeneratorsandbranchesareremoved, alongwithanygeneratorsorbranchesconnectedtoisolatedbuses. Thebusesarerenumberedconsecutively,beginningat1,andthein-servicegeneratorsaresortedbyincreasingbusnumber. Alloftherelatedindexinginformationandtheoriginaldatamatricesare stored in anorder eld in the case struct to be used later byint2ext to performthereverseconversionswhenthesimulationiscomplete.The rst stage callback is invoked from within theext2int function immediatelyafterthecasedatahasbeenconverted. InputsareaMatpowercasestruct(mpc),freshlyconvertedtointernalindexingandany(optional)argsvaluesuppliedwhenthecallbackwasregisteredviaadduserfcn. Outputisthe(presumablyupdated)mpc. Thisistypicallyusedtoreorderanyinputargumentsthatmaybeneededininternal orderingbytheformulationstage. Theexampleshowshowe2ifieldcanalso be used, with a case struct that has already been converted to internal indexing,toconvertotherdatastructuresbypassingin2or3extraparametersinadditiontothecasestruct. Inthiscase,itautomaticallyconvertstheinputdataintheqty,costandzoneseldsof mpc.reservestobeconsistentwiththeinternal generatorordering, whereo-linegeneratorshavebeeneliminatedandtheon-linegeneratorsaresortedinorder ofincreasingbus number. Notice thatit istheseconddimension(columns)of mpc.reserves.zonesthatisbeingre-ordered. Seetheon-linehelpfore2ifieldande2idataformoredetailsonwhatalltheycando.57function mpc = userfcn_reserves_ext2int(mpc, args)mpc = e2i_field(mpc, {'reserves', 'qty'}, 'gen');mpc = e2i_field(mpc, {'reserves', 'cost'}, 'gen');mpc = e2i_field(mpc, {'reserves', 'zones'}, 'gen', 2);Thisstageisalsoagoodplacetochecktheconsistencyofanyadditionalinputdatarequiredbytheextensionandthrowanerrorifsomethingismissingornotasexpected.7.2.2 formulationCallbackThisstageiscalledfromopfaftertheOPFModel (om)objecthasbeeninitializedwiththestandardOPFformulation,butbeforecallingthesolver. Thisistheidealplaceformodifyingtheproblemformulationwithadditional variables, constraintsandcosts,usingtheaddvars, addconstraintsandaddcostsmethodsoftheOPFModel object. Inputsaretheomobjectandany(optional)argssuppliedwhenthecallbackwasregisteredviaadduserfcn. Outputistheupdatedomobject.The om object contains both the original Matpower case data as well as all of theindexingdataforthevariablesandconstraintsofthestandardOPFformulation.18See the on-line help foropfmodel for more details on the OPF model object and themethodsavailableformanipulatingandaccessingit.Intheexamplecode, anewvariableblocknamedRwithngelementsandthelimits from(7.2) is addedtothemodel viathe addvarsmethod. Similarly, twolinearconstraintblocksnamedPgplusRandRreq, implementing(7.4)and(7.5),respectively,areaddedviatheaddconstraintsmethod. Andnally,theaddcostsmethod is used to add to the model a user-dened cost block corresponding to (7.3).Noticethatthelastargumenttoaddconstraintsandaddcostsallowsthecon-straintsandcoststobedenedonlyintermsoftherelevantpartsoftheoptimiza-tion variable x. For example, theA matrix for thePgplusR constraint contains onlycolumnscorrespondingtorealpowergeneration(Pg)andreserves(R)andneednotbother withvoltages, reactivepower injections, etc. As illustratedinFigure7-1,thisallowsthesamecodetobeusedwithboththeACOPF, wherexincludesVmandQg, andtheDCOPFwhereitdoesnot. Thiscodeisalsoindependentofany18Itisperfectlylegitimatetoregistermorethanonecallbackperstage, suchaswhenenablingmultipleindependentOPFextensions. Inthiscase, thecallbacksareexecutedintheordertheywereregisteredwithadduserfcn. E.g. whenthesecondandsubsequentformulationcallbacksare invoked, the om object will reect any modications performed by earlier formulation callbacks.58additional variables that may have been added by Matpower (e.g. y variables fromMatpowersCCVhandlingofpiece-wiselinearcosts)orbytheuserviapreviousformulationcallbacks. Matpowerwill placetheconstraintmatrixblocksintheappropriate place when it constructs the overallA matrix at run-time. This is an im-portantfeaturethatenablesindependentlydevelopedMatpowerOPFextensionstoworktogether.VaA = 0 A1 0 0 0 A2A = 0 A1 0 A2Ar = A1 A2Va Pg Vm y Qg RPg y RAC OPFDC OPFFigure7-1: AddingConstraintsAcrossSubsetsofVariables59function om = userfcn_reserves_formulation(om, args)%% initialize some thingsdefine_constants;mpc = get_mpc(om);r = mpc.reserves;ng = size(mpc.gen, 1); %% number of on-line gens%% variable boundsRmin = zeros(ng, 1); %% bound below by 0Rmax = r.qty; %% bound above by stated max reserve qty ...k = find(mpc.gen(:, RAMP_10) > 0 & mpc.gen(:, RAMP_10) < Rmax);Rmax(k) = mpc.gen(k, RAMP_10); %% ... and ramp rateRmax = Rmax / mpc.baseMVA;%% constraintsI = speye(ng); %% identity matrixAr = [I I];Pmax = mpc.gen(:, PMAX) / mpc.baseMVA;lreq = r.req / mpc.baseMVA;%% costCw = r.cost * mpc.baseMVA; %% per unit cost coefficients%% add them to the modelom = add_vars(om, 'R', ng, [], Rmin, Rmax);om = add_constraints(om, 'Pg_plus_R', Ar, [], Pmax, {'Pg', 'R'});om = add_constraints(om, 'Rreq', r.zones, lreq, [], {'R'});om = add_costs(om, 'Rcost', struct('N', I, 'Cw', Cw), {'R'});7.2.3 int2extCallbackAfterthesimulationiscompleteandbeforetheresultsareprintedorsaved, Mat-powerconvertsthecasedataintheresultsstructbacktoexternal indexingbycallingthefollowing.results = int2ext(results);This conversion essentially undoes everything that was done byext2int. Generatorsare restoredtotheir original ordering, buses totheir original numberingandallout-of-serviceorisolatedgenerators,branchesandbusesarerestored.Thiscallbackisinvokedfromint2extimmediatelybeforetheresultingcaseisconvertedfrominternal backtoexternal indexing. At this point, thesimulation60hasbeencompletedandtheresultsstruct, asupersetoftheoriginal MatpowercasestructpassedtotheOPF, containsall of theresults. This resultsstructispassedtothecallback, alongwithany(optional)argssuppliedwhenthecallbackwasregisteredviaadduserfcn. Theoutputofthecallbackistheupdatedresultsstruct. This is typically used to convert any results to external indexing and populateanycorrespondingeldsintheresultsstruct.The results struct contains, in addition to the standard OPF results, solution in-formation related to all of the user-dened variables, constraints and costs. Table 7-2summarizeswherethevariousdataisfound. Eachof theeldslistedinthetableisactuallyastructwhoseeldscorrespondtothenamedsetscreatedbyaddvars,addconstraintsandaddcosts.Table7-2: ResultsforUser-DenedVariables,ConstraintsandCostsname descriptionresults.var.val nalvalueofuser-denedvariablesresults.var.mu.l shadowpriceonlowerlimitofuser-denedvariablesresults.var.mu.u shadowpriceonupperlimitofuser-denedvariablesresults.lin.mu.l shadowpriceonlower(left-hand)limitoflinearconstraintsresults.lin.mu.u shadowpriceonupper(right-hand)limitoflinearconstraintsresults.cost nalvalueofuser-denedcostsIn the example code below, the callback function begins by converting the reservesinput data in the resulting case (qty, cost and zones elds of results.reserves) backtoexternalindexingviacallstoi2efield. Seethehelpfori2efieldandi2edataformoredetailsonhowtheycanbeused.Then the reserves results of interest are extracted from the appropriate sub-eldsofresults.var,results.lin andresults.cost, converted from per unit to per MWwherenecessary, andstoredwithexternal indexingfortheenduserinthechoseneldsoftheresultsstruct.61function results = userfcn_reserves_int2ext(results, args)%%----- convert stuff back to external indexing -----%% convert all reserve parameters (zones, costs, qty, rgens)results = i2e_field(results, {'reserves', 'qty'}, 'gen');results = i2e_field(results, {'reserves', 'cost'}, 'gen');results = i2e_field(results, {'reserves', 'zones'}, 'gen', 2);r = results.reserves;ng = size(results.gen, 1); %% number of on-line gens (internal)ng0 = size(results.order.ext.gen, 1); %% number of gens (external)%%----- results post-processing -----%% get the results (per gen reserves, multipliers) with internal gen indexing%% and convert from p.u. to per MW units[R0, Rl, Ru] = getv(results.om, 'R');R = results.var.val.R * results.baseMVA;Rmin = Rl * results.baseMVA;Rmax = Ru * results.baseMVA;mu_l = results.var.mu.l.R / results.baseMVA;mu_u = results.var.mu.u.R / results.baseMVA;mu_Pmax = results.lin.mu.u.Pg_plus_R / results.baseMVA;%% store in results in results structz = zeros(ng0, 1);results.reserves.R = i2e_data(results, R, z, 'gen');results.reserves.Rmin = i2e_data(results, Rmin, z, 'gen');results.reserves.Rmax = i2e_data(results, Rmax, z, 'gen');results.reserves.mu.l = i2e_data(results, mu_l, z, 'gen');results.reserves.mu.u = i2e_data(results, mu_u, z, 'gen');results.reserves.mu.Pmax = i2e_data(results, mu_Pmax, z, 'gen');results.reserves.prc = z;for k = 1:ng0iz = find(r.zones(:, k));results.reserves.prc(k) = sum(results.lin.mu.l.Rreq(iz)) / results.baseMVA;endresults.reserves.totalcost = results.cost.Rcost;7.2.4 printpfCallbackThepretty-printingofthestandardOPFoutputisdoneviaacalltoprintpfafterthe case has been converted back to external indexing. This callback is invoked fromwithinprintpfafterthepretty-printingof thestandardOPFoutput. Inputsare62theresults struct,the le descriptor to write to,a Matpower options struct,andany(optional)argssuppliedviaadduserfcn. Outputistheresultsstruct. Thisistypicallyusedforanyadditionalpretty-printingofresults.Inthisexample,theout.allagintheoptionsstructischeckedbeforeprintinganything. If it is non-zero, the reserve quantities and prices for each unit are printedrst, followedbytheper-zonesummaries. Anadditional tablewithreservelimitshadowpricesmightalsobeincluded.63function results = userfcn_reserves_printpf(results, fd, mpopt, args)%% define named indices into data matrices[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;%%----- print results -----r = results.reserves;ng = length(r.R);nrz = size(r.req, 1);if mpopt.out.all ~= 0fprintf(fd, '\n=======================================================');fprintf(fd, '\n| Reserves |');fprintf(fd, '\n=======================================================');fprintf(fd, '\n Gen Bus Status Reserves Price');fprintf(fd, '\n # # (MW) ($/MW)');fprintf(fd, '\n---- ----- ------ -------- --------');for k = 1:ngfprintf(fd, '\n%3d %6d %2d ', k, results.gen(k, GEN_BUS), ...results.gen(k, GEN_STATUS));if results.gen(k, GEN_STATUS) > 0 && abs(results.reserves.R(k)) > 1e-6fprintf(fd, '%10.2f', results.reserves.R(k));elsefprintf(fd, ' - ');endfprintf(fd, '%10.2f ', results.reserves.prc(k));endfprintf(fd, '\n --------');fprintf(fd, '\n Total:%10.2f Total Cost: $%.2f', ...sum(results.reserves.R(r.igr)), results.reserves.totalcost);fprintf(fd, '\n');fprintf(fd, '\nZone Reserves Price ');fprintf(fd, '\n # (MW) ($/MW) ');fprintf(fd, '\n---- -------- --------');for k = 1:nrziz = find(r.zones(k, :)); %% gens in zone kfprintf(fd, '\n%3d%10.2f%10.2f', k, sum(results.reserves.R(iz)), ...results.lin.mu.l.Rreq(k) / results.baseMVA);endfprintf(fd, '\n');%% print binding reserve limit multipliers ...end647.2.5 savecaseCallbackThesavecaseisusedtosaveaMatpowercasestructtoanM-le, forexample,tosavetheresultsofanOPFrun. Thesavecasecallbackisinvokedfromsavecaseafterprintingall of theotherdatatothele. Inputsarethecasestruct, theledescriptor to write to, the variable prex (typically 'mpc.') and any (optional)argssuppliedviaadduserfcn. Outputisthecasestruct. Thepurposeofthiscallbackistowriteanynon-standardcasestructeldstothecasele.Inthisexample,thezones, req, costandqtyeldsofmpc.reservesarewrittento the M-le. This ensures that a case with reserve data, if it is loaded vialoadcase,possiblyrun, thensavedviasavecase, will notlosethedatainthereserveseld.This callbackcouldalsoinclude the savingof the output elds if present. Thecontributedserializefunction19canbeveryusefulforthispurpose.19http://www.mathworks.com/matlabcentral/fileexchange/120665function mpc = userfcn_reserves_savecase(mpc, fd, prefix, args)%% mpc = userfcn_reserves_savecase(mpc, fd, mpopt, args)%% This is the 'savecase' stage userfcn callback that prints the M-file% code to save the 'reserves' field in the case file. It expects a% MATPOWER case struct (mpc), a file descriptor and variable prefix% (usually 'mpc.'). The optional args are not currently used.r = mpc.reserves;fprintf(fd, '\n%%%%----- Reserve Data -----%%%%\n');fprintf(fd, '%%%% reserve zones, element i, j is 1 iff gen j is in zone i\n');fprintf(fd, '%sreserves.zones = [\n', prefix);template = '';for i = 1:size(r.zones, 2)template = [template, '\t%d'];endtemplate = [template, ';\n'];fprintf(fd, template, r.zones.');fprintf(fd, '];\n');fprintf(fd, '\n%%%% reserve requirements for each zone in MW\n');fprintf(fd, '%sreserves.req = [\t%g', prefix, r.req(1));if length(r.req) > 1fprintf(fd, ';\t%g', r.req(2:end));endfprintf(fd, '\t];\n');fprintf(fd, '\n%%%% reserve costs in $/MW for each gen\n');fprintf(fd, '%sreserves.cost = [\t%g', prefix, r.cost(1));if length(r.cost) > 1fprintf(fd, ';\t%g', r.cost(2:end));endfprintf(fd, '\t];\n');if isfield(r, 'qty')fprintf(fd, '\n%%%% max reserve quantities for each gen\n');fprintf(fd, '%sreserves.qty = [\t%g', prefix, r.qty(1));if length(r.qty) > 1fprintf(fd, ';\t%g', r.qty(2:end));endfprintf(fd, '\t];\n');end%% save output fields for solved case ...667.3 RegisteringtheCallbacksAs seen in the xed zonal reserve example, adding a single extension to the standardOPF formulation is often best accomplished by a set of callback functions. A typicalusecasemightbetorunagivencasewithandwithoutthereserverequirementsactive, so a simple method for enabling and disabling the whole set of callbacks as asingleunitisneeded.The recommended method is to dene all of the callbacks in a single le containinga toggle function that registers or removes all of the callbacks depending on whetherthe value of the second arg