Welcome to the world of Optimizations

In this blog concepts of conventional and unconventional optimization techniques are discussed.

Friday, March 28, 2025

Running MATLAB from Windows command Line

Motivation

MATLAB is an excellent tool for scientific computing.

It can  be used either as  installed desktop or MATLAB online versions.

 MATLAB is offered as a coursework in most of the universities. It can be Introduction to MATLAB programming or simulation tool for signal/image processing ,operations research or differential equations to name a few courses.

The visually impaired students use screen readers (like JAWS, and NVDA) to operate the computer. 

The MATLAB  online is fully accessible, but some recent versions of MATLAB desktop are inaccessible to screen readers.

Doing coursework assignments on online version may not be a good idea, so making the desktop version accessible  is a necessity. 

the cost effective method is  operating MATLAB via the windows command line option. 

So in this blog post, running MATLAB through windows command line(CMD) is explained.

 This will help the screen reader users confidently take the course works  with MATLAB.

 The visually impaired are encouraged to ask their doubts regarding MATLAB.

THE readers of this blog especially Screen reader users are encouraged to discuss the problems they try to solve with MATLAB. i tested all the codes presented in this blog, with NVDA, JAWS and Narrator. 

you can have a look at my MATLAB central file exchange page. 


https://www.mathworks.com/matlabcentral/profile/authors/1281371


i usually publish my code after I tested it


So If you have a problem to solve, present a similar problem to me through the comments section.   

I will try in such a way that the concept can be learned with MATLAB. thanks for reading. All the best !!!.


1. Introduction


MATLAB renowned for its numerical computation and visualization capabilities, can seamlessly interact with the Microsoft Windows command line (CMD).

 This integration allows you to leverage the power of both environments, executing system-level commands from within MATLAB scripts and automating tasks by combining MATLAB functionality with CMD scripts (known as batch files with extention .bat).

 This synergy enhances workflow efficiency and expands MATLAB's application beyond its inherent capabilities.

whenever you come across  uppercase `MATLAB` word  means that  it denotes the MATLAB application .

The lower case `matlab` is the command used to run MATLAB application  on windows. So always use left and right arrow keys in your screen reader  to confirm the case or symbol.

(the graph ` symbol is used in this blog post to indicate commands and path notations, so ignore the graph symbol and use the command inside.). 

In this blog post we are going to run a `matlab` script named main.m. 

the program and command window outputs are written as text or csv files.

MATLAB program code: main.m

```

%this code writes a data contained in a cell array and saving graph in .png and .jpeg formats.

%it is better to format the output results as a cell array which can contain many data formats.

clear;

clc;

data={'salo',44,'m',1000;'lyla',8,'f',0};

%writing the results to a csv file

        fileID = fopen('r1.csv', 'w');

    if fileID == -1

error('Could not open file for writing.');

    end


    % Write header row

fprintf(fileID, 'number,name,age,sex,income\n');  % Comma separated


    % Write data rows

    for i = 1:2

        fprintf(fileID, '%d,%s,%d,%s,%d\n', i, cell2mat(data(i,1)),cell2mat(data(i,2)),cell2mat(data(i,3)), cell2mat(data(i,4)));  

        end


    fclose(fileID);

    disp('Data written to r1.csv');

%plotting a sine wave and saving it

figure(1)

x=0:.1:2*pi;

y=sin(x);

title('sine wave')

xlabel('x axis');

ylabel('y axis');

plot(x,y)

grid on; % Adds a grid to the plot (optional)


% --- Save the plot as a PNG file ---

filename_png = 'sine_wave.png';  % Name of the PNG file

saveas(gcf, filename_png);       % gcf = Get Current Figure


% --- Save the plot as a JPEG (or JPG) file ---

filename_jpeg = 'sine_wave.jpeg'; % Name of the JPEG file

saveas(gcf, filename_jpeg);       % Or you can use 'sine_wave.jpg'

disp('figures  written as png and jpeg formats. ');


```

2. Methods of using MATLAB with windows CMD

2.1. running MATLAB in batch mode:

Running MATLAB  in batch mode means ,the program runs only in the backround. suitable for non interactive scripts. Of course interaction is possible if the script is written as a function file.

the syntax is 

`matlab -batch main -logfile log.txt`

explanation:

the first lowercase `matlab` means matlab command.

`-batch` means the program runs only in the backround, not visible. The command window/error messages written to logfile named log.txt.

main the script file is written without extention.

`-logfile log.txt` means the program outputs written as a log.txt. you can change the log.txt to any name you prefer.


2.2.Using `matlab -r` 

 the Most Reliable method is the matlab followed by `-r`  ) ) followed by a string containing the script name and exit command.

    This is the most straightforward and generally preferred method.


   ```batch

```

matlab -r \"run('main.m'); exit;\" -logfile log.txt

```


use your screen reader left and right arrow  keys to familiarize with the above command. 

the commands have following parts

`matlab` the matlab command

`-r` indicator to run the script. 

\"run('main.m');exit;\'

You can replace main.m with your script name.

   if your script name is main1.m, then the command you should use on windows cmd is...


`matlab -r \"run('main1.m'); exit;\" -logfile log.txt`


-logfile log.txt : the output of command window with errror messages(if any) are written to log.txt. you can change log.txt to any name. 

Explanation

matlab : This invokes the MATLAB executable.


-r:  This  (minus sign followed by r) is the \"run\" option.  It tells MATLAB to execute the string that follows as a MATLAB command.


\"run('main.m'); exit;\" :  This is the MATLAB command string.

`run('main.m')`:  Executes the MATLAB script named `main.m` in your default folder.

Make sure to replace `main.m` with the actual filename.

 If the script is not in the current directory, you have to  specify the full path of the file.


Example

If the path of the file main.m is 

`c:\\folder1\\folder2\\main.m`

them the run command should be

 `run('c:\\folder1\\folder2\\main.m')`


exit; :  This is crucial! It tells MATLAB to close after the script finishes executing. Without `exit`, MATLAB will remain open in the command window, waiting for further commands, and you won't see the command prompt return.

If the script needs some input then the MATLAB command window will not exit. You  have to type the input at the open MATLAB command window and press enter key.

 


3. Example (assuming main.m is in your current directory):


       ```batch

       matlab -r \"run('main.m');exit;\"


 (if `main.m` is in `C:\\folder1\\folder2`


       ```batch

`matlab -r \"run('C:\\folder1\\folder2\\main.m'); exit;\" -logfile log.txt`


``


Advantages:


Reliable and consistent output.

Handles most MATLAB scripts correctly.

This can handle interactive scripts also. But visually impaired people needs more attention because the MATLAB command window will not be read by the screen reader..

The `exit;` command ensures MATLAB closes cleanly.


Disadvantages:

   The command string can become long if your script path is lengthy,

 or if you want to pass arguments to your script (see below).



   If your MATLAB script needs input arguments, you can pass them within the `-r` option.


   ```batch

   matlab -r \"main(arg1, arg2); exit;\"

Example:


       Suppose `main.m` is defined as:


       ```matlab

function result=main(a, b)

result = a + b;

           disp(['The sum of ' num2str(a) ' and ' num2str(b) ' is ' num2str(result)]);

       end


Then, you can execute it from the command line like this:


       ```batch

matlab -r \"my_script(5, 3); exit;\"

or using batch mode

 matlab -batch main(3,4)

This will output:

The sum of 5 and 3 is 8

       ```


3. Using a batch script to simplify complex commands


Create a batch file (.bat) to avoid typing long commands repeatedly.

windows batch file auto.bat


```

@echo off

matlab -r \"run('main.m'); exit;\" -logfile log.txt

```


Save this as, say, `auto.bat` in the same folder of main.m, then just type `

If you type auto.bat in the CMD  the main.m script will be executed. 

4.  Using a Callback Function for Output (More Advanced, for Specific Cases)


   If your MATLAB script generates output using functions like `fprintf` or `disp`, the above methods should work fine.  However, if you have more complex output requirements or are using graphics, you might need to consider more advanced techniques.


      Redirecting Output in MATLAB Script: You can use `diary` command within your script.


     ```matlab

diary output.txt  % Start recording output to output.txt

     % Your MATLAB code here

diary off         % Stop recording

     ```


     Then, in the command window:


     ```batch

     matlab -r \"run('your_script_name.m'); exit;\"

diary command is an alternat method to -logfile method. diary is within the script whereas -logfile used in the CMD.      


5. Error Handling:

  If your MATLAB script encounters an error, the command window might not show the complete error message. To get more detailed error information, consider these options:

       Use `try...catch` blocks in your MATLAB script to handle potential errors and display more informative messages.

       Redirect the standard error stream to a file:


        ```batch

        matlab -r \"run('main.m'); exit;\" > error.txt

        ```

this is another alternate method todiary and logfile methods.


        This will save any error messages to the `error.txt` file.

Displaying Figures:

 If your MATLAB script creates figures, they will notbe displayed in the command window. They will appear in separate figure windows.  If you need to save the figures, you can use the `saveas` command in your MATLAB script:


the main.m already having the code to save figures.

    ```matlab

    figure(1);

    plot(1:10);

    saveas(gcf, 'my_plot.png', 'png');  % Save as PNG

    ```


Conclusion.

The batch mode is good for simple non interactive scripts. It is faster. 

The `-r` option is generally the most reliable and recommended method for running MATLAB scripts from the command window and displaying the output.  Remember to include `exit;` to ensure MATLAB closes properly. 

Pay close attention to file paths and potential errors.        ],


Discussions are welcome!!!. I published the powerflow solution by Halomorphic embedding (including PV) in my file exchange. Next post I will explain that.        ),

As my sight becomes poor, I am using MATLAB  with screen reader.

I published powerflow solution by Halomorphic embedding (including PV) IN THE FILE EXCHANGE. Next post I will discuss that code.

I explained how I used MATLAB to develop the script.

I will explain the script in my next post.                                            


https://www.    hmathworks.com/matlabcentral/fileexchange/180504-power-flow-solution-by-halomorphic-embedding-including-pv?s_tid=prof_contriblnk 


I am trying my best to make MATLAB  easier for the screen reader users like me. 

Thank you. 

RMS Danaraj                     

Monday, April 1, 2019

Power Flow Solution by Holomorphic Embedding Method Part 1

In this article  the Holomorphic embedding based  power flow is explained .
Power flow problem is one of the oldest and important power system problems.It is the steady state solution of the power network. In a N bus  power system, There are 4N variables.


1.Pi-Real  Power bus number 'i'
2.Qi-Reactive   Bus  Power bus number 'i'
Si=Pi+i.Qi
The 2*N equations are formed by Kirchoffs currect law.
Though these equations are well known ,it can be observes that ,the equations are little bit manipulated. The 'i'th bus voltage Vi is moved to right hand side.This is the first step in Holomorphic embedding.
Why it is moved?
In algebra RHS(right hand side) is known values and the LHS is  unknown variables. So the Vi moved to RHS must be known. By the Halomorphic embedding it will be made known.That is the logic behind this method.The power flow problem is modified as recursive linear equations by making LHS as linear system.

The Vi is expressed as power series  polynomial in 's'.
Vi(s)=Vi[0]+s.Vi[1]+....(s^n).Vi[n]; 
Theoreticaly 'n' can be infinity.But we can choose n according to the accuracy of the solution. For the IEEE 118 bus system just 10th order polynomial is sufficient.
The coefficients are to be determined.  

The Holomorphicaly embedded equations are given below.


What is this 's' ?

s is a real variable .To solve power flow s is treated as variable. The objective is to determine the polynomial coefficients ,by recursive linear relationship evolving from the equations [H1 to H4]..  polynomial.After  determining the polynomial coefficients , Vi(s=1) will give the bus voltages for given base loading..  Vi(s=2) will give the power flow solutions 200% loading .
(To be continued)



Sunday, January 11, 2015

An Introduction to Non-Traditional Optimization Algorithms: Part 1

I have decided to make some lecture videos on non traditional optimization. I have just made an introductiory lecture on conventional optimization algorithms.
The drawbacks of  conventional algorithms gives the motivation for non traditional algorithms like Genetic algorithms and its variants.
Part 1



Part 2


I will add more videos on this topic.
Thanks for reading.

Saturday, February 5, 2011

Optimal capacitor placement Part 1.

Optimal capacitor placement problem is one of the important power system optimization problems.In A.C circuits the reactive flow in the system causes three effects..

(i) Bus Voltage drops.
(ii) Transmission loss increase 
(iii) Low Power factor.

Though the D.C System has so many advantages the A.C system is simply preferred because it is its easily transmittable.'The electrical power is generated ,transmitted ,distributed ans utilized in A.C only.The A.C system has the reactive elements which consume the reactive power. 

D.C system is perfect because it does nor have reactive element..If A.C system  is made as having less reactive elements its performance will be like D.C system..From the circuit theory it is known that the induction and capacitive reactive element have opposite characteristics .

The above video will refresh your understanding about capaciotrs and Inductors.
In the next part we will see formulation of optimal capacior problem.

Tuesday, January 11, 2011

Sunday, January 2, 2011

Transmission loss allocation-Part 1

Introduction

In the deregulated power market one of the most important issues is the allocation of transmission losses among market participants since system losses can typically represent significant portion of the total generation. The main difficulty of loss allocation is caused by the highly nonlinear and non-separable properties of the loss function.

A number of allocation schemes have been proposed in the literature [1-12].  Some approaches are based on DC power flow, while some use AC load flow for matching the calculation results and actual power flows. Some schemes are branch-power-flow based, while some focus on the branch-current based allocation techniques

I
The allocation is done in two ways.
(i) User Based
(ii) Transaction based

A:User Based Transmission allocation


The user based transmission allocation also done in three ways.

(i) Allocation only among producers(Generators)

(ii) Allocation only among Consumers (Loads)

(iii) Allocation only among producers and consumers(Generators and loads)

There are so many methods are available in the literature.I will just explain the method incorporating current injection model.

To solve the  Transmission Allocation Problem the power flow solution of that operating point should be available. Consider a power system or with Ng generator buses,Nl Load buses and 'M' transmission lines  the transmission allocation problem is defined as follows.


.

Solution methodology


1. As per the equation A3 the  transmission loss for different coalitions are calculated for each transmission line.

2. The total transmission loss of that line is the grand  coalition values.

3. After getting all the coalition values the solution (core) is determined by  cooperative game theory.

4.The contribution of a particular generator for every transmission line is summed up to calculate in allocation of the transmission loss.

For allocation to Loads the same procedure is just reversed. For allocation of both generators and loads
Vnn=Zbus*diag(Ibus) and the reamining procedures are same.


   

Thursday, December 9, 2010

SCILAB: An Introduction

Like MALAB there are some more software packages which are also user friendly with so many toolboxes. I am naming some of th software like SCILAB, Python, Mathematica, Octave, and  R. These software are free and almost having C/MATLAB syntax. It is easier to change the syntax between these programming languages.

In this page I am giving a general introduction about scilab

What is Scilab?

Developed at INRIA, Scilab has been developed for system control and signal processing applications. It is freely distributed in source code format (see the copyright file).
A key feature of the Scilab syntax is its ability to handle matrices:
Polynomials, polynomials matrices and transfer matrices are also defined and the syntax used for manipulating these matrices is identical to that used for manipulating constant vectors and matrices.
Scilab provides a variety of powerful primitives for the analysis of non-linear systems. Integration of explicit and implicit dynamic systems can be accomplished numerically.
The scicos(similar to simulink) toolbox allows the graphic definition and simulation of complex interconnected hybrid systems.
There exist numerical optimization facilities for non linear optimization (including non differentiable optimization), quadratic optimization and linear optimization.
Scilab has an open programming environment where the creation of functions and libraries of functions is completely in the hands of the user.
Finally, Scilab is easily interfaced with Fortran or C subprograms. This allows use of standardized packages and libraries in the interpreted environment of Scilab.
The scilab can be downloaded form the following link.



The site gives detailed documentation also.

I will post some programs in scilab  to solve some optimization problems soon.

Download scilab and install it. All the best

Wednesday, December 8, 2010

Binary integer programming.

Integer programming is one of the important branch of optimization where some of the variables are bound to be integers.
The integer linear programming is described as follows.
min f'*X
Subject to:  A*X <= b,
Aeq*X = beq,
Where the elements of X are integers.
There are two types of integer programming problems.
1. Binary integer programming.
2. Mixed integer Programming
The mixed integer programming can be modeled as binary integer programming by making some simplifications.
Solving a binary integer programming problem.
To solve binary integer programming problem in Matlab the routine “bintprog” is used
  [X FVAL] = bintprog(f,A,b,Aeq,beq,X0) sets the starting point to X0. The   starting point X0 must be binary integer and feasible, or it will   be ignored.
 
   This routine returns the value of the objective function at
    FVAL = f'*X.
Example
Minimize -9x1-5x2-6x3-4x4
Subject to
6x1+3x2+5x3+2x4<9
      x3+x4  <1
    -x1+x3   <   0
     -x2 +  x4<  0

    
Program
Clear;
clc;
f = [-9; -5; -6; -4];
      A = [6 3 5 2; 0 0 1 1; -1 0 1 0; 0 -1 0 1];
      b = [9; 1; 0; 0];
      [X F] = bintprog(f,A,b)
      l=[0 0 0 0]';
      u=[1 1 1 1]';
[X1 F1]=linprog(f,A,b,[],[],l,u)
Results
Binary integer programming
X =

     1
     1
     0
     0
F =  -14
Linear programming
X1 =
    0.6667
    1.0000
    0.0000
    1.0000
F1 = -15.0000
It can be observed that function value in integer programming is little more.
Rounding off the linear programming results does not yield the integer programming results.

Wednesday, November 24, 2010

Solving Optimization Problems Using PSO algorithm.

Introduction
As we have discussed the difference between the conventional optimization algorithms and the unconventional algorithms are summarized below.
1.The conventional algorithms start from a single  initial feasible  solution where as the unconventional algorithms start with a set of initial(feasibility not a prerequisite)  solutions. 
2.The conventional algorithms need the function to be continuously differentiable through out the range of search.
3.The accuracy of the conventional algorithms depending on the selection of initial solution.Always a local solution is assured. The performance of the unconventional algorithms will  vary for every run. A solution is assured.It may be local or global.Very rarely diverges.

Particle Swarm Optimization(PSO)
This  PSO algorithm also one of the important unconventional optimization algorithms.PSO optimizes a problem by having a population of candidate solutions, here dubbed particles, and moving these particles around in the search-space according to simple mathematical formulae. The movements of the particles are guided by the best found positions in the search-space which are updated as better positions are found by the particles.
PSO is originally attributed to KennedyEberhart and Shi  and was first intended for simulating social behaviour. The algorithm was simplified and it was observed to be performing optimization. The book by Kennedy and Eberhart  describes many philosophical aspects of PSO and swarm intelligence.
As I am more interested in the implementation of this algorithm interested readers can get more details in the web regrading this algorithm.To implement PSO you neeed not know anything about the algorithm,you should know how to use the code to solve your modelled problem.
PSO Code in MATLAB
There are so many variants of this PSO the code  which  I found simple and powerful is the vectorised PSO  Toolbox by Mr Brian Birge.I thank him for the excellent toolbox.It can be downloaded from the link.
Just download it and unzip it as a folder.You can either add it to MATLAB path or make it as  the default folder.
Solving an Optimization problem by PSO
For implementing  most of  the unconventional algorithms(including the PSO)   follow the steps.

1. Model the problem as unconstrained minimization problem( you can refer my earlier post on MATLAB GA toolbox ).

2. Write it as a function file.There are two types of functiones (i) scalar function(ii)vector function

In the scalar function for for every value of X the corresponding function value is returned.

X1-----------F(X1)

In the vector function for for every set of X values the corresponding function values are returned.

[X1 X2 X3 X4...Xn]-------------[F(X1),F(X2),F(X3),F(X4)...F(Xn)]

The code by Mr Brian Birge requires a vector function file .

3.After writing the function file save it in the same PSO folder and change it as default.
The toolbox has lot of details regarding the setting..
4.Run it .You get the solution as well the progressive graphs( iteration vs best solution and movement of particles in two dimension) .

Implementation

The same problem discussed in GA tool box is considered. Same way two files have to be written the first one is  the pso setting file(test1.m) .This calls the subroutine vector function file ex2.m.

program 1 test1.m
clear;
clc
% lower limir
l=[0 0];
% upper limit
u=[ 10 10];
ran=[l' u'];
% number of variables
n=2;
% settings for pso
%1. population,2. no of iterations,3 refresh on screen 4&5 type of PSO 06&7
%are final and initial swarm velocity 8. final iteration to reach final
%velocity 9. expected function value
Pdef = [20 200 10 2 2 0.9 0.4 200 50 5000 NaN 0 0];
[OUT]=pso_Trelea_vectorized('ex2',n,1,ran,0,Pdef);
out=abs(OUT)
P=out(1:n)

[F x]=ex2(P')



Program 2 vector function file ex2.m

function [F x]=ex2(x);
F=sum((x.*x).').'+1000*((sum(x')-10))^2;

Results

PSO: 1/200 iterations, GBest =                  100.
PSO: 20/200 iterations, GBest =   52.210493585432118.
PSO: 40/200 iterations, GBest =   50.166913798388642.
PSO: 60/200 iterations, GBest =   49.997052264769565.
PSO: 80/200 iterations, GBest =   49.978589042793075.
PSO: 100/200 iterations, GBest =   49.978455656591841.
PSO: 120/200 iterations, GBest =   49.975851601760063.
PSO: 140/200 iterations, GBest =   49.975342456412399.
PSO: 160/200 iterations, GBest =   49.975036994685418.
PSO: 180/200 iterations, GBest =    49.97501323855063.
PSO: 200/200 iterations, GBest =   49.975012959884864.

out =

   4.99798359369474
   4.99701881234046
  49.97501295916326


P =

   4.99798359369474
   4.99701881234046


F =

  49.97501295916326


x =

   4.99798359369474   4.99701881234046

You are welcome to make some suggestions .All the best.


Saturday, November 20, 2010

Power System State Estimation: Part 3


If G1 is having a rank of ‘n’ then the system is fully observable.
Algorithm

1. Start iterations, set the iteration index i=0.
2. Initialize the state vector x0, typically as a flat start.
3. Calculate the matrix G(x0) as per (4)
4. Calculate the matrix H as per (5)
5. Determine x1 as per (6).
6. Test for convergence, max [G(x1)]< e
7. If no, update x , and go to step 3. If yes stop.
For power system state estimation the matrix H is the jacobian matrix of the Power flow the difference is that the jacobian is not square it is mX n


Power System State Estimation: Part 2

Least Squares Estimation & Weighted Least Squares Estimation

If the number of equations(linear or non linear ) is more than the no of variables to be determined least squares estimation is used to find a compromising solution.First let us discuss the linear least square problem ,then we turn our attention to the non linear and weighted least square problems.

The linear least square problem is determined as follows.

Determine X
 which satisfy the set of equations

A*X=b
                                                                                                                                         (1)
where A is a m X n matrix where m is the number of linear equations.

X =[x1 x2 ...xn] the solution vector of nX1 ,where m>n

so A is not a square matrix it's rank may be equal or less than 'n'.  

To solve this system of equations the concept of least squares is used.

The variable J is the summation of least squares. The solution vector which minimize the  ‘’J is called least squares solution.

J=(A*X-b)T*(A*X-b)                                                                                                                        (2)

By applying khun tucker conditions the condition for optimality can be derived as .

AT*A*X=AT*b                                                                                                                                  (3)

 If the term AT*A is having rank of ‘n’ the solution is easily determined  bys solving (3).If it is less than ‘n’ Orthogonal-triangular decomposition. is used to solve the system of equations.





% Example 1. Start with
%program to solve linear least squares pproblem
clear;
clc;
A =  [ 1     2     3
       4     5     6
       7     8     9
      10    11    12 ]
% This is a rank-deficient matrix; the middle column is the average of the other two columns. The rank deficiency is revealed by the factorization: [Q,R] = qr(A)




b = [1;3;5;7]
[Q,R] = qr(A)
  x = R\(R'\(A'*b))
        r = b - A*x
        e = R\(R'\(A'*r))
        x = x + e;


Solution

A =


     1     2     3
     4     5     6
     7     8     9
    10    11    12




b =


     1
     3
     5
     7




Q =


   -0.0776   -0.8331    0.5456   -0.0478
   -0.3105   -0.4512   -0.6919    0.4704
   -0.5433   -0.0694   -0.2531   -0.7975
   -0.7762    0.3124    0.3994    0.3748




R =


  -12.8841  -14.5916  -16.2992
         0   -1.0413   -2.0826
         0         0   -0.0000
         0         0         0


Warning: Rank deficient, rank = 2,  tol =   2.2550e-014.


x =


    0.5000
         0
    0.1667




r =


  1.0e-013 *


    0.3575
    0.1732
   -0.0089
   -0.1954


Warning: Rank deficient, rank = 2,  tol =   2.2550e-014.
e =


  1.0e-013 *


   -0.2709
         0
    0.2095

Thursday, November 18, 2010

Power System State Estimation: Part 1


Introduction

Power system state estimation is defined as the act of estimating the state of the network from the redundant telemetry measurements. Static state estimation refers to the procedure of obtaining the voltage phasors at all of the system buses at a given point in time. This can be achieved by direct means which involve very accurate synchronized phasor measurements of all bus voltages in the system. However, such an approach would be very vulnerable to measurement errors or telemetery failures. 

Instead,state estimation procedure makes use of a set of redundant measurements in order to filter out such errors and find an optimal estimate.The measurements may include not only the conventional power and voltage measurements, but also those others such as the current magnitude or synchronized voltage phasor measurements as well. Simultaneous measurement of quantities at different parts of the system is practically impossible, hence a certain amount of time skew between measurements is commonly tolerated. This tolerance is justified due to the slowly varying operating conditions of the power systems under normal operating conditions..

Data for State Estimation

1. Network data
2. Measured Data
(i) Real Power (P)
(ii) Reactive Power (Q)
(iii) Real Line Flow (Pij)
(iv) Reactive Line Flow (Qij)
(v)Magnitude of Line current( [Iij] )
(vi) Voltage magnitude ([V])










Saturday, November 13, 2010

Solving Linear and Quadratic Programming Problems by MATLAB

Introduction
Optimization is defined as Minimizing (or Maximizing) an objective function subject to some constraints .If the objective function and the all the constrains are linear it is called linear programming. If the objective function is quadratic and the all the constraints are linear, it is known as quadratic programming. Let us learn how to use the linear and quadratic programming routines of the MATLAB.
Linear programming
The command for implementing the matlab linear programming routine is ‘linprog’.
Let us consider a linear programming problem with ‘n’ variables, ‘m’ inequality constraints, ‘k’ equality constraints, and the lower ,upper bounds LB and UB.
The linear programming is defined in matlab like this
min f'*x    subject to:   A*x <= b, Aeq*x = beq ,LB≤ x ≤ UB
x-=[x1 x2 x3 ….xn]T x is a column matrix of 1 X n) to be determined.  
f=[c1 c2 c3 ….cn]  f is a vector(row matrix of n X 1)
A is the matrix of inequalities having a size of m X n
Aeq is the matrix of equalities having a size of k X n
LB-=[l1 l2 l3 ….ln]T x is a column matrix of 1 X n)
UB= [u1 u2, u3 ….un]T x is a column matrix of 1 X n)
Example
f=[10 5 12 13 20];
A= [10     6     1     0     8
     2     8     4     7     0
     6     9     8     4     7
     5     7     0     9     4
     9     2     1     5     8
     8     4     2     4     5
     5     9     2     8     7
     0     9     6     5     4
     8     4     3     2     3
     4     9     2     7     2];
b=[70    63   104    80    81    68   101    81    53    71]';
Aeq=[1 1 1 1 1]
beq=15;
LB=[0 0 0 0 0]'
UB=[20 20 20 20 20]'
X=linprog(f,A,b,Aeq,beq,LB,UB)
Solution
Optimization terminated.
X =
    2.1683
    0.0000
    9.6931
    2.8416
    0.2970
Quadratic programming
The command for implementing the matlab quadratic programming routine is ‘quadprog’.Let us consider a quadratic programming problem with ‘n’ variables, ‘m’ inequality constraints, ‘k’ equality constraints, and the lower, upper bounds LB and UB.
The quadratic programming is defined in matlab like this
   min 0.5*x'*H*x + f'*x    subject to:   A*x <= b, Aeq*x = beq ,LB≤ x ≤ UB
x-=[x1 x2 x3 ….xn]T x is a column matrix of 1 X n) to be determined.  
H= is a square matrix of n X n
f=[c1 c2 c3 ….cn]  f is a vector(row matrix of n X 1)
A is the matrix of inequalities having a size of m X n
Aeq is the matrix of equalities having a size of k X n
LB-=[l1 l2 l3 ….ln]T x is a column matrix of 1 X n)
UB= [u1 u2, u3 ….un]T x is a column matrix of 1 X n)
Example
Minimize x1^2+x1x2+x22+3x1+5x2
Subject to the constraints
x1+x2=20;
2x1+3x2≤100
[0 0]T≤x1,x2≤[50 50]T
H=[2 1;1 2];
f=[3 5];
A= [2 3];
b=[100];
Aeq=[1 1]
beq=20;
LB=[0 0 0 0 0]';
UB=[50 50]';
[X ff]=quadprog(H,f,A,b,Aeq,beq,LB,UB)
Solution
X =
   11.0000
    9.0000
ff is the objective function value
ff =  379.0000