A C/C++ Program and Source Code for Computing Ybus and Zbus Matrices
Below is a C/C++ program and source code that computes the Ybus and Zbus of a given electrical network of any size. The input system is written on “rx.txt” with the following column format; ‘From bus’,'To bus’,'r’, and, ‘x’. The ‘From bus’ and ‘To bus’ must be a consecutive positive integer starting from zero. Bus zero is assume to be the slack or swing bus. A complex header file was used to assist the matrix operations. Zbus was computed by simply inverting the Ybus.


//-----------------------------
#pragma hdrstop
//-----------------------------
#pragma argsused
#include < stdio.h >
#include < conio.h >
#include "matrix.h"
#include < complex.h >
using std::complex;
using namespace math;
typedef complex Complex;
typedef matrix Matrix;
void main(void)
{
//declare variables
int cnt,i,j,matsize=1;
double tmp3,tmp4;
Complex tmp6;
Matrix Y,Ybus,Zbus;
FILE*in;
Y.SetSize(matsize,matsize); //set a temporary matrix size
//get the branch data
in=fopen("rx.txt","r"); //open file
if(in==NULL)
{printf("nrx.txt not found");
getch();
}
cnt=j=i=0;
for(;;)
{if(fscanf(in,"%d",&i)==EOF)
{break;}
if(i>matsize)
{matsize=i;}
fscanf(in,"%d",&j);
if(j>matsize)
{matsize=j;}
Y.SetSize(matsize+1,matsize+1);
fscanf(in,"%lf",&tmp3);
fscanf(in,"%lf",&tmp4);
tmp6=Complex(tmp3,tmp4);
Y(i,j)=1.0/tmp6;
cnt++;
}
fclose(in);
//end of getting branch data
//Create Ybus
Ybus.SetSize(matsize+1,matsize+1);
//Diagonal entries
for(i=0;i<=matsize;i++)
{for(j=0;j<=matsize;j++)
{Ybus(i,i)=Ybus(i,i)+Y(i,j);}
}
for(j=0;j<=matsize;j++)
{for(i=0;i<=matsize;i++)
{Ybus(j,j)=Ybus(j,j)+Y(i,j);}
}
//end
//off diagonal entries
cnt=0;
for(j=cnt;j<=matsize;j++)
{for(i=0;i<=matsize;i++)
{if(j!=i)
{Ybus(i,j)=Ybus(j,i)=-1.0*Y(i,j);}
}
cnt++;
}
// end
//end of creating Y bus
//bus 0 is not included in the Ybus Matrix
//because it is the reference bus
for(j=1;j<=matsize;j++)
{for(i=1;i<=matsize;i++)
{Ybus(i-1,j-1)=Ybus(i,j);
}
}
Ybus.SetSize(matsize,matsize);
Zbus.SetSize(matsize,matsize);
printf("nnYbus Matrixn");
cout << Ybus << endl;
Zbus=!Ybus; //get the inverse of the Ybus
printf("nnZbus Matrixn");
cout << Zbus << endl;
getch();
}