Home
MPCMath User Manual - 2
Contents
1. 15 2 ODEMethods Enumeration ODEMethods ODE solver methods enumeration enum ODEMethods 226 CHAPTER 15 ODE SOLVERS Fields DOPRI5 DOPRI5 4 7 stages order 4 ERK1 Explicit Euler ERK2A Explicit Trapezoidal alpha 1 ERK2B Explicit Trapezoidal alpha Three stage ERK ERK3B Three stage ERK ERK4A Four Stage ERK ERK4B Four Stage ERK ERK4C Classical Runge Kutta 4 order 4 tages ERK4D Four Stage ERK ESDIRK12 Explicit Singly Diagonally Implicit Runge Kutta method 12 ESDIRK23 Explicit Singly Diagonally Implicit Runge Kutta method 23 ESDIRK34 Explicit Singly Diagonally Implicit Runge Kutta method 34 15 3 ODESolver Class ODESolver ODE solver for ordinary differential eguations class ODESolver Constructors ODESolver ODEMethods Method IModel Model double Step this Method Model Step null null Constructor for fixed step size Parameters Method Integration Method Model Differential equations Step Step size ODESolver ODEMethods Method IModel Model double InitialStep Vector AbsTol Vector RelTol Constructor for adaptive step size Parameters Method Integration Method Model Differential equations Step Initial step size AbsTol Absolute tolerance RelTol Relative tolerance Properties A Butcher tableau A 15 3 ODESOLVER Matrix A get AcceptedSteps Number of Accepted steps int AcceptedSteps set get B Butcher tableau B Vector B get
2. 5tnQnan t Ik 12 4b 2 176CHAPTER 12 UNCONSTRAINED AND CONSTRAINED MINIMIZATION The initial state is a parameter and not a decision variable The following code example illustrates the use of the Riccati Solver class console WriteLine Test Riccati int N 100 Double T 1 0 Second order system double gain double dela double tau 3 double sigma 0 1 TransferFunction G new TransferFunction gain delay tau sigma StateSpaceModel Plant new StateSpaceModel G T StateSpaceModel Show Model Plant Plant Dimension Plant NU Plant NY int nx int nu int ny y 1 0 0 0 10 0 initial condition Vector Matrix Matrix Vector XO Ak Bk bk new Vector nx 1 0 Plant A Plant B Plant Off Vector theta new Vector ny 1 0 Vector rho new Vector nu 1 0 define stage penalties Matrix Qk Matrix MulTransposed Plant C new Matrix theta Plant C Vector gk new Vector nx Matrix Rk new Matrix rho Vector rk new Vector nu Matrix Mk new Matrix nx nu end condition penalties Matrix PN Ak Vector pN qk Matrix Show Rk Rk Vector Show rk rk Matrix Show Qk Qk Vector Show qk qk Matrix Show Mk Mk Matrix Show Pn PN Vector Show pn pN 12 2 EXTENDED LINEAR QUADRATIC OPTIMAL CONTROL PROBLEM177 Matrix Show Ak Ak Matrix Show Bk Bk Vector Show bk bk store st
3. Bq dt ARXModel Show plant plant Arx model with noise model double alfa 0 7 ARXModel model new ARXModel delayCount Aq Bq dt alfa ARXModel Show model model plant ARX Model Delay 25 steps A Vector 1 1 5580 0 5769 B Vector 0 0 2094 0 1744 model ARX Model Delay 25 steps 1 6 ARX MODELS 17 A Vector 1 2 5580 2 1349 0 5769 Vector 0 0 2094 0 0350 0 1744 ARX and EAARX objects can be directly created from transfer functions The transfer function 20 50 8 508 1 48 1 can be realized as ARX and EAARX objects by G s gain 20 0 delay 50 0 dt 2 0 Vector taus new Vector 50 0 4 0 TransferFunction Furnace TransferFunction TauForm gain delay taus TransferFunction Show Furnace Furnace plant new ArxModel Furnace dt ArxModel Show plant plant Furnace TransferFunction Delay 50 0000 seconds R 0 1000 P 0 0050 0 2700 1 Gain 0 1000 Roots Complex List 0 0200 i 0 0 2500 i 0 plant Arx Model Delay 25 steps A Vector 1 1 5673 0 5827 B Vector 0 0 1681 0 1405 The time responses from the ARX model can be calculated using the NextState and Observed functions 18 CHAPTER 1 INTRODUCTION x new Vector plant Dimension double u 100 0 double eps double epsVariance 0 1 double epsMean 0 0 resp new Vector steps for int step O step lt steps eps MPCMathLib WhiteGaussianNoise eps
4. ExitReason Reason for leaving Minimizer string ExitReason get Iterations Number of Iterations int Iterations get 188CHAPTER 12 UNCONSTRAINED AND CONSTRAINED MINIMIZATION LambdaE Equality Lagrange multipliers Vector LambdaE set get Lambdal Inequality Lagrange multipliers Vector Lambdal set get MaxlIterations Maximum number of iteration steps int MaxIterations get Mu Penalty of squared constraints double Mu get Mu0 Initial penalty of sguared constraints double Mu0 set get Ok Minimize or Consistent results OK bool Ok get ResGradL Lagrange iteration residual double ResGradL get ResGradX X iteration residual on gradient double ResGradX get 12 5 CONFUNMIN ResStepX X iteration residual on step length double ResStepX get Trace Trace iterations bool Trace set get TraceLevel Trace level int TraceLevel set get X Argmin X Vector X get XIterations Total number of iterations i X Minimizer int XIterations get X Minimizer Reference to Minimizer for augmented Lagrangian function FunMin XMinimizer get Methods Consistent Check consistence of function to be minimized bool Consistent Vector x Parameters X operation point returns true if consistent 189 190CHAPTER 12 UNCONSTRAINED AND CONSTRAINED MINIMIZATION Consistent Check consistence of function to be minimized bool Consistent Vector x Vec
5. R R matrix A Q R R upper triangular Matrix R get R1 R1 matrix R upper triangular Ry 22 Matrix R1 get Methods Solve Solve A x Vector Solve Vector r Parameters vector returns vector x 8 4 CHOLESKYEQUATIONSOLVER 137 Solve Solve A X R Matrix Solve Matrix R Parameters Matrix R returns Matrix X 8 4 CholeskyEquationSolver Class CholeskyEquationSolver Cholesky equations solver class CholeskyEquationSolver ISolver Constructors CholeskyEquationSolver Matrix Constructor Set Equations and do Cholesky decomposition Parameters a Coificient matrix Properties LTR Factor lower triangular Matrix LTR get Methods Solve Solve A x Vector Solve Vector r Parameters vector returns vector x 138 CHAPTER 8 EQUATION SOLVERS Solve Solve R Matrix Solve Matrix Parameters R Matrix R returns Matrix X 8 5 SymmetricEquationSolver Class SymmetricEquationSolver Symmetrical Equation solver class class SymmetricEquationSolver ISolver Constructors SymmetricEquationSolver Matrix Constructor Parameters Symmetrical coifficient matrix Methods Invert Invert matrix Matrix Invert Solve Solve A x Vector Solve Vector r Parameters vector returns vector x Solve Solve R Matrix Solve Matrix R Parameters Matrix R returns Matrix X 8 6 SYMMETRIC
6. b Input b returns a b operator Multiply constant and BVector static BVector operator double alpha BVector a Parameters alpha constant a Input returns alpha a operator Multiply BVector and constant static BVector operator BVector a double alpha Parameters a Input alpha Constant returns alpha a operator Divide BVector and constant static BVector operator BVector a double alpha Parameters alpha Constant a Input returns a alpha operator Multiply inner product static double operator BVector a BVector b Parameters a Input b Input b returns a b 90 CHAPTER 4 BLOCK VECTORS AND MATRICES operator Matrix vector operator static BVector operator BMatrix a BVector x Parameters a Input BMatix a Input BVector x returns operator Vector matrix operator static BVector operator BVector x BMatrix a Parameters BVector a BMatrix a returns x a Random Random BVector static BVector Random Structure strc double min double max Parameters stre Structure min Minimum value max Maximum value Restructure Restructure Vector from plain Vector static BVector Restructure Structure strct Vector a Parameters stret Structure a Input vecto returns Block vector Show Show static void Show string text BVector a Parameters text text string a BVector object 4 3 BMATRIX 91 Show Show fi
7. 1 0 Math Abs b 6 Limit static bool LimitViolation double a double b double Limit Parameters Value Limit Limit Violation Test for Limit violation Abs A i B i 1 0 Abs B i Limit for all elements in Vectors and B static bool LimitViolation Vector A Vector B double Limit Parameters B Limit 16 5 MPCMATHLIB UTIL 241 ProperZero Return a proper 0 0 if a less than MaxError static double ProperZero double a Parameters a ProperZero Return a proper 0 0 if a less than Eps static double ProperZero double a double Eps Parameters a Eps PseudoRandom Set Pseudo random mode if seed 0 Needed for debugging purposes get the same random number every time the program is started static void PseudoRandom int seed Parameters seed WhiteGaussianNoise White Gaussian Noise static double WhiteGaussianNoise double mean double var Parameters var mean mean variance WhiteGaussianNoise White Gaussian Noise static Vector WhiteGaussianNoise Vector mean Vector var Parameters mean mean var variance 242 CHAPTER 16 MPCMATHLIB Chapter 17 Miscellaneous functions 17 1 Complex Class complex Basic complex functionality Serializable class complex ICommon lt complex gt IComparable lt complex gt IEquatable lt complex gt Constructors complex 0 Constructor complex double RV double IV Constructor Parameters RV real v
8. 2 3 Using Console for test of GUI programs It can be very convenient to use the Console as a part of a GUI program Here console can be used to display debug information or detailed information about program operation Define a new WPF application and with two buttons Run and Console 38 CHAPTER 2 CONSOLE FUNCTIONS Run Console Q Design t EIXAML n m cj Window x Class TestConsole MainWindow xmlnss http schemas microsoft com winfx 2006 xaml presentation xmlns xe http schemas microsoft com winfx 2006 xaml Titles MainWindow Height 350 Width 525 gt lt Grid gt 7 Button Content Run Height 100 HorizontalAlignment Left Margin 92 33 0 0 Name btnRun VerticalAlignment Top Width 300 Click btnRun Click Button Content Console Height 100 HorizontalAlignment Left Margin 92 169 0 0 Name btnConsole VerticalAlignment Top Width 300 Clicke btnConsole Click gt lt Grid gt lt Window gt 100 using System Windows Media Imaging using System Windows Navigation using System Windows Shapes using MPCMath namespace TestConsole 1 lt summary gt Interaction logic for MainWindow xaml lt summary gt public partial class MainWindow Window private MPCMathConsole console public MainWindow InitializeComponent this console new MPCMathConsole true private void bt
9. 3 000 Bk Matrix Form General 2 1 0 0050 0 0049 bk Vector c 0 12 3 Function Minimization The function minimizer FunMin finds a local minima of a non linear function using a quasi Newton method BFGS min fun z 12 5a The function to be minimized must implement the Fun interface 11 1 with the property N and methods Value and D2 FunMin does not use the Hessian function DD The constrained function minimizer Con FunMin 12 5hnd a locals minima of fun x subject to equality and inequality constraints min fun a 12 62 st C x 20 12 6b Ci x gt 0 12 6c Where C is a vector of n equality conditions and C is a vector of ni inequality conditions The function to be minimized must implement the ConFun interface with the properties N Ne N1 and methods value Vale Dze Vali and Dzi ConFunMin does not require the Hessian functions DDx DDxi Use of FunMin and ConFunMin are illustrated on a simple non linear function 12 3 FUNCTION MINIMIZATION 179 fun zi z2 z2 11 a z2 7 12 7a s t C3 21 2 21 2 9 gt 0 12 7b Co z1 2 47 1072 gt 0 12 7c 200 160 160 140 120 100 80 60 40 20 The implementation of fun with the Con Fun interface is shown in appendix D The use of Fun Min is demonstrated is the code example below console WriteLine Test Constrained M
10. SetKalmanGain Set Kalman Gain from noise spectrum void SetKalmanGain Vector q Vector r Parameters q Process Noise r Measurement Noise 7 1 STATESPACEMODEL Show Show State Space model static void Show string txt StateSpaceModel model Parameters txt model 131 132 CHAPTER 7 STATE SPACE MODELS Chapter 8 Equation solvers Equation solvers are used to solve linear equations x The factor ization of the coefficient matrix is performed during the creation of the solver object making multiple solutions equations with equal coefficient matrices very efficient int dim 5 Matrix A Matrix Random dim dim 100 0 100 0 ISolver solver new LinearEquationSolver A Vector Random dim 100 0 100 0 Vector x solver Solve r Vector AssertEqual r A x Vector r Matrix R Matrix Random dim 3 100 0 100 0 Matrix X solver Solve R Matrix AssertEqual R A X R In this example the Vector AssertEqual and Matrix AssertEqual tests whether the correct solutions to the equations has been obtained The Linear EquationSolver performs the A L x U factorizations and can be used to invert matrices The equation solvers implements the interface Solver facilitating easy switch between solvers The SparseEquationSolver is using Inte s PARDISO solver 8 1 ISolver Interface ISolver Interface for Equation solvers 133 134 CHAPTER 8 EQUATION SOLVERS i
11. case Norm Huber strx Structure Values cols rows rows rows stry strz Structure Values rows Structure Values rows rows rows rows Gqp new BMatrix MatrixForm Diagonal strx g new BVector strx new BMatrix MatrixForm General stry strx b new BVector stry Cqp new BMatrix MatrixForm General strz strx d new BVector strz 1 Vector gammal new Vector rows gamma Gqp 1 1 I g 2 gammaI gammaI Aqp 0 O A 0 1 I 0 2 0 3 I 0101 y 0 1 I Cqp 1 1 I Matrix UnityMatrix rows 16 2 MPCMATHLIB RK4 233 2 2 3 I 4101 gammal 4111 gammal break KKTSolver kktsolver new KKTSolver Gqp g b d qpsolver new QPSolver kktsolver gpsolver MaxIterations 100 qpsolver ErrorLimit errorlim qpsolver Solve x qpsolver X 0 if gpsolver Iterations gt gpsolver MaxIterations throw new MPCMathException norm ToString else lssolver new LeastSquareEquationSolver A x lssolver Solve y return y else throw new MPCMathException enum Norm Fields Huber Huber norm 1 Norm 1 absolute value Norm2 Norm2 Euclid norm NormInfinity Norm Infinity 16 2 MPCMathLib RK4 Class MPCMathLib partial class MPCMathLib 234 CHAPTER 16 MPCMA
12. double Norm Norm1 Norm 1 of Matrix double Normi NormInf Norm Infinity of Matrix double NormInf operator Clone Matrix A B static Matrix operator Matrix a Parameters a Input matrix returns clone of input matrix 71 72 CHAPTER 3 VECTORS AND MATRICES operator Negate Matrix A B static Matrix operator Matrix Parameters a Input matrix returns Negated input matrix operator Add binary operator Res A B static Matrix operator Matrix a Matrix b Parameters a A matrix b B matrix returns Sum of input matrices operator Sub binary operator Res A B static Matrix operator Matrix a Matrix b Parameters a matrix b matrix operator Matrix multiplication operator Res A B static Matrix operator Matrix a Matrix b Parameters a Input matrix b Input matrix b returns Product operator Multiply matrix with constant Res alpha A static Matrix operator double alpha Matrix a Parameters alpha constant a Input matrix returns Result matrix 3 4 MATRIX 73 operator Multiply matrix with constant Res A alpha static Matrix operator Matrix a double alpha Parameters a Input matrix alpha constant returns Result matrix operator Divide matrix with constant Res A alpha static Matrix operator Matrix a double alpha Parameters a Input matrix alpha constant returns Result matrix
13. this mA this vb this mC this vd o Ou 09 this strcx this strcy this strcz this strc for int ro 1 this strc row this strcx row this mG rowStructure this mA rowStructure this mC rowStructure new Structure G rows A rows 301 0 row lt this strcx Dimension row int p this strcx Dimension for int ro this strc p A rowStructure row ptt this J new BMatrix MatrixForm General strc 0 row lt A rows structure structure structure structure structure 302 APPENDIX F KKTSOLVER CODE p this strcx Dimension for int row 0 row lt this strcy Dimension row for int col 0 col lt 1 J row p col this mA row coll lt summary gt X Structure lt summary gt Structure IKKTSolver Strcx get return this strcx lt summary gt Structure lt summary gt Structure IKKTSolver Strcy get return this strcy lt summary gt X Structure lt summary gt Structure IKKTSolver Strcz get return this strcz F lt summary gt Slacks lt summary gt BVector IKKTSolver d get 303 return this vd lt summary gt Calculate residulas lt summary gt lt param name x gt s
14. Butcher tableau Vector C get Evaluations Number of evaluations of Model Derivative int Evaluations set get Factorizations Number of factorizations int Factorizations set get InfeasibleSteps Number of Backtracks due to infeasible states int InfeasibleSteps set get Iterations Number of Newton iterations used by ESDIRK step int Iterations set get 227 228 CHAPTER 15 ODE SOLVERS MaxlIterations Max Iterartions for ESDIRK Newton steps int MaxIterations get NewtonErrors Number of Newton iterations not converged int NewtonErrors set get RejectedSteps Number of Rejected steps int RejectedSteps set get Step Integration step size double Step set get Tolerance Tolerance for ESDIRK Newton iterations double Tolerance set get Methods Integrate Integrate ODE for T time units and return all integration steps void Integrate double Vector Vector 0 out Vector Steps out Matrix Xnew Parameters T Integration time X0 Initial state U Manipulated variables Steps Integration steps time values Xnew Integration states stored column wise 15 3 ODESOLVER 229 Next Integrate ODE for T time units and calculate Sensitivity matrices void Next double Vector 0 Vector U out Vector X out Matrix SX out Matrix SU Parameters Integration time T 0 Initial state U Manipulated variables Next Stete SX Sen
15. static complex operator complex a complex b Parameters a input var b input var returns a b operator Subtract complex numbers static complex operator double a complex b Parameters a input var b input var returns a b operator Subtract complex numbers static complex operator complex a double b Parameters a input var b input var returns a b operator Multiply complex numbers static complex operator complex a complex b Parameters a input var b input var returns a b 17 1 COMPLEX 247 operator Multiply complex numbers static complex operator double a complex b Parameters a input var b input var returns a b operator Multiply complex numbers static complex operator complex a double b Parameters a input var b input var returns a b operator Divide complex numbers static complex operator complex a complex b Parameters a input var b input var returns a b operator Divide complex numbers static complex operator double a complex b Parameters a input var b input var returns a b operator Divide complex numbers static complex operator complex a double b Parameters a input var b input var returns a b 248 CHAPTER 17 MISCELLANEOUS FUNCTIONS operator Equal operator static bool operator complex a complex b Parameters a input var b input var returns true if equal operator Not equal opera
16. 155 4 156 CHAPTER 9 LINEAR FILTER Chapter 10 ARX models The ARX model describes the process A g y t B g u t e t q is the time shift operator and the polynomials are ny A q 1 5 ajq 7 7 1 4 5 Ba j l The ExtendedAARX 2010 model is 1 aq peat un A a y t B g u t 1 see description given in Introduction 1 6 10 1 ARXModel Class ARXModel ARX model and Extended Delta ARX Model Serializable class ARXModel ICommon lt ARXModel gt Constructors ARXModel this 0 new Vector 1 1 0 new Vector 1 1 0 Default constructor for serialization ARXModel int Delay Vector A Vector B double T 157 10 1 10 2 10 3 10 4 158 CHAPTER 10 ARX MODELS Constructor ARX Model Parameters Delay Delay A A polynomial B B polynomial T Sample time ARXModel int Delay Vector A Vector B double T double Alfa Constructor Extended Delta ARX Model Parameters Delay Delay A A polynomial B B polynomial T Sample time Alfa Alfa coifficient ARXModel TransferFunction TF double T this 0 new Vector 1 1 0 new Vector 1 1 0 Constructor ARX model Parameters TF System transfer function Sample time ARXModel TransferFunction TF double T double Alfa Constructor Extended Delta ARX Model Parameters TF System transfer function T Sample time Alfa Alfa coifficient Properties A ARX coefficients A q 1 y t q delay
17. B q 1 u t Vector A get Alfa Extended Delta ARX model alpha coefficient double Alfa get ASP State space matrix ASP X ASP X BSP U KSP eps Y C X eps Matrix ASP get 10 1 ARXMODEL B ARX coefficients B A q 1 y t q delay B q 1 u t Vector B get BSP State space matrix BSP X ASP X BSP U KSP eps Y C X eps Vector BSP get State space vector C X ASP X BSP U KSP eps Y C X eps Vector C get Delay Delay states int Delay get Dimension State dimension int Dimension get ExtendedDeltaARX Extended Delta ARX model bool ExtendedDeltaARX get Gain ARX function gain double Gain get 159 160 CHAPTER 10 ARX MODELS KSP State space matrix KSP X ASP X BSP U KSP eps Y C X eps Vector get T Sampling time in seconds double T get Methods AssertEqual Assert equal and show function if nor equal static void AssertEqual string txt ARXModel a ARXModel b Parameters txt text string a Actual ARX model b Expected ARX model NextState Next state Vector NextState Vector X double u double eps Parameters state vector u Manipulated variables eps Noise vector returns Next state x Observed Observed values double Observed Vector X Parameters state vector returns Y vector 10 1 ARXMODEL Reset Reset u delay chain void Reset Show Show ARX Mode
18. Buy Key 14 1a yy 1415 where p is the plant state vector the manipulated variables noise and y is the observed plant output Knowing the present plant state x and the measured plant output y the noise e can be estimated from The MPC control problem is formulated as minimization of N 1 1 2211 5 5 1 lAw s 5 5 8 14 3a 0 k 1 211 212 CHAPTER 14 MODEL PREDICTIVE CONTROL MPC subject to the constraints At Buk Ke k 0 N 1 14 3b y k k 0 N 14 3 Umin Uk Umax k 0 N 1 14 3d AUmin lt Aur X Aumax k 0 N 1 14 3e Uk lt Ymax Nk k 1 N 14 3f Uk 2 Vmin Nk k 1 N 14 36 m gt 0 k 1 N 14 3h In which Au uj uj i The term yk 1 rello in penalizes the deviation between plant output and the reference rp The term Au 2 penalizes the movements of the manipulated variables ymin and Ymax are the soft constraint limits on the controlled variables m is the violation of soft constraints a is the penalty for violation of the soft constraints Nominal 5 Penalty Function a 0 1 2 The state space description of the plant 14 1 can be rearranged to yk CA zo CAF Ke Bu 1 lt SkSN 14 4 8 1 where the predicted future value of ia
19. Offset Ofsett returns u k Offset delay Reset Reset DelayChain void Reset Set Set value void Set double value Parameters value u k 174 HUBERFUNCTION 257 Show Show DelayChain static void Show string text DelayChain x Parameters text text string x DelayChaiin object 17 4 HuberFunction Class HuberFunction Huber penalty function val A X ple amp e lt y ple y lel 7 gt 7 class HuberFunction IFun Constructors HuberFunction double Gamma Matrix A Vector Y Constructor Parameters Gamma _ Threshhold y A Coifficient matrix Y Value vector Properties A A in val Ax X Matrix A get Gamma Threshhold double Gamma set get Y y in val Ax Vector Y get 258 CHAPTER 17 MISCELLANEOUS FUNCTIONS 17 5 Spline and Cubic Smoothing Spline func tions A spline function is a curve constructed from polynomial segments Splines that are subject to continuity conditions at their joints A spline function is approximating a set of data zo yo 1 Y1 2 Y2 n Yn of the function y y x The Spline function segments are S x a x 0 bi x x0 2 cj x 20 di 17 1 For a simple Spline function the spline function segments fulfils the condi tions Si i 2 94 4 17 2a Si 2i Si i 17 2b S 25 5 ai 17 2 Si ti
20. PseudoInvert Pseudo Invert static Matrix PseudoInvert Matrix a Parameters a Input matrix returns Result matrix Random Random Matrix static Matrix Random int n int m double min double max Parameters n Number of Rows m Number of Columns min Minimum value max Maximum value returns Random Matrix Set Set sub matrix void Set int row int col Matrix a Parameters row Row position col Column position a sub matrix T4 CHAPTER 3 VECTORS AND MATRICES SetColumn Set Column void SetColumn int col Vector Vals Parameters col Column Vals Vector of values SetRow Set Row void SetRow int row Vector Vals Parameters row Row Vals Vector of values Show Show matrix static void Show string text Matrix a Parameters text text string a Matrix Sub SubB B A void Sub Matrix a Parameters a Matrix to be subtracted SVD SVD Dcomposition A U S VT static void SVD Matrix a out Matrix U out Vector S out Matrix VT Parameters a Input matrix A U Left side othogonal matrix 5 Singular Values vector VT Rigth side orthogonal matrix 3 4 MATRIX T5 ToSparse Copy Matrix to Sparse Matrix equivalent to Sparse SparseMatrixType RealUnsymmetrical UPLO Lower A static Matrix ToSparse Matrix A Parameters Input matrix returns Sparse matrix ToSparse Copy Matrix to Sparse Matrix equivalent to Sparse type UPLO Lower A static Matrix ToSparse SparseMatrixType ty
21. To support XmlSerialization a number of properties with names like xvl and xvla has been defined These routines are not for general use 17 12 BinarylO Class BinaryIO Binary Input Output routines Saves or read a serializable object to or from binary file static class BinaryIO Methods Read Read object from file static Object Read string FileName Parameters FileName File name returns read object Save Save object to disc static void Save string FileName Object ObjGraph Parameters FileName File name ObjGraph Object to be saved 266 CHAPTER 17 MISCELLANEOUS FUNCTIONS 17 13 XmlIO Class XML Input Output routines Saves or read a serializable object to or from XML file static class XmlIO lt T gt where new Methods Read Read object from file static T Read string FileName Parameters FileName File name returns read object Save Save object to disc static void Save string FileName T ObjGraph Parameters FileName File name ObjGraph Object to be saved 17 14 MPCMathLib JacobianEstimation Class MPCMathLib Calculate Jacobian extimation partial class MPCMathLib Methods JuEstimate Jacobian Estimation for debugging of models implemented using Model inte face The initial variation of U DU is reduced until norm of error is less than eps static Matrix JuEstimate IModel model Vector X Vector U Vector DU double eps 17 14 MPCMATHLIB JACOBIANESTIMATION 267
22. Vector yDet G u Stochatic resonse Vector yStoch H LinearFilter Niid N mean var Vector yPlant yDet yStoch int np 3 int nz 2 int k 6 Estimate model from input signal u and output signal yPlant LinearFilter GHat LinearFilter Regress np yPlant k nz u LinearFilter Show GHat GHat Estimated deterministic response Vector yHat GHat u double max 2 0 max double min console Plot new Plot new PlotSeries u min max u new PlotSeries yPlant min max SeriesColor Red yPlant new PlotSeries yDet max SeriesColor Green yDet 147 new PlotSeries yHat min SeriesColor Blue yHat with the following output Test Linear Filter G ShiftFunction K 6 Z 0 0049 0 0048 P 1 1 9321 0 9418 H ShiftFunction Z P 1 1 9321 0 9418 H Gain 103 1159 GHat ShiftFunction K 6 Z 0 0023 0 0087 P 1 1 9298 0 9409 end the plotted time series MPCMath Plot 7 9 ae Options 148 CHAPTER 9 LINEAR FILTER 9 1 LinearFilter Class Linear Filter LinearFilter Discrete Transfer function Serializable class LinearFilter ICommon lt LinearFilter gt Constructors LinearFilter this new Polynomial 1 0 Default constructor F q 1 LinearFilter int K Polynomial R Polynomial P Constructor F q q R q P q Parameters Delay R Polynomial P P Polynomial Line
23. XMax console WriteLine Iterations min Iterations Minimum value val X min X Vector Show X X Vector Show fun Dx fun Dx X Matrix Show fun DDx fun DDx X y else console WriteLine Inconsistent function The constrained minimizer ConFunMin is based on the Augmented La grange multiplier method The Lagrange function for the optimization problem 12 8 is L x re 2 z fun z x A Ci x 2 12 9a st 220 12 95 where z is a vector of slack variables This Lagrange function is augmented to the Lagrange function L x re z fun z 2 Ai Ci z 2 34 C 2 Cela 2 Ci a 2 12 10 The square term 114 C 2 Ci ax 2 C x z gives a penalty on constraint violations Con fixes a set of Ae i H 2 and then uses the unconstrained minimizer FunMin to minimize the augmented Lagrange function over x If the constraint violations are unacceptable the value of is increased and a new minimization is 5 Con F unM in continues to iterate on the parameter set Ac Ai 4 2 until an optimal solutions is found For further details see Nocedal and J Wright Nocedal and J Wright 2006 Or K Madsen et al 2004 The following code demonstrate how to locate all four minima s in the simple problem IConFun fun new TestConFun Vector XMin new Vector 5 0 5 0 Vector XMax
24. a base a Count Constructor from List of complex values Parameters a List of Complex values CVector Vector rv Vector iv base rv Dimension Constructor from real and imaginary values Parameters rv real parts iv imaginary parts Methods Arg Get Argument Vector Arg Parameters returns Vector of argument AssertEqual Assert equal Show actual and expected if no equal static bool AssertEqual string text CVector actual CVector expected Parameters text text string actual actual value expected expected values Equal Equal static bool Equal CVector a CVector b Parameters a Vector a b Vector b returns true if equal 18 CHAPTER 3 VECTORS AND MATRICES EqualRoots Equal Roots static bool EqualRoots CVector a CVector b Parameters a Vector a b Vector b returns true if equal Get Get subvector CVector Get int pos int dim Parameters pos dim IV Get imaginary values Vector IVQ Parameters returns Vector of Imaginary values Mod Get moduli Vector Mod Parameters returns Vector of Moduli operator Clone vector res x static CVector operator CVector x Parameters x Input vector 3 5 CVECTOR 79 RV Get real values Vector RV Parameters returns Vector of real values Show Show Complex Vector static void Show string txt CVector a Parameters txt text string a complex vector Sort Sort elements in vector descentin
25. following convex quadratic program 1 min 52 Ge 9 x 14 13a 84 Emin 2 Tmax 14 13b b lt Cz by 14 13c in which U min Umax Lmin 0 Jua 22 14 142 AU min A 0 AU max bi 00 Ilb Zmax C 14 14b Zimin 1 CO In a model predictive controller only the first vector uj of U u is implemented on the process At the next sample time the open loop opti mization is repeated with new information due to a new measurement 111 MiMoMPC Class MiMoMPC Multiple Input Multiple Output MPC MPCMath class MiMoMPC Constructors MiMoMPC StateSpaceModel Model int History int Horizon Vector Theta Vector Mu Vector YMin Vector YMax Vector Rho Vector UMin Vector UMax Constructor for MiMoMPC object Parameters UN 1 y 141 MIMOMPC 215 Model Controller model History History length Horizon Control horizon N Theta Reference violation penalty Q Mu Soft constraint violation penalty S YMin Y Max soft constraint Ymax YMax Y Min soft constraint ymin Rho U change penalty Su UMin U max value UMax U min value Properties Alfa Error integration coifficient Alfa 0 0 Dedadbeat elimination of stationary er ror Alfa 1 0 No elimination of stationary error Vector Alfa set get History Length of History part int History get Horizon Length of control Horizon int Horizon get Model reference to
26. lt param gt lt returns gt lt returns gt Vector IFunt Dx Vector x double t Vector dx new Vector 4 dx 2 Math Exp x 0 t dx 3 Math Exp x 1 t dx 0 t x 2 dx 2 dx 1 t x 3 dx 3 return dx y lt summary gt Hessian not implemented lt summary gt lt param name x gt lt param gt lt param name t gt lt param gt lt returns gt lt returns gt Matrix IFunt DDx Vector x double t return null 192CHAPTER 12 UNCONSTRAINED AND CONSTRAINED MINIMIZATION Plot of the input data with and without noise 8 MPCMath Plot Options The program below illustrates the use of LeastSquareFit to estimate the four parameters of the function console WriteLine Test Least Square Fit double taul 0 005 double tau2 0 01 double gain 300 0 double var 1 0 Vector X new Vector taul tau2 gain gain Vector Show X X IFunt fun new Function int m 1000 Vector T new Vector m Vector Y new Vector m Vector Ym new Vector m for int i 0 i lt m i double time 1000 0 i m T i time Y i fun Value X time Ym i Y i MPCMathLib WhiteGaussianNoise 0 0 var console Plot new Plot new PlotSeries Y 0 0 100 0 Y 12 6 LEAST SQUARE FITTING 193 new PlotSeries Ym 0 0 100 0 SeriesColor Green Ym LeastSquareFit lsqfit new L
27. new Vector 5 0 5 0 double val Vector X 182CHAPTER 12 UNCONSTRAINED AND CONSTRAINED MINIMIZATION Constrained Minimization console WriteLine Constrained minimizer ConFunMin ConFunMin lmin new ConFunMin fun int ntry 50 List lt Vector gt minimas new List lt Vector gt for int i 0 i lt ntry i Vector Vector Random XMin XMax val lmin Minimize X0 XMin XMax X lmin X if lmin 0k 1 bool insert true for int p 0 p lt minimas Count pt 1 Vector Xminima minimas p if X Xminima Norm 1 0e 2 1 insert false break if insert minimas Add X y y console WriteLine Search end found minimas Count minimas for int p 0 p lt minimas Count pt 1 X minimas p val fun Value X console Show val val Vector Show X X The program starts minimization for ntry random start points Found min imas are collected in the list minims if it is not already in the list The console output is 12 4 FUNMIN 183 Test Constrained Minimizer Constrained minimizer ConFunMin Search end found 4 minimas val 65 4261 X Vector 0 2983 2 8956 val 72 8556 X Vector 3 5485 1 4194 val 0 0000 X Vector 3 0000 2 0000 val 35 9298 X Vector 3 6546 2 7377 12 4 FunMin Class FunMin Unconstrained function minimizer Quasi Newton method BFGS class FunMin Constructors FunMin IFun Fun Constructor Parameters Fun Fu
28. partial class MPCMathLib Properties Iterations Iterarions static int Iterations get MaxIterations Maximum number of iterations default 100 static int MaxIterations set get 236 CHAPTER 16 MPCMATHLIB Methods SteadyState Find Steady State of Process static Vector SteadyState IModel model Vector XI Vector US Parameters model Plant model XI Initial guess off state variables US Manipulated variables returns XS state variable 16 5 MPCMathLib Util Class MPCMathLib MPCMathLib Utility routines partial class MPCMathLib Properties MaxError Maximum error for comparing doubles static double MaxError set get Ran Random number generator static Random Ran get Methods BFGS BFGS Hessian approximation Nocedal Wright Numerical optimization chapter 6 static Matrix BFGS Matrix H Vector s Vector y Parameters H Hessian apprimation matrix to be updated must be symmetrical and positive definit S iteration step y curvature change 16 5 MPCMATHLIB UTIL 237 BFGSInv BFGS Inverse Hessian approximation update Nocedal Wright Numerical optimization chapter 6 static Matrix BFGSInv Matrix H Vector s Vector y Parameters Hinv Inverse Hessian apprimation matrix to be updated must be symmetrical and positive definit 8 iteration step y curvature change Difference Diffference Math Abs a b 1 0 Math Abs b static double Difference double a double b Para
29. steps 1 y4 step Math Sin 32 0 pi step steps 1 console Plot new PlotSeries yi 0 0 0 0 SeriesColor Green yl new PlotSeries y2 0 0 0 0 SeriesColor Red y2 2 2 DISPLAYING AND PLOTTING VARIABLES 35 new PlotSeries y3 0 0 0 0 SeriesColor Blue y3 new PlotSeries y4 0 0 0 0 SeriesColor Brown y4 fa MPCMath Plot cue Options Using the Plot class several plot series can be shown in one coordinate sys tem console Plot new Plot new PlotSeries x 0 0 0 0 SeriesColor Green x new PlotSeries y1 0 0 0 0 SeriesColor Red y1 36 CHAPTER 2 CONSOLE FUNCTIONS a MPCMath Plot Options The Plot class also allows one to specify the plot type using the PlotType enumeration console Plot new Plot PlotType XY new PlotSeries x 1 0 1 0 x new PlotSeries yi 1 0 1 0 y2 a MPCMath Plot Options 2 3 USING CONSOLE FOR TEST OF GUI PROGRAMS 37 steps 50 Vector z new Vector steps for int step 0 step lt steps step z step 0 8 Math Sin 2 0 pi step steps 1 console Plot new Plot PlotType TBar new PlotSeries z 1 0 1 0 SeriesColor Yellow z 7 MPCMath Plot Options
30. where the parameter determines the systems stiffness 0 0 gives non stiff sinus curve values of 100 0 gives a very stiff problem The differential equations to be integrated must be implemented using the I Model interface Implementation of Van der Pol equation is shown in appendix E The ERK methods does not require implementation of the Jaco bian method but the ESDIRK methods require that the Jacobian method is implemented The ODESolver class can be run with fixed step length and with adaptive step length if you specify a tolerance for the integration The step length is adjusted based on calculation of the index i icl 15 1 mar maa abstol zi reltol The error e is estimated based on comparing integration result with of one step with two integration steps with half the step length Values of r gt 1 0 rejects the step and decreases the step length Values of r lt 1 0 increases the step length and the step is accepted The program for integration of the Van der Pol equation is console WriteLine Test Ordinary Differential Equation solvers double dt 0 01 223 224 CHAPTER 15 ODE SOLVERS double T 200 0 ODEMethods method ODEMethods ESDIRK34 Create Van der Pol model double mu 10 0 IModel fun new VanDerPol mu dt double tol 1 0e 6 Vector absTol new Vector 2 tol Vector relTol new Vector 2 tol Create ODE solver ODES
31. xiMean 0 SetVal step 800 900 0 02 Fineness xiMean 1 SetVal step 1000 1100 1 0 Measurement and process noise eps MPCMathLib WhiteGaussianNoise epsilonVar epsilonMean xi MPCMathLib WhiteGaussianNoise 22 CHAPTER 1 INTRODUCTION xiVar xiMean Plant measurement with measurement noise YPlant Plant bserved XPlant eps YModel Model Observed XModel Update Plant and Model state innov YPlant YModel XModel Model NextState XModel UC innov XPlant Plant NextState XPlant UC xi collect plot indformation ypload step YPlant 0 ymload step 1 0 ypfineness step YPlant 1 ymfineness step YModel 1 Feed step UC 0 Speed step UC 1 dLoad step 01 dFineness step xiMean 1 console Plot sypload symload sFeed sdLoad console Plot sypfineness symfineness sSpeed sdFineness The manipulated variable feed UC 0 is increased to 10 0 from step 0 to 300 The separator Speed UC 1 is increased to 100 0 from step 600 to 700 and the unmeasured disturbances are active from step 800 to 900 and step 100 to 1100 respectively The simulated measurement noise and process noise are calculated and stored in vectors eps and xi The Yplant and Ymodel are the observed re sponses from the plant and the Model respectively The differences between these in stored in the innovation vector which transferred to t
32. 2 2 2 2 813 ObjectType 103 Observed ET T9 r70 ODEMethods ODESolver Off Ox s rs operator 06 SE E AA L 05 n pi Ei E Dx OuterProduct 159 0 196 Parameters PARDISO Bd Nas PBRS PlotType PLU Polynomial Position 260 Print ProperZero 241 ProperZeroes Pseudolnvert PseudoRandom 0 155 QPSolver OR 138 QR factorization 136 EE RLI Ran Random 5 73 BO 6 53 Read ReadLine 279 Regress RejectedSteps 228 Rem 253 ReportBuilder Reset Reset Value ResGrad ResGradL 314 ResGradX Residuals ResStep ResStepX Restructure Rho RiccatiSolver 196 RKA Roots E19 1 51 Rows 01 88 RowStructure 288 Runge Kutta 235 Runge Kutta 4 234 RV 79 Ba s Pc ps 59 Save 265 200 ScalePlot Serialization SeriesColor Set 2 73 E07 SetColumn SetKalmanGain SetRef ind Show 44 112 23 131 155 257 27911283 ShowStructure 28 Side Sigma 259 SMType SoftConStrained 216 Solve 13211123 196 197 207 209 Solver Sort Sparse 168 SparseEquationSolver 139 SparseMatrixType Spline 258 Splines 5416 StateSpaceModel SteadyState Step 228 Steps Strex Strcy Strez Structure d 6 N INDEX Sub 53 74 1
33. 50 CHAPTER 2 Properties PlotSeries Plot Series PlotSeries PlotSeries set get Type Plot Type PlotType Type set get XMax X axis maximum value double XMax set get XMin X axis minimum value double XMin set get Enumeration PlotType Plot type enum PlotType Fields MPC Operator plot TBar TY with bars only one series TY TY plots Time for x axis series for Y axix XY Y versus X Plot 2 7 MPCMathWindow xaml Class MPCMathWindow CONSOLE FUNCTIONS MPCMath Console window MPCMathWindow xaml This is mainly for in ternal use partial class MPCMathWindow Window 2 7 MPCMATHWINDOW XAML Constructors MPCMathWindow bool EnableHide Constructor for MPCMathWindow Parameters EnableHide Enable Hide field in menu Properties Text Get window text string Text get Methods AddLine Add line to text area void AddLine string Line Parameters Line Text line Clear Clear Text area void Clear 51 52 CHAPTER 2 CONSOLE FUNCTIONS Chapter 3 Vectors and Matrices Linear algebra is handled using Vector and Matrix objects Vector and Matrix objects supports operator over loads documented as operator static Vector operator Matrix a Vector x Parameters a a matrix vector returns result vector means that the compiler accepts the A z statement in the code below int dim 5 Vector x Vector Random dim 100 0 100 0 Matr
34. Arx model for MPC controller StateSpaceModel Model get Mu Soft Constrained penalty Qn Vector Mu set get Rho Delta U penalty 5 Vector Rho set get 216 CHAPTER 14 SoftConStrained MPC controller soft constrained bool SoftConStrained get Solver Reference to QP solver QPSolver Solver get Theta Delta Y penalty O Vector Theta set get U Reference to U response Matrix get UMax U maximum value Umaz Vector UMax set get UMin U minimum value Umin Vector UMin set get X Reference to state Vector X get YFree Reference to YFree response Matrix YFree get MODEL PREDICTIVE CONTROL MPC 14 1 Soft Constrained Uppper Limit Ymax Vector set get YMin Soft Constrained Lower Limit ymin Vector YMin set get YModel Reference to YModel response Matrix YModel get YPlant Reference to YPlant response Matrix YPlant get YRef Reference to YRef Matrix YRef get Methods Next Next control step Vector Next Vector YPlant Parameters YPlant Plant value returns U value NextY Next expected Y value Vector NextY 217 218 CHAPTER 14 SetRef Set future reference void SetRef Matrix Ref Parameters Ref future reference Matrix SetRef Set future reference void SetRef Vector Ref Parameters Ref future reference value MODEL PREDICTIVE CONTROL MPC 14 2 LINEARMODEL 2
35. BVector X new BVector strc Structure Show x structure X Structure X 0 Vector Random 3 100 0 100 0 X 1 Vector Random 2 100 0 100 0 X 2 Vector Random 1 100 0 100 0 BVector Show x X 81 82 CHAPTER 4 BLOCK VECTORS AND MATRICES Vector xsub X 1 Vector Show xsub xsub The MPCMathConole output is x structure 3 x Vector 60 3688 xsub Vector 22 4367 48 1193 98 3050 22 4367 49 2921 82 2724 49 2921 The following code defines a block matrix A with random sub matrices It displays the structure of A and finally demonstrates a multiplication between a block matrix and a block vector Structure rowStr Structure Values 1 2 3 1 Structure colStr Structure Values 3 2 1 BMatrix A new BMatrix MatrixForm General rowStr colStr A O 0 Matrix Random 1 3 100 0 100 0 1 1 Matrix UnityMatrix 2 2 1 Matrix Random 3 2 100 0 100 0 BMatrix ShowStructure A structure A BMatrix Show A A BVector R A X BVector Show R R The MPCMathConole output is A structure Matrix Form General General matrix 4 3 General Null Null Null Null Null ConstantDiagonal Null General Null Null Null A Matrix Form General 7 6 4 1 STRUCTURE 23 0554 85 4168 79 6318 0 ooooo oooooo oooooo R Vector 1705 0789 2 0829 90 7942 2075 5061 2400 4981 6665 9496 0 1 0 27 7048 19 7783 34 7124 0 23
36. Clone Clone Polynomial static Polynomial Clone Polynomial a Parameters a input value returns Cloned polynomial Derivative Derivative of polynomial Polynomial Derivative Parameters returns Derivative polynomial Div Divide Polynomials res a b static Polynomial Div Polynomial a Polynomial b Parameters a Polynomial a b Polynomial b returns a b 17 2 POLYNOMIAL 251 Equal Equal Polynomial static bool Equal Polynomial a Polynomial b Parameters a Input a b Input b returns true if equal Mul Multiply Polynomial with constant res fak b static Polynomial Mul double fak Polynomial b Parameters fak Constant b Polynomila Mul Multiply Polynomials operator res P Q static Polynomial Mul Polynomial P Polynomial Q Parameters Polynomial P Q Polynomial Q returns P Q operator Clone operator res a static Polynomial operator Polynomial a Parameters a input a returns Cloned polynomial operator Negate operator res a static Polynomial operator Polynomial Parameters a input a returns a 252 CHAPTER 17 MISCELLANEOUS FUNCTIONS operator Add operator static Polynomial operator Polynomial a Polynomial b Parameters a Input a b Input b returns a b operator Subtract operator static Polynomial operator Polynomial a Polynomial b Parameters a Input a y Input b returns a b operator Multiply operator res fak
37. General matrix 5 5 General ConstantDiagonal Null Null Null Null General ConstantDiagonal Null Null Null Null General ConstantDiagonal Null Null Null Null General ConstantDiagonal Null Null Null Null General that AS is a structured 5x5 matrix where the diagonal A matrices are general matrices the superdiagonal J matrices are diagonal with a constant value and all the other matrices are null matrices The Matrix Vector routines exploits this structure information to speed up computations Block Matrices and vectors support the operators clone etc 1 4 Complex numbers and Vectors MPCMath implement complex numbers using the complex class complex a new complex 1 0 3 0 complex b complex Exp a complex b console Show a console Show b console Show c complex i complex Sqrt 1 0 console WriteLine console Show i i with the output a 1 0000 3 0000 2 6911 i 0 3836 1 6911 3 3836 0 0000 1 0000 Complex objects supports Add Sub Mul Div value IV imag inary value Mod Modulus Arg Argument and the operators and Complex vectors are implemented using the CVector class Presently CVec tor implements a limited set of functionalities which will be increased when needed MPCMath does not support Complex Matrices presently 1 5 TRANSFER FUNCTIONS 13 1 5 Transfer Functions Transfer f
38. IsMiminimum IFun Fun Vector X Vector XMin Vector XMax double Eps Parameters Fun Function IFun or IConFun X Minimizer candidate XMin Lower box limits XMax Upper box limits Eps Accuracy returns true if x is a local minimizer IsMiminimum Is X a local minimizer for Fun static bool IsMiminimum IFun Fun Vector X Vector XMin Vector XMax double Eps bool Trace Parameters Fun Function IFun or IConFun X Minimizer candidate XMin Lower box limits XMax Upper box limits Eps Accuracy Trace Trace result returns true if x is a local minimizer IsZero Is Zero test wheter MaxError gt a MaxError static bool IsZero double a Parameters a returns true if a j MaxError IsZero Is Zero test wheter MaxError gt a lt Eps Static bool IsZero double a double Eps 240 CHAPTER 16 MPCMATHLIB Parameters a Eps returns true if a j Eps KalmanGain Kalman filter gain static Matrix KalmanGain Matrix a Matrix Vector Vector Parameters a system matrix x a x b u c system matrix y c x Process Noise r Measurement Noise KalmanGain Kalman filter gain static void KalmanGain Matrix a Matrix c Vector q Vector r out Matrix K out Matrix P Parameters a system matrix x4 a x b u c system matrix y c x q Process Noise r Measurement Noise Gain Error Covariance Limit Violation Test for Limit violation Math Abs a b
39. Manipulated variables Disturbance Process Noise returns Next value of state X Next Next step with sensitivity matrices void Next Vector Vector 0 Vector W out Vector X out Matrix A out Matrix B Parameters XO Initial state value Manipulated variables Disturbance Process Noise Next value of state X Sensitivity 4 4 0 Sensitivity 4 40 Mid Observed Observed output Vector Observed Vector X Vector U Parameters X State X U variables 170 CHAPTER 11 FUNCTION AND MODEL INTERFACES Observed Observed output with sensitivities void Observed Vector X Vector U out Vector Y out Matrix C out Matrix D Parameters X State X U Manipulated variables Y Output C sensitivity Dy DX D sensitivity Dy DU 11 5 IFeasible Interface IFeasible Feasible interface defining the feasible region of a function as boxlimits interface IFeasible Properties XFMax Upper limit on feasible region Vector XFMax set get XFMin Lower limit on feasibke region Vector XFMin set get 11 6 Infeasible State exceptions Programs implementing Models using the Model interface can can notify the calling program if it has entered into an infeasible state For the U Loop reactor example below the states are Chemical concentrations which must be positive The ODESolver and the SteadyState 16 4 routines uses these exceptions to back track if error parameter set to 1 other wise
40. Matrix lt T gt a Parameters alpha constant a Input AssertEqual Assert equal Show if a not equal to b static bool AssertEqual string text Matrix lt T gt actual Matrix lt T gt expected Parameters text actual expected 110 CHAPTER 5 GENERIC VECTORS AND MATRICES Equal Equal generic Matrix static bool Equal Matrix lt T gt a Matrix lt T gt b Parameters a Input a b Input b returns true if a equal to b Get Get submatrix Matrix lt T gt Get int row int col int rows int cols Parameters TOW Row position col Column position rows Number of rows cols Number of columns returns Sub matrix MulAdd MulAdd r rs a b void MulAdd Matrix lt T gt a Matrix lt T gt b Parameters a Inputa b Input b MulTransposed Multiply Transposed res a b static Matrix lt T gt MulTransposed Matrix lt T gt a Matrix lt T gt b Parameters a Input a b INput b returns a b operator Clone Matrix static Matrix lt T gt operator Matrix lt T gt a Parameters a Input returns a 5 3 TMATRIX 111 operator Negate Matrix static Matrix lt T gt operator Matrix lt T gt Parameters a Input a returns a operator Add binary operator static Matrix lt T gt operator Matrix lt T gt a Matrix lt T gt b Parameters a Input a b Input b returns a b operator Sub binary operator static Matrix lt T gt operator Matrix lt T gt a Matrix lt T
41. N n 20 hd ll N where zk is the plant response ry the set point AU the movement of the manipulated variables The Q S and 5 are weighing matrices for reference error penalty 9 movement of manipulated variables penalty and 5 the penalty for coming outside the dead band zone Setting S to zero result in a conven tional MPC controller The first constraint for zj is the linear process model For further details consult ZPrasath and J rgensen 2010 MPC contoller data int history 100 history for operator display int horizon 50 optimization horion Vector theta null Vector my null 1 8 MODEL PREDICTIVE CONTROL 25 Vector ymax null Vector ymin null if SoftConstraint soft constrained MPC reference penalty theta new Vector 0 1 0 2 soft constraint penalty my 7 new Vector 1000 0 500 0 soft constraint max values ymax new Vector 2 0 5 0 soft constraint min values ymin new Vector 2 0 5 0 y else conventional MPC reference penalty theta new Vector 1000 0 500 0 y manipulated vars movement penalty Vector rho new Vector 100 0 200 0 Hard constraint U max value Vector umax new Vector 15 0 30 0 Hard constraint U min value Vector umin new Vector 30 0 30 0 The actual MPC controller and the control loop is defined by the code be low Model and Plant objects are the StateSpace models of the Cement mill des
42. Parameters model Plant model X Operating state U Manipulated variables DU Initial Variation of U eps Error limit returns Approximated Jacobian JxEstimate Jacobian Estimation for debugging of models implemented using Model inte face The initial variation of X DX is reduced until norm of error is less than eps static Matrix JxEstimate IModel model Vector X Vector U Vector DX double eps Parameters model Plant model Operating state U Manipulated variables DX Initial Variation of X eps Error limit returns Approximated Jacobian 268 CHAPTER 17 MISCELLANEOUS FUNCTIONS Bibliography Stephen Boyd and Lieven Vanderberghe Convex Optimization Cambridge University Press 2004 Jakob Kjebsted Huusom Niels Kj lstad Poulsen Sten Bay J rgensen and John Bagterp J rgensen Offset free model predictive control based on arx models In American Control Conference Marriot Waterfront Baltimore MD USA June July 02 2010 Intel Intel math kernel library http software intel com en us articles intel mkl K H Johanson The guadruple tank process A multivariable laboratory pro cess with an adjustable zero IEEE Transactions on control systems technol ogy 8 3 456 465 2000 John Bagterp J rgensen Moving Horizon Estimaton and Control Ph D thesis Department of Chemical Engineering Technical University of Denmark 2004 K Madsen Nielsen and O Tinglev Optimizationtimization with Con straint
43. ReportBuilder object provides a simple solution to the problem The following program demonstrates the use of the report builder object console WriteLine Test Report Builder console WriteLine string names Sten Peter John Jorgen Niels double values 1000 00 33234 12 27945 28 1677 45 56 44 ReportBuilder rb new ReportBuilder 500 int pname 0 position of name column int pvalue 15 position of value column int fieldsize 10 int digits 2 rb Write pname Name rb Write pvalue value rb NewLine for int 0 p lt names Length p 1 rb Write pname names p rb Write pvalue values p fieldsize digits rb NewLine console WriteLine rb ToStringO with the output Test Report Builder Name value Sten 1000 00 Peter 33234 12 17 10 REPORTBUILDER 263 John 27945 28 Jorgen 1677 45 Niels 56 44 17 10 ReportBuilder Class ReportBuilder Report builder class ReportBuilder Constructors ReportBuilder int Capacity Constructor for Report builder Parameters Capacity Capcity of report builder Methods NewLine New line void NewLine NewLine New Lines void NewLine int lines Parameters lines Number of new lines ToString ToString override string ToString 264 CHAPTER 17 MISCELLANEOUS FUNCTIONS Write Write void Write int Pos object Value Parameters Pos Value Write Write string vo
44. Sum Parameters returns Sum of all element in vector 64 CHAPTER 3 VECTORS AND MATRICES Variance Get variance double Variance Parameters returns Variance of vector elements 3 3 MatrixForm Enumeration MatrixForm Matrix Form Enumerator enum MatrixForm Fields ConstantDiagonal Matrix with constant diagonal elemenets Diagonal Diagonal matrix General General matrix Null Null matrix Sparse Sparse matrix in PARDISO format Enumeration MatrixOp Operator Enumerator for BLAS LAPACK routines enum Matrix0p Fields C Conjungate Transpose complex No tranpose Transpose Enumeration UPLO Upper or Lower part of Matrix for BLAS LAPACK routines enum UPLO Fields Lower Lower triangular Upper Upper triangular 3 4 MATRIX 65 Enumeration Side Side of matrix for BLAS LAPACK routines enum Side Fields Left Left side Right Right side Enumeration Diagonal of diagonal matrix for BLAS LAPACK routines enum Diagonal Fields NonUnit Unit matrix Unit Non unit matrix Enumeration SparseMatrixType Sparse Matrix type enumeration enum SparseMatrixType Fields RealUnsymmetrical Real and unsymmetrical matrix StructurallySymmetrical Real and structurally symmetrical matrix SymmetricalIndefinite Real and symmetric indfinite matrix SymmetricalPositiveDefinit Real and symmetrical positive definite matrix 3 4 Matrix Class Matrix Matrix class Serializable class
45. V L 2 y z Ca d lt 0 220 Cr d z 0 i l 2 mc Slack variables s Cz d gt 0 13 10a 13 10b 13 10c 13 1 QUADRATIC OPTIMIZATION implies Car s d 0 s gt 0 Optimality Conditions rp g Ay 2 0 ra 6 0 ro 8 0 220 820 84 0 4 1 2 Notation 51 21 1 82 22 1 5 ic e Sm Zm The complementarity conditions 5 24 0 i Ly 2 5551 can be expressed as SZe 0 The optimality conditions can be expressed as rp Gr g A y C z 0 ra Ar b 0 ro 8 0 rsz SZe 0 820 220 which is the same as TL es g Ay _ 9 2 8 x TC 752 2 8 20 Solve F x 2 8 0 such that 2 8 gt 0 using Newton s method 203 13 16 204 CHAPTER 13 AND LP SOLVERS 13 2 Matrix Factorization Matrix factorizations are used by QP Solver to speed up calculation The equations C 0 Ax T 0 0 0 Ay ra C 0 1 1 4 13 21 0 0 S Z As i sg can be factorized as follows The fourth equation gives SAz ZAs 7sz gt As Z rsg Z SAz 13 22 Substitution in the third equation gives As C Az Z SAz Z gg 13 23 and C Ax Z 18 z ro 271752 13 24 Augmented form 0 0 TA 13 25 0 34 18 Az Z Foz 13 3 KKT solvers QPSolver solves the KKT equations by calling a K
46. Ww 17 2d In the cubic smoothing Spline function the spline function is allowed to devi ate from the data points The cubic smoothing spline function is m minimizing the value TL min A Si saa f S 17 3 In the limiting case where 0 0 the spline function will become a straight line At the other extreme where 1 0 the smoothing spline converges to the simple spline function 17 6 Spline Class Spline Spline function S x a x 20 b x 20 x 2 cs x 20 d class Spline IComparable Properties A Spline cubic coifficient double A set get 17 6 SPLINE 15 Spline square coifficient double set get Spline linear coifficient double set get D Spline constant coifficient double D set get H Spline length double set get Sigma Spline data weight double Sigma set get Spline starting point double XO set get Y Spline data value double Y set get 259 260 CHAPTER 17 MISCELLANEOUS FUNCTIONS Methods Position Is x inside Spline interval int Position double X Parameters returns 1 if x below spline 0 if inside 1 if above Value Spline value double Value double X Parameters 17 7 CubicSpline Class CubicSpline Smoothing Cubic Spline class CubicSpline Constructors CubicSpline Vector X Vector Y this X Y 1 0 null Constructor for non s
47. a Parameters txt Variable description a double array 46 CHAPTER 2 CONSOLE FUNCTIONS WriteLine Write empty line to console void WriteLine WriteLine Write line to console void WriteLine string txt Parameters txt text string 2 5 PlotSeries Class PlotSeries Class for definition of plot series Serializable class PlotSeries Constructors PlotSeries Default constructor for serialization PlotSeries string Text double Min double Max Vector Values this Text Min Max SeriesColor Black Values Constructor If both Min 0 0 and Max 0 0 uses the NiceMin and NiceMax routines to find suitable Min and Max values Parameters Text Series desciption Min Minimum plot value Max Maximum plot value Values Vector with series values PlotSeries string Text double Min double Max SeriesColor Color Vector Values Parameters Text Series desciption Min Minimum plot value Max Maximum plot value Color series color Values Vector with series values 2 5 PLOTSERIES Properties Color Series color SeriesColor Color set get Max Maximum plot value double Max set get Min Minimum plot value double Min set get Text Series desciption string Text set get Values Plot values Vector Values set get Methods Egual Egual Plotseries objects static bool Egual PlotSeries a PlotSeries b Parameters a Plotseries object a b Plotseries object a re
48. b b BMatrix Show C C BVector Show d d QPSolver solver new QPSolver G g A b C d solver Solve BVector Show x optimal solver X console WriteLine console WriteLine KKT conditions console Show Dual gap solver My BVector Show A X A solver X b BVector Show C X d C solver X d BVector Show S E BVector MulElements solver S solver Z with the output Test QP solver 3 sy 1 SZ 3 3 G Matrix Form General 3 3 1 0 0 0 1 0 0 0 1 g Vector 1 2 0000 1 A Matrix Form General 1 3 1 1 0 b Vector 0 5000 C Matrix Form General 6 3 1 0 0 202 CHAPTER 13 AND LP SOLVERS 0 1 0 0 0 1 1 0 0 0 1 0 0 0 1 4 Vector 1 1 1 f optimal Vector 1 0000 0 5000 0 9934 KKT conditions Dual gap 0 0000 A X b Vector 0 C X d Vector 2 0000 1 5000 1 9934 0 0000 0 5000 S E Vector 0 0000 0 0000 0 0000 0 0000 0 0000 0 0066 0 0000 The interior point algorithm requires that the initial value of X strictly fulfils the inequality conditions Cx gt The equality condition Az b don t have to be fulfilled For most MPC problems X 0 fulfils this requirement 13 1 Quadratic Optimization Quadratic program 5 1 min 226244 Sib Lagrange function 1 L z y z 27 Gr g Ax b z Cx d Optimality Conditions VsL z y z 9 2 0 VyL 2z y z b 0
49. be found in the c 2 control MPCMath di rectory The Intel MKL routines are provided in the folders c 2 control MPCMath MKLx86 and c 2 control MPCMath MKLx64 folders 4 Trouble shooting Debugging and Excep tions The MPCMath dll requires that the directories C 2 control MPCMath and C 2 controlM License exists Its also required that a valid license file is present in the License directory If the MPCMathTemplate runs properly and display the license informa tion Then the License information is ok If MPCMathTemplate executes and MPCMathConsoleTemplate don t execute properly then there is a prob lems with the Intel MKL librariesc 2 control MPCMath MKLx86 and c 2 control MPCMath MKLx64 folders Use DependencyWalker to test whether your operating system is missing some sub dll in MPCmathMKLx86 dll or MPC MathMKLX64 dll Dependency Walker is free sw which can be downloaded from the net If you move programs as MIMOMPC UnitTestMPCMath or MPCMath Template away from the c 2 control directory the reference til MPCMath must be redefined Its done in the solution explorer Add references Browse to the routine c 2 control MPCMath MPCMath dll The MPCMath function checks parameter values and error situations If an error happens the function creates an MPCMathException as show below where the vector x and y should have the same dimension 5 273 static void Work console Wr
50. gt b Parameters a Input b Input b returns atb operator Matrix constant multiplikation static Matrix lt T gt operator Matrix lt T gt a double alpha Parameters a Input a alpha constant returns alpha a operator Constrant matrix multiplikation static Matrix lt T gt operator double alpha Matrix lt T gt a Parameters alpha constant a Input a returns alpha a 112 CHAPTER 5 GENERIC VECTORS AND MATRICES operator Matrix constant division static Matrix lt T gt operator Matrix lt T gt a double alpha Parameters a Input a alpha constant returns a alpha operator Matrix multiply operator static Matrix lt T gt operator Matrix lt T gt a Matrix lt T gt b Parameters a Input a b Input b returns a b Set Set submatrix void Set int row int col Matrix lt T gt a Parameters row Row Position col Column position a Sub matrix Show Show matrix static void Show string text Matrix lt T gt a Parameters text A Sub Sub r r a void Sub Matrix lt T gt a Parameters Inputa 5 3 TMATRIX TMulAdd TMulAdd r r a b void TMulAdd Matrix lt T gt a Matrix lt T gt b Parameters a Inputa b Input b Transpose Transpose static Matrix lt T gt Transpose Matrix lt T gt a Parameters a Input a returns a 113 114 CHAPTER 5 GENERIC VECTORS AND MATRICES Chapter 6 Transfer Functions Transfer Functions are the classica
51. m Matrix MatrixForm Form int n int m base Form n m Constructor n x m matrix Parameters n Rows m Columns Matrix int n T val base n val Constructor ConstantDiagonal Matrix Parameters n Dimension val value of all diagonal elements Matrix Vector lt T gt a base a values Constructor Diagonal matrix Parameters a Vector vith diagonal values Matrix params T vals base vals Constructor Diagonal matrix Parameters vals Array of diagonal values Matrix Structure Structure base Structure Dimension Constructor for square matrix Null matrix Parameters Structure Structure Matrix MatrixForm form Structure Structure base form Structure Dimension Constructor for square matrix Parameters form Matrix Form Structure Structure 5 3 TMATRIX 109 Matrix Structure RowStructure Structure ColStructure base RowStructure Dimension ColStructure Dimension Constructor null matrix Parameters Structure Structure Matrix MatrixForm form Structure RowStructure Structure ColStructure base RowStructure Dimension ColStructure Dimension Constructor Parameters form Matrix Form RowStructure Row structure ColStructure Column structure Properties T Set or get matrix value override T this int row int col set get Methods Add Addr r a void Add Matrix lt T gt a Parameters Inputa AddScaled Add scaled r alpha a void AddScaled double alpha
52. state O _ State penalties M cross term penalties null is legal R Penalties on inputs A Linear state equation matrices B Linear state equation matrices Properties Initial Gain Matrix KO get pO Initail cost Vector pO get PO Initial cost PO Matrix PO get Methods Solve Solve Riccati series 12 8 RICCATISOLVER 197 void Solve Vector Vector pn BVector BVector BVector b out BVector U out BVector X Parameters XO Initial state pn linear penalty on final state 4 linear penalty on state r linear penalty on inputs b linear state space term U Optimal inputs X _ Optimal plant state Solve Solve Riccati series void Solve Vector X0 Vector pn BVector q BVector r BVector b out BVector U out BVector X out BVector Lambda Parameters X0 Initial state pn linear penalty on final state linear penalty on state linear penalty on inputs linear state space term Optimal inputs Optimal plant state Lambda Dual variable Mar 198CHAPTER 12 UNCONSTRAINED AND CONSTRAINED MINIMIZATION Chapter 13 QP and LP solvers The QPSolver class is used to solve quadratic and linear optimization tasks O PSolver implements a Primal Dual Interior Point Algorithm including Mehro tra s modifications For quadratic problems the problem 1 min 2 92 st gt is solved For linear problems the problem mm ga s t gt is solve
53. 0 8072 30 0282 18 1162 79 1933 41 7612 76 4280 18 1162 79 1933 41 7612 76 4280 0 0 0 42 3467 26 4536 35 7596 83 8892 0 42 3467 26 4536 35 7596 83 8892 oooo 3 5851 72 9231 34 8921 75 5007 3 5851 72 9231 34 8921 75 5007 Symmetrical banded matrix A with n rows and columns and kd 1 non zero sub and super diagonals is stored in a compact matrix AB with 1 kd rows and n columns The first row is the diagonal of A and the following rows are the sub diagonals of A The elements marked NaN inAB are ignored A Matrix Form General 8 8 62 0381 20 6993 20 6993 50 3402 0 40 3750 ooooo 81 3391 34 3952 84 5224 81 3391 34 3952 84 5224 oooooo 39 6899 10 9481 39 6899 10 9481 NaN NaN 142 CHAPTER 8 40 3750 42 2135 13 3814 0 0 13 3814 103 5437 0 0 0 14 6392 0 0 0 0 0 0 0 0 0 0 0 0 Matrix Form General 2 8 62 0381 50 3402 42 2135 103 5437 20 6993 40 3750 13 3814 14 6392 8 0 BandEquationSolver Class BandEquationSolver Band Equation solver class class BandEquationSolver ISolver Constructors BandEquationSolver int int Ku Matrix AB Constructor Parameters Number of sub diagonals Ku Number of Super diagonals AB Coefficient matrix for banded matrix Methods Solve Solve A x Vector Solve Vector r Parameters vector returns vector x Solve Solve A X R Matrix Solve Matrix R
54. 00 i 0 1i 0 Roots Complex List 0 2 0000 1 0 3 0000 1 0 4 0000 1 0 Transfer functions supports the and operators Time responses are obtained using the Value function 1 6 ARX MODELS 15 gain 5 0 delay 2 0 TransferFunction G new TransferFunction gain delay roots zeroes TransferFunction Show G G TransferFunction GR OscillationgSecond rder Step int steps 300 Vector resp new Vector steps for int step O step lt steps step t double time step resp step GR Value time console Plot new PlotSeries Oscillating system 0 0 2 0 resp with the plotted output a MPCMath Plot Options Oscillating system 1 6 ARX Models ARX models describes linear plant dynamics as 16 CHAPTER 1 INTRODUCTION A g y t B g u t e t Ny A q 5 i 0 Bq Y 1 0 q is the time shift operator qy t y t 1 and is the noise The EAARX model integrates the noise using the filter _l og Teg where a is in the range 0 0 to 1 0 The EAARX integrates the noise in order to remove offsets in the closed control loop see Huusom et al 2010 The following code generates an ARX object plant and a EAARX object model Arx model Vector Aq new Vector 1 0 1 558 0 5769 Vector Bq new Vector 0 0 0 2094 0 1744 int delayCount 25 double dt 2 0 ARXModel plant new ARXModel delayCount
55. 120 250 Cnsl 277 Coefficients 249 Color Columns ColumnStructure 288 Complex complex ae Con ConFunMin Consistent Console Covr Created CubicSpline 260 CVector D 259 DDx I63 E68 DDxe 165 DDxi 165 165 Delay 9 128 1555 DelayChain 255 Delays Density Derivative Description 128 Determinant DFormat 42 Diagonal 65 Difference Digits Ho 277 Dimension 84 84 128 Disabled Discretize Distribution 237 Div EX 250 DivElements Dx 164 165 Dxe 165 Dxi 165 W 68 Entry 43 EpsGrad 184 184 194 311 312 EpsGradL EpsGradX Epsilon EpsStep EpsStepX Equal 47 56 68 77 84 101 1 150 251 256 EqualRoots Equals ErrorLimit Evaluations 227 ExitReason Exp S ExtendedDeltaARX Fact Factorizations 227 Factorize FieldSize Fit FlatDimension Flatten Form FourTankProcess FunMin 178 1779 511153 253 25 Gain 19 119 159 279 Gamma Gauss 238 GaussDistribution cp Gemv Ger 69 Get 57 69 TS P E03 110 254 GetColumn 69 70 um GetHashCode GetRow 411110 259 History 215 Horizon 215 HuberFunction 257 ICommon 100 IConFun 164 102 179 180 IConFunMin IFeasible Iun 168 78 IFunt INDEX IKKTSolver Model 67 255 277
56. 1211158 954 5 Sum SVD SymmetricalBlockEquationSolver 139 SymmetricBandEquationSolver SymmetricEquationSolver 138 TET 160 168 286 288 Tau Tub ID 23 124 Text TextLength Theta Time 206 TMatrix 107 TMulAdd Tolerance 228 ToSparse ToString Trace BO 185 159 195 Tracelterations TraceLevel 189 TraceText TransferFunction Transpose Trmm Truncate 254 TVector Type 135 BIS JMax Min 216 nityMatrix PLO 5 1129 seBFGS Vale 165 Vali vae 3 OO EI Values VanDerPol 221 Variance VBase 285 Vector w WarmStart WhiteGaussianNoise 241 C INDEX Work Write 264 WriteLine x 7 155 15207 16 251 59 x64 272 270 x86 279 270 XFMax 170 XFMin 170 XIterations 189 XMin XMinimizer 189 XmlIO XS XUnchanged xvl vo ps S per YFree 217 YMin 217 YModel YPlant YRef 7 Zeroes 315
57. 19 14 2 LinearModel Class LinearModel Linear Model dx dt A X B U W Y C X V class LinearModel IModel Constructors LinearModel Matrix A Matrix B Matrix C double T this A B C T T Constructor Parameters System matrix A B System matrix A C System matrix A Step size for NextSate LinearModel Matrix A Matrix Matrix C double T double DT Constructor Parameters System matrix A B System matrix A System matrix A T Step size for NextSate DT Integration step size 14 3 Four Tank Process The four tank process is an simple multi variable process used to demonstrate MIMO process dynamic in education The four tank system was introduced by 2000 as a benchmark for control design 220 CHAPTER 14 The Controlled variables are the water levels in the four tanks H1 H2 H3 and H4 The manipulated variables are the two inflows F1 and F2 The parameters in the IModel interface are Parameters Parameters Parameters Parameters Parameters Parameters Parameters Parameters Parameters Parameters 0 1 2 3 oo cross sectional area of outlet al cm2 cross sectional area of outlet a2 cm2 cross sectional area of outlet a3 cm2 cross sectional area of outlet a4 cm2 cross sectional area of inlet A1 cm2 cross sectional area of inlet A2 cm2 cross sectional area of inlet A3 cm2 cross sectional area of inlet A4 cm2 valve positio
58. 4950 26 8926 74 2146 ooooooo 83 Block vectors and block matrices can be created from vector dimensions or numbers of rows and columns Then the block matrix builds the structure information when the sub matrix object are stored in the matrix In general its safer and prevents a lot of indexing errors if you one carefully plan the structure of the task and use Structure objects to define the block vectors and matrices 4 1 Structure Class Structure Structure class Serializable class Structure Constructors Structure Default constructor for serialization Structure int n Constructor for basic structure Parameters n Dimension Structure int n int val Structure with egual substructures Parameters n Dimension val Substructure dimensions 84 CHAPTER 4 BLOCK VECTORS AND MATRICES Properties Dimension Dimension int Dimension get Flat Dimension Flat dimension int FlatDimension get Indexer Get or set value int this int p set get Methods AssertEqual assert equal Compare two Structures and output value if not equal static void AssertEqual string text Structure actual Structure expected Parameters text Text string actual Vector with actual values expected Vector with expected values Equal Test if two structrures are equal static bool Equal Structure a Structure b Parameters a Input a b Input b returns true if equal operator Merge structures warni
59. ALBLOCKEQUATIONSOLVER 139 8 6 SymmetricalBlockEquationSolver Class SymmetricalBlockEquationSolver Symmetrical Block Equation Solver exploiting diagonal elements in diagonal of block matrix class SymmetricalBlockEquationSolver Constructors SymmetricalBlockEquationSolver BMatrix Constructor Parameters Symmetrical block matrix with values stored in lower triangle Methods Solve Solve A x r BVector Solve BVector r Parameters coificient block vector 8 7 SparseEquationSolver Class SparseEquationSolver Sparse Linear Equation Solver PARDISO Parallel Direct Sparse Solver Solve A x r and R class SparseEquationSolver ISolver Constructors SparseEquationSolver Matrix A this SparseMatrixType RealUnsymmetrical UPLO Upper A Constructor for unsymmetrical matrix Parameters A Coificient matrix SparseEquationSolver SparseMatrixType type UPLO UpLo Matrix A 140 CHAPTER 8 EQUATION SOLVERS Constructor Parameters type Sparse matrix type UpLo Upper or lower triangular for symmetric matrices A Coificient matrix SparseEquationSolver BMatrix A this SparseMatrixType RealUnsymmetrical UPLO Upper A Constructor for Block Matrix Vector equations Parameters A Coificient matrix SparseEquationSolver SparseMatrixType type UPLO UpLo BMatrix A Constructor for Block Matrix Vector equations Parameters type Sparse matrix type UpLo Upper or lower triangular for symmetric matri
60. BVectors static BMatrix OuterProduct BVector a BVector b Parameters a Input a b Input b returns BMatrix Random Random Block Matrix static BMatrix Random Structure rowStrc Structure colStrc double min double max Parameters rowStrc Row structure colStre Column structure min Minimum value max Maximum value returns Random BMatrix Restructure Restructure Matrix static BMatrix Restructure Structure rowStr Structure colStr Matrix a Parameters rowStr Row Structure colStr Columns structure a Input matrix returns BMatrix 4 3 BMATRIX 97 Show Show static void Show string text BMatrix a Parameters text Text string a BMatrix object ShowStructure Show matrix structure static void ShowStructure string text BMatrix A Parameters text text string A BMatrix object ToSparse Copy Block Matrix to sparse matrix Equivalent to ToSparse SparseMatrixType RealUnsymmetrical UPLO Lower static Matrix ToSparse BMatrix A Parameters Input matrix returns Sparse matrix ToSparse Copy Block Matrix to sparse matrix Equivalent to ToSparse type UPLO Lower A static Matrix ToSparse SparseMatrixType type BMatrix A Parameters type Sparse matrix Type A Input matrix returns Sparse matrix ToSparse Copy Block Matrix to sparse matrix static Matrix ToSparse SparseMatrixType type UPLO UpLo BMatrix A Parameters type Sparse matrix Type UpLo Position for values in symmetric val
61. CES MulAdd MulAdd this this ax b void MulAdd T a T b Parameters a object a b object b returns Result object Restructure Restructure Object void Restructure int Rows int Cols Parameters form Rows Cols Show Show object void Show string txt Parameters txt text string a object TMulAdd Transpose a and MulAdd this this a x b void TMulAdd T a T b Parameters a object a b object b Transpose Transpose T Transpose Parameters returns Transposed object 5 2 TVECTOR 103 Enumeration ObjectType Object type enum ObjectType Fields Element Matrix Vector 5 2 TVector Class Vector Generic Vector class Serializable class Vector lt T gt VBase lt T gt ICommon lt VBase lt T gt gt where T ICommon lt T gt new Constructors Vector int n base n Constructor Parameters n Vector int n T val base n val vector with equal values Parameters n val Vector params T vals base vals Constructor Parameters vals Vector Structure s base s Dimension Construct Vector from structure Parameters 8 104 CHAPTER 5 GENERIC VECTORS AND MATRICES Properties T Set or get matrix value override this int pos set get Methods AssertEqual assert equal Show if not equal static void AssertEqual string text Vector lt T gt actual Vector lt T gt expected Parameters text actual expected Equal Equal static bo
62. CMath complex 0 0 0000 i 0 0000 1 0 0000 i 1 0000 2 0 0000 i 1 4142 3 0 0000 i 1 7321 A Matrix Form General Size 4 4 Pos 0 0 0 0000 i 0 0000 Pos 0 1 0 0000 i 1 0000 Pos 0 2 0 0000 4 i 2 0000 Pos 0 3 0 0000 i 3 0000 Pos 1 0 1 0000 i 0 0000 Pos 1 1 1 0000 i 1 0000 Pos 1 2 1 0000 i 2 0000 Pos 1 3 1 0000 i 3 0000 Pos 2 0 2 0000 i 0 0000 Pos 2 1 2 0000 i 1 0000 Pos 2 2 2 0000 i 2 0000 Pos 2 3 2 0000 i 3 0000 Pos 3 0 3 0000 4 i 0 0000 Pos 3 1 3 0000 i 1 0000 Pos 3 2 3 0000 4 i 2 0000 Pos 3 3 3 0000 4 i 3 0000 Res MPCMath Vector1MPCMath complex 0 9 0246 i 0 0000 1 9 0246 1 4 1463 2 9 0246 i 8 2925 3 9 0246 i 12 4388 The generic Show routine cannot produce compact printouts 5 1 ICommon Interface ICommon Common functions for elements in Generic Vectors and Matrices interface ICommon lt T gt 5 1 ICOMMON Properties Columns Columns int Columns get Form Object form MatrixForm Form get Rows Rows int Rows get Methods AddScaled Add Clone alpha this T AddScaled double alpha Parameters alpha constant AddScaled Add this alpha a T AddScaled double alpha T a Parameters alpha constant a object Equal Equal bool Equal T a Parameters a Compared to returns true if equal 101 102 CHAPTER 5 GENERIC VECTORS AND MATRI
63. EBUGGING TOOL FOR CONSOLE APPLICATIONS TraceText Trace console output to file console txt in bin debug or bin release directory static bool TraceText set get Methods AssertEqual Assert equal for bool variable Show actual and expected if they are not equal static void AssertEqual string text bool actual bool expected Parameters text variable desription actual actual value expected expected value AssertEqual Assert equal for integers Show actual and expected if they are not equal static void AssertEqual string text int actual int expected Parameters text variable desription actual actual value expected expected value AssertEqual Assert equal for integer array Show actual and expected if they are not equal static void AssertEqual string text int actual int expected Parameters text variable desription actual actual value expected expected value AssertEqual Assert equal for double Show actual and expected if they are not equal static void AssertEqual string text double actual double expected Parameters text variable desription actual actual value expected expected value B 1 CNSL 279 AssertEqual Assert equal for complex Show actual and expected if they are not equal static void AssertEqual string text complex actual complex expected Parameters text variable desription actual actual value expected expected value DFormat Format double variable stati
64. Generic matrix of TransferFunction objects T Sample time StateSpaceModel Matrix lt TransferFunction gt model double T Vector Alfa this model T Alfa null Constructor MiMo TransferFunction to StateSpace Models Parameters model Generic matrix of TransferFunction objects T Sample tim alpha Noise Integrator Coificients StateSpaceModel Matrix lt TransferFunction gt model double T Matrix EL this model T new Vector model rows 1 0 EL Constructor MiMo TransferFunction to StateSpace Models Parameters model Generic matrix of TransferFunction objects T Sample tim EL Error level StateSpaceModel Matrix lt TransferFunction gt model double T Vector Alfa Matrix EL Constructor MiMo TransferFunction to StateSpace Models Parameters model Generic matrix of TransferFunction objects T Sample tim alpha Noise Integrator Coificients EL Error level StateSpaceModel Matrix lt ARXModel gt model this model null Constructor MiMo ARX model to StateSpace Parameters model Generic matrix of ArxModel objects StateSpaceModel Matrix lt ARXModel gt model Matrix EL Constructor MiMo ARX model to StateSpace Parameters model Generic matrix of ArxModel objects EL ErrorLevel 128 CHAPTER 7 STATE SPACE MODELS Properties A System Matrix A Matrix A set get B System Matrix B Matrix B set get System Matrix Matrix C set get Created Created Administrative field DateTime Cr
65. Indexer InfeasibleSteps Initial Value Integrate 228 Tnvert O 155 138 E50 Invertible 150 IsMiminimum ISolver IsZero Iterations 1 187 164206 227 255 tv rs prid Ju I8 JuEstimate 266 1x 103 JxEstimate 267 K 120 KO KalmanGain KKTSolver KSP Ly Lambda LambdaE Lambdal LAPACK LeastSquareEquationSolver LeastSquareFit Limit Violation 240 LinearEquationSolver 134 LinearFilter LinearModel Log 245 LPKKTSolver 209 LTR LU factorization Matrix MatrixForm MatrixOp Max MaxBacktrack MaxBacktracks MaxError Maxlterations 235 INDEX MaxlterationSteps Max TextLength MBase 286 Mean MiMoMPC Min 7 BS 57 Minimize MinNorm 231 MKL Mod Model MPCMathConsole MPCMathLib MPCMathLib Discretize 234 MPCMathLib JacobianEstimation 266 MPCMathLib MinNorm 231 MPCMathLib RK4 MPCMathLib SteadyState MPOCMathLib Util MPCMathWindow MPCMathWindow xaml Mu Tri 158 206 33 Mul 70 E20 121 551 MulAdd 71 10 110 MulElements 5 88 MulTransposed 71 7i 94 110 165 108 029 ewLine 263 ewtonErrors 228 ewtonMethod ext 160 817 P2 extState ext Y i T6 iceMax iceMin iid orm 8 77 ES 231 orml ormalize ormInf ormRel v 129 167 umbersPerLine Y 25 167 Z 288 de 2 12 2 12 2 2 2 2 2 2 2 2 2 2 2 2 2
66. KTSolver routine The KKT solver determines the type of optimization problem quadratic linear second order cone problems The KKT solver must implement the interface KTSolver making it possible to switch between solvers and making it possible to produce custom KKT solvers exploiting matrix structures The relevant KKTSolver is passed to OP Solver using a constructor The two following calls are equivalent as KKT Solver is the default solver for QPSolver QPSolver solver new QPSolver G g b 4 QPSolver solver new QPSolver new KKTSolver G g b C 40 The IK Solver defines three methods used by QPSolver The solves the augmented equations 13 25 e Calculate the residuals rr rA and rc e Factorize 0 0 13 26 0 2 15 13 4 QPSOLVER 205 e Calculate Newton search directions Ay and Az The default KKTSolver perform a further factorization of 13 25 to the form G 5 12 C 25 5 12 2 1 2 0 Ay 7 TA 13 27 The main computational effort for QPSolver and the associated KKTSolver is the computation of the term S Z C and the factorization of 13 27 using a SymmetricalBlockEquationSolver 8 6 MPCMath automatically exploits structures in the block matrices but but further exploitation of marix structures or other factorization methods can be implemeneted by writing a new KK TSolver The sou
67. L 14 3 Four Tank 144 145 A xo P dh Bch VIA 15 2 15 3 ODESolver 22 222 2 4 2 4 4 16 MPCMathLib 16 2 16 3 16 4 MPCMathLib SteadyState FF ug 165 1 06 ee 17 Miscellaneous functions Tf sa xoc ee a Bele we a aa a ouch wp uk War as UA S Os ate tees te ee y ahaa o db RRR DOD GWR Ae RR A 17 9 Reports i c7 m b eon n ba RW y PE 6 20 Seep ae pep TEM lr 12BinarylO iau ee 93 3 Rum cR m EUR DA XmllO ee ee A ee ee 17 14MPCMathLib JacobianEstimation FE A eas Fer oo ae Es eAOe O Oe AO Y WN 5 MPCMathlemplate A 8 MPCMathConsoleTemplate B Debug
68. LTER operator Operator divide constant with linear filter static LinearFilter operator double alpha LinearFilter A Parameters alpha constant A A Filter object returns alpha A PBRS Pseudo Binary Random Signal series Produces a PRBS series u of length N where 4 switches between 1 and 1 with probality prob static Vector PBRS int N double prob Parameters Series length prob Probability for switch returns u series Regress Find Shift Function F q 1 P g where P q y t e t P q and and e t Njia 0 0 1 0 static LinearFilter Regress int np Vector y Parameters np Number of poles y Output series returns F q 1 P g Regress Find Shift Function F q q FR g P g where R g y oria P g Zizo Piq and y t F g u t static LinearFilter Regress int np Vector y int k int nz Vector u Parameters np Number of poles y Output series k Delay nz Number of poles u Output series 9 1 LINEARFILTER Regress Find Shift Function F q q R g P q where R q Dio pi0 and y t F q u t static LinearFilter Regress Norm norm double gamma int np Vector y int k int nz Vector u Parameters norm Regression norm gamma Huber norm parameter np Number of poles y Output series k Delay nz Number of poles u Output series Show Show LinearFilter static void Show string txt LinearFilter A Parameters txt text string A A Filter object
69. MPCMath User Manual Jorgen K H Knudsen March 26 2015 Contents 1 Introduction 7 ll uu Sm 24528324 By ws eed See ot Bk es 8 1 2 Matrices i s ae ee a Ro ee 8 1 3 Block vectors and matrices 11 bow Be nd ee 12 1 5 Transfer 5 13 L6 ARX Models 22255255546 Ge wa Aw ao Sx X 15 gy oy See oe ae he 18 1 8 Model Predictive Controll 23 1 9 Intel Math Kernel Library BLAS LAPACK 28 31 31 32 Pr 37 24 MPCMathConsole 39 2 5 46 2 6 i 4 SAO Oe BRE 49 2 1 00 50 53 5 5 esu P reete el Ge 54 3 2 Min T 54 Tcr 64 a Ree AGAU ccc 65 3 5 Mo a cuis ke ye imap EOS ede ie Ee BS 76 81 4l Str ct re l 83 d 2 Vector 9 m RD hm Xa 85 44 21 a Abo dee eo Nap E BOR Exp Dub dust Bod 91 99 ee naa ee NER WU RF AN HD 100 0 24 WVector Asa eb apa ma RW S AG O Tn 103 Ee NEN NENN 107 4 CONTENTS 115 qm 117 125 71 StateSpaceModel 2222s 126 133 S l_ odd m RY ded XR koX DECO
70. Math console The next statements defines a vector x with 5 elements all having the value pi 3 141 a vector y with 5 elements having random values between 100 0 and 100 0 The fourth statement adds vector x and y storing the result in Vector z The Vector Show statements displays the three vectors in a MPCMath console x Vector 3 1416 3 1416 3 1416 3 1416 3 1416 y Vector 132 8023 51 3077 691 7185 895 7004 672 5596 z Vector 735 9439 54 4493 694 8601 898 8420 675 7012 Vector functionality includes Add Subtract Multiply Clone Negate Equal Normalize OutherProduct Sort Sum and other functions Vectors support the operators as shown in the example above Many functions are also im plemented as methods z Add x where the vector z is overwritten with z x 1 2 Matrices Matrices are implemented using the Matrix class 1 2 MATRICES Matrix definition Matrix A new Matrix MatrixForm General 3 5 Matrix B Matrix Random 3 5 100 0 100 0 Matrix C A 2 3 25 0 C A B Matrix Show A A Matrix Show B B Matrix Show C C These statements defines matrix A with 3 rows and 5 columns Matrix B is defined as a 3 rows 5 columns matrix with random elements in the range 100 0 to 100 0 Element 2 3 of A is set to 25 0 and matrix C is the sum of matrix A and B The Matrix Show calls displays the matrices A Matrix Form General 3 5 0 0 0 0 0 0 0 0 0 0 0 0 0 25 0000 0 Mat
71. Matrix MBase lt double gt ICommon lt Matrix gt Constructors Matrix base 0 Constructor default for serialization 66 CHAPTER 3 VECTORS AND MATRICES Matrix int n base n Constructor square matrix Form Null Parameters n Dimenson Matrix MatrixForm Form int n base Form n Constructor square matrix Parameters Form Matrix form n Dimenson Matrix int n int m base n m Constructor n x m matrix Form Null Parameters n Rows m Columns Matrix MatrixForm Form int n int m base Form n m Constructor n x m matrix Parameters Form Matrix form n Rows m Columns Matrix int n double val base n val Constructor ConstantDiagonal Matrix Form ConstantDiagonal Parameters n Dimension val value Matrix int n int m double vals base n m vals Constructor general matrix from array of values Parameters n Rows m Columns vals Value array Matrix Vector a base a values Constructor Diagonal matrix Form Diagonal Parameters a Vector of diagonal values Matrix params double vals base vals Constructor Diagonal matrix Form Diagonal Parameters vals array of values 3 4 MATRIX 67 Properties Density Matrix density 0 0 1 0 Null 0 0 General 1 0 double Density get MatrixForm Matrix form Null ConstantDiagonal Diagonal Sparse or General Moving from Null towards General preserves data Moving from General to Null Con stantDia
72. NTATION OF TEST FUN USING ICONFUN lt summary gt lt param name x gt lt param gt lt returns gt lt returns gt Vector IConFun Vali Vector x 1 Vector Cval new Vector 2 Cval 0 Math Pow x 0 2 0 2 0 x 1 Cval 1 4 0 0 10 0 x 1 return Cval lt summary gt Cosntraint gradients lt summary gt lt param name x gt lt param gt lt returns gt lt returns gt Matrix IConFun Dxi Vector x Matrix Dx new Matrix MatrixForm General 2 2 0 0 2 0 x 0 2 0 Dx O 1 1 0 Dx 1 0 4 0 Dx 1 1 10 0 return Dx lt summary gt Constraint Hessians lt summary gt lt param name x gt lt param gt lt returns gt lt returns gt BMatrix IConFun DDxi Vector x BMatrix DDx null DDx new BMatrix MatrixForm Diagonal new Structure 1 2 Matrix ddx00 new Matrix MatrixForm Diagonal 2 44 0010 01 2 0 DDx 0 0 44 00 return DDx Appendix E Implementaion of Van der Pol equations using Model Implementation of the Van der Pol equations using Model is shown below using System using System Collections Generic using System Linq using System Text using MPCMath namespace MPCMath 1 summary Nan der Pol s problem y Nu 1 y t 2 y t y t lt summary gt public class VanDerPol IModel 1 pr
73. ONSTRAINED AND CONSTRAINED MINIMIZATION Methods Consistent Check consistence of function to be minimized bool Consistent Vector x Parameters X operation point returns true if consistent Consistent Check consistence of function to be minimized bool Consistent Vector x Vector dx Parameters x X operation point dx variations of x returns true if consistent Minimize Minimize function find local minimum double Minimize Vector Parameters X0 Inital X returns minimum value Minimize Minimize function find local minimum with box constraints on variables double Minimize Vector XO Vector XMin Vector XMax Parameters Initial X guess XMin Min values for X null if no check wanted XMax values for X null if no check wanted returns minimum value at local minimum 12 5 ConFunMin Class ConFunMin Constrained Minimization of Function using Augmented Lagrangian method se Nocedal and Wright Numerical optimization chap 17 4 and K Madsen 12 5 CONFUNMIN 187 Nielsen O Tingleff Optimization with Constraints 2nd Edition march 2004 chap 4 1 class ConFunMin IFun Constructors ConFunMin IConFun Fun Constructor Parameters Fun Properties EpsGradL Lagrange iteration residual limit double EpsGradL set get EpsGradX X iterations limit on gradient double EpsGradX set get EpsStepX X iterations limit on step length double EpsStepX set get
74. ORS AND MATRICES AssertEqual assert equal Compare two vectors and output value if not equal static void AssertEqual string text Vector actual Vector expected Parameters text Text string actual Vector with actual values expected Vector with expected values Axpy Add Vector y a x y void Axpy double a Vector x Parameters factor Xx vector Covariance vector cov k static Vector Covr int kFirst int kLast Vector a Vector b Parameters kFirst first k kLast end k a Input vector b Input vector returns Vector of covariances DivElements Divide Vector elements res i y i x i static Vector DivElements Vector y Vector x Parameters y y vector 7 vector returns result vector Equal Equal compare two vectors Error limit given in MPCMathLib MaxError static bool Equal Vector y Vector x 3 2 VECTOR 57 Parameters y Vector y Vector returns true if equal Gemv Gemv y alpha op a x beta y void Gemv Matrix a Vector x MatrixOp opr double alpha double beta Parameters a Matrix a Vector opr MatrixOp N T alpha constant beta constant Get Get subvector Vector Get int pos int dim Parameters pos Initial position dim Dimension of subvector returns Subvector Get Get subvector with increments Vector Get int pos int incr int dim Parameters pos Initial position incr Increment dim Dimension of subvec
75. Parameters Matrix R returns Matrix X EQUATION SOLVERS 0 0 14 6392 0 65 9977 60 5258 60 5258 16 3448 0 15 1430 0 0 65 9977 16 3448 60 5258 15 1430 15 1430 83 1616 61 1746 83 1616 61 1746 61 1 65 3 65 3 8 10 SYMMETRICBANDEQUATIONSOLVER 143 8 10 SymmetricBandEquationSolver Class SymmetricBandEquationSolver Symmetrical positive definite band matrix Equation solver class class SymmetricBandEquationSolver ISolver Constructors SymmetricBandEquationSolver int Kd Matrix A Constructor Parameters Kd number of super and sup diagonals A Coifficent matrix Methods Solve Solve A x Vector Solve Vector r Parameters vector returns vector x Solve Solve A X R Matrix Solve Matrix R Parameters R Matrix R returns Matrix X 144 CHAPTER 8 EQUATION SOLVERS Chapter 9 Linear Filter The linear filter or the discrete transfer function is defined by F q R g P g 9 1 where q is the shift operator u t 1 qu t and q u t u t 1 The numerator and denominator polynomials are defined by nz RQ X rq P gt pi 9 2 4 0 1 0 The following example illustrates the use of linear filters We have ARX process modelled as YPiant Ystoc 9 3 G g u t H g e t 9 4 a 15 22 ao 9 5 where the input signal u t is a pseudo random binary signal and e t is white noise The process is a second order oscillati
76. RE 133 Domos Heth dts vod Aman etaed 134 D 136 c LC 137 TP Ge Ge 138 Gh SAD 139 gt a deh ae Bee oe 139 foe ARE we Ak dea a p we eas 141 URINE Ge UAE meee 142 Wondha 4 Bow Boke ee oes 143 145 91 LinearFilter 2 148 157 101 157 11 Function Model interfaces 163 VETT 163 pest Gog o p we dod eO 164 11 3 i213 heme Se e RON 166 TTA I Model 167 11 5 1 a gosse dou dao 170 170 173 12 1 4 173 175 178 183 p TEE 186 12 6 Least Square 190 12 7 LeastSquareFit 194 12 8 Hiceatisolvet se 26 ice A dw S 196 199 denos de ditus Oa COUR e d 202 204 13 3 A KT solyetgl uem FAL RID Reb Woche 4 204 doh OR Re EE S dE o EU 205 13 5 IKK TSolvetr xo ER ede Rode roe A we 207 13 6 KKTSolver 209 13 7 LPKKTSolver CONTENTS 14 Model Predictive Control MPC T41 MiMoMPG 2 1 kom RR EG ER domo SR Sem box 304 14 2 LinearModell ce 3o nex Gk a REE
77. Show string text Matrix a Parameters text text string a Matrix a Show Show ARX Model static void Show string txt ARXModel a Parameters txt text string a ARXModel object Show Show Structure static void Show string txt Structure a Parameters txt text string a Structure object 282 APPENDIX DEBUGGING TOOL FOR CONSOLE APPLICATIONS Show Show static void Show string text BMatrix a Parameters text Text string a BMatrix object Show Show static void Show string text BVector a Parameters text text string a BVector object Show Show Polynomial static void Show string txt Polynomial a Parameters txt text string a Polynomial Show Show Iransfer function static void Show string txt TransferFunction a Parameters txt text string a IransferFunction Show Show Complex Vector static void Show string txt CVector a Parameters txt text string a complex vector B 1 CNSL 283 Show Show LinearFilter static void Show string txt LinearFilter A Parameters txt text string A A Filter object Show Show State Space model static void Show string txt StateSpaceModel model Parameters txt model ShowStructure Show matrix structure static void ShowStructure string text BMatrix A Parameters text text string A BMatrix object WriteLine Write empty line to console static void WriteLine WriteLine Write line to console static void WriteLin
78. THLIB Methods RK4 Runge Kutta 4 integrator static Vector RK4 IModel model Vector X Vector U double T Parameters model Process model X Present state U Manipulated variables T End time returns State at endtime RK4 Runge Kutta 4 integrator static Vector RK4 IModel model Vector X Vector U double T double step Parameters model Process model X Present state U Manipulated variables T End time step Step size returns State at endtime 16 3 MPCMathLib Discretize Class MPCMathLib partial class MPCMathLib Methods Discretize Calculate disretized linear equations from Linear differential equations 0 Ag t Bu t z k 1 AdX k BdU k static void Discretize Matrix A Matrix B double T out Matrix AD out Matrix BD 16 4 MPCMATHLIB STEADYSTATE 235 Parameters A matrix B B matrix T Discretization time AD AD matrix for discrete system BD BD matrix for discrete system Discretize Discretize linear or unlinear Plant Model around an operating point SO Fun X t U x k 1 AdX k BdU k static void Discretize IModel model Vector XS Vector US double T out Matrix AD out Matrix BD Parameters model _ IModel model XS State of operating point US State of manipulated var operating point AD AD matrix for discrete system BD BD matrix for discrete system 16 4 MPCMathLib SteadyState Class MPCMathLib Find stationary state of Process with manipulated variable US given
79. Variance epsMean x plant NextState x u eps resp step plant Observed x eps The state space matrices for the and EAARX objects are given the ASP BSP KSP and C properties The code sequence for int step O step lt steps 1 eps MPCMathLib WhiteGaussianNoise epsVariance epsMean x plant ASP x plant BSP u plant KSP eps resp step plant C x eps gives the same results obtained using NextState and Observed routines 1 7 State Space Models The state space model is used to describe linear multiple input multiple output MIMO systems AX B Uy ex Where is the process noise and 7 the measurement noise The StateSpace object can be created directly from a set of A B C and K matrices in this case with matrices with random numbers 1 7 STATE SPACE MODELS 19 int nx 5 int ny 2 int nu 3 A Matrix Random nx nx 100 0 100 0 B Matrix Random nx nu 100 0 100 0 K Matrix Random nx ny 100 0 100 0 C Matrix Random ny nx 100 0 100 0 StateSpaceModel spmodel new StateSpaceModel A B C K StateSpaceModel Show spmodel spmodel where nz are the number of states nu the number of manipulated variables and ny the number of observed variables StateSpaceM odel objects can also be created from an ARX model spmodel new StateSpaceModel plant where plant is the ARX model from th
80. Vector x Parameters y Input y Input X returns 4 2 BVECTOR 87 Flatten Flatten BVector to plain Vector static Vector Flatten BVector a Parameters a Input BVector returns Vector Get Get subvector new BVector Get int pos int dim Parameters pos Start position dim Dimension Get Get subvectorwith increments new BVector Get int pos int incr int dim Parameters pos Start position incr Position incremenst dim Dimension Max Maximum value double Max Parameters returns Maximum value of all elements in member vectors Min Minimum value double Min Parameters returns Minimum value of all elements in member vectors 88 CHAPTER 4 BLOCK VECTORS AND MATRICES MulElements Multiply Vecor elements z i y i static BVector MulElements BVector y BVector x Parameters y Input y x Input X returns Norm Euclidian norm of Vector double Norm Parameters returns Norm of vector elements operator Clone unary operator static BVector operator BVector a Parameters a input a returns a operator Negate unary static BVector operator BVector Parameters a Input a returns a operator Binary add operator static BVector operator BVector a BVector b Parameters a Input a b Input b returns a b 4 2 BVECTOR 89 operator Binary Sub static BVector operator BVector a BVector b Parameters a Input
81. a static Polynomial operator double fak Polynomial a Parameters fak Constant a Polynomial a a returns fak res operator Multiply operator res a fak static Polynomial operator Polynomial a double fak Parameters a Polynomial a fak Constant returns res fak operator static Polynomial operator Polynomial a double fak Parameters a Polynomial a fak constant returns a fak 17 2 POLYNOMIAL 253 operator Multiply Polynomials operator res P Q static Polynomial operator Polynomial P Polynomial Q Parameters P Polynomial P Q Polynomial Q returns P Q operator Div operator res a b static Polynomial operator Polynomial a Polynomial b Parameters a Polynomial a b Polynomial b returns a b operator Remainder operator static Polynomial operator Polynomial a Polynomial b Parameters a Polynomial a b Polynomial a returns a Random Generate random Polynomial static Polynomial Random int n double min double max Parameters n dimension min min coifficients max max coifficients Rem Remainder static Polynomial Rem Polynomial a Polynomial b Parameters a Polynomial a b Polynomial a returns a 254 CHAPTER 17 MISCELLANEOUS FUNCTIONS Show Show Polynomial static void Show string txt Polynomial a Parameters txt text string a Polynomial Sub Subtract static Polynomial Sub Polynomial a Polynomial b Parameters a Input a
82. a function of k and the future values of the manipulated variables ux Defining yfree k C A zo Keg and C A17 B The Markov parameters gives Uk Ufree k 5 Hijuj i 1 lt 1 lt N 14 5 j l Define the vectors Y Yfree R and 7 yi Ufree 1 T1 uo y gt Ufree 2 T2 U1 72 Y 4 Yfree R a U i T 14 6 UN Ufree N TN UN 1 TIN 213 and the matrix Al 0 O 0 H H O 0 pel s 14 7 Hw 2 0 Hyni Hi Then the prediction from 14 5 can be expressed as Y FTU 14 8 Define the matrix A and vector 10 by A and Ig by I 0 0 0 0 I T 0 0 0 0 0 11 O 0 0 14 9 0 00 I0 0 0 0 0 af I 0 Define Q 5 and 6 0 Su Sn Q Su S Oy y 5 8 Oy Su Sn 14 10 1 2 2 2 llynaa 12115 2 medi Ms y 7 S 1 2 12 IY RIB 5 Jou alld 5 Inl 1 1 1 5 TU RIS 5 tiale 5 17 2 5 1 5U I QT A S A U I O Yrs R AS Iyu U 0441 2 1 1 Tries RIG 5 Mow 1 1 5U GU Lg U p4 Sm 1 gt Ge 2 214 CHAPTER 14 MODEL PREDICTIVE CONTROL MPC with Ger DAS A 14 12a g rode E R A S Ipu 4 14 12b 1 1 p 5 RIB 5 llu 14 12c 210 G 0 g 14 124 Consequently we may solve MPC regulator problem 14 3 by solution of the
83. actual value expected expected value 42 CHAPTER 2 CONSOLE FUNCTIONS AssertEqual Assert equal for integer array Show actual and expected if they are not equal void AssertEqual string text int actual int expected Parameters text variable desription actual actual value expected expected value AssertEqual Assert equal for double Show actual and expected if they are not equal void AssertEqual string text double actual double expected Parameters text variable desription actual actual value expected expected value AssertEqual Assert equal for complex Show actual and expected if they are not equal void AssertEqual string text complex actual complex expected Parameters text variable desription actual actual value expected expected value Clear Clear Console window void Clear DFormat Format double variable static string DFormat double a Parameters a double variable returns Formatted output string 2 4 MPCMATHCONSOLE 43 DFormat Format double variable static string DFormat int Fieldsize double a Parameters Fieldsize Field size a double variable returns Formatted output string Entry Delegate specifing Work routine format delegate void Entry Plot Plot series in new window each series have a separate coordinate system Up to four series void Plot params PlotSeries Series Parameters Series Series definition Plot Plot series i new or exist
84. age penalites as diagonal elements in Block matrices BMatrix Q new BMatrix N Qk BMatrix R new BMatrix N Rk BMatrix M new BMatrix N Mk BMatrix A new BMatrix N Ak BMatrix B new BMatrix N Bk RiccatiSolver ricattiSolver new RiccatiSolver PN Q M R A B BVector q new BVector N qk BVector r new BVector N rk BVector b new BVector N bk BVector U BVector X ricattiSolver Solve X0 pN b out U out X Plot results Vector y new Vector N Vector u new Vector N for int k 0 k lt N k k u k X xk 01 0 console Plot new PlotSeries u 0 0 0 0 SeriesColor Red u new PlotSeries y 0 0 0 0 SeriesColor Blue y The code produces the following output 178CHAPTER 12 UNCONSTRAINED AND CONSTRAINED MINIMIZATION ee UU OU __ Options Test Riccati Model StateSpace model nx 2 1 nu 1 Delay 0 87 MPCMath Plot 8 8 Matrix Form General 2 2 Options 1 9703 1 0 9802 0 5 000 u B Matrix Form General 2 1 0 0050 0 0049 K Matrix Form General 2 1 1 9703 0 9802 C Matrix Form General 1 2 2 0 Rk Matrix Form Diagonal 1 1 1 rk Vector 0 2 Qk Matrix Form General 2 2 non 0 2 000 0 2 20 000 gk Vector 0 0 Matrix Form Null 2 1 0 0 Pn Matrix Form General 2 2 1 9703 1 0 9802 0 pn Vector 0 Ak Matrix Form General 2 2 1 9703 1 a b 0 9802 0
85. al matrix C 3 4 creates an indexing error The best way to locate the sinner is to look in the call stack until you find your call Forgetting to specify the MatrixForm also generates a lot of indexing errors The form of a Matrix is read or changed using the Form property Upgrade C matrix to a general matrix C Form MatrixForm General Upgrades to a Matrix preserves data Attempts to degrade the status of a Matrix are ignored 3 1 Sparse Matrices MPCMath implements sparse matrices using the PARDISO storage scheme de scribed in appendix The sparse matrices are used by the SparseSolver and the sparse format are supported for matrix vector and matrix matrix multiplications 3 2 Vector Class Vector Vector class 3 2 VECTOR Serializable class Vector VBase lt double gt ICommon lt Vector gt Constructors Vector 0 Default constructor for serialization Vector int n base n Constructor Parameters n Dimension Vector int n double val base n val vector with equal values Parameters n Dimension val Value Vector params double vals base vals Constructor from array of doubles Vector dimension equal to array length Parameters vals Array of doubles Methods Add Add Vector void Add Vector x Parameters X vector Add Add constant to vector y i yli a void Add double a Parameters a constant 55 56 CHAPTER 3 VECT
86. alue IV imaginary value static implicit operator complex double a implicit conversion from double to complex Parameters a input var Properties Arg Angle double Arg get 243 244 CHAPTER 17 Complex conjugate complex Con get IV Imaginary value double IV set get Mod Modulus double Mod get RV Real value double RV set get Methods Equals override bool Equals object 0 Exp Complex exponential static complex Exp complex a Parameters a input var returns GetHashCode override int GetHashCode MISCELLANEOUS FUNCTIONS 17 1 COMPLEX 245 Complex logarithm static complex Log complex a Parameters a input var returns Log a operator Unary operator clone static complex operator complex a Parameters a Input complex returns Out complex operator Add complex numbers static complex operator complex a complex b Parameters a input a b input b returns atb operator Add complex numbers static complex operator double a complex b Parameters a input a b input b returns atb operator Add complex numbers static complex operator complex a double b Parameters a input a b input b returns a b 246 CHAPTER 17 MISCELLANEOUS FUNCTIONS operator Unary operator static complex operator complex a Parameters a input var returns a operator Subtract complex numbers
87. ameters Filter object fak constant returns F fak operator Add Linear Filters static LinearFilter operator LinearFilter A LinearFilter B Parameters A Filter object B B Filter object returns A B operator Subtract Linear Filters static LinearFilter operator LinearFilter A LinearFilter B Parameters A Filter object B B Filter object returns operator Add constant and LinearFilter static LinearFilter operator double alpha LinearFilter A Parameters alpha constant A A Filter object returns A alpha 9 1 LINEARFILTER 153 operator Add LinearFilter and constant static LinearFilter operator LinearFilter A double alpha Parameters A Filter object alpha constant returns alpha A operator Subtract constant and LinearFilter static LinearFilter operator double alpha LinearFilter A Parameters alpha constant A A Filter object returns alpha operator Subtract LinearFilter and constant static LinearFilter operator LinearFilter A double alpha Parameters A Filter object alpha constant returns alpha operator Multiply operator static LinearFilter operator LinearFilter A LinearFilter B Parameters A Filter object B B Filter object returns B operator Divide operator static LinearFilter operator LinearFilter A LinearFilter B Parameters A Filter object B B Filter object returns 154 CHAPTER 9 LINEAR FI
88. arFilter Polynomial R Polynomial P Constructor F g R q P q Parameters R Polynomial Polynomial LinearFilter Polynomial R Constructor F q R q Parameters Polynomial LinearFilter params 400016 1 vals Constructor F g R q Parameters vals coificient array LinearFilter TransferFunction TF double T Constructor LinearFilter from TransferFunction Parameters TF TransferFunction object T Sample time LinearFilter int K params double vals Constructor F q g FR g Parameters K Delay vals coificient array 9 1 LINEARFILTER 149 Properties Gain Gain stationary double Gain get Initial Value Inital value for input time series used by LinearFilter object for y t where t lt 0 double InitialValue get K Delay int K set get Denominator Polynomial Polynomial P set get R Numerator Polynomial Polynomial R set get Roots Roots CVector Roots get Zeroes Zeroes CVector Zeroes get 150 CHAPTER 9 LINEAR FILTER Methods AssertEqual Assert Equal show if not equal static bool AssertEqual string text LinearFilter actual LinearFilter expected Parameters text text string actual actual filter object expected expected filter obkject returns true if equal Equal Test if Equal static bool Equal LinearFilter A LinearFilter B Parameters A Filter object B B Filter object returns true
89. arameter vector X Fun Approximation function Properties EpsGrad Gradient residual limit double EpsGrad set get EpsStep Step size residual limit double EpsStep set get Iterations Number of Iterations int Iterations get MaxIterations Maximum number of iteration steps int MaxIterations get 12 7 LEASTSQUAREFIT 195 ResGrad Gradient residual double ResGrad get ResStep Step size residual double ResStep get Tau Tau initial mu factor Tau equal 0 0 start with Newton direction Tau equal infinity start with steepest descent direction double Tau set get Trace Trace iterations bool Trace set get Methods Fit Fit parameter Vector Fit Vector Parameters X0 Initial parameter guess returns Local Minimizer parameters Fit Fit parameter constrained Vector Fit Vector X0 Vector XMin Vector XMax Parameters X0 Initial parameter guess XMin Min values for X null if no check wanted Max values for X null if no check wanted returns Local Minimizer parameters 196CHAPTER 12 UNCONSTRAINED AND CONSTRAINED MINIMIZATION 12 8 RiccatiSolver Class RiccatiSolver Riccati solver for extended linear quadratic optimal control problem class RiccatiSolver Constructors RiccatiSolver Matrix Pn BMatrix Q BMatrix BMatrix BMatrix A BMatrix B Constructor with Factorization Parameters Horizon Pn Penalty on final
90. b Input b returns a b Truncate Truncate Polynomial to effective dimension void Truncate Value Polynomial value double Value double x Parameters x input x returns Value Value Polynomial value complex Value complex x Parameters x Complex value returns Complex value 17 3 DELAYCHAIN 255 17 3 DelayChain Class DelayChain Delay Chain for delay of manipulated variables Serializable class DelayChain Constructors DelayChain Constructor for serialization DelayChain int Delay Constructor Parameters Delay Delay DelayChain int Delay double Value Constructor Parameters Delay Delay Value Initial value Properties Delay Delay int Delay set get Reset Value Reset value double ResetValue set get Methods AssertEqual assert equal Compare two DelayChains and output value if not equal static void AssertEqual string text DelayChain actual DelayChain expected 256 CHAPTER 17 MISCELLANEOUS FUNCTIONS Parameters text Text string actual DelayChain with actual values expected DelayChain with expected values Equal Equal compare two Delay chains Error limit given in MPCMathLib MaxError static bool Equal DelayChain y DelayChain x Parameters y DelayChain y x DelayChain x returns true if equal Get Get delayed value double Get Parameters returns delay Get Get delayed value with offset double Get int Offset Parameters
91. by setting Q null class KKTSolver IKKTSolver Constructors KKTSolver BMatrix 0 BVector g BMatrix BVector b BMatrix C BVector d Constructor for KKT solver Parameters G coefficients g coefficients A coefficients b coefficients C coefficients d coefficients OE 13 7 LPKKTSolver Class LP KK TSolver Linear problem KKT solver for problems defined in equation 13 2 class LPKKTSolver IKKTSolver 210 Constructors CHAPTER 13 QP AND LP SOLVERS LPKKTSolver BVector g BMatrix BVector b BMatrix C BVector d Constructor Linear Programming KK TSolver Parameters BOT poe g coefficients A coefficients b coefficients C coefficients d coefficients Chapter 14 Model Predictive Control MPC This chapter describes how to set up MPC controller using MPCMath The implementation of MPC is based on the MiMoMPC object Source code for MiMoMPC is available for the MPCMath user making it possible to tailor the MPC controllers specifications and functionality to the users requirement The MiMoMPC class implements both conventional MPC and Soft Con strained MPC Prasath and Jorgensen 2010 2010 The con ventional has a guadratic penalty function and the Soft Constrained has a dead band zone around the set point where the penalty for not reaching the exact set point is low The plant is assumed to be a linear state space system in innovation form 2x41
92. c TransferFunction operator TransferFunction a double b Parameters a input a b constant returns a b 6 1 TRANSFERFUNCTION 123 operator Divide TransferFunction with constant operator static TransferFunction operator TransferFunction a double b Parameters a input b constant returns a b operator Divide transferfunctions operator static TransferFunction operator TransferFunction a TransferFunction b Parameters a input a b input b returns a b Show Show Transfer function static void Show string txt TransferFunction a Parameters txt text string a TransferFunction Sub Transferfunction Sub static TransferFunction Sub TransferFunction a TransferFunction b Parameters a input a b input b returns a b TauForm 08 1 Constructor for Tau form G s ye static TransferFunction TauForm double Gain double Delay Vector Taus Parameters Gain Gain Delay Delay 0 Tau Time constants T returns Transfer function 124 CHAPTER 6 TRANSFER FUNCTIONS TauForm Constructor for Tau form G s ye Ret static TransferFunction TauForm double Gain double Delay Vector Taus Vector Zeroes Parameters Gain Gain Delay Delay 0 Tau time constants T zeroes returns Transfer function Value Time response of Transfer function double Value double t Parameters t time returns f t Chapter 7 State Space Models The StateSpaceM odel cla
93. c string DFormat double Parameters a double variable returns Formatted output string DFormat Format double variable static string DFormat int Fieldsize double a Parameters Fieldsize Field size a double variable returns Formatted output string ReadLine ReadLine from console static void ReadLine Show Show bool static void Show string text bool a Parameters text Variable description a bool variable 280 APPENDIX DEBUGGING TOOL FOR CONSOLE APPLICATIONS Show Show int integer static void Show string text int r Parameters text Variable description integer variable Show Show integer array static void Show string txt int a Parameters txt Variable description a integer array Show Show double static void Show string text double r Parameters text Variable description r double variable Show Show complex static void Show String text complex c Parameters text Variable description complex variable Show Show complex List static void Show string txt List lt complex gt a Parameters txt Variable description a list of complex variables B 1 CNSL 281 Show Show double double array static void Show string txt double a Parameters txt Variable description a double array Show Show vector on console static void Show string txt Vector a Parameters txt Text string a Vector Show Show matrix static void
94. ced functionalities e LU decomposition e QR decomposition e Eigenvalue decomposition giving eigenvalues and Eigenvectors e Linear equation solvers based on LU decompositions and Cholesky decom positions e And other functions MPCMath keeps track of the form of the Matrix object as e Null e ConstantDiagonal e Diagonal e General enabling MPCMath to exploit matrix forms and an automatic speeding up of calculations 1 3 BLOCK VECTORS AND MATRICES 1 3 Block vectors and matrices 11 Block vectors and matrices stores vector and matrices in their cells enabling a high level programming style Block vectors and matrices are implemented using the BVector and BMatrix classes The block matrix below were A and J are submatrices A I 0 O 0 0 O O AS 0 O A 10 0 00 A I 0 000 A is implemented with the code dim 5 int n 3 A Matrix Random n n 100 0 100 0 Matrix I Matrix UnityMatrix n BMatrix AS new BMatrix MatrixForm General dim for int pos 0 pos lt dim post AS pos pos A if pos lt dim 1 AS pos pos 1 I Matrix Show A A BMatrix Show AS AS 0 0 0 0 0 0 0 0 1 0 bby cow The Matrix object keeps track of the form of its submatrices the statement BMatrix ShowStructure AS Structure AS as shown by 12 CHAPTER 1 INTRODUCTION with the following output AS Structure Matrix Form General
95. ces A Coificient matrix Methods Solve Solve equations Vector Solve Vector r Parameters right hand side coifficients returns solution vector Solve Solve equations Matrix Solve Matrix R Parameters R right hand side coifficients returns solution matrix Solve Solve equations BVector Solve BVector r Parameters right hand side coifficients returns solution vector 8 8 BANDED MATRIX STORAGE Solve Solve equations BMatrix Solve BMatrix R Parameters R right hand side coifficients returns solution matrix 8 8 Banded matrix storage 141 The equation solvers BandEquationSolver B 9 and SymmetricBandEquationSolver 8 10 stores the data in a compact format as follows The m by n band matrix A with ku 1 non zero super diagonals and kl 2 sub diagonals is stored in a matrix with m kl 14 ku rows and n columns Columns of the matrix is stored in the corresponding columns in the AB matrix and diagonals of the ma trix are stored in the rows of the array Thus aj is stored in ab ku 4 1 4 i j 3 for maz 1l j ku 1 min n j kl The elements marked NaN inAB are ignored A Matrix Form General 8 8 78 7643 94 1250 26 2801 ooooo 65 9043 2 6987 61 2631 21 6376 0 0 0 0 0 9 3032 61 8430 80 8072 30 0282 0 0 0 Matrix Form General 4 8 NaN 78 7643 94 1250 26 2801 65 9043 2 6987 61 2631 21 6376 9 3032 61 8430 8
96. ckEquationSolver J lt summary gt Find Newton search directions lt summary gt lt param name rL gt residual lt param gt lt param name rA gt residual lt param gt lt param name rC gt residual lt param gt lt param name DX gt X search direction lt param gt lt param name DY gt Y search direction lt param gt lt param name DZ gt Z search direction lt param gt void IKKTSolver Solve BVector rL BVector rA BVector out BVector DX out BVector DY out BVector DZ BVector rX rL this mCTSinvZ rC BVector new BVector this strc int nx this strcx Dimension for int 0 lt nx ptt R pl rX pl for int 0 lt this strcy Dimension R p nx rA pl BVector res this solver Solve R DX DY new BVector this strcx new BVector this strcy for int 0 lt nx ptt DX p res pl for int 0 lt this strcy Dimension DY p res p nx 305 DZ DX this mCTSinvZ 1115 rC return 306 APPENDIX KKTSOLVER CODE Appendix G PARDISO sparse matrix storage format The compression of the non zeros of a sparse matrix A into a linear array is done by walking down each column column major format or across each row row major format in order and writing the non zero elements to a linear array in the order that they appear in the walk When storing symmetric matric
97. cribed in the previous section Setup MiMo MPC MiMoMPC mpc new MiMoMPC Model history horizon theta my ymin ymax rho umin umax Get references to operator information Matrix ypopr mpc YPlant Matrix ymopr mpc YModel Matrix yropr mpc YRef Matrix uopr mpc U MPC control for int step 0 step lt steps 26 CHAPTER 1 INTRODUCTION Manipulate setpoints Fineness setpoint YRef 1 SetVal step 0 100 100 0 elevator load setpoint YRef 0 SetVal step 150 250 10 0 mpc SetRef YRef Measurement and process noise eps MPCMathLib WhiteGaussianNoise epsilonVar epsilonMean xi MPCMathLib WhiteGaussianNoise xiVar xiMean Plant measurement with measurement noise YPlant Plant Observed XPlant eps MPC constroller UC mpc Next YPlant send control signal and process noise to plant XPlant Plant NextState XPlant UC xi console WriteLine step step ToString iterations mpc Solver Iterations ToString The set point for the Fineness Y Ref 2 is set to 100 0 for step 0 to 100 and the setpoint for the Elevator load Y Ref 0 is set to 100 0 for step 150 to 250 The conventional MPC controller gives the following result a MPCMath Plot Options plant load 1 8 MODEL PREDICTIVE CONTROL 27 a good control of elevator load and the fineness are ac
98. ctor BMatrix BVector BMatrix BMatrix BMatrix summary Cons tructor lt summary gt lt par lt par lt par lt par lt par lt par am name G gt G am name g gt g am name A gt A am name b gt b am name C gt C 4 4 mG vg mA vb mC vd J W mCTSinvZ for KKT solver coefficients lt param gt coefficients lt param gt coefficients lt param gt coefficients lt param gt coefficients lt param gt coefficients lt param gt public KKTSolver BMatrix G BVector g BMatrix BVector b BMatrix C BVect if G null I else 1 if Structure Equal G rowStructure G columnStructure A throw new MPCMathException MPCMath KKTSolver Illegal G struct this mG this mG G new BMatrix g structure if Structure Equal G rowStructure g structure throw new MPCMathException MPCMath KKTSolver Illegal g if Structure Equal G rowStructure A columnStructure throw new MPCMathException MPCMath KKTSolver Illegal A if Structure Equal A rowStructure b structure throw new MPCMathException MPCMath KKTSolver Illegal b if Structure Equal G rowStructure C columnStructure throw new MPCMathException MPCMath KKTSolver Illegal C if Structure Equal C rowStructure d structure throw new MPCMathException MPCMath KKTSolver Illegal d this vg
99. d An quadratic problem example gd gn 2 gs 1 s t 21 79 0 5 1 lt a lt 1 1 lt 219 lt 1 1 lt 2103 lt 1 reformulaions of 13 3 to the standard form 13 1 gives 199 13 1a 13 1b 13 1c 13 2a 13 2b 13 2c 200 CHAPTER 13 AND LP SOLVERS 100 G 0 1 0 13 4 001 g 1 2 1 13 5 1 1 0 13 6 5 0 5 13 7 1 0 0 0 1 0 0 0 1 ioo 13 8 0 1 0 0 0 4221 1 1 1 1 1 1 13 9 The MPCMath code for this problem is static void Work console WriteLine Test QP solver int nx 3 int ny int nz 3 Structure sx new Structure 1 nx Structure sy new Structure 1 ny Structure sz new Structure 2 nz o e BMatrix G new BMatrix MatrixForm General sx BVector g new BVector sx BMatrix A new BMatrix MatrixForm General sy sx BVector b new BVector sy BMatrix C new BMatrix MatrixForm General sz sx BVector 4 new BVector sz Matrix I Matrix UnityMatrix nx G 0 0 I 01 new Vector 1 2 1 A O 0 new Matrix MatrixForm General ny nx ALO 0110 0 1 0 ALO 0110 1 1 0 101 new Vector 1 0 5 ClO 0 I C 1 0 1 4101 new Vector 1 1 1 4111 new Vector 1 1 1 201 Structure Show sx sx Structure Show sy sy Structure Show sz sz BMatrix Show G G BVector Show g g BMatrix Show A A BVector Show
100. e defined by MPC contoller data int history 100 history for operator display int horizon 50 optimization horion 216 APPENDIX A INSTALLING The history value must be equal or larger the the state space model s time delay UnitTestMPCMath The UnitTestMPCMath application test the functionality of MPCMath Run the application If everything is OK the output will look like this a MPCMath Console Options Unit Test MPCMath End Unit test In the source code for the unit test presents lot of MPCMath code examples The solution file UnitTestMPCMath test the 32 version x86 of MPCMath The solution file UnitTestMPCMathx64 test the 64 bits x64 version 8 MPCMathConsoleTemplate This template can be used to develop or test MPCMath applications without MPCMath s console Typically intended for the final runtime systems Appendix Debugging tool for Console applications B 1 Cnsl Class Cnsl MPCMath Cnsl class for test and debugging of MPCMath programs Running DOS Command console It requires a valid Demo or Developer license Output is ignored when running under runtime licenses static class Cnsl Properties Digits Digits for doubles static int Digits set get FieldSize Field size of vector and matrix diplay static int FieldSize set get NumbersPerLine Numbers per Line static int NumbersPerLine set get 277 278 APPENDIX D
101. e previous section As the ARX model is a Single Input Single Output SISO state space model this conversion is rather trivial It more interesting creating State space models object from an arrays of transfer functions or ARX functions A plant can be described by the following set of transfer functions with 2 observed variable and 2 manipulated variables In this case a model for a cement mill derived from experimental data 0 62 58 0 29 8s 1 1 58 4584 1 88 1 28 1 3854 1 G s 15 e758 5 e 01s 6054 1 14s 1 s 1 These four transfer functions are inserted in an array of transfer functions with the code Cement mill MIMO system Double T 1 0 int ny 2 int nu NON il Matrix lt TransferFunction gt CMModel new Matrix lt TransferFunction gt MatrixForm General ny nu CMModel 0 0 TransferFunction TauForm 20 CHAPTER 1 INTRODUCTION 0 62 5 0 new Vector 45 0 8 0 CMModel i 0 TransferFunction TauForm 715 0 5 0 new Vector 60 0 CMModel 0 1 TransferFunction TauForm 0 29 1 5 new Vector 2 0 38 0 new Vector 8 0 CMModel i 1 TransferFunction TauForm 5 00 0 1 new Vector 14 0 1 0 and the state space model objects Plant and Model are generated Noise integration factor Vector alfa new Vector 0 7 0 7 generate state space model of Cement Mill StateSpaceModel Plant new StateSpaceModel CMModel T StateSpaceModel Model new StateSpaceM
102. e string txt Parameters txt text string 284 APPENDIX DEBUGGING TOOL FOR CONSOLE APPLICATIONS Appendix Base classes for Vectors and Matrices C 1 VBase Class VBase Base class for Vector holding values of type T Serializable abstract class VBase lt T gt Constructors VBase int n Constructor Parameters n VBase int n T val Constructor vector with equal values Parameters n Dimension value value VBase T vals Generate vector from array Parameters vals array of values 285 286 APPENDIX BASE CLASSES FOR VECTORS AND MATRICES Properties Dimension Get vector Dimension int Dimension get Structure Get vector structure Structure Structure get T Set ot get vector value virtual T this int pos set get Methods G Get value equivalent to res a pos T G int pos Parameters pos position returns value 5 Set value equivalent to a pos val void S int pos T val Parameters pos val C 2 MBase Class MBase Base class for Matrix objects type T Serializable abstract class MBase lt T gt 2 MBASE Constructors MBase int n Constructor for square matrix Parameters n Dimension MBase MatrixForm Frm int n Constructor for square matrix Parameters n MBase int n int m Constructor for matrix Parameters n Rows m Columns MBase MatrixForm Frm int n int m Constructor for matrix Parameters n Rows m Co
103. e throws an MPCMathConsole Maximum text length ex ceeded exception long texts in the SchrollViewer slows down the per formance and has the same effect as the good old memory leaks in C4 4 and c The exception can be avoided by clearing the conetnt of the console using console Clear 2 7 statements If the output must be preserved use the MPC MathConsole Trace to save the output in a text file Plots are generated using the Plot routine The following code defines a vector and fills it with a sinus curve The PlotSeries defines the label min max plot values to be found automatically and finally set as the vector holding the values to be plotted The call to console Plot creates a new window with the plot 34 The resulting plot is CHAPTER 2 CONSOLE FUNCTIONS int steps 500 Vector x new Vector steps for int step 0 step lt steps steptt x step 0 8 Math Sin 2 0 pi step steps 1 PlotSeries xs new PlotSeries x 1 0 1 0 x console Plot xs MPCMath Plot Options Plot can handle of to four plot series Vector y1 new Vector steps Vector y2 new Vector steps Vector y3 new Vector steps Vector y4 new Vector steps for int step 0 step lt steps steptt yi step Math Sin 4 0 step steps 1 y2 step Math Sin 8 0 pi step steps 1 y3 step Math Sin 16 0 pi step
104. eastSquareFit T Ym fun Vector X0 new Vector 0 0 0 0 100 0 100 0 Vector Xhat lsgfit Fit X0 console WriteLine Iterations lsqfit Iterations Vector Show X X Vector Show Xhat Xhat constrain the function parameters Vector XMin new Vector 10 0 10 0 0 0 500 0 Vector XMax new Vector 0 0 0 0 290 0 310 0 Xhat lsqfit Fit X0 XMin XMax console WriteLine console WriteLine Constrained result Vector Show XMin XMin Vector Show XMax XMax console WriteLine Iterations lsqfit Iterations Vector Show X X Vector Show Xhat Xhat The console output is Test Least Square Fit Xhat Vector X Vector 0 0050 0 0100 300 0000 300 0000 Iterations 50 X Vector 0 0050 0 0100 300 0000 300 0000 0 0050 0 0098 311 1983 311 1504 Constrained result XMin Vector 10 0000 XMax Vector Iterations 56 X Vector Xhat Vector 10 0000 0 500 0000 0 0 290 0000 310 0000 0 0050 0 0100 300 0000 300 0000 0 0050 0 0098 290 0000 311 1504 The LeastSquareFit uses the Levenberg Marquardt method as described in 194CHAPTER 12 UNCONSTRAINED AND CONSTRAINED MINIMIZATION Nocedal and J Wright 2006 and Madsen et al 12004 12 7 LeastSguareFit Class LeastSquareFit class LeastSquareFit Constructors LeastSquareFit Vector T Vector Y IFunt Fun Constructor Least Square Fit Parameters t values Y y values Initial guess for p
105. eated set get Delay Minimum delay for all manipulated vars int Delay get Delays Delay chains for U 17 3 DelayChain Delays set get Description Description Administrative field string Description set get Dimension States int Dimension set get 7 1 STATESPACEMODEL 129 K System Matrix K Matrix K set get NU Manipulated vars int NU set get NY Observed vars int NY set get Off Offset X A X 4 B U 4 K Eps 4 Off Vector Off get US Operating point for inputs Administrative field Vector US set get XS Operating point for State Vector XS set get Methods AssertEqual Assert equal and show objects if not equal static void AssertEqual string text StateSpaceModel actual StateSpaceModel expected Parameters text text string actual actual statespace model expected expected statespace model 180 CHAPTER 7 STATE SPACE MODELS Equal Equal compare two StateSpace models static bool Equal StateSpaceModel actual StateSpaceModel expected Parameters actual actual statespace model expected expected statespace model NextState Next state X A X B U K Eps Vector NextState Vector X Vector U Vector Eps Parameters State vector U Manipulated vector Eps Noise returns Next state Observed Observed Y C X Vector Observed Vector X Parameters returns Observed vector Reset Reset delay chains void Reset
106. edefined Its done in the solution explorer Add references Browse to the routine c 2 control MPCMathMPCMath dll 274 APPENDIX A INSTALLING Rename the Solution and the project to MyApplication Right click Rename Open the main program program cs by double clicking it Now the screen should look like this PCMathTemp Edit View Projet Debug Data Tools Window Help 4 amp 217 55 Bl i Add ow LOCA ala cE 4 Solution MPCMathTemplate I project Properies od References 4 programes Entry Pregean Morl system Windows Application The first routine staticvoidMain starts the MPCMath console in a sepa rate thread this section should not be modified by you Your code should be placed in the staticvoidW ork routine Start the application by clicking the run havent If everything is ok the MPCMath console should look like this MPCMath Console Options MPCMath template License Name Jergen K H Knudsen Type Expires Issued Closing the MPCMath console window or clicking the the system to development mode Before starting developing new code I recommend that you study the Test MiMoMPC application and the chapter Introduction to MPCMath button returns A 6 TestMiMoMPC This folder contains the Mu
107. es it is necessary to store only the upper triangular half of the matrix upper triangular format or the lower triangular half of the matrix lower triangular format The Intel MKL direct sparse solver uses a row major upper triangular stor age format That is the matrix is compressed row by row and for symmetric matrices only non zeros in the upper triangular half of the matrix are stored The Intel MKL storage format accepted for the PARDISO software for sparse matrices consists of three arrays which are called the values columns and rowIndex arrays The following table describes the arrays in terms of the values row and column positions of the non zero elements in a sparse matrix A values A real or complex array that contains the non zero entries of A The non zero values of A are mapped into the values array using the row major upper triangular storage map ping described above columns Element i of the integer array columns contains the number of the column in A that contained the value in values i rowInder Element j of the integer array rowIndex gives the index into the values array that contains the first non zero element in a row j of A The length of the values and columns arrays is equal to the number of zeros in A Since the rowIndex array gives the location of the first non zero within a row and the non zeros are stored consecutively then we would like to be able to compute the number of non zeros in the i th r
108. from the work tread enables print out of information during program execution private static MPCMathConsole console STAThread static void Main 1 console new MPCMathConsole console Work new MPCMath MPCMathConsole Entry Program Work System Windows Application app new System Windows Application app Run console the work routine is static void Work t console WriteLine My Application int res 1 1 console WriteLine 1 1 res ToStringO Running the application shows The MPCMathConsole MPCMath Console Options My Application 141 2 2 2 Displaying and plotting variables Text output to the console is done using the Show and Writeline routines some exaples are Show routines console WriteLine output a line to console 2 2 DISPLAYING AND PLOTTING VARIABLES 33 output a blank line console WriteLine output a bool var bool Ok true console Show Ok Ok output an array of integers int intArr 1 4 5 6 console Show Integer array intArr output double double pi Math PI console Show pi short pi MPCMathConsole Digits 8 console Show pi pi with the following output output a line to console Ok True Integer array 1 4 5 6 7 pi short 3 1416 pi 3 14159265 Integer array 1 45 6 7 If the content of the console winodw exceeds 300000 characters appr 2500 lines the consol
109. g according 1 according to real part 2 accord ing to imag part void Sort 80 CHAPTER 3 VECTORS AND MATRICES Chapter 4 Block Vectors and Matrices A block vector is a vector who s elements consist of vectors A Block matrix is a matrix who s elements consists of matrices Block vectors and block matrices are very convenient for two reasons It simplifies the programming task making it easier to configure matrices for Optimization tasks MPC controllers are often described in literature using block matrices Secondly MPCMath stores information about the structure of the block matrix and its sub matrices making it possible to exploit structures automatically during program execution The MatrixForm enumeration is described in There are some rules for block vectors and block matrices that must be obeyed All sub matrices in a block matrix row must have an equal number rows All sub matrices in a block matrix column must have the same number of columns The structure of a block matrix or block vector is recorded in a Structure object For a block vector the Structure object defines the number of sub vectors and the dimension of each sub vector T he code below defines a a block vector X with three sub vectors The dimension of the sub vectors are 3 3 and 1 Three random sub vectors are stored in X and finally a sub vector rsub is retrieved from Structure strc new Structure 3 strc 0 3 strc 1 2 strc 2 1
110. ging tool for Console applications B 1 Cnsl 211 214 219 219 220 221 223 223 225 226 231 231 233 234 235 236 243 243 248 255 257 258 258 260 261 262 263 264 265 266 266 271 271 272 272 273 274 276 276 277 o Base classes for Vectors and Matrices VIB ASE MUTA E 72 MBasel xls vat RR uode 5 OR KK TSolver code CONTENTS 285 285 286 291 295 299 307 309 Chapter 1 Introduction MPCMath is a mathematical library for real time implementation of process identification model predictive control and other optimization tasks Introduction to MPCMath MPCMath is a library of C4F NET routines designed for real time implementa tion of Process Identification packages Model Predictive Control and Optimiza tions tasks The foundation of MPCMath is a comprehensive implementation of Matrix and Vector calculus Development and test of mathematical algorithms are often based on inter active environments as Matlab or Python providing a high level mathematical language and efficient debugging facilities with high productivity These pack ages are not suited for on line applications running continuously controlling chemical plants or embedded systems where the controllers are implemented on small processors During the recent years Microsoft C language combined with the very comprehensive NET libraries has been a very popular platform fo
111. gonal and Diagonal are ignored Moving from General to Sparse is executed override MatrixForm Form set get SMType Sparse Matrix type SparseMatrixType SMType set get Methods Add Add B B A void Add Matrix a Parameters a Matrix to be added AddScaled Add scaled this alpha a this void AddScaled double alpha Matrix a Parameters alpha Constant a Input matrix AddScaled res alpha this Matrix AddScaled double alpha 68 CHAPTER 3 VECTORS AND MATRICES Parameters a txt alpha AssertEqual Assert equal Show actual and expected matrices are not equal static bool AssertEqual string text Matrix actual Matrix expected Parameters text text string actual actual matrix expected expected matrix returns true if equal Eigen Values Eigenvalues static CVector EigenValues Matrix a Parameters a Input matrix returns Complex vector with eigenvalues Equal Equal matrices test whether two Matrices are equal static bool Equal Matrix a Matrix b Parameters a Input matrix a b Input Matrix b returns true if equal Exp Exponential function static Matrix Exp Matrix A Parameters A 3 4 MATRIX Gemm General Matrix Multiplication this alpha Op a Op b beta this void Gemm Matrix a Matrix b Matrix0p Matrix0p oprb double alpha double beta Parameters a input matrix a b input matrix b MatrixOp direct or transposed oprb Matri
112. he Model in order to track the plant measurements from the Plant object The NextState func tions are used to update the Plant object with process noise xi and the Model object with the innovation 1 8 MODEL PREDICTIVE CONTROL 23 Load dist a T MPCMath Plot plant Fineness 120 0 model Finen The Model objects act as a Kalman filter tracking the Plant state Due the the noise integration the Model is able to track the unmeasured disturbances without offsets 1 8 Model Predictive Control Model predictive control can be implemented using the MiMoMPC class The MiMoMPC class implements both conventional MPC and Soft Constrained MPC The conventional MPC has a quadratic penalty function and the Soft Constrained MPC has a dead band zone around the set point where the penalty 24 CHAPTER 1 INTRODUCTION for not reaching the exact set point is low 25 Nominal 5 20 Penalty Function 5 e 0 1 2 The SoftConstrained MPC minimizes the problem N 1 1 2 2 0 2 laa 0 124415 z u n 50 N 1 2 yg 4 5 1 subject to the constraints Zk bk gt Hiug i k 1 J N i 1 min lt Uk 0 N 1 Aumin Auk Aumax 0 1 N 1 Zk lt Zmax k T k E 1T N Zk 2 Zmin k Nk 1 21
113. hieved but the ma nipulated variables very active The SoftConstrained MPC results in Options Plant load 200 000 plant Finen The achieved control is as good the conventional MPC but the manipulated variables are much better The SoftConstrained MPC is much more robust for model errors than the conventional MPC The MPC problems are solved using the QuadraticProblemSolver object This object find the minimum of the object function Minimize X G X g x s t A X b G X gt d QPSolver solver new QPSolver G g A b C d solver Solve console Show iterations solver Iterations console Show My solver My dual gap BVector Show x solver X solution equality lagrange variables BVector Show y solver Y slack variables BVector Show s solver S inequality lagrange variables BVector Show z solver Z The object uses a Primal Dual Interior Point algorithm to find the mini 28 CHAPTER 1 INTRODUCTION mum Its a general routine which exploit the structure of G A C to speed up calculations especially for problems with long time horizons The QPSolver solves the KKT system by a call to a KKTSolver defined by an interface This makes it possible to develop KKT solver that exploit structures in the system matrices solver new QPSolver new SoftConstraintKKTSolver G g by The complete source code for this example
114. id Write int Pos string Value Parameters Pos position Value text string Write Write double void Write int Pos double Value int Size int Digits Parameters Pos Position Value Value Size Field size Digits Digits 17 11 File I O and serialization Serialization refers to the term of converting or eventually transferring he state of an object into a stream e g a file stream or a memory stream The stream contains all the information needed to reconstruct deserialize the object for later use This can be used to store object on disc or transferring object between applications or computers MPCMath objects defined as Serializable can be serialized using NET s BinaryFormatter MPCMath provides the BinaryIO class to save and read object from binary files and the XmlIO class to save and read from XML files As shown below Vector x Vector Random 10 100 0 100 0 save and read binary file string file object txt 17 12 BINARYIO 265 Binaryl0 Save file x Vector y Vector BinaryI0 Read file Vector AssertEqual BinaryIO Vector y x save and read XML file string xfile xobject xml XmlIO lt Vector gt Save xfile x y XmlIO lt Vector gt Read xfile Vector AssertEqual XmlIO Vector y x Some of the MPCMath objects marked as Serializable can be serialized using NET a SoapFormatter as ASCII streams The SoapFormatter does not support generic classes as Matrix BV ector
115. ier for Ax b reference BVector Y set get 7 Lagrange multiplier for 4 reference BVector Z set get Methods Solve Solve void Solve 13 5 IKKTSolver Interface IKK TSolver KKT Solver interface for solving KKT equation system in augmented form se equation 13 25 interface IKKTSolver Properties d BVector d get 208 CHAPTER 13 AND LP SOLVERS Strcx X structure Structure Strcx get Strcy Y structure Structure Strcy get Strcz Z structure Structure Strcz get Methods Factorize Factorize KKT system void Factorize BVector SInvZ Parameters SInvZ 5712 diagonal vector Residuals Calculate residulas void Residuals BVector x BVector y BVector z BVector s out BVector rL out BVector rA out BVector rC out BVector rSZ Parameters x state variables y Lagrange multipliers for equality conditions 7 Lagrange multipliers for inequality conditions 8 Slack variables rL residuals rA residuals rC residuals rSZ residuals 13 6 KKTSOLVER 209 Solve Find Newton search directions void Solve BVector rL BVector rA BVector out BVector DX out BVector DY out BVector DZ Parameters rL residual rA residual rC residual DX X search direction DY Y search direction DZ Z search direction 13 6 KKTSolver Class KKTSolver Quadratic Program KKT solver default KKT solver for QPSolver Q must be positive semidefinit Solves Linear problems
116. if equal Invert Invert LinearFilter LinearFilter Invert Parameters returns F7 Invertible Check if LinearFilter is invertible If v H q e t implies that e t H q u t bool Invertible Parameters returns true if invertible Niid Normal independent identical distributed process static Vector Niid int N double Mean double Variance Parameters N Series lenght Mean Series mean Variance Series variance 9 1 LINEARFILTER 151 operator Filter time series static Vector operator LinearFilter F Vector u Parameters Filter object u Input time series returns F g u t operator Filter time series Static Vector operator Vector u LinearFilter H Parameters u Input time series F Filter object returns F g u t operator Operator 4 clone static LinearFilter operator LinearFilter F Parameters F Filter object returns F operator Operator static LinearFilter operator LinearFilter F Parameters F Filter object returns F operator Multiply by constant static LinearFilter operator double fak LinearFilter F Parameters fak constant F Filter object returns fak F 152 CHAPTER 9 LINEAR FILTER operator Multiply by constant static LinearFilter operator LinearFilter F double fak Parameters Filter object fak constant returns fak F operator Divide by constant static LinearFilter operator LinearFilter F double fak Par
117. ij i 0 ny 1 j 0 nu 1 7 4 nu 1 wy 1 0 7 4b j 0 In the StateSpaceM odel constructors the the fractions are specified as a ma trix of ErrorLevels FL with dimension ny The fractions w are calculated from EL mu l wig ELiy EL i 0 ny 1 7 5 2 0 A low Errorlevel EL j 0 indicates that model of the dynamic between y and is very accurate a high value indicates a an inaccurate model The default ErrorLevel is a matrix with EL 1 nu ie with even distri bution of the ErrorLevels 7 1 StateSpaceModel Class StateSpaceModel State Space model class X A X B U eps off Y C X eps Serializable class StateSpaceModel Constructors StateSpaceModel Constructor for serialization StateSpaceModel Matrix A Matrix Matrix C Matrix K Constructor from system matrices Parameters System matrix B System matrix B D System matrix C System matrix StateSpaceModel ARXModel arxModel Constructor ArxModel to StateSpace Nodel Parameters arxModel ARX model 7 1 STATESPACEMODEL 127 StateSpaceModel TransferFunction G double T this new ARXModel G T Constructor TransferFunction to StateSpace Model Parameters G Transfer function T Sample time StateSpaceModel Matrix lt TransferFunction gt model double T this model T new Vector model rows 1 0 Constructor MiMo TransferFunction to StateSpace model Parameters model
118. ing window void Plot string PlotID params PlotSeries Series Parameters PlotID Window identifiction string Series Series definition Plot Plot plots in new window Each plot can have a number of series Up to four plots in the window void Plot params Plot Plots Parameters Plots 44 CHAPTER 2 CONSOLE FUNCTIONS Plot Plot plots in new or existing window void Plot string PlotID params Plot Plots Parameters PlotID window identification Plots Plot definitions Print Print console window void Print Print Print text void Print string text Show Show Console Window void Show Show Show bool void Show string text bool a Parameters text Variable description a bool variable Show Show int integer void Show string text int r Parameters text Variable description integer variable 2 4 MPCMATHCONSOLE 45 Show Show integer array void Show string txt int a Parameters txt Variable description a integer array Show Show double void Show string text double r Parameters text Variable description double variable Show Show complex void Show String text complex c Parameters text Variable description complex variable Show Show complex List void Show string txt List lt complex gt a Parameters txt Variable description a list of complex variables Show Show double double array void Show string txt double
119. inimizer IConFun fun new TestConFun Vector XO new Vector 3 5 1 5 Vector XMin new Vector 5 0 5 0 Vector XMax new Vector 5 0 5 0 Vector Show XO X0 Vector Show fun Dx fun Dx X0 Matrix Show fun DDx fun DDx X0 180CHAPTER 12 UNCONSTRAINED AND CONSTRAINED MINIMIZATION double val Vector X Unconstrained minimization FunMin min new FunMin fun val min Minimize X0 XMin XMax console WriteLine Iterations min Iterations Minimum value val X 7 min X Vector Show X X Vector Show fun Dx fun Dx X Matrix Show fun DDx fun DDx X Notice that the interface Con inherits the interface J Fun making the function T estConFun usable as argument requiring an 7 F un interface The resulting output on the console is XO Vector 3 5000 1 5000 fun Dx Vector 36 0000 2 0000 fun DDx Matrix Form General 2 2 31 0000 20 0000 20 0000 15 0000 Iterations 32 Minimum value 3 09858265117597E 18 X Vector 3 0000 2 0000 fun Dx Vector 0 0000 0 0000 fun DDx Matrix Form General 2 2 34 0000 20 0000 20 0000 34 0000 The Consistent routine can be used to check the coding of the function to be optimized Consistent checks the approximation flat f x Vo f x Aa 12 8 The use of Consistent is demonstrated in the code below FunMin min new FunMin fun if min Consistent X0 1 12 3 FUNCTION MINIMIZATION 181 val min Minimize X0 XMin
120. is given in the MPCMath down load package from http www 2 control dk the TestMiMoMPC project 1 9 Intel Math Kernel Library BLAS and LA PACK Many of MPCMath s functions are based on Intel Math Kernel Library 1 a highly optimized implementation of the public domain computing packages BLAS Basic Linear Algebra Subroutines and LAPCK Linear Algebra Pack age This gives MPCMath a boost in performance resulting more than an order of magnitude The critical cpu consuming calculations in the MPC controllers and the QPSolver are the matrix multiplications and The Cholesky factorizations The speed of these operations can be measured with the following code console WriteLine Test Cholesky Speed MPCMath console WriteLine int dim 32 for int test 0 test lt 7 test dim 2 dim Matrix A Matrix Random dim dim 100 0 100 0 Matrix AT Matrix Transpose A Vector r Vector Random dim 1000 0 1000 0 Matrix multiplication DateTime start DateTime Now A AT A TimeSpan tm DateTime Now start 1 9 INTEL MATH KERNEL LIBRARY BLAS AND LAPACK 29 Cholesky factorizatio solve start DateTime Now CholeskyEquationSolver solver new CholeskyEquationSolver A Vector x solver Solve r TimeSpan tc DateTime Now start console WriteLine dim dim ToString matrix tm TotalMilliseconds ToString Cholesky tc TotalMilliseconds ToStri
121. iteLine Test Exceptions try Vector x Vector Random 4 100 0 100 0 Vector y Vector Random 3 100 0 100 0 double res x y catch MPCMathException e console WriteLine e Message the console print out is Test Exceptions MPCMath Vector Mul Illegal dimensions Normally its easier debug programs without the try catch construction and use the information from the call stack to locate the sinner In the final program its advisable to include try catch construction 5 MPCMathTemplate This is the starting point for development of a new MPCMath application Copy the contents of MPCMathTemplate to a new folder named MyApplication Cvs IMyApplication Y Date modified Type 15 01 201210 54 File Folder 15 01 201210 54 File Folder 15 01 20121054 File Folder 12 05 2011 10 58 XML Configuratio G MPCMathTemplate cs 06 12 2011 17 48 Visual C Project f EEIMPCMathTemplatesin 06 12 2011 17 48 Microsoft Visual S MPCMathTemplatesuo 15 01 201210 55 Visual Studio Solu 9 program cs 20 07 2011 1652 112 MPCMathConsoleTemplate MPCMathTemplate J MyApplication TestMiMoMPC A 8 items Double click the solution file MPCMathTemplate sln to start Microsoft Vi sual C 2010 Express Click the menu View Other Windows Solution Explorer to open the Solution explorer If My Application in not located the c 2 control directory the reference til MPCMath must be r
122. ivate double mu private double t summary Construtor lt summary gt lt param name Mu gt mu parameter lt param gt lt param name T gt Step size lt param gt public VanDerPol double Mu double T this mu Mu this t T 295 296APPENDIX E IMPLEMENTAION OF VAN DER POL EQUATIONS USING IMODEL int IModel Dimension get return 2 int IModel NU get return 0 int IModel NY get return 1 Vector IModel Derivative Vector X Vector U Vector res new Vector 2 res 0 X 1 res 1 this mu 1 0 X 0 X 0 X 1 X 0 return res Matrix IModel Jacobian Vector X Vector U Matrix res new Matrix MatrixForm General 2 res 0 1 1 0 res 1 0 2 0 this mu X O X 1 1 0 res 1 1 this mu 1 0 X 0 X 0 return res BMatrix IModel BJacobian Vector X Vector U return null Vector IModel NextState Vector X Vector U Vector W throw new NotImplementedException 297 Vector IModel Observed Vector X Vector U return X StateSpaceModel IModel LinearModel Vector XS Vector US throw new NotImplementedException Vector IModel Parameters get return new Vector 1 this mu this mu value 0 298APPENDIX E IMPLEMENTAION VAN DER POL EQUATIONS USING IMODEL Appendix F KKTSolver code Source code listing for default KKTSolver implementing interface IKKT So
123. ix A Matrix Random dim dim 100 0 100 0 Vector res x The individual elements of a vector can be read or set using pos row col statements as below double velm x 3 double aelm A 0 4 x 2 1 3 x 3 A 4 4 veln The Vector class is build on the base class V Base double gt and imple ments the interface Common Vector gt VBase provides basic vector func tionalities and ICommon allows the Vector object to be included as elements in Block and Generic Vectors and Matrices The Matrix class is build on the base class M Base lt double gt and im plements the interface Common Matrix gt MBase provides basic matrix 53 54 CHAPTER 3 VECTORS AND MATRICES functionalities and Common allows the Matrix object to be included as ele ments in Block and Generic Vectors and Matrices VBase Mbase and ICommon are documented in appendix C Matrices are created as null matrices as a default The different MatrixForms can be created using special constructors Examples are Null matrix with 5 rows and 5 columns Matrix B new Matrix dim Constant diagonal matrix with 5 rows and 5 columns Matrix C new Matrix MatrixForm ConstantDiagonal 5 Diagonal matrix with 6 rows and 7 columns Matrix D new Matrix MatrixForm Diagonal 6 7 General matrix with 10 rows and 20 columns Matrix e new Matrix MatrixForm General 10 20 Addressing non diagonal element in a diagon
124. king parameter 0 0 lt Beta lt 1 0 double Beta set get Epsilon Error margin double Epsilon set get Lambda Newton decrement double Lambda get MaxBacktrack Maximum number of backtrack steps long MaxBacktrack set get MaxIterationSteps Maximum number of iteration steps long MaxIterationSteps set get Mu Dual variables Vector Mu get 12 2 EXTENDED LINEAR QUADRATIC OPTIMAL CONTROL PROBLEM175 Steps number of Newton steps long Steps get X Postion of optimum Vector X get Methods Minimize Minimize function double Minimize Vector xo Parameters Start position of x returns Minimum value 12 2 Extended linear Quadratic Optimal Con trol problem The extended Linear Quadratic Optimal Control Problem is a special equality constrained minimization problem which are encountered in solvers for MPC and LQR controllers This problem can be solved extremely cpu efficient using the RiccatiSolver class 12 8 For a detailed description of the mathematics behind the Extended Linear Quadratic Optimal Control problem and the the Riccati series a description can be found in 2004 The RiccatiSolver class solves the problem 1 min ly 2x Uk tly an 12 3a k 0 subject to Dei 0 k 0 N 1 12 3b with the stage costs 1 1 ly xy Uk 52601 2 gw Ru 9 26 fk 12 4a 1
125. l static void Show string txt ARXModel a Parameters txt text string a ARXModel object 161 162 CHAPTER 10 ARX MODELS Chapter 11 Function and Model interfaces MPCMath provides the J Fun and ConF un interfaces as general interfaces to unconstrained and Constrained functions The function interface IFunt is useful for fitting function parameters as described in section Least Square Fitting 12 6 Th interface Feasible is inherited by all the interfaces above I Feasible makes it possible to define boxlimits for the feasible region of a model or a function The IModel interfaces is general interface to plant objects 11 1 IFun Interface IFun Interface for function R gt R interface IFun IFeasible Properties N Number of variables in x int N get Methods DDx Hessian matrix 163 164 CHAPTER 11 FUNCTION AND MODEL INTERFACES Matrix DDx Vector x Parameters state returns Hessian matrix null if Hessian undefined or x infeasible Dx Jacobian vector Vector Dx Vector x Parameters state returns Jacobian vector or null if x infeasible Value Function value double Value Vector x Parameters State returns function value or double MaxValue if x infeasible 11 2 IConFun Interface IConFun Interface for Constrained functions R Equality constraints Ce X 0 and Inequality Constraints Ci x gt 0 interface IConFun IFun Properties Ne Number of Eq
126. l way to describe the dynamics of a linear system Creating transfer functions using delay and time constants are an intu itive way to specify process dynamic The transfer function can be used directly or the can be used to as input to Linear Filter which are the discrete form of transfer functions The use of the TransferFunction class can be illustrated by a simple example The example shows the closed loop response for a PI controller controlling a Plant describes as a second order systems The Plant is described by the transfer function 1 Plant s anie rs 2ros 1 The PI Controller is defined by Controller s 1 S Tis where P is the controller gain and 7 the integration time double gain 1 0 double delay 0 0 double tau 10 0 double sigma 0 5 second order process TransferFunction Plant new TransferFunction gain delay tau sigma double P 3 0 double TI 25 0 Integrator TransferFunction Integrator new TransferFunction 1 0 TI 0 0 TransferFunction Controller P 1 0 Integrator creates the Plant and controller objects The closed loop dynamic Ga is defined by 115 116 CHAPTER 6 TRANSFER FUNCTIONS Controller s Plant s 1 Controller s Plant s Gals Closed loop dynamics TransferFunction Gcl Controller Plant 1 0 Controller Plant reference signal step after 5 time units TransferFunction Ref new Transfe
127. lay Polynomial P 0s 1 TransferFunction constructor G s e P s Parameters Delay Delay 0 Root polynomial 8 TransferFunction double Delay Polynomial P Polynomial R TransferFunction constructor G s e 95 eS Parameters Delay Delay 0 Root polynomial 8 R Zero polynomial R s TransferFunction double Delay Constructor Transfer function Impulse G s e Parameters Delay Delay 0 TransferFunction double Gain double Delay Constructor Transfer function Step G s ye s Parameters Gain Gain y Delay Delay 0 TransferFunction double Gain double Delay double Tau constructor Transfer function one pole G s ye 95 rs 1 Parameters Gain Gain y Delay Delay 0 Tau time constant 0 TransferFunction double Gain double Delay double Tau double Sigma constructor Transfer function two poles G s ye rs 2ars 1 Parameters Gain Gain y Delay Delay 0 Tau Time constant 0 Sigma Damping c 6 1 TRANSFERFUNCTION 119 Properties Delay Transfer function Delay double Delay set get Gain Transfer function Gain double Gain set get Denominator Polynomial G s e 95 P Polynomial get R Numerator Polynomial G s e Pis Polynomial R get Roots Transfer function Roots CVector Roots get Zeroes Transfer function Zeroes CVector Zeroes get Methods Add Add transfer functio
128. le operator Vector y Vector x Parameters y y vector x vector returns Inner product of vectors operator Matrix vector operator res A x static Vector operator Matrix a Vector x Parameters a a matrix vector returns result vector operator Vector Matrix operator res x A static Vector operator Vector x Matrix a Parameters x x vector a a matrix returns res vector operator Multiply scalar and Vector operator res i alpha x i static Vector operator double alpha Vector x Parameters alpha constant vector returns res vector operator Multiply scalar and Vector operator res i x i alpha static Vector operator Vector x double alpha Parameters vector alpha constant returns res vector 3 2 VECTOR 61 operator Divide vector with scalar resi x i alpha static Vector operator Vector x double alpha Parameters vector alpha constant returns res vector operator Add scalar to vector resi x i alpha static Vector operator Vector x double alpha Parameters vector alpha constant returns res vector operator Add scalar to vector res i alpha x i static Vector operator double alpha Vector x Parameters alpha constant vector returns res vector operator Subtract scalar from vector x i alpha static Vector operator Vector x double alpha Paramete
129. ln In the Solution explorer window rename the solution and the project file to your applications name Finally enter some code in program work routine as shown below i MyApplication Microsoft Visual C 2010 Express JM 9 cie 2 0 n Edit View Project Debug Data Tools d 11 41 25 44 45 135 19 0 55 2 538 Add Row Solution Explorer using System 12 Solution MyApplication 1 project using System Collections Generic 4 MyApplication using System Ling Properties using System Text Ga References using MPCMath By app config using System Threading program cs Einamespace MPCMathApplication class Program private static MPCMathConsole console STAThread static void Main console new MPCHathConsole console Work new MPCMath MPCMathConsole Entry Program Work System Windows Application new System Windows Application app Run console static void Work console writeLine My Application int res 1 1 console wWriteLine 1 1 res ToString The normal Main program for the application creates the MPCMathCon sole set the entry of the Program Work routine and then starts the created MPCMathConsole by calling app Run console The MPCMath console runs 31 32 CHAPTER 2 CONSOLE FUNCTIONS in a new parallel tread execution the code specified in the Program Work rou tine Separating the MPCMathConsole main tread
130. lpha Vector lt T gt a Parameters alpha constant a Input a returns alpha a operator Scalar vector multiply static Vector lt T gt operator Vector lt T gt a double alpha Parameters a Input a alpha constant returns alpha a operator Vector Scalar divide static Vector lt T gt operator Vector lt T gt a double alpha Parameters alpha constant a Input operator Sub operator static Vector lt T gt operator Vector lt T gt a Vector lt T gt b Parameters a Input b Input b returns a b 5 3 TMATRIX Set Set subvector void Set int pos Vector lt T gt a Parameters position a sub vector Set Set subvector with increments void Set int pos int incr Vector lt T gt a Parameters position incr increment a sub vector Show Show static void Show string txt Vector lt T gt a Parameters txt text string a Object 5 3 TMatrix Class Matrix Generic Matrix class Serializable class Matrix lt T gt MBase lt T gt ICommon lt Matrix lt T gt gt Constructors Matrix int n base n Constructor sguare matrix null form Parameters n Dimension Matrix MatrixForm Form int n base Form n where 107 ICommon lt T gt new 108 CHAPTER 5 GENERIC VECTORS AND MATRICES Constructor square matrix Parameters Form Matrix Form n Dimension Matrix int n int m base n m Constructor n x m matrix Parameters n
131. ltiple Input Multiple Output MPC program used in the Introduction to MPCMath document Start the application by opening the solution file TestMiMoMPC sln 6 TESTMIMOMPC 275 static void Work console writeLine Test softconstrained mimo console writeuine E TestMiMcMPC TemporanKey pfe J contoller data int history 100 history for operator display int horizon 50 optimization horion if SoftConstreint 01 soft constrained HPC theta Vector 2 6 2 JJ reference penalty my new Vector 1000 0 500 0 soft constraint penalty ynax new Vector 2 8 5 0 J soft constraint max values ynin Vector 2 0 5 0 soft constraint min values Solution plover RUPEES View Project Debug Dita Took Window Help PI HN Sa 20 000 load 200 000 Fineness ae ui ER 20 002 plant Load 200 020 plant rn 200 900 40 002 E Locals The MPC controller runs 500 steps and display an operator display with history and predicted performance After 500 step an overview plot is displayed Press the stop button to revert to edit mode Play with the application parameter and study the code bool MPC true MPC or trackin exaple bool noise true noise on off bool SoftConstraint true Conventional or softconstrained MPC The MiMoMPC history and prediction horizon ar
132. lumns MBase int n int m T vals Constructor for general matrix Parameters n Rows m Columns vals Values stored row vise MBase int n T val Constructor for diagonal matrix with constant diagonal values Parameters n Dimension val value MBase T vals Constructor for diagonal matrix from vector xfi Parameters vals vector of values Properties Columns Columns int Columns get 287 288 APPENDIX C BASE CLASSES FOR VECTORS AND MATRICES ColumnStructure Get Column structure Structure ColumnStructure get MatrixForm Matrix form Null ConstantDiagonal Diagonal or General Moving from Null towards General preserves data Moving from General to Null ConstantDiago nal and Diagonal are ignored Moving from General to Sparse is executed virtual MatrixForm Form set get NZ Get or set space for Non zero values in sparse matrix If NZ is set to less than the actual number of of non zero values the value buffer is shortened to actual number of non zero values int NZ set get Rows Rows int Rows get RowStructure Get Row structure Structure RowStructure get T Set or get matrix value res A row col virtual T this int row int col set get Type Object type ObjectType Type get 2 MBASE Methods G Get value equivalent to res a row col T G int row int col Parameters row Row col S Set value equivalent to a row col re
133. lver 13 5 lt code header gt lt ile gt KKTSolver cs lt file gt lt author gt Jrgen Knudsen lt author gt lt copyright gt Copyright 2 control Aps 201 lt code header gt using System using System using System Collections Generic using System Linq using System Text namespace MPCMath Quadratic Program KKT solver Q gt 0 Linear Program solver Q Null matrix min xGx g s t Ax b Cx gt d IG DX A 0 0 DY 1 0 21015 DZ Factorized into IG C SinvZ C A DX l A 0 IDY DZ DX SInvZ SInvZ rC lt summary gt Quadratic Program KKT solver default Q must be positive semidefinit K 299 1 lt copyright gt or Q Form MatrixForm Null rL rA rC rL SinvZ rc rA KT solver for QPSolver 300 APPENDIX F KKTSOLVER CODE Solves Linear problems by setting Q null lt summar public class KKTSolver 1 y IKKTSolver private static MPCMathConsole console MPCMathConsole Console Linear equation solver SymmetricalBlockEquationSolver solver private private private private private private private private private private private private private private Structure strc Structure strcx Structure strcy Structure strcz BMatrix BVector BMatrix BVe
134. meters a b Difference Diffference between vectors Max Abs A i B i 1 0 Abs B i static double Difference Vector A Vector B Parameters B Difference Difference from Zero Max Abs A p 1 0 4 Math Abs A p static double Difference Vector A Parameters A Distribution Density curve for a values static Vector Distribution int N double Range Vector a Parameters N Groups Range max variantion a input vector 238 CHAPTER 16 MPCMATHLIB Fact Factorial n static int Fact int n Parameters n input returns n Gauss Gauss density function static double Gauss double x double mean double var Parameters x Input mean Mean var Variation GaussDistribution Gauss Distribution static Vector GaussDistribution int N double Range double mean double var Parameters N Groups Range max variantion mean var IsMiminimum Is X a local minimizer for Fun static bool IsMiminimum IFun Fun Vector X double Eps Parameters Fun Function Ifun or IConFun X Minimizer candidate Eps Accuracy returns true if x is a local minimizer IsMiminimum Is X a local minimizer for Fun static bool IsMiminimum IFun Fun Vector X double Eps bool Trace 16 5 MPCMATHLIB UTIL 239 Parameters Fun Function Ifun or IConFun X Minimizer candidate Eps Accuracy Trace Trace result returns true if x is a local minimizer IsMiminimum Is X a local minimizer for Fun Static bool
135. moothing Spline Parameters X data values Y funtion value CubicSpline Vector X Vector Y double Lambda this X Y Lambda null Constructor for smoothing Spline Parameters X data values Y funtion value Lambda Smoothing factor CubicSpline Vector X Vector Y double Lambda Vector Sigma Constructor for smoothing Spline Parameters data values funtion value Lambda Smoothing factor Sigma Weigths for data points 17 8 BARRIERFUNCTION 261 Properties Lambda Smoothing factor 0 0 lt Lambda lt 1 0 double Lambda set get Splines Array of Spline functions Spline Splines get X Spline x points Vector X get Y Spline y points Vector Y get Methods Value Value of smoothed spline double Value double x Parameters 17 8 BarrierFunction Class BarrierFunction Logaritmic barrier function Given a set of inequality conditions B gt Az the barrier function is N 1 5 In b aix 17 4 i 0 where a is the i row of A and N is the number of rows in A class BarrierFunction Fun 262 CHAPTER 17 MISCELLANEOUS FUNCTIONS Constructors BarrierFunction Matrix A Vector B Constructor Parameters A matrix vector 17 9 Reports In C it is surprisingly difficult to program a simple plain report with some values in nice columns One way is to use Windows Presentation Foundation WPF function to make the columns but in many cases its an over kill The
136. n valve y1 valve position valve y2 1444 FourTankProcess Class Four TankProcess Four Tank Process model class FourTankProcess IModel Constructors FourTankProcess double T this T false Constructor Parameters Step size MODEL PREDICTIVE CONTROL MPC 14 5 VANDERPOL FourTankProcess double bool Extended Constructor Parameters Step size Extended Extended model 14 5 VanDerPol Class VanDerPol Van der Pol s problem t u 1 y t y t y t class VanDerPol IModel Constructors VanDerPol double Mu double T Construtor Parameters Mu yu parameter T Step size Implementation of Van der Pol equation is shown in appendix E 221 222 CHAPTER 14 MODEL PREDICTIVE CONTROL MPC Chapter 15 ODE solvers 15 1 Introduction Ordinary Differential Equations can be solved using the ODESolver class ODE Solver implements a number of Explicit Runge Kutta methods where the solu tions can be found without iterations and a number of ESDIRK methods where the solution in each integration step requires a number of iteration steps The simpler Explicit Runge Kutta methods are suitable for differential equation sys tem where the eigenvalues have an equal order of magnitude The ESDIRK methods are recommended for stiff differential equation systems where there is a large difference between the systems eigenvalues The test example below shows how to integrate the Van der Pol equation
137. nRun_Click object sender RoutedEventArgs MPCMath Matrix A MPCMath Matrix Random 5 5 100 0 100 0 MPCMath Matrix Show A A private void btnConsole_Click object sender RoutedEventArgs 24 MPCMATHCONSOLE 39 this console Show The constructor creates the MPCMathConsole and stores a reference to in the private variable console The Run button creates some output on the console The Run makes the console visible The console can be hidden by selecting the menu item Hide Re A MPCMath Console Options Matrix Form General 5 5 50 5473 45 5474 98 0583 8 3 5192 11 5029 xaml dow 8 MainWindow 4 Console 2 4 MPCMathConsole Class MPCMathConsole MPCMath console class for test and debugging of MPCMath programs Run ning MPCMath Console requires a valid Development or Demo license class MPCMathConsole MPCMathWindow Constructors MPCMathConsole this false Default constructor without Hide option in console window MPCMathConsole bool EnableHide base EnableHide 40 CHAPTER 2 CONSOLE FUNCTIONS Constructor Parameters EnableHide Enable Hide option in console window Properties Console Get reference to MPCMath console static MPCMathConsole Console get Digits Digits for doubles static int Digits set get FieldSize Field size of vector and mat
138. nction to be minimized Properties Alpha0 Initial Steepest descent gain double AlphaO set get BackTracks number of backtracks in minimization int BackTracks get C1 Wolfe condition constant C1 double C1 set get C2 Wolfe condition constant C2 double C2 set get 184CHAPTER 12 UNCONSTRAINED AND CONSTRAINED MINIMIZATION EpsGrad Gradient residual limit double EpsGrad set get EpsStep Step size residual limit double EpsStep set get ExitReason Reason for leaving Minimizer string ExitReason get Iterations Number of Iterations int Iterations get MaxBacktracks Maximum number af backtracks in each line search int MaxBacktracks set get MaxIterations Maximum number of iteration steps int MaxIterations get Ok Minimize or Consistent result bool Ok get ResGrad Gradient residual double ResGrad get 12 4 FUNMIN ResStep Step size residual double ResStep get Trace Trace iterations bool Trace set get TraceLevel Trace level int TraceLevel set get UseBFGS Use BFGS methis to appaximate inverse Hessian bool UseBFGS set get W Inverse Hessian BFGS approximation Matrix W get WarmStart Warm start keep BFGS Hesssian estimate between calls to Minimize bool WarmStart set get X Argmin X Vector X get XUnchanged X was not changed during minimixation X X0 bool XUnchanged get 185 186CHAPTER 12 UNC
139. ng a b b a static Structure operator Structure a Structure b 4 2 BVECTOR 85 Parameters a Input a b Input b returns a b Show Show Structure static void Show string txt Structure a Parameters txt text string a Structure object Values Construct new Structure from array of values static Structure Values params int vals Parameters vals array of dimensions returns Structure 4 2 BVector Class BVector Block Vector class Serializable class BVector Vector lt Vector gt Constructors BVector base Constructor default BVector int n base n Constructor Parameters n Dimension BVector int n Vector val base n val 86 CHAPTER 4 BLOCK VECTORS AND MATRICES Constructor vector with equal values Parameters n Dimension value Value BVector params Vector vals base vals Generate vector from array of Vectors Parameters vals Vector array BVector Vector lt Vector gt a base a Dimension Constructor BVector from Vector lt Vector gt Parameters a BVector Structure s Construct BVector from structure Parameters s Structure BVector Structure s double val Construct BVector from structure with equal values Parameters 8 Structue val value BVector Vector a base 1 Constructor Wrap Vector a in block vector Parameters a Methods DivElements Divide Vector elements z i y i x i static BVector DivElements BVector y B
140. ng like this 28 12 2011 18 05 28 12 2011 1810 14 01 2012 13 34 06 12 2011 1816 1 MPCMathConsoleTemplate 20 07 2011 17 20 J MPCMathTemplate 15 01 2012 10 52 olders amp SW Preload C MyApplication 15 01 2012 10 54 Ji TestMiMoMPC 28 12 2011 18 07 UnitTestMPCMath 28 12 2011 18 09 Ji XXXMiMoMPC 29 12 2011 16 21 0 01 4 212 44 BeautifulDenmark Lk 10 items The c 2 control folder contains the following folders 271 272 APPENDIX A INSTALLING MPCMATH License Holding the license file MPCMath The binary MPCMath dll MPCMathConsoleTemplate Template for Console based MPCMath applications Can be used with MCMath Runtime licenses MPCMathWPF Template Template for WPF based application this is the nor mal starting point for development of a new MPCMath application Using the WPF based console requires a Demo or a Development license Test MiMoMPC Multiple Input Multiple Output MPC program used in the Introduction to MPCMath chapter Unit TestMPCMath Unit test of the MPCMath library It contains many examples of calls to MPCMath XXXMiMoMPC As TestMiMoMPC with included source code for MI MOMPC object A 3 Windows x86 and x64 platforms MPCMath supports both the 32 bits platform x86 and the 64 bits platform x64 The x86 platform is the default platform where the MPCMath routines are delivered in the MPCMath Dll The x64 platform requires the use of the library MPCMathx64 dll Both libraries can
141. ng process defined by the transfer func tion Plant The LinearFilter G q describing the deterministic part of is derived directly from Plant and the sample time DT The LinearFilter H q is derived from G q denominator polynomial The input signal u t is generated using the PBRS 9 1foutine The determin istic part comes from G g u t The stochastic part H g e t where the white noise series is generated using the N iid 9 1 routine The plant response comes from Ypjant Ystoc Having an input_and an output series a LinearFilter G q can be estimated using the Regress routine An estimate Y t of the deterministic response is calculated The estimated deterministic response is calculated from Y t G g u t The code is 145 146 CHAPTER 9 LINEAR FILTER console WriteLine Test Linear Filter int N 1000 double mean 0 0 double var 1 0e 4 double gain 1 0 int delay 5 double tau 10 0 double sigma 0 3 double DT 1 0 second order system TransferFunction Plant new TransferFunction gain delay tau sigma model for deterministic part LinearFilter G new LinearFilter Plant DT model for stochastic part LinearFilter H new LinearFilter new Polynomial 1 0 G P LinearFilter Show G G LinearFilter Show H H console Show H Gain H Gain Pseudo Random Binary Signal Vector u LinearFilter PBRS N 0 005 Deterministic response
142. ngO which measures calculation time for multiplication of random square matri ces and subsequent Cholesky factorization The results obtained with the best possible C code is Console e a x J est Cholesky Speed MathLib ve im 64 matri dim 128 12 dim 256 dim 512 dim 1024 matr ddim 2048 matrix 2540 where multiplication of two 2048x 2048 matrices takes 254015 ms or 4 2 minutes MathLib was a predecessor to MPCMath written entirely in C With MPCMath using Intel MKL the results is MPCMath Console eleal g j Test Cholesky Speed MPCMath version din 64 matrix 11 Cholesky 6 ms din 128 matrix 1 Cholesky 1 ms matrix 8 where multiplication of two 2048x 2048 matrices takes 3545 ms a factor 70 improvement 30 CHAPTER 1 INTRODUCTION Chapter 2 Console functions The MPCMathConsole is the development and debugging tool for MPCMath applications The MPCMathConsole is normally created from the MPCMath template application delivered together with the MPCMath Package Using MPCMathCosole requires a valid Development or a Demo license It not avail able using a Runtime license 2 1 Creating a new MPC Math application Copy the folder C 2 controlMPCMathTemplate to a new folder and rename the new folder the name of your application i e MyApplication Open the new folder and double click the solution file MPCMathTemplate s
143. ns static TransferFunction Add TransferFunction a TransferFunction b Parameters a input a b input b returns a b 120 CHAPTER 6 TRANSFER FUNCTIONS AssertEqual Assert equal Show transfer function if not equal static void AssertEqual string text TransferFunction actual TransferFunction expected Parameters text text string actual actual transfer function expected expected transfer function Clone Clone Transfer function static TransferFunction Clone TransferFunction a Parameters a input a returns Clone TransferFunction Div Divide transferfunctions static TransferFunction Div TransferFunction a TransferFunction b Parameters a input a b input b returns a b Equal Equal function static bool Equal TransferFunction a TransferFunction b Parameters a Input a b Input b returns true if a equal Mul Multiply transferfunctions static TransferFunction Mul TransferFunction a TransferFunction b Parameters a input a b input b returns a b 6 1 TRANSFERFUNCTION 121 Mul Multiply Transferfunction with constant static TransferFunction Mul double a TransferFunction b Parameters a constant b input b returns a b operator TransferFunction clone operator static TransferFunction operator TransferFunction a Parameters a input TransferFunction returns Cloned TransferFunction operator TransferFunction Negate operator static TransferFunction operator T
144. nstructor for square matrix Parameters form Matrix Form Structure Structure for rows and Columns BMatrix Structure RowStructure Structure ColStructure base RowStructure Dimension ColStructure Dimension Constructor for general matrix as Null matrix Parameters RowStructure Row Structure ColStructure Column Structure BMatrix MatrixForm form Structure RowStructure Structure ColStructure base RowStructure Dimension ColStructure Dimension 4 3 BMATRIX 93 Constructor for general matrix Parameters form Matrix Form RowStructure Row Structure ColStructure Column Structure BMatrix Matrix lt Matrix gt base a form a rows a columns Constructor BMatrix from generic MatrixjMatrixj Obs Values and structures are copied by reference not cloned Parameters Inputa BMatrix Matrix a base 1 Constructor Wrap matrix a in Block Matrix Parameters Input matrix Methods Allocate Allocate Matrix element If null element a new matrix is allocated If element exist matrix form is changed void Allocate int row int col Parameters TOW col form Allocate Allocate Matrix element Empty elements of a Block matrix are nor allocated by the constructor void Allocate int row int col MatrixForm form Parameters row col form Flatten Flatten BMatrix static Matrix Flatten BMatrix a 94 CHAPTER 4 BLOCK VECTORS AND MATRICES Parameters a Input Bmatrix returns Plain Mat
145. nterface ISolver Methods Solve Solve A x Vector Solve Vector r Parameters r Vector r returns Vector x Solve Solve R Matrix Solve Matrix R Parameters Matrix R returns Matrix X 8 2 LinearEquationSolver Class LinearEquationSolver Linear equation solver PLU factorization Matrix determinant Solve A x and A X R class LinearEquationSolver ISolver Constructors LinearEquationSolver Matrix Constructor Parameters A Coifficient matrix Properties L Lover factor in A PLU factiorization Matrix 1 get 8 2 LINEAREQUATIONSOLVER U Upper factor in A PLU factiorization Matrix U get Methods Determinant Determinant double Determinant Parameters returns determinant of A Invert Invert matrix Matrix Invert Parameters AT 1 returns Pivot void Pivot Matrix LU Parameters LU L U Solve Solve A x Vector Solve Vector r Parameters vector returns vector x Solve Solve A X R Matrix Solve Matrix R Parameters r Matrix R returns Matrix X 135 186 CHAPTER 8 EQUATION SOLVERS 8 3 LeastSquareEquationSolver Class LeastSquareEquationSolver Least Square Equation Solver QR Factorization class LeastSquareEquationSolver ISolver Constructors LeastSquareEquationSolver Matrix Constructor Parameters A Coifficient matrix Properties Q Q matrix A Q R Q orthogonal Matrix Q get
146. odel CMModel T alfa StateSpaceModel Show Plant Plant StateSpaceModel Show Model Model The StateSpaceModel object Model is created via EAARX objects with integration of noise leading to offset free control Plant StateSpace model nx 14 ny 2 nu 2 Delay 0 A Matrix Form General 14 14 5 1 0 B Matrix Form General 14 2 x Form General 14 2 C Matrix Form General 2 14 1 0 1 In order to integrate the state space models the following objects are created 1 7 STATE SPACE MODELS 21 Define states of observed Variabes Vector XPlant new Vector Plant Dimension Vector XModel new Vector Model Dimension Vector YPlant new Vector ny Vector YModel new Vector ny Vector UC new Vector nu Vector innovation Vector Zero new Vector Measurement noise and process noise Vector epsilonVar new Vector Vector xiVar new Vector nu if noise epsilonVar new Vector 0 05 10 0 xiVar new Vector 0 0001 0 1 Vector xiMean new Vector 0 0 0 0 Vector epsilonMean new Vector ny The simulation of the plant dynamics and tracking the plant with the model is done by the following code steps 1500 Tracking simulation for int step 0 step lt steps steptt Exerxice manipulated vars feed UC 0 SetVal step O 300 10 0 Separator speed UC 1 SetVal step 600 700 30 0 umeasured disturbances Load
147. ol Equal Vector lt T gt y Vector lt T gt x Parameters y Vector y x Vector x returns true if equal Get Get subvector Vector lt T gt Get int pos int dim Parameters pos Position dim Dimension returns Subvector Get Get subvector with increment Vector lt T gt Get int pos int incr int dim Parameters pos Position incr Increment dim Dimension returns Subvector 5 2 TVECTOR 105 operator Unary add clone operator static Vector lt T gt operator Vector lt T gt a Parameters a Input a returns a operator Unary Sub clone operator static Vector lt T gt operator Vector lt T gt Parameters a Input a returns a operator Add operator static Vector lt T gt operator Vector lt T gt a Vector lt T gt b Parameters a Input a b Input b returns a b operator Vector Vector inner product static Vector lt T gt operator Vector lt T gt a Vector lt T gt b Parameters a Input a b Input b returns atb operator Vector Matrix operator static Vector lt T gt operator Matrix lt T gt a Vector lt T gt x Parameters a Input a x Input b returns a x 106 CHAPTER 5 GENERIC VECTORS AND MATRICES operator Matrix Vector operator static Vector lt T gt operator Vector lt T gt x Matrix lt T gt a Parameters a Input a x Input b returns x a operator Scalar vector multiply static Vector lt T gt operator double a
148. olver solver new ODESolver method fun dt absTol relTol integrate Van der Pol Vector tval null Matrix X null Vector XS new Vector fun Dimension 1 0 Vector US new Vector fun NU DateTime start DateTime Now solver Integrate T XS US out tval out X TimeSpan elapsed DateTime Now start console WriteLine console WriteLine Method method ToString absTol tol ToString Tolerance solver Tolerance ToStringO console Show Time ms elapsed TotalMilliseconds console Show stepsize solver Step console Show steps tval Dimension console Show evaluations solver Evaluations console Show accepted solver AcceptedSteps console Show rejected solver RejectedSteps console Show Factorizations solver Factorizations Plot results Vector YO X GetRow 0 Vector Y1 X GetRow 1 console Plot new Plot PlotType XY new PlotSeries t 0 0 T tval new PlotSeries YO 0 0 0 0 SeriesColor Green YO new Plot PlotType XY new PlotSeries t 0 0 T tval new PlotSeries Y1 0 0 0 0 SeriesColor Green Y1 The console output is 15 2 ODEMETHODS 225 Test Ordinary Differential Equation solvers Method ESDIRK34 absTol 1E 06 Tolerance 1E 16 Time ms 2005 0000 stepsize 0 1242 steps 4099 evaluations 208592 accepted 4098 rejected 1171 Factorizations 15848 The resulting plots are a MPCMath Plot Options
149. operZeroes IModel interface expanded with BJacobian SparseMatrixSolver 8 7 based in Intel s PARDISO routine ODESolver and SteadyState 16 4Bupport for BJacobian 22 and support for Infeasible State Exception 22 JacobianApprox 22 for debugging models implemented using IModel 11 4 interface May 12 2012 IModel 11 4 interface included parameter for sample time T and renamed NextStep to Next Added administrative properties to StateS paceModel 7 1 June 8 2012 Sparse matrices implemented using PARDISO matrix storage Matrix GetSubmatrix and SetSubmatrix changed to Get and Set June 23 2012 Sparse matrices implemented as one of the possible Matrix Forms C 2 A quite big jobs with a lot of testing IModel 11 4 changed as usual It will probably not stabilize until work with Non linear MPC is finished July 4 2012 BMatrix 4 3 Get parameter sequence changed to same form as Matrix Get routine August 4 2013 Minor changes to StateSpaceModel 7 1 Removed property YS included properties XS and Off New constructor included Included Ric catiSolver 12 8 object Included Cnsl class B 1 for debugging of Console based programs December 15 2014 Added BandEquationSolver 8 9 SymmetricBandEqua tionSolver Spline CubicSpline IConFun IFunt Fun Min 12 4 ConFunMin 12 5 LeastSquareFit 12 7 and an additional version of Vector Random March 23 2014 Modified StateSpaceM odel 7 1 calculation of Kalman gain for MIMO state space models de
150. ow as the difference of rowIndex i and rowIndex i 1 In order to have this relationship hold for the last row of A we need to add an entry dummy entry to the end of rowIndex whose value is equal to the number of non zeros in A plus one This makes the total length of the rowIndex 307 308 APPENDIX G PARDISO SPARSE MATRIX STORAGE FORMAT array one larger than the number of rows of A The Intel MKL sparse storage scheme uses the Fortran programming lan guage convention of starting array indices at 1 rather than the C programming language convention of starting at 0 MPCMath takes care of all updating of the indexes of this storage scheme and the indexes rowIndex and Columns are not presented for the MPCMath programmer This description is provided solely to give an understanding of the sparse matrix storage mechanism Appendix MPCMath change history Feb 25 2012 Moved NiceMax and NiceMin from Plot class to PlotSeries class March 1 2012 Support for serialization 17 11 of MPCMath objects New BinaryIO 17 12 for saving and reading objects to disc files March 6 2012 IModel property Hessian renamed to Jacobian March 13 2012 ODESolver included chapter 15 Van der Pol routines 14 5 and appendix E for demonstration of ODESolver included March 14 2012 Support for serialization 17 11 of MPCMath objects to XML files New XmlIO 17 13 for saving and reading objects to XML files May 8 2102 New Vector functionality Pr
151. pe Matrix A Parameters type Sparse matrix Type A Input matrix returns Sparse matrix ToSparse Copy Matrix to Sparse Matrix static Matrix ToSparse SparseMatrixType type UPLO UpLo Matrix A Parameters type Sparse matrix Type UpLo Position for values in symmetric values A Input matrix returns Sparse matrix Transpose Transpose matrix static Matrix Transpose Matrix a Parameters a Input matrix returns Transposed input matrix Trmm Matrix product with triangular matrix Side Left this alpha Opr A this side Right this alpha this Opr A void Trmm Side side UPLO uplo MatrixOp opr double alpha Matrix A 76 CHAPTER 3 VECTORS AND MATRICES Parameters side Position af A matrix uplo Upper or lower matrix opr Transpose operator alpha constant A input matrix Unity Matrix Unity matrix static Matrix UnityMatrix int n Parameters n Dimension returns Unity matrix 3 5 CVector Class C Vector Complex vector Serializable class CVector VBase lt complex gt Constructors CVector 0 Constructor for serialization CVector int n base n Constructor Parameters n Dimension CVector int n complex val base n val Constructor with equal elements Parameters n Dimension val complex value CVector params complex vals base vals 3 5 CVECTOR 77 Constructor form array of complex values Parameters vals CVector List lt complex gt
152. r development of client and server solutions MPCMath provides a set off tools enabling the programmers to implement process control task MPC controllers and optimization tasks on the platform providing intelligent objects and functionality enabling high productivity and quality solutions Many of MPCMath s functions are based on Intel Math Kernel Library Intel a highly optimized implementation of the public domain computing packages BLAS Basic Linear Algebra Subroutines and LAPCK Linear Algebra Pack age This gives MPCMath a boost in performance resulting more than an order of magnitude increased computational speed MPCMath are aimed at organizations and companies developing equipment for process control having programmers mastering C and object oriented programming MPCMath is callable from any NET language as C Visual Basic NET and F This chapter gives a walk through how to program tasks related to MPC control in MPCMath starting with an introduction to the basic Vector and Matrix objects 8 CHAPTER 1 INTRODUCTION 1 1 Vectors Vector functionality is implemented in the Vector class A simple example console WriteLine MPCMath Introduction console WriteLine Vector definition Vector x new Vector 5 Math PI Vector y Vector Random 5 100 0 1000 0 Vector Z Z xty Vector Show x x Vector Show y y Vector Show z z The console Writeline writes a text string on the MPC
153. rFunction 1 0 5 0 Closed loop response TransferFunction Y Gcl Ref creates the transfer function of the closed loop dynamic and the a ref erence signal Ref a step delayed 5 seconds and the response signal Y Plotting of the Ref and Y signal are performed by the code int steps 150 Vector yresp new Vector steps Vector Reference new Vector steps for int step 0 step lt steps step Reference step Ref Value step yresp step Y Value step double max 1 5 console Plot new Plot new PlotSeries ref 0 0 SeriesColor Red Reference new PlotSeries yresp 0 0 max SeriesColor Green yresp 6 1 TRANSFERFUNCTION 117 MPCMath Plot 6 1 TransferFunction Class TransferFunction 08 R S 08 5 Linear Transfer Function 5 Pi Serializable class TransferFunction ICommon lt TransferFunction gt Constructors TransferFunction this 0 0 0 0 Default constructor TransferFunction double Gain double Delay CVector Roots TransferFunction Constructor G s ye Wea Parameters Gain Gain y Delay Delay 0 Roots Roots pi TransferFunction double Gain double Delay CVector Roots CVector Zeroes 118 CHAPTER 6 TRANSFER FUNCTIONS e 95 H s ri TransferFunction Constructor G s y Mep Parameters Gain Gain y Delay Delay 0 Roots Roots Zeroes Zeroes rj TransferFunction double De
154. ransferFunction Parameters a Input TransferFunction returns Negated TransferFunction operator Transfer function Add operator MPCMath requires the two Transferfunction a b to have equal delay static TransferFunction operator TransferFunction a TransferFunction b Parameters a input b input b returns a b operator Transfer function Add operator MPCMath requires the two Transferfunction b to have equal delay 0 static TransferFunction operator double a TransferFunction b Parameters a constant b TransferFunction returns TransferFunction 122 CHAPTER 6 TRANSFER FUNCTIONS operator Transfer function Add operator MPCMath requires the two Transferfunction a to have equal delay 0 static TransferFunction operator TransferFunction a double b Parameters a TransferFunction b constant returns TransferFunction operator Transferfunction Sub static TransferFunction operator TransferFunction a TransferFunction b Parameters a input a b input b returns a b operator Multiply transferfunctions operator static TransferFunction operator TransferFunction a TransferFunction b Parameters a input a b input b returns a b operator Multiply TransferFunction with Constant operator static TransferFunction operator double a TransferFunction b Parameters a constant b Input b returns a b operator Multiply TransferFunction with Constant operator stati
155. rce code for the default KKTSolver is given in appendix 13 4 QPSolver Class QPSolver IP Solver class Primal Dual Interior Point Algorithm class QPSolver Constructors QPSolver BMatrix G BVector g BMatrix A BVector b BMatrix C BVector d this new KKTSolver G g A b C d Constructor with default Solver min X Gx g x s t Ax b Gx gt d Parameters G coefficients g g coefficients A A coefficients b b coefficients coefficients d d coefficients QPSolver IKKTSolver Solver Solver with specific KKT solver Parameters Solver KKT solver 206 CHAPTER 13 AND LP SOLVERS Properties Disabled Disabled inequality constrains Included 0 disabled 1 BVector Disabled get ErrorLimit Error limit double ErrorLimit set get Iterations Iterations in last solve call int Iterations get MaxlIterations Maximum iterations int MaxIterations get Mu Duality gap double Mu get 5 Slack variables for Cx d reference BVector S set get Time Execution Time for last Solve call TimeSpan Time get TraceIterations Trace iterations bool TraceIterations set get 13 5 IKKTSOLVER 207 TraceLevel Trace level 0 trace residual 1 trace residual and 2 trace residual and x y z s 3 trace residual x y z s and detailed info int TraceLevel set get X Solution vector x BVector X set get Lagrange multipl
156. rived from generic arrays of Transferfunctions or ARXModels 309 310 APPENDIX CHANGE HISTORY September 29 2014 JacobianApprox replaced by routines JxEstimate 17 14 and JuEstimate October 26 2014 Imodel modified once again and as consequence hereof the LinearModel 14 2 VanderPol 14 5 and FourTankProcess 14 4 has been up dated 64 bit operating system support November 25 2014 Debugging and improvement of FunMin 12 4 and Con FunMIn functions Added the following utility routines BFGD BFGSInv and IsMiminimum 16 5 February 9 2015 Debugging and improvement of FunMin 12 4 and ConFun MIn 12 5 functions once again Now they are working quite good but there will always be room for improvements for these functions Added a new interface IFeasible 11 5 used to define the feasible regions for models and functions February 19 2015 Complex logarithm included 17 1 Index A E28 58 228 57 58 Abort ape Add sl E593 AddLine 51 AddScaled 67 i 101 109 Al 158 173 BIS Allocate Alpha Avg Pr 20 ARXModel ASP AssertEqual 77 84 150 160 25 255 278 279 56 I28 T3 227 259 Back Tracks BandEquationSolver BarrierFunction Beta BFGS BFGSInv BinaryIO BLAS BMatrix BSP BVector y ms au C2 E83 Cholesky factorization 137 CholeskyEquationSolver 137 Clear 42 51 Clone 120
157. rix Get Get submatrix new BMatrix Get int row int rows int col int cols Parameters row Row position rows Number of Rows col Column position cols Number of Columns returns Submatrix MulTransposed Multiply transposed a b static BMatrix MulTransposed BMatrix a BMatrix b Parameters a Input a b Input b returns a b operator Clone operator static BMatrix operator BMatrix a Parameters a Input a returns a operator Negate operator static BMatrix operator BMatrix Parameters a Input a returns a 4 3 BMATRIX 95 operator Binary add static BMatrix operator BMatrix a BMatrix b Parameters a Input a b Input b returns atb operator Binary sub static BMatrix operator BMatrix a BMatrix b Parameters a Input b Input b returns a b operator Multiply static BMatrix operator BMatrix a BMatrix b Parameters a Input b Input b returns a b operator Multiply with constant static BMatrix operator double alpha BMatrix a Parameters alpha constant a Input returns alpha a operator Multiply with constant static BMatrix operator BMatrix a double alpha Parameters a Input alpha Constant 96 CHAPTER 4 BLOCK VECTORS AND MATRICES operator Divede by constant static BMatrix operator BMatrix a double alpha Parameters a Input a alpha constant returns a alpha OuterProduct Ouher Product of two
158. rix Form General 3 5 87 4640 74 9052 50 3092 14 7262 73 6282 82 9797 27 8304 5 4292 4 7578 61 5226 7 0211 19 3501 98 1663 27 1058 58 8416 Matrix Form General 3 5 87 4640 74 9052 50 3092 14 7262 73 6282 82 9797 27 8304 5 4292 4 7578 61 5226 7 0211 19 3501 98 1663 52 1058 58 8416 The matrix standard functionality includes Add Sub Mul Transpose Mul Transposed Clone Negate Invert Eigenvalues SVD decompositions As for Vectors the Matrix objects support operators int dim 5 x Vector Random dim 50 0 50 0 A Matrix Random dim dim 50 0 50 0 B Matrix Random dim dim 50 0 50 0 y A B x Vector Show x x Matrix Show A A Matrix Show B B Vector Show y y 10 CHAPTER 1 INTRODUCTION with the following output to the MPCMath console x Vector 3 3038 47 6437 27 9289 6 2165 8 0053 A Matrix Form General 5 5 13 7145 22 0332 24 2230 29 2905 43 0788 45 0651 43 9516 46 3690 6 4084 3 0715 33 1575 5 9085 21 6215 43 2811 22 5939 44 6817 36 3091 38 1826 22 8073 11 0903 37 0345 5 7952 27 6559 32 9791 2 6289 B Matrix Form General 5 5 40 3434 23 3530 48 6669 3 6267 1 2521 43 3688 14 1737 41 6677 30 7539 14 8256 20 0622 34 2421 8 8289 16 4055 48 6315 30 4909 1 4764 24 4871 4 8784 46 8946 28 3770 43 4818 14 0516 18 4139 49 8697 y Vector 807 8519 5225 6046 1077 2666 3483 0406 3209 2488 MPCMath implements the following more advan
159. rix diplay static int FieldSize set get MaxTextLength Maximum textlength in console window static int MaxTextLength set get NumbersPerLine Numbers per Line static int NumbersPerLine set get TextLength length of text in console window static int TextLength get Trace Trace console output to file console txt in bin debug or bin release directory static bool Trace set get 2 4 MPCMATHCONSOLE Al Work Callback entry point defining work thread Entry Work set Methods Abort Abort execution of Work thread Usefull for debugging code generating unhan dled Exceptions which prevents reading the output on the MPCMath console The routine aborts the current work thread void Abort Abort Abort execution of Work thread Usefull for debugging code generating unhan dled Exceptions which prevents reading the output on the MPCMath console The routine aborts the current work thread void Abort string text Parameters text Text string outputted to console AssertEqual Assert equal for bool variable Show actual and expected if they are not equal void AssertEqual string text bool actual bool expected Parameters text variable desription actual actual value expected expected value AssertEqual Assert equal for integers Show actual and expected if they are not equal void AssertEqual string text int actual int expected Parameters text variable desription actual
160. rs vector alpha constant returns res vector operator Subtract scalar from vector res i alpha x i static Vector operator double alpha Vector x Parameters alpha constant vector returns res vector 62 CHAPTER 3 VECTORS AND MATRICES ProperZeroes Convert small values to proper xeroes void ProperZeroes Random Random vector static Vector Random int n double min double max Parameters n Dimension min Minimum value of random elements max Minimum value of random elements returns Vector with random values Random Random vector static Vector Random Vector XMin Vector XMax Parameters XMin Minimum values XMax Maximum values returns Vector with random values Set Set insert subvector void Set int pos Vector a Parameters pos Start position a Subvector Set Set subvector with increments void Set int pos int incr Vector a Parameters pos Start position incr Increment a Subvector 3 2 VECTOR 63 Show Show vector on console static void Show string txt Vector a Parameters txt Text string a Vector Show Show Vector void Show string txt Parameters txt Text string Sort Sort elements in vector descenting void Sort Sub Sub Vector y void Sub Vector x Parameters vector Sub Subtract constant from vector y i y i void Sub double a Parameters a constant Sum Get Sum of elements double
161. rst elements of each subvector static void Show string text BVector a int dim Parameters text text string a BVector object dim Number of elemenets to show from each subvector 4 3 BMatrix Class BMatrix Blok Matrix class Serializable class BMatrix Matrix lt Matrix gt Constructors BMatrix base Constructor default BMatrix int n base n Constructor square matrix as Null matrix Parameters n Dimension BMatrix MatrixForm Form int n base Form n Constructor square matrix Parameters Form Matrix form n Dimension BMatrix int n int m base n m Constructor n x m matrix as Null matrix Parameters n Rows m Columns 92 CHAPTER 4 BLOCK VECTORS AND MATRICES BMatrix MatrixForm Form int n int m base Form n m Constructor n x m matrix Parameters Form Matrix Form n Rows m Columns BMatrix int n Matrix val base n val Constructor Constant Diagonal Matrix Parameters n Dimension val Value BMatrix BVector a base a Dimension Constructor Diagonal matrix from BVector Parameters a Diagonal elements BMatrix params Matrix vals base vals Constructor Diagonal matrix Parameters vals Diagonal sub matrices BMatrix Structure Structure base Structure Dimension Constructor for square matrix as null matrix Parameters Structure Structure for rows and Columns BMatrix MatrixForm form Structure Structure base form Structure Dimension Co
162. s void S int row int col T val Parameters row col val 289 290 APPENDIX BASE CLASSES FOR VECTORS AND MATRICES Appendix D Implementation of test fun using JConFun Implementation of linear test function using System using System Collections Generic using System Linq using System Text using MPCMath namespace MPCMathApplication lt summary gt Non linear function with four minimas and two inequality constriants index IConFun lt summary gt public class TestConFun IConFun fun x0 xi 072 x1 11 2 0 x1 2 7 72 int IFun N get return 2 y y lt summary gt Value lt summary gt lt param name x gt lt param gt lt returns gt lt returns gt 291 292 APPENDIX D IMPLEMENTATION OF TEST FUN USING ICONFUN double IFun Value Vector x 1 double ra x 0 x 0 x 1 11 0 double rb x 0 x 1 x 1 7 0 double res rb rb return res lt summary gt Jacobian lt summary gt lt param name x gt lt param gt lt returns gt lt returns gt Vector IFun Dx Vector x double x 0 x 0 x 1 11 0 double rb x 0 x 1 x 1 7 0 Vector dx new Vector 2 dx 0 4 0 x 0 ra 2 0 rb dx 1 2 0 ra 4 0 x 1 rb return dx lt summary gt Hessian lt summary gt lt param name x gt l
163. s IMM DTU 2004 K Madsen Nielsen and O Tinglev MethiOp for Nn Linear Least Squares Problems IMM DTU 2004 Jorge Nocedal and Stephen J Wright Numerical Optimization Springer 2006 Prasath and John Bagterp J rgensen Soft constraints for robust mpc of uncertain systems In DYCOPS 2010 pag 288 293 Leuven Belgium 2010 G Prasath B Recke M Chidambaram and J B Jorgensen Application of soft constrained mpc to a cement mill circuit In 9th International Symposium on Dynamics and Control of Process Systems DYCOPS 2010 2010 269 270 BIBLIOGRAPHY Appendix A Installing MPCMath This appendix describes how to get MPC Math up and running on your machine If you get any problems or have any questions please don t hesitate to contact me A 1 Prerequisites MPCMath requires that visual Studio is installed on your computer A free version of Microsoft Visual C 2010 Express can be downloaded from Microsoft http www microsoft com express Downloads 2010 Visual CS Remember to register Microsoft Visual C 2010 Express otherwise it be comes inactive after 30 days A 2 Installing MPCMath Unzip the file 2 control 14 feb 2011 zip to c creating the folder c 2 control If the file you received has the extension sip rename it to zip Copy the license file MPCMath00007 lic to c 2 control License That s all now you should be ready to use MPCMath The c 2 control folder should look somethi
164. sitivity DX DX0 SU Sensitivity DX DX0 Next Integrate ODE for T time units Vector Next double T Vector Vector U Parameters T Integration time Initial state U Manipulated variables returns new State 230 CHAPTER 15 ODE SOLVERS Chapter 16 MPCMathLib 16 1 MPCMathLib MinNorm Class MPCMathLib Minimize sum norm y A x partial class MPCMathLib Methods MinNorm Minimize sum norm y A x static Vector MinNorm Norm norm double gamma Matrix A Vector y Parameters norm Norm gamma Huber norm coificient A Coifficient matrix y vector of observed values returns vector x Enumeration Norm 0 Zeroes g 1 Ones 0 0 A 0 1 I Cqp 1 0 Cqp 1 11 uo oM 1 m 231 232 CHAPTER 16 MPCMATHLIB 2 1 I 4101 y 4111 y errorlim 1 0e 9 break case Norm NormInfinity Ones new Vector 1 1 0 Zeroes new Vector cols I Matrix Random rows 1 1 0 1 0 strx Structure Values cols 1 stry new Structure 0 strz Structure Values rows rows 1 g new BVector strx new BMatrix MatrixForm General stry strx b new BVector stry new BMatrix MatrixForm General strz strx d new BVector strz new BMatrix strx g 0 Zeroes 8111 Ones Cqp 0 0 A Cqp 0 1 I Cqp 1 0 4 Cqp 1 1 I Cqp 2 1 new Matrix 1 1 0 4101 y 4111 y break
165. ss implements the discrete state space model 221 Aa Buk Key of f 7 1 y x 7 15 where x Process states at time k Dimension ng ur Process inputs at time k Dimension nu Innovation at time Dimension ny Yk Process outputs at time k Dimension ny The matrix and the innovation e implements a Kalman filter estimating the process state based on measurements of the plant outputs The innovation at sample k is defined by Ek Uk Cay 7 2 where the term Cz is the models estimate of the plant output based on 2 1 1 and 1 For State space models derived from transfer functions 6 1 or ARXModels 10 1 the Kalman gain K are calculated analytically SISO State space models with one process input nu 1 and one process output ny 1 can be constructed directly from a transfersfunction or an ARXModel MIMO State space models with more than one input or output are can be generated from generic matrices 5 of TransferFunctions or ARXModels If the state space model derived from transfer functions or ARXModels has more than one process input the distribution of the innovation between the individual process inputs uj j 0 nu 1 and process outputs yi i y 1 must be specified cl of fij 7 3a y CA ij 7 35 is calculated as a fraction wj of the total innovation given by 125 126 CHAPTER 7 STATE SPACE MODELS jj W
166. t param gt lt returns gt lt returns gt Matrix IFun DDx Vector x Matrix DDX null double ra x 0 x 0 x 1 11 0 double rb x 0 x 1 x 1 7 0 DDX new Matrix MatrixForm General 2 DDX O0 0 4 0 8 0 1 x 1 2 0 DDX O 1 4 0 x 0 111 DDX 1 0 DDX O 1 DDX 1 1 2 0 4 0 rb 8 0 x 1 x 1 return DDX lt summary gt Number of Equality Constraints lt summary gt int IConFun Ne get return 0 lt summary gt Equality coinstraint values lt summary gt lt param name x gt lt param gt lt returns gt lt returns gt Vector IConFun Vale Vector x Vector Cval new Vector 0 return Cval lt summary gt Equality constraint gradients lt summary gt lt param name x gt lt param gt lt returns gt lt returns gt Matrix IConFun Dxe Vector x Matrix Dx new Matrix 0 2 return Dx lt summary gt Equality constraint Hessians lt summary gt lt param name x gt lt param gt lt returns gt lt returns gt BMatrix IConFun DDxe Vector x BMatrix DDx null DDx new BMatrix new Structure 1 2 return DDx lt summary gt Number of Inequality Constraints lt summary gt int IConFun Ni get return 2 y y lt summary gt Constraint values 293 294APPENDIX D IMPLEME
167. tate variables lt param gt lt param name y gt Lagrange multipliers for equality conditions lt param gt lt param name z gt Lagrange multipliers for inequality conditions lt param gt lt param name s gt Slack variables lt param gt lt param name rL gt residuals lt param gt lt param name rA gt residuals lt param gt lt param name rC gt residuals lt param gt lt param name rSZ gt residuals lt param gt void IKKTSolver Residuals BVector x BVector y BVector z BVector s out BVector rL out BVector rA out BVector rC out BVector rSZ rL Ay Cz rL this mG x this vg y this mA z this mC b rA this vb this mA x rC da Cx s this vd this mC x s rSZ SZe rSZ BVector MulElements s z summary Factorize KKT system lt summary gt lt param name SInvZ gt diagonal vector lt param gt void IKKTSolver Factorize BVector SInvZ x this W new BMatrix SInvZ this mCTSinvZ BMatrix MulTransposed this mC W J C SInvZ C A A 0 BMatrix GM this mG this mCTSinvZ this mC int dim this strcx Dimension for int row 0 row lt dim row t 304 APPENDIX F KKTSOLVER CODE 1 for int col 0 col lt dim 1 1 this J row col GM row col y this solver new SymmetricalBlo
168. the exception is passed on the calling program 11 6 INFEASIBLE STATE EXCEPTIONS 171 lt summary gt Test whether input are feasible lt summary gt lt param name X gt lt param gt lt param name U gt lt param gt private void Feasible Vector X Vector U X ProperZeroes for int p 0 p lt X Dimension 1 if X p 0 0 1 throw new MPCMathException ULoop reactor Infeasible state 1 In the example above ULoop reactor can be replaced by your own iden tifying text 172 CHAPTER 11 FUNCTION AND MODEL INTERFACES Chapter 12 Unconstrained and constrained minimization Unconstrained minimization defined by min 6 fun z 12 1a and equality constrained minimization problems min 6 fun z 12 2a st Ax b 12 2b are solved using the Newton method Boyd and Vanderberghe 2004 The function to be minimized must implement the Fun interface 12 1 NewtonMethod Class NewtonMethod Newtons Method class NewtonMethod Constructors NewtonMethod IFun function Constructor for unconstrained solver Parameters function function definition NewtonMethod IFun function Matrix A Vector B 173 174CHAPTER 12 UNCONSTRAINED AND CONSTRAINED MINIMIZATION Constructor for equality constrained solver Parameters function function definition Properties Alfa Back tracking parameter 0 0 lt Alfa lt 0 5 double Alfa set get Beta Back trac
169. tor Static bool operator complex a complex b Parameters a input var b input var returns true if not equal Sqrt Complex Sqrt static complex Sqrt complex a Parameters a input var returns sqrt a 17 2 Polynomial Class Polynomial Polynomial class with p x c 0 x c 2 x c n Serializable class Polynomial Constructors Polynomial this 0 Constructor fro serialization Polynomial double Gain CVector Roots 17 2 POLYNOMIAL 249 Constuctor from a vector of roots Parameters dim Dimension Gain Gain Roots Roots Polynomial Vector Constructor from vector of coifficients Parameters Coef ficientsa0 al z 2 Polynomial params double vals Constructor from an array of coifficinets Parameters vals ficientsa0 al x a2 x Properties Coefficients Polynomial coifficients Vector Coefficients get Gain Gain double Gain get N Polynomial dimension int N get Roots Polynomial roots CVector Roots get 250 CHAPTER 17 MISCELLANEOUS FUNCTIONS Methods Add Add polynomials static Polynomial Add Polynomial a Polynomial b Parameters a Input a b Input b returns a b AssertEqual Assert equal show actual and expected if not equal static bool AssertEqual string text Polynomial actual Polynomial expected Parameters text text string actual actual value expected expected value
170. tor returns Subvector Max Get Maximum value double Max Parameters returns Maximum value of vector elements 58 CHAPTER 3 VECTORS AND MATRICES Mean Get Mean value double Mean Parameters returns Mean value of vector elements Min Get Minimm value double Min Parameters returns Minimum value of vector elements MulElements Multiply Vecor elements res i y i static Vector MulElements Vector y Vector x Parameters y y vector vector returns res vector Norm Euclidian norm of Vector double Norm Parameters returns Norm of vector elements Normalize Normalize vector Making Norm 1 0 void Normalize NormInf Infinity Norm of vector double NormInf 3 2 VECTOR NormRel Relative maximium element of vector Max ai 1 ai double NormRel operator Clone vector operatos res x static Vector operator Vector x Parameters Input vector returns Clone of x operator Add vector operator res y x static Vector operator Vector y Vector x Parameters y y vector X operator Negate vector res x static Vector operator Vector x Parameters vector operator Sub vector operator res y x static Vector operator Vector y Vector x Parameters y y vector vector returns 59 60 CHAPTER 3 VECTORS AND MATRICES operator Multiply operator res y x static doub
171. tor dx Parameters X operation point dx variations of x returns true if consistent Minimize Minimize Constrained function double Minimize Vector Parameters X0 Inital X returns minimum value Minimize double Minimize Vector XO Vector XMin Vector XMax Parameters Initial X guess XMin Min values for X null if no check wanted XMax values for X null if no check wanted returns minimum value 12 6 Least Square Fitting The class LeastSquareF it is useful for fitting the parameters of a given function to a set of experimental results An example is fun 2 e t 12 11 where is measurement noise The function fun must implement the J Funt interface as shown in the code example below lt summary gt test function for parameter fitting Least square fit lt summary gt public class Function IFunt 1 12 6 LEAST SQUARE FITTING 191 lt summary gt X dimension lt summary gt int IFunt N get return 4 y lt summary gt Function value lt summary gt lt param name x gt lt param gt lt param name t gt lt param gt lt returns gt lt returns gt double IFunt Value Vector x double t return x 2 Math Exp x 0 t x 3 Math Exp x 1 t lt summary gt Jacobian lt summary gt lt param name x gt lt param gt lt param name t gt
172. turns true if equal 4T 48 CHAPTER 2 CONSOLE FUNCTIONS NiceMax Nice Maximum value for plot example x 0 75464 NiceMax x 0 8 static double NiceMax double x Parameters x value NiceMin Nice Minimum value for plot static double NiceMin double x Parameters ScalePlot Scale Plot void ScalePlot Enumeration SeriesColor Series Colors enum SeriesColor Fields Black Blue Brown Cyan DarkBlue DarkGreen DarkRed Gray Green LightGray Magenta Orange Red Yellow 2 6 PLOT 49 2 6 Plot Class Plot Plot definition class Serializable class Plot Constructors Plot Constructor Plot params PlotSeries Series Constructor for default plot with PlotType TY Up to four series can be spec ified Parameters Series Plot PlotType Type Constructor for plot plot type series must be set using property Series Parameters Type Plot type Plot PlotType Type params PlotSeries Series Constructor for up to four series Parameters Type Plot type Series Plot Series Plot PlotType Type double XMin double XMax Constructor for a plot type series must be set separately Parameters Type Plot type XMin Min x axis value XMax Max x axis value Plot PlotType Type double XMin double XMax params PlotSeries Series Constructor a given plottype with up to four series Parameters Type Plot type XMin Min x axis value XMax Max x axis value Series Plot Series
173. uality conditions int Ne get Ni Number of Inequality conditions int Ni get 11 2 ICONFUN 165 Methods DDxe Hessians of Equality Constraints BMatrix DDxe Vector x Parameters state returns Hessian of constraints null if Hessian undefined or x infeasible DDxi Hessians of Inequality Constraints BMatrix DDxi Vector x Parameters x state returns Hessian of constraints null if Hessian undefined or x infeasible Dxe Gradients of Equality constraints Matrix Dxe Vector x Parameters state returns Gradients of constraints Dxi Gradients of Inequality constraints Matrix Dxi Vector x Parameters x state returns Gradients of constraints Vale Equality Constraint Values Vector Vale Vector x Parameters State returns Constraint values 166 CHAPTER 11 FUNCTION AND MODEL INTERFACES Vali Inequality Constraint Values Vali gt 0 Vector Vali Vector x Parameters State returns Constraint values 11 3 IFunt Interface IFunt Interface for function gt R interface IFunt IFeasible Properties N Number of variables in x int N get Methods DDx Hessian Matrix DDx Vector x double t Parameters t returns Hessian matrix null if Hessian undefined or x infeasible Dx Jacobian Vector Dx Vector x double t Parameters parameters t t returns Jacobian or null if infeasible 11 4 IMODEL Value Function value return infinit
174. ues A Input matrix returns Sparse matrix 98 CHAPTER 4 BLOCK VECTORS AND MATRICES Transpose Transpose static BMatrix Transpose BMatrix a Parameters a Input a returns a Chapter 5 Generic Vectors and Matrices The main part of the block vector 4 2 and block matrix 4 3 functionality is build using the generic Vector and generic matrices classes Generic vector and matrices are populated with objects that implements the interface Common and a default new T constructor In MPCMath this is the case for the Classes complex 22 Vector Matrix For the classes ArxModel 10 1 LinearF ilter 9 1 TransferFunction 6 1 there is a limited implementation of ICommon that does not support calculations The following code demonstrates generic vector and matrices for complex objects int dim 4 Vector lt complex gt x new Vector lt complex gt dim Matrix lt complex gt A new Matrix lt complex gt MatrixForm General dim dim fill in some crazy numbers for int row 0 row lt dim rowt 1 x row complex Sqrt row for int col 0 col lt dim 1 1 A row col new complex row col y y Vector lt complex gt Show x x Matrix lt complex gt Show A A Matrix calculation Vector lt complex gt Res A x 99 100 CHAPTER 5 GENERIC VECTORS AND MATRICES Vector lt complex gt Show Res Res The console output is Test Generic Matrix x MPCMath Vector 1 MP
175. unction used in linear control applications are implemented using the TransferFunction class The following code shows examples of definitions of transfer functions double gain 1 0 double delay 0 0 Impulse TransferFunction Impulse new TransferFunction delay Step function TransferFunction Step new TransferFunction gain delay Pole double tau 10 0 TransferFunction Pole new TransferFunction gain delay tau second order Oscillating tau 10 0 double sigma 0 1 TransferFunction OscillationgSecondOrder new TransferFunction gain delay tau sigma TransferFunction Show UscillationgSecond0rder OscillationgSecondOrder tranfer function from poles and zeroes int np 5 CVector roots new CVector np for int pos 0 pos lt roots pos int nr 4 CVector zeroes new CVector nr for int pos 0 pos lt nr postt zeroes pos pos gain 5 0 delay 2 0 TransferFunction G new TransferFunction gain delay roots zeroes 14 CHAPTER 1 INTRODUCTION TransferFunction Show G G with the output OscillationgSecondOrder TransferFunction R 0 0100 P 0 0100 0 0200 T Gain 0 0100 Roots Complex List 0 0100 i 0 0995 0 0100 i 0 0995 G TransferFunction Delay 2 0000 seconds R 30 0000 55 0000 30 0000 5 0000 24 0000 50 0000 35 0000 10 0000 1 Gain 5 0000 Zeroes Complex List 3 0000 i 0 2 00
176. xOp direct or transposed alpha constant beta constant Ger Rank1 update of Matrix a alpha x y a void Ger Vector x Vector y double alpha Parameters input vector y input vector y alpha constant Get Get Submatrix Matrix Get int row int n int col int m Parameters TOW Row position n Rows col Column position m Columns returns Submatrix GetColumn Get GetColumn Vector GetColumn int col Parameters col Column returns Column vector 69 70 CHAPTER 3 VECTORS AND MATRICES GetColumn Get GetColumn Vector GetColumn int col int indx int length Parameters col Column indx First row length Number of rows GetRow Get Row Vector GetRow int row Parameters row Row returns row vector GetRow Get Row Vector GetRow int row int indx int length Parameters row Row indx First Column position length Nomber of columns Invert Invert Matrix static Matrix Invert Matrix a Parameters a Mul outer product A x y static Matrix Mul Vector x Vector y Parameters input vector y input vector y returns outer product matrix 3 4 MATRIX MulAdd Multiply Add r r a b void MulAdd Matrix a Matrix b Parameters a Input matrix a b input matrix b MulTransposed Multiply tranpose res a b static Matrix MulTransposed Matrix a Matrix b Parameters a Input matrix a b Input matrix b returns a b Norm Frobenius Norm of matrix
177. y if x infeasible double Value Vector x double t Parameters parameters t t returns function value or infinity if infeasible 11 4 IModel Interface Model Process model interface interface IModel IFeasible Properties Dimension Number of states int Dimension get NU Number of manipulated vars int NU get NY Number of Observed vars int NY get Parameters Model parameters useful for iterative optimization programs Vector Parameters set get 167 168 CHAPTER 11 FUNCTION AND MODEL INTERFACES Sparse Sparse matrices supported bool Sparse get T Sample time for Next and LinearModel functions double T get Methods Derivative Derivative function dx dt Vector Derivative Vector X Vector U Parameters Present state U Manipulated variables returns Time derivative of state X or null Ju Jacobian with respect to Inputs Matrix Ju Vector X Vector U Parameters State vector U Manipulated vars returns Jacobian or Null Jx Jacobian with respect to outputs Matrix Jx Vector X Vector U Parameters State vector U Manipulated vars returns Jacobian or Null 11 4 IMODEL 169 Linear Model Linear State Space Model StateSpaceModel LinearModel Vector XS Vector US Parameters XS Stationary State XY returns StateSpaceModel Next Next step function Vector Next Vector X Vector 0 Vector Parameters of state X U
Download Pdf Manuals
Related Search
Related Contents
System for viewing multiple data streams simultaneously Samsung F480I Instrukcja obsługi Whirlpool GCGM2991LQ0 User's Manual User Manual Copyright © All rights reserved.
Failed to retrieve file