Exemple #1
0
        async Task ReceiveClientTry(TryRequest t)     // Simulate the POST /try function
        {
            WriteLine($"..... receive try {t}");
            await Task.Delay(0);

            GeneticAlgorithm(t);

            return;  // emphatic empty return
        }
Exemple #2
0
        async void GeneticAlgorithm(TryRequest treq)
        {
            WriteLine($"..... GeneticAlgorithm {treq}");
            await Task.Delay(0);

            // just an ad-hoc PR test - you will remove this
            // await ProportionalRandomTest ();

            // YOU CODE GOES HERE
            // FOLLOW THE GIVEN PSEUDOCODE

            // ...

            var id      = treq.id;
            var monkeys = treq.monkeys;

            if (monkeys % 2 != 0)
            {
                monkeys += 1;
            }
            var length    = treq.length;
            var crossover = treq.crossover / 100.0;
            var mutation  = treq.mutation / 100.0;
            var limit     = treq.limit;

            if (limit == 0)
            {
                limit = 1000;
            }

            // ... UDOO

            for (int loop = 0; loop < limit; loop++)
            {
                // ... UDOO
            }
        }
        async void GeneticAlgorithm(TryRequest treq)
        {
            WriteLine($"..... GeneticAlgorithm {treq}");
            await Task.Delay(0);

            var id      = treq.id;
            var monkeys = treq.monkeys;

            if (monkeys % 2 != 0)
            {
                monkeys += 1;
            }
            var length = 0;

            if (treq.length == 0)
            {
                var nullText = new[] { "" }.ToList();
                var r = new AssessRequest {
                    id = id, genomes = nullText
                };
                AssessResponse ares = await PostFitnessAssess(r);

                var scores = ares.scores;
                length = scores[0];
            }
            else
            {
                length = treq.length;
            }
            var crossover = treq.crossover / 100.0;
            var mutation  = treq.mutation / 100.0;
            var limit     = treq.limit;

            if (limit == 0)
            {
                limit = 1000;
            }
            var topscore = int.MaxValue;
            var genomes  = Enumerable.Range(0, monkeys).Select(i => {
                var genome = Enumerable.Range(0, length).Select(n => {
                    return((char)NextInt(32, 127));
                }).ToList();
                return(string.Join("", genome));
            }).ToList();

            var obj1 = new AssessRequest {
                id = id, genomes = genomes
            };

            for (int loop = 0; loop < limit; loop++)
            {
                AssessResponse x = await PostFitnessAssess(obj1);

                var Id          = x.id;
                var scores      = x.scores;
                var smallest    = scores.Min();
                var largest     = scores.Max();
                var index       = scores.IndexOf(smallest);
                var genome_list = obj1.genomes;
                var genome      = genome_list[index];
                if (smallest < topscore)
                {
                    var obj2 = new TopRequest {
                        id = Id, loop = loop, score = smallest, genome = genome
                    };
                    await PostClientTop(obj2);

                    topscore = smallest;
                }

                if (smallest == 0)
                {
                    break;
                }
                else
                {
                    var weights = scores.Select(s => {
                        return(largest - s + 1);
                    });
                    var para = treq.parallel;

                    if (para)
                    {
                        var newGenomes = ParallelEnumerable.Range(1, monkeys / 2).SelectMany <int, string>(i => {
                            var c1     = "";
                            var c2     = "";
                            var index1 = ProportionalRandom(weights.ToArray(), weights.Sum());
                            var index2 = ProportionalRandom(weights.ToArray(), weights.Sum());
                            var p1     = genome_list[index1];
                            var p2     = genome_list[index2];

                            if (NextDouble() < crossover)
                            {
                                var crossoverIndex = NextInt(0, length);
                                c1 = p1.Substring(0, crossoverIndex) + p2.Substring(crossoverIndex, p2.Length - crossoverIndex);
                                c2 = p2.Substring(0, crossoverIndex) + p1.Substring(crossoverIndex, p1.Length - crossoverIndex);
                            }
                            else
                            {
                                c1 = p1;
                                c2 = p2;
                            }

                            if (NextDouble() < mutation)
                            {
                                char[] c = c1.ToCharArray();
                                c[NextInt(0, c1.Length)] = (char)NextInt(32, 127);
                                c1 = new string(c);
                            }
                            if (NextDouble() < mutation)
                            {
                                char[] c = c2.ToCharArray();
                                c[NextInt(0, c2.Length)] = (char)NextInt(32, 127);
                                c2 = new string(c);
                            }
                            var mylist = new List <string>();
                            mylist.Add(c1);
                            mylist.Add(c2);
                            return(mylist);
                        }).ToList();
                        obj1.id      = Id;
                        obj1.genomes = newGenomes;
                    }
                    else
                    {
                        var newGenomes = Enumerable.Range(1, monkeys / 2).SelectMany <int, string>(i => {
                            var c1     = "";
                            var c2     = "";
                            var index1 = ProportionalRandom(weights.ToArray(), weights.Sum());
                            var index2 = ProportionalRandom(weights.ToArray(), weights.Sum());
                            var p1     = genome_list[index1];
                            var p2     = genome_list[index2];

                            if (NextDouble() < crossover)
                            {
                                var crossoverIndex = NextInt(0, length);
                                c1 = p1.Substring(0, crossoverIndex) + p2.Substring(crossoverIndex, p2.Length - crossoverIndex);
                                c2 = p2.Substring(0, crossoverIndex) + p1.Substring(crossoverIndex, p1.Length - crossoverIndex);
                            }
                            else
                            {
                                c1 = p1;
                                c2 = p2;
                            }

                            if (NextDouble() < mutation)
                            {
                                char[] c = c1.ToCharArray();
                                c[NextInt(0, c1.Length)] = (char)NextInt(32, 127);
                                c1 = new string(c);
                            }
                            if (NextDouble() < mutation)
                            {
                                char[] c = c2.ToCharArray();
                                c[NextInt(0, c2.Length)] = (char)NextInt(32, 127);
                                c2 = new string(c);
                            }

                            var mylist = new List <string>();
                            mylist.Add(c1);
                            mylist.Add(c2);
                            return(mylist);
                        }).ToList();

                        obj1.id      = Id;
                        obj1.genomes = newGenomes;
                    }
                }
            }
        }
Exemple #4
0
        async void GeneticAlgorithm(TryRequest treq)
        {
            var           length  = treq.length;
            var           monkeys = treq.monkeys;
            List <string> post    = new List <string>();
            string        bestStr = "";

            if (monkeys % 2 != 0)
            {
                monkeys += 1;
            }

            //discover length
            if (length == 0)
            {
                List <string> test = new List <string>()
                {
                    ""
                };
                var content = new StringContent(JsonSerializer.Serialize(test), System.Text.Encoding.UTF8,
                                                "application/json");
                var response = await client.PostAsync("http://localhost:8091/assess", content);

                var l = await response.Content.ReadAsAsync <List <int> >();

                length = l[0];
            }

            //create start genome

            IEnumerable <string> strings =
                Enumerable.Repeat(
                    Nextstr(length), monkeys);

            post = strings.ToList();



            WriteLine($"..... POST length {length}");
            for (var count = 0; count < treq.limit; count++)
            {
                //Send content
                var content = new StringContent(JsonSerializer.Serialize(post), System.Text.Encoding.UTF8,
                                                "application/json");
                var response = await client.PostAsync("http://localhost:8091/assess", content);

                var ress = await response.Content.ReadAsAsync <List <int> >();

                //find best
                var min            = ress.Min();
                var tempBestString = post[ress.IndexOf(min)];
                var tempBest       = min;


                if (0 == tempBest)
                {
                    best    = tempBest;
                    bestStr = tempBestString;
                    var top     = new TopRequest(8081, count, best, bestStr);
                    var topcont = new StringContent(JsonSerializer.Serialize(top), System.Text.Encoding.UTF8,
                                                    "application/json");
                    var resp = await client.PostAsync($"http://localhost:{treq.id}/top", topcont);

                    WriteLine($" DONE {tempBestString}");
                    return;
                }
                if (tempBest < best)
                {
                    best    = tempBest;
                    bestStr = tempBestString;
                    WriteLine($" BEST {tempBestString}");
                    var top     = new TopRequest(8081, count, best, bestStr);
                    var topcont = new StringContent(JsonSerializer.Serialize(top), System.Text.Encoding.UTF8,
                                                    "application/json");
                    var resp = await client.PostAsync("http://localhost:8101/top", topcont);
                }



                //if its parallel
                if (treq.parallel)
                {
                    post = ParallelEnumerable.Range(1, monkeys / 2)
                           .SelectMany <int, string>(i =>
                    {
                        var p1 = post[ProportionalRandom(ress.ToArray(), ress.Sum())];
                        var p2 = post[ProportionalRandom(ress.ToArray(), ress.Sum())];
                        var c1 = "";
                        var c2 = "";
                        //cross over chance
                        if (NextInt(0, 100) < treq.crossover)
                        {
                            var Index = NextInt(0, p1.Length - 1);
                            c1        = p1.Substring(0, Index) + p2.Substring(Index, p2.Length - Index);
                            c2        = p2.Substring(0, Index) + p1.Substring(Index, p1.Length - Index);
                        }
                        else
                        {
                            c1 = p1;
                            c2 = p2;
                        }

                        if (NextInt(0, 100) < treq.mutation)
                        {
                            var item = NextInt(0, c1.Length);
                            StringBuilder strBuilder = new System.Text.StringBuilder(c1);
                            strBuilder[item]         = Convert.ToChar(NextInt(32, 126));
                            ;
                            c1 = strBuilder.ToString();
                        }

                        if (NextInt(0, 100) < treq.mutation)
                        {
                            var item = NextInt(0, c2.Length);
                            StringBuilder strBuilder = new System.Text.StringBuilder(c2);
                            strBuilder[item]         = Convert.ToChar(NextInt(32, 126));
                            ;
                            c2 = strBuilder.ToString();
                        }

                        return(new[] { c1, c2 });
                    }).ToList();
                }
                else
                {
                    post = Enumerable.Range(1, monkeys / 2)
                           .SelectMany <int, string>(i =>
                    {
                        var p1 = post[ProportionalRandom(ress.ToArray(), ress.Sum())];
                        var p2 = post[ProportionalRandom(ress.ToArray(), ress.Sum())];
                        var c1 = "";
                        var c2 = "";
                        //cross over chance
                        if (NextInt(0, 100) < treq.crossover)
                        {
                            var Index = NextInt(0, p1.Length - 1);
                            c1        = p1.Substring(0, Index) + p2.Substring(Index, p2.Length - Index);
                            c2        = p2.Substring(0, Index) + p1.Substring(Index, p1.Length - Index);
                        }
                        else
                        {
                            c1 = p1;
                            c2 = p2;
                        }

                        if (NextInt(0, 100) < treq.mutation)
                        {
                            var item = NextInt(0, c1.Length);
                            StringBuilder strBuilder = new System.Text.StringBuilder(c1);
                            strBuilder[item]         = Convert.ToChar(NextInt(32, 126));
                            ;
                            c1 = strBuilder.ToString();
                        }

                        if (NextInt(0, 100) < treq.mutation)
                        {
                            var item = NextInt(0, c2.Length);
                            StringBuilder strBuilder = new System.Text.StringBuilder(c2);
                            strBuilder[item]         = Convert.ToChar(NextInt(32, 126));
                            ;
                            c2 = strBuilder.ToString();
                        }

                        return(new[] { c1, c2 });
                    }).ToList();
                }
            }
        }
Exemple #5
0
        async void GeneticAlgorithm(TryRequest treq)
        {
            WriteLine($"..... GeneticAlgorithm {treq}");
            await Task.Delay(0);

            var id      = treq.id;
            var monkeys = treq.monkeys;

            if (monkeys % 2 != 0)
            {
                monkeys += 1;
            }
            var length    = treq.length;
            var crossover = treq.crossover / 100.0;
            var mutation  = treq.mutation / 100.0;
            var limit     = treq.limit;

            if (limit == 0)
            {
                limit = 1000;
            }
            var isParallel = treq.parallel;

            if (treq.length == 0)   // Dynamic cal length
            {
                var list = new List <string>()
                {
                    ""
                };
                var res = await PostFitnessAssess(new AssessRequest { id = id, genomes = list, });

                length = res.scores[0];
            }

            // Create randoms
            currentGeneration = new List <string>();
            currentGeneration = createRandoms(monkeys, length);

            string currentBestGenome = currentGeneration[0]; // Randomly choose initially
            string targettxt         = currentBestGenome;

            for (int loop = 0; loop < limit; loop++)    // The evolutaion loop
            // Get the fitness values from the fitness server
            {
                var res = await PostFitnessAssess(new AssessRequest { id = id, genomes = currentGeneration, });

                var fs = res.scores;

                currentBestGenome = getCurrentBest(fs);

                // Get the fitness of current best as well as the targettext
                var list = new List <string>()
                {
                    currentBestGenome, targettxt
                };
                var res2 = await PostFitnessAssess(new AssessRequest { id = id, genomes = list, });

                var fs2 = res2.scores;

                if (fs2[0] < fs2[1])   // current best genome's fitness < best's fitness
                {
                    targettxt = currentBestGenome;

                    // Post the evolutaion string to the clinet
                    await PostClientTop(new TopRequest { id = id, loop = loop, score = fs2[0], genome = targettxt, });

                    if (fs2[0] == 0)
                    {
                        break;              // Find the target and break the loop
                    }
                }

                // Create new generations
                currentGeneration = createNewGeneration(monkeys, mutation, crossover, fs, isParallel);
            }
        }