Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

What's wrong with this simple Genetic Algorithm?

  1. Apr 21, 2015 #1
    Hey all, writing this simple genetic algorithm but its not working. Any idea why?

    Code (C):
    static int len = 30;
            static char[,] dog = new char[len, 30];
            static void breed()
            {
                sort();
                int Ii0 = r.Next(0,15);
                int Ii1=r.Next(0,15);
                string i0 = get(Ii0);
             
                string i1 = get(Ii1);
                Cross(Ii0, Ii1);
                Mut(r.Next(0,10), r.Next(0,30),3);
            }
            static void sort()
            {
                for (int p = 0; p < 30; p++)
                {
                    for (int i = 0; i < 30 - 1; i++)
                    {
                        if (fitness(i) > fitness(i + 1))
                        {
                            string i0 = get(i);
                            string i1 = get(i + 1);
                            set(i, i1);
                            set(i + 1, i0);
                        }
                    }
                }
            }
         
            static int getnum(string s)
            {
                int u = 0;
                for (int i = 0; i < s.Length; i++)
                {
                    if ((int)s[i] == (int)'1')
                    {
                        u++;
                    }
                    else if ((int)s[i] == (int)'-')
                    {
                        u--;
                    }
                }
                return u;
            }
            static double fitness(int y)
            {
                dog.ToString();
                string s = get(y);
                int u = getnum(get(y));
                  return ( 1 / ((2 * u * u) + (33.25f * u) + 20));//30//-30
          ;
            }
            static double fitness(string y)
            {      
                int u = getnum(y);
                return ( 1 / ((2 * u * u) + (33.25f * u) + 20));//30//-30
            }
            static void init()
            {
                string[] lines = System.IO.File.ReadAllLines("C:/users/e/desktop/init.txt");
                                   //      StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < len; i++)
                {
                    for (int j = 0; j < 30; j++)
                    {
                        dog[i, j] = lines[i][j];
                    }
                }
             
            }
            static void Mut(int chr,int pos,int chance)
            {
                var yy = r.Next(0,300);
                if (r.Next(0, 100) < chance)
                {

                    if (dog[chr, pos] == '0')
                    {
                        if (r.Next(100) < 50)
                        {
                            dog[chr, pos] = '1';
                        }
                        else
                        {
                            dog[chr, pos] = '-';
                        }

                    }

                    if (dog[chr, pos] == '1')
                    {
                        if (r.Next(100) < 50)
                        {
                            dog[chr, pos] = '0';
                        }
                        else
                        {
                            dog[chr, pos] = '-';
                        }

                    }

                    if (dog[chr, pos] == '-')
                    {
                        if (r.Next(100) < 50)
                        {
                            dog[chr, pos] = '1';
                        }
                        else
                        {
                            dog[chr, pos] = '0';
                        }

                    }

                }
            }
           static Random r = new Random();
            static void Cross(int j, int k)
            {
                for (int i = 0; i < len; i++)
                {
                    if (r.Next(100) < 50)
                    {
                        char jt = dog[j, i];
                        char kt = dog[k, i];
                        dog[k, i] = jt;
                        dog[j, i] = kt;
                    }
                }
            }
            static string get(int y)
            {
                string h = "";
                for (int i = 0; i < 30; i++)
                {
                    h += dog[y, i];
                }
                return h;
            }
            static void set(int y,string s)
            {
                for (int i = 0; i < 30; i++)
                {
                    dog[y, i] = s[i];
                }
            }
            static void Main(string[] args)
            {
                init();
                for (int i = 0; i < len; i++)
                {
                    Console.WriteLine(getnum(get(i)));
                }
           
                for (int j = 0; j < 10; j++)
                {
                    for (int i = 0; i < 400; i++)
                    {
                        breed();
                     
                    }
                    sort();
                    Console.WriteLine(fitness(0));
                    Console.WriteLine(getnum(get(0)));
                }
                for (int i = -30; i < 30; i++)
                {
                    Console.WriteLine(i.ToString() + ":" + (i).ToString());
                }
           
                Console.Read();
            }
    Any help apreciated.
     
  2. jcsd
  3. Apr 21, 2015 #2

    jedishrfu

    Staff: Mentor

    Have you stepped through your code with a debugger line by line?

    Or inserted print statements where you think the error is?

    Are you using an IDE to develop the code? They usually have a debugger that can be used.

    Also your code doesn't look formatted cleanly, again an IDE will usually have a source reformat action.
     
  4. Apr 21, 2015 #3
    Yes,
    Yes,
    Yes,
    Yes,

    I meant is there a logical error in my fitness function, crossover, mutation etc? The general steps of the GA, its supposed to find the minimum of a function.
     
  5. Apr 21, 2015 #4

    Mark44

    Staff: Mentor

    "It's not working" doesn't give us much of a clue. If it's not working, give us a hint, such as what it should be doing vs. what it's actually doing.

    You asked whether there was a logical error in your fitness function, one overload of which is this one:
    Code (C):
    static double fitness(string y)
            {      
                int u = getnum(y);
                return ( 1 / ((2 * u * u) + (33.25f * u) + 20));//30//-30
            }
    Logic error? Hard to say without knowing what the purpose of this code is. I don't see a single explanatory comment in your code, not counting where you have commented out some code.

    It's not obvious from looking what some of the other functions you asked about are doing.
     
  6. Apr 21, 2015 #5

    jedishrfu

    Staff: Mentor

    If you think something is wrong with your fitness function then why not unit test ie test it by itself giving it some input and see if you get the expected result.

    Writing programs doesn't mean write and test it whole. It really means unit test each function or method and then combine them together and test the bigger assembly of components. It's the only way to really know if your program will perform.
     
  7. Apr 22, 2015 #6
    Ive tried doing everything seperatly, every function seems to work by itself, but as a whole it doesn't, maybe im leaving something out or doing it in the wrong order?
    Sorry should have put it in main post.
     
  8. Apr 22, 2015 #7

    jedishrfu

    Staff: Mentor

    You're missing the point here. "Its not working" doesn't tell us anything.

    If you tell me you got a NullPointerException on line 999 then I have something to go on. In general, we are sight reviewing your code. We aren't actually trying to run it trying to look for possible trouble spots for you to investigate.

    I guess the problem you are encountering is that it runs for a long time and never converges onto the answer you expect and so its not working. These kinds of problems are some of the hardest to diagnose and in the end only the programmer who wrote the code needs to suffer through the analysis and figure out why things aren't working as expected.

    Doing so will make you a better programmer.

    My understanding of GA's are that they follow theses steps:
    - initially generate a set of solution vectors
    - scores the solution vectors
    - use some sort of cutoff that passes half and discards half of the solutions
    - use the "good" solutions to make new solutions using random adjustments or element swapping between any two good solutions
    - and repeating the steps until the "best" solutions are found.

    http://en.wikipedia.org/wiki/Genetic_algorithm
     
  9. Apr 23, 2015 #8

    meBigGuy

    User Avatar
    Gold Member

    The reason it isn't working is because there are no comments. Go through and comment every line and I'll bet it works (because you will find the error while writing the comments). If, by chance,I am wrong and you don't find the error, then at least we will understand what you are trying to do and be able to help.
     
  10. Apr 23, 2015 #9
    Before all :
    Are you sure that your problem absolutely need an génétic algorithm ?
    Gradient, levemberg maquardt, gauss-newton fail ?
    Don't forget that genetic algorithm are SLOW !
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook