Wednesday, May 27, 2009

Reflector on the job

 

You have a list full of custom class items and want to find according to one property.Ok the best way is lambda functions(Or Not?).Other than lambda functions you can use reflection and use some code like:

 

public NeuronList FindByProperty(string PropertyName, object Value)
 {
     try
     {
         NeuronList foundItems = new NeuronList();
 
         foreach (NeuronBase item in List)
         {
             System.Type itemType = item.GetType();
             PropertyInfo[] itemProperties = itemType.GetProperties();
 
             foreach (PropertyInfo info in itemProperties)
             {
                 if (info.Name == PropertyName)
                 {
                     object itemValue = info.GetValue(item, null);
                     if (Convert.ChangeType(itemValue, info.PropertyType).Equals(Value))
                     {
                         foundItems.Add(item);
                     }
                 }
             }
         }
 
         return foundItems;
     }
     catch (Exception ex)
     {
         throw new Exception("Can not find property", ex);
     }
 }

Neural Networks

Have written a basic ann app which can do anything known about neural networks and has a simple ui, of course it needs lots of improvements but to get the basic idea you can take a look.

I am assuming you have some idea about neural networks

BaseNeuron is my neuron class which derives from user control. Input Neuron Middle Neuron and Output Neurons are derived from Base Neuron .Input Neuron is the neurons where you apply input output neurons are as name implies output :).Every neuron can be connected to another by synaps.A synaps becomes more powerful as it transmit signals

NeuralNetwork is our network and contains two collections inputneurons and neurons(middle and output).NeuralNetwork stores the fired neurons you can find all fired neurons in our network in nth turn.

NeuralPort is the ports where you can make connections(input and output) to ann.

NeuronList is our List that hold neurons and enables us to find desired neuron by neuronNo

NetworkVisualiser is the gui that shows our neural network connections and fired neurons.

Network builder is obsolete now network build her own.

I am uploading a copy in google code under hyacinth.

http://code.google.com/p/hyacinth/downloads/list

Wednesday, May 20, 2009

N-Depend

I have been busy with artificial neural networks for some time so couldn’t post much.

NDepend is a static code analyzer it inspects your code and tells dependincies metrics code analysis. I found metrics very useful.It tell if you used boxing if your namings are wrong, if you used wrong access modifier, you have too many fields.You can also write your own queries it uses cql code query language very similar to sql, You can select methods which returns int.

http://www.ndepend.com/ is the web page.

Take a look

Thursday, May 7, 2009

Hyacinth v1.1

I added some missing things to hyacinth my jabber client.She can now encrypt messages .

Monday, April 27, 2009

Pollard’s Rho factoring algorithm in C#

Pollard’s rho algorithm is used to factor composite integers. Suppose you have 8633, 89 *97 are the factors.

Here is the code:

static void Main(string[] args)
        {
            Int64 a = p.PollardRho(12187823);
        }
        public Int64 customFunct(Int64 param, Int64 mod)//Custom number generator
        {
            return ((param * param + 1 )% mod);
        }
        public Int64 PollardRho(Int64 number)
        {
            Int64 a = 2, b = 2, tmp;//initail starting values
            while(true)
            {
            a = customFunct(a,number);//get first number
            b = customFunct(customFunct(b,number),number);//get second double run custom func
            tmp = GCD(Math.Abs(b-a), number);// if a =  b mod d(divisor one of the divisors of our number) then a-b is multiple of d and number is multiple of d 
            if (tmp > 1)
                break;
            }
            return tmp;
        
        }
        public Int64 GCD(Int64 x, Int64 y)//Greatest Common Divisor
        {
            if (x == 0)//Find it? return
                return y;
            if (y == 0)//Find it? return
                return x;
            x = x % y;// take the mod of the large val to small one if the order is wrong in the next recursive loop it will be correct
            return GCD(y, x);//Parameters changed place
        }

I put comments on the code and included usage.The code includes a custom function you may experiment with and a greatest common divisor calculator.

Sunday, April 26, 2009

Reflection

This code is used to change all off  one kind of controls one property to any value in a form.Hard to understand ? Ok let me give you an ex: you want to disable all text box in a form property is enabled value is false very easy.

private static ArrayList controls = new ArrayList();
    public static Control[] LookControls(Form f,Type ctrlType,string property,object value)
    {
  
        foreach (Control c in f.Controls)
        {
            LookControls(c, ctrlType,property,value);
        }
        return (Control[])controls.ToArray(typeof(Control));
    }
    private static void LookControls(Control ctrl, Type ctrlType,string property,object value)
    {
        if (ctrl.GetType() == ctrlType)
        {
            controls.Add(ctrl);
            PropertyInfo p = ctrl.GetType().GetProperty(property);
            p.SetValue(ctrl, value, null);
        }
       
        if (ctrl.Controls != null)
        {
            foreach (Control ctrl1 in ctrl.Controls)
            {
                LookControls(ctrl1,ctrlType,property,value);
            }
        }
    }

Friday, April 24, 2009

LU Decomposition and Linear Equation Solving in c#

LU decomposition is used to write a matrix in Upper and Lower triangle forms which is used to solve linear equations.Here is my code for LU decomposition and Linear Equation Solving, it is based on some very old fortran code, i think lapack may have the original sources but they are hard to understand.I added a few comments but to really understand what is going on i can recommend using  pen and paper and doing with hand.

static void Main(string[] args)
{
    double[,] lu = new double[3, 3] { { 2, 1, -1 }, { -3, -1, 2 }, { -2, 1, 2 } };
    double[] b = new double[] { 8, -11, -3 };
    double[] x = new double[3];
    int[] indx = new int[b.Length];
    Program p = new Program();
    p.LUDecompose(ref lu, ref indx);
    p.Solve(ref b, ref x, indx, lu);
}
private void LUDecompose(ref double[,] lu, ref int[] indx)
{
    int i, imax = 0, j, k, n = lu.GetLength(0);
    double big, temp;
    double[] vv = new double[n];
    //preChecks
    if (lu.GetLength(0) != lu.GetLength(1) || lu.GetLength(0) != indx.Length)
        throw new Exception("matrix dimension problem only use square matrices");
    //for each row find the absolute value of the greatest cell and store in vv
    for (i = 0; i < n; i++)
    {
        big = 0.0;
        for (j = 0; j < n; j++)
            if ((temp = Math.Abs(lu[i, j])) > big) big = temp;
        if (big == 0.0)
        throw new Exception("singular matrix");
         
        vv[i] = 1.0 / big;//calculate scaling and save
    }
    //k is for colums start with the left look for the columns under the diagonal for the biggest value want to move the largest over diagonal
    for (k = 0; k < n; k++)//find the largest pivot element 
    {
        big = 0.0;
        for (i = k; i < n; i++)
        {
            temp = vv[i] * Math.Abs(lu[i, k]);
            if (temp > big)
            {
                big = temp;
                imax = i;
            }
        }
 
        if (k != imax)//do we need a row change 
        {
            for (j = 0; j < n; j++)// counter for the colums
            {
                temp = lu[imax, j];// change the rows
                lu[imax, j] = lu[k, j];
                lu[k, j] = temp;
            }
            vv[imax] = vv[k];
        }
        indx[k] = imax;
 
        for (i = k + 1; i < n; i++)
        {
            temp = lu[i, k] /= lu[k, k];//divide pilot element
            for (j = k + 1; j < n; j++)
                lu[i, j] -= temp * lu[k, j];
        }
    }
 
}
private void Solve(ref double[] b, ref double[] x, int[] indx, double[,] lu)
{
    if (b.Length != lu.GetLength(0) || x.Length != lu.GetLength(0))
        throw new Exception("vector dimension problem");
 
    int n = lu.GetLength(0);
    int i, ii = 0, ip, j;
    double sum = 0;
    for (i = 0; i < n; i++) x[i] = b[i];
    for (i = 0; i < n; i++)
    {
        ip = indx[i];
        sum = x[ip];
        x[ip] = x[i];
        if (ii != 0)
            for (j = ii - 1; j < i; j++) sum -= lu[i, j] * x[j];
        else if (sum != 0.0)
            ii = i + 1;
        x[i] = sum;
    }
    for (i = n - 1; i >= 0; i--)
    {
        sum = x[i];
        for (j = i + 1; j < n; j++) sum -= lu[i, j] * x[j];
        x[i] = sum / lu[i, i];
    }
}

The code also has an example how to use b is the vector right hand side of the equation x is the solution vector, lu is the matrix.

Thursday, April 23, 2009

tricky or idiomatic

Ok  have written all this page and windows live writer stopped working when  i was posting, i hate programs when they do that (dont   get backup) i will tell about backing up in another post.I will not write all the stuff back i have things to do, please tell your best wishes to live writer group .

int x = 2;
int y = x << 1 | 1;
int z = x << 1 + 1;

ok these are not same y = 5 and z is 8 because of order of evaluation.

//x   y
//0   2   
//1   0
//2   1
 
int x, y = 1; ;
x = (2 - y) * (1 + 3 * y) / 2;
 
x = y + 1;
if (x == 3) x = 0;
 
switch (y)
{
    case 2:
        x = 0;
        break;
    case 0:
        x = 1;
        break;
    case 1:
        x = 2;
        break;
    default:
        {
           throw new Exception("incorrect parameter");
        }
}

ok here is 3 different codes that do the same thing : return values associated in table above code like 0 if 2 is given as parameter.

the first one is tricky and bad the second is good idiomatic and the last one is suboptimal and slow only may be used if algorith should be broken with future numbers.

Ok i know i didn’t told anything but i am sure codes will be explanatory enough.