예제 #1
0
        private static void SolveHC()
        {
            HillClimbing hc = new HillClimbing();

            Console.WriteLine("FA HC Solver Started");
            Console.WriteLine("Press ESC to stop");

            hc.Solve(3);

            Console.WriteLine("FA HC Solver Finished");
        }
예제 #2
0
        private void FindOptimalDecision()
        {
            double optimal = 1000;

            for (int i = 0; i < AmountOfTests; i++)
            {
                var temp = new HillClimbing(Elements, 5);
                if (temp.OptimalValue.Value < optimal)
                {
                    Algorithm = temp;
                    optimal   = temp.OptimalValue.Value;
                }
            }
        }
        private void ButtonHillStart_Click(object sender, RoutedEventArgs e)
        {
            DisableAllControls();

            _infoBacklog = new List <Tuple <int, ulong, double, ulong> >(_viewModel.MaxGenerationCount);

            var hill = new HillClimbing(_viewModel, _geneticAlgorithmController.CityModels);

            hill.OnAlgorithmStateHasChangedEvent += OnAlgorithmStateHasChangedEvent;
            hill.OnAlgorithmFinishedEvent        += OnAlgorithmFinishedEvent;
            hill.OnLogChangedEvent += OnLogChangedEvent;

            _algorithmCancellationToken = new CancellationTokenSource();

            Task.Factory.StartNew(() => hill.DoAlgorithm(_algorithmCancellationToken.Token),
                                  _algorithmCancellationToken.Token);
        }
예제 #4
0
        private void SameInitValuebutton_Click(object sender, EventArgs e)
        {
            double alpha = Convert.ToDouble(textBox11.Text);

            File.Delete(@"C:\Users\User\Downloads\ResultFAHillClimbing.txt");

            var hill = new HillClimbing(knapsackModel);

            File.Delete(@"C:\Users\User\Downloads\ResultHillClimbing.txt");

            var resultModel = hill.HillClimbingMethod(knapsackModel, alpha);

            textBoxResultC2.Text = Convert.ToString(resultModel.ResultC);
            textBoxResultW2.Text = Convert.ToString(resultModel.ResultW);
            listBoxSelectedItems2.Items.Clear();
            if (checkBoxShowFull2.Checked)
            {
                listBoxSelectedItems2.Items.Add("cost\t\tweight");
                for (int i = 0; i < resultModel.X.Length; i++)
                {
                    if (resultModel.X[i] == true)
                    {
                        listBoxSelectedItems2.Items.Add(knapsackModel.Items[i].Item1 + "\t" + knapsackModel.Items[i].Item2);
                    }
                }
            }

            resultModel         = hill.NewFirstAscendHillClimbingMethod(knapsackModel, alpha);
            textBoxResultC.Text = Convert.ToString(resultModel.ResultC);
            textBoxResultW.Text = Convert.ToString(resultModel.ResultW);
            listBoxSelectedItems.Items.Clear();
            if (checkBoxShowFull.Checked)
            {
                listBoxSelectedItems.Items.Add("cost\t\tweight");
                for (int i = 0; i < resultModel.X.Length; i++)
                {
                    if (resultModel.X[i] == true)
                    {
                        listBoxSelectedItems.Items.Add(knapsackModel.Items[i].Item1 + "\t" + knapsackModel.Items[i].Item2);
                    }
                }
            }
        }
예제 #5
0
        static void Main(string[] args)
        {
            //MonteCarlo mc = new MonteCarlo(15, short.MaxValue, 100, LandscapeFilling.Random);
            //var result = mc.DoAlgo();

            HillClimbing hc = new HillClimbing(5, 32, LandscapeFilling.ValueOfBinary, HillClimbingType.Width);

            hc.DoAlgo();

            //            var values = new List<List<double>>
            //            {
            //new List<double>{0.00, 10.44, 11.18, 4.24, 13.60, 7.00, 12.21, 13.45, 13.45, 9.49, 11.05, 3.16, 1.41, 7.21, 10.20},
            //new List<double>{10.44, 0.00, 2.00, 13.00, 8.25, 4.24, 4.00, 7.07, 6.00, 14.32, 13.60, 8.06, 11.18, 14.32, 13.89},
            //new List<double>{11.18, 2.00, 0.00, 13.15, 6.32, 5.83, 2.00, 5.10, 4.00, 13.60, 12.53, 9.22, 11.70, 14.04, 13.00},
            //new List<double>{4.24, 13.00, 13.15, 0.00, 13.60, 10.44, 13.60, 13.89, 14.32, 6.00, 8.25, 7.21, 2.83, 3.16, 7.07},
            //new List<double>{13.60, 8.25, 6.32, 13.60, 0.00, 11.05, 4.47, 1.41, 2.83, 11.18, 9.00, 13.00, 13.45, 13.00, 10.05},
            //new List<double>{7.00, 4.24, 5.83, 10.44, 11.05, 0.00, 7.62, 10.20, 9.49, 13.45, 13.60, 4.12, 8.06, 12.53, 13.45},
            //new List<double>{12.21, 4.00, 2.00, 13.60, 4.47, 7.62, 0.00, 3.16, 2.00, 13.15, 11.70, 10.63, 12.53, 14.04, 12.37},
            //new List<double>{13.45, 7.07, 5.10, 13.89, 1.41, 10.20, 3.16, 0.00, 1.41, 12.04, 10.05, 12.53, 13.45, 13.60, 11.00},
            //new List<double>{13.45, 6.00, 4.00, 14.32, 2.83, 9.49, 2.00, 1.41, 0.00, 13.00, 11.18, 12.21, 13.60, 14.32, 12.04},
            //new List<double>{9.49, 14.32, 13.60, 6.00, 11.18, 13.45, 13.15, 12.04, 13.00, 0.00, 2.83, 11.66, 8.25, 3.16, 1.41},
            //new List<double>{11.05, 13.60, 12.53, 8.25, 9.00, 13.60, 11.70, 10.05, 11.18, 2.83, 0.00, 12.65, 10.00, 5.83, 1.41},
            //new List<double>{3.16, 8.06, 9.22, 7.21, 13.00, 4.12, 10.63, 12.53, 12.21, 11.66, 12.65, 0.00, 4.47, 9.90, 12.08},
            //new List<double>{1.41, 11.18, 11.70, 2.83, 13.45, 8.06, 12.53, 13.45, 13.60, 8.25, 10.00, 4.47, 0.00, 5.83, 9.06},
            //new List<double>{7.21, 14.32, 14.04, 3.16, 13.00, 12.53, 14.04, 13.60, 14.32, 3.16, 5.83, 9.90, 5.83, 0.00, 4.47},
            //new List<double>{10.20, 13.89, 13.00, 7.07, 10.05, 13.45, 12.37, 11.00, 12.04, 1.41, 1.41, 12.08, 9.06, 4.47, 0.00},
            //            };

            //            EGA ega = new EGA(values);

            //            ega.SetupInitialPopulation(Encoding.ClosestTown)
            //                .SetupParents(Pairs.Quality)
            //                .SetupCrossover(Crossover.Order)
            //                .SetupMutation(0.1, Mutation.Inversion)
            //                .SetupBreeding(Breeding.Roulette, 0.15)
            //                .EnableElitary()
            //                .DoAlgo(10);

            //            ega.PrintBestResult();
        }
예제 #6
0
        private void MultiStartHillClimbingButton_Click(object sender, EventArgs e)
        {
            var maxAttemt  = Convert.ToInt32(textBoxMaxAttemps.Text);
            var objDetails = checkBoxObjDetails.Checked;


            double alpha       = Convert.ToDouble(textBox11.Text);
            var    resultModel = new HillClimbing().MultiStartHillClimbingMethod(knapsackModel, maxAttemt, objDetails, alpha);
            Series ser1        = new Series("Attempts statistics");

            chart1.Series.Clear();
            foreach (var pair in resultModel.AttemptStatistics)
            {
                ser1.Points.AddXY(pair.Key.ToString(), pair.Value.ToString());
            }
            chart1.Series.Add(ser1);
            chart1.ChartAreas[0].AxisX.Interval = 1;
            textBoxDelta.Text = Convert.ToString(resultModel.Delta);

            if (objDetails)
            {
                chart2.Series.Clear();
                Series ser2 = new Series("Objective");
                ser2.ChartType = SeriesChartType.Line;

                chart2.ChartAreas["Area1"].AxisX.ScaleView.Zoom(0, 50);
                chart2.ChartAreas["Area1"].AxisX.Interval = 1;

                for (int i = 0; i < resultModel.ObjectivesDetails.Count; i++)
                {
                    for (int j = 0; j < resultModel.ObjectivesDetails[i].Count; j++)
                    {
                        ser2.Points.AddXY(j.ToString(), resultModel.ObjectivesDetails[i][j]);
                    }
                }

                chart2.Series.Add(ser2);
            }
        }
예제 #7
0
        public async Task <IActionResult> Index(ICollection <IFormFile> files, UserInput u)
        {
            /* Uploader File */
            user_input = u;
            var uploads = Path.Combine(_environment.WebRootPath, "uploads");

            foreach (var file in files)
            {
                if (file.Length > 0)
                {
                    uploads = Path.Combine(uploads, file.FileName);
                    using (var fileStream = new FileStream(uploads, FileMode.Create))
                    {
                        await file.CopyToAsync(fileStream);
                    }
                }
            }
            var openFile = new FileStream(uploads, FileMode.Open, FileAccess.Read);

            using (var readStream = new StreamReader(openFile))
            {
                int    conflict = 0;
                string line;

                Boolean           isRuangan = false;
                Boolean           isKelas   = false;
                string            temp      = "";
                char              b;
                RuanganManagement listOfRuangan = new RuanganManagement();
                KelasManagement   listOfKelas   = new KelasManagement();


                /* ADT RUANGAN */
                string     nama      = "";      // Contoh: "7602"
                int        jam_buka  = 0;       // Contoh: 7 (buka mulai jam 7)
                int        jam_tutup = 0;       // Contoh: 14 (tutup jam 14)
                List <int> hari_buka = new List <int>();

                /* ADT KELAS */
                // Domain value yang dimiliki 'Kelas'
                string        ruangan       = "";
                List <string> domainRuangan = new List <string>();
                List <int>    domainMulai   = new List <int>(); // Contoh: [7, 8, 9] (Kelas hanya bisa mulai jam 7, 8, atau 9)
                List <int>    domainHari    = new List <int>(); // Contoh: [1, 3, 5] (Kelas hanya bisa dilakukan hari Senin, Rabu, atau Jumat)
                int           durasi        = 0;                // Contoh: 4 (4 jam)


                while ((line = readStream.ReadLine()) != null)
                {
                    if (line.Equals(""))
                    {
                        // Do nothing
                    }
                    else if (line.Equals("Ruangan"))
                    {
                        isRuangan = true;
                        isKelas   = false;
                    }
                    else if (line.Equals("Jadwal"))
                    {
                        isRuangan = false;
                        isKelas   = true;
                    }
                    /* Membaca data ruangan */
                    else if (isRuangan)
                    {
                        var sr    = new StringReader(line);
                        int point = 0;
                        temp        = "";
                        hari_buka   = new List <int>();
                        domainMulai = new List <int>();
                        for (int k = 0; k < line.Length; k++)
                        {
                            b = (char)sr.Read();
                            if (b == ';')
                            {
                                if (point == 0)
                                {
                                    nama = temp;
                                }
                                else if (point == 1)
                                {
                                    jam_buka = timeToInt(temp);
                                }
                                else if (point == 2)
                                {
                                    jam_tutup = timeToInt(temp);
                                }
                                point++;
                                temp = "";
                            }
                            else
                            {
                                if (b != ',')
                                {
                                    temp += b;
                                }
                            }
                        }
                        var parse = new StringReader(temp);
                        for (int j = 0; j < temp.Length; j++)
                        {
                            char val = (char)parse.Read();
                            hari_buka.Add(Int32.Parse(val.ToString()));
                        }
                        listOfRuangan.addRuangan(new Ruangan(nama, jam_buka, jam_tutup, hari_buka));
                    }
                    /* Menambah info kelas */
                    else if (isKelas)
                    {
                        var sr    = new StringReader(line);
                        int point = 0;
                        temp          = "";
                        hari_buka     = new List <int>();
                        domainRuangan = new List <string>();
                        for (int k = 0; k < line.Length; k++)
                        {
                            b = (char)sr.Read();
                            if ((point == 1) && (b != ';'))
                            {
                                if (b == ',')
                                {
                                    domainRuangan.Add(temp);
                                    temp = "";
                                }
                                else
                                {
                                    temp += b;
                                }
                            }
                            else if (b == ';')
                            {
                                if (point == 0)
                                {
                                    nama = temp;
                                }
                                else if (point == 1)
                                {
                                    domainRuangan.Add(temp);
                                }
                                else if (point == 2)
                                {
                                    jam_buka = timeToInt(temp);
                                }
                                else if (point == 3)
                                {
                                    jam_tutup = timeToInt(temp);
                                }
                                else if (point == 4)
                                {
                                    durasi = Int32.Parse(temp);
                                }
                                point++;
                                temp = "";
                            }
                            else
                            {
                                if (b != ',')
                                {
                                    temp += b;
                                }
                            }
                        }
                        var parse = new StringReader(temp);
                        for (int j = 0; j < temp.Length; j++)
                        {
                            char val = (char)parse.Read();
                            hari_buka.Add(Int32.Parse(val.ToString()));
                        }
                        Kelas c = new Kelas(nama, domainRuangan, jam_buka, jam_tutup, durasi, hari_buka, listOfRuangan);
                        listOfKelas.addKelas(c);
                    }
                }

                KelasManagement ans = new KelasManagement();
                if (user_input.choice == 0)
                {
                    HillClimbing hc = new HillClimbing(listOfKelas, listOfRuangan);
                    ans = hc.getSol();
                    ViewData["Choice"] = "Hill Climbing";
                }
                else if (user_input.choice == 1)
                {
                    SimulatedAnnealing sa = new SimulatedAnnealing(listOfKelas, listOfRuangan);
                    sa.execute(1000, 0.9f);
                    ans = sa.getSol();
                    ViewData["Choice"] = "Simulated Annealing";
                }
                else if (user_input.choice == 2)
                {
                    Population p = new Population();
                    p.generatePopulation(200, listOfKelas);
                    GeneticAlgorithm ga = new GeneticAlgorithm(p);
                    for (int ax = 0; ax < 100000; ax++)
                    {
                        if (ga.getSolution().getConflict() == 0)
                        {
                            break;
                        }
                        else
                        {
                            ga.crossover();
                            ga.mutation();
                        }
                    }
                    ans = ga.getSolution();
                    ViewData["Choice"] = "Genetic Algorithm";
                }

                ViewData["tes"] = ans.getConflict();
                int i = 0;
                // Inisialisasi
                for (int j = 7; j < 18; j++)
                {
                    for (int k = 1; k < 6; k++)
                    {
                        ViewData["marker" + j.ToString() + k.ToString()]  = 5;
                        ViewData["nama" + j.ToString() + k.ToString()]    = "";
                        ViewData["ruangan" + j.ToString() + k.ToString()] = "";
                    }
                }
                // Pengisian kelas di tabel

                foreach (Kelas k in ans.getArrayKelas())
                {
                    ViewData["nama" + i.ToString()]    = k.getNama();
                    ViewData["ruangan" + i.ToString()] = k.getNamaRuangan();
                    ViewData["durasi" + i.ToString()]  = k.getDurasi();
                    ViewData["hari" + i.ToString()]    = k.getHari();
                    ViewData["jam" + i.ToString()]     = k.getMulai();
                    for (int z = k.getMulai(); z < (k.getMulai() + k.getDurasi()); z++)
                    {
                        if (ViewData["ruangan" + z.ToString() + k.getHari().ToString()].Equals(""))
                        {
                            ViewData["kelas" + z.ToString() + k.getHari().ToString()]   = i.ToString();
                            ViewData["marker" + z.ToString() + k.getHari().ToString()]  = 0;
                            ViewData["nama" + z.ToString() + k.getHari().ToString()]    = k.getNama();
                            ViewData["ruangan" + z.ToString() + k.getHari().ToString()] = k.getNamaRuangan();
                            //Kurangi waktu available dan tambahkan waktu terpakai;
                            listOfRuangan.getRuangan(k.getNamaRuangan()).decrement_waktu_available();
                        }
                        else if (cekRuanganSama(k.getNamaRuangan(), ViewData["ruangan" + z.ToString() + k.getHari().ToString()].ToString()))
                        {
                            conflict++;
                            ViewData["kelas" + z.ToString() + k.getHari().ToString()]    = i.ToString();
                            ViewData["marker" + z.ToString() + k.getHari().ToString()]   = 1;
                            ViewData["nama" + z.ToString() + k.getHari().ToString()]    += " " + k.getNama();
                            ViewData["ruangan" + z.ToString() + k.getHari().ToString()] += " " + k.getNamaRuangan();
                        }
                        else
                        {
                            ViewData["kelas" + z.ToString() + k.getHari().ToString()]   += " " + i.ToString();
                            ViewData["marker" + z.ToString() + k.getHari().ToString()]   = 2;
                            ViewData["nama" + z.ToString() + k.getHari().ToString()]    += " " + k.getNama();
                            ViewData["ruangan" + z.ToString() + k.getHari().ToString()] += " " + k.getNamaRuangan();
                            /* Kurangi waktu available dan tambahkan waktu terpakai*/
                            listOfRuangan.getRuangan(k.getNamaRuangan()).decrement_waktu_available();
                        }
                    }
                    i++;
                }
                ViewData["tes"]    = conflict;
                ViewData["Length"] = i;

                /* Memasukkan data keefektifan untuk ditampilkan di web */
                int nRuangan = 0;
                foreach (Ruangan ruang_ruang in listOfRuangan.getAllRuangan())
                {
                    ViewData["namaruangan" + nRuangan.ToString()] = ruang_ruang.getName();
                    ViewData["efektifitas" + nRuangan.ToString()] = ruang_ruang.getEfektifitasRuangan();
                    nRuangan++;
                }
                ViewData["banyakruangan"] = nRuangan;
            }
            ViewData["color0"] = "green";
            ViewData["color1"] = "yellow";
            ViewData["color2"] = "brown";
            ViewData["color3"] = "blue";
            ViewData["color4"] = "black";
            ViewData["color5"] = "aqua";
            ViewData["color6"] = "purple";
            ViewData["color7"] = "wood";
            ViewData["color8"] = "pink";
            ViewData["color9"] = "orange";
            ViewData["Start"]  = 1;
            return(View());
        }
예제 #8
0
        static void TestRun(bool randomWorkloadJumps, string fileName)
        {
            // Ported from http://mattwarren.org/2017/04/13/The-CLR-Thread-Pool-Thread-Injection-Algorithm/

            Console.WriteLine("Running Hill Climbing algorithm ({0})", fileName);

            var options = new HillClimbingOptions();

            options.MinThreads = () => 2;
            options.MaxThreads = () => 1000;

            var hc = new HillClimbing(options);

            int  newMax = 0, threadAdjustmentInterval = 0;
            long totalCompletions = 0, priorCompletionCount = 0;
            int  timer = 0, lastSampleTimer = 0;

            int currentThreadCount = options.MinThreads();

            hc.ForceChange(currentThreadCount, HillClimbingStateTransition.Initializing);

            var randomGenerator = new Random();

            using (var fp = new StreamWriter(fileName))
            {
                fp.WriteLine("Time,Throughput,Threads");
                for (int mode = 1; mode <= 5; mode++)
                {
                    int currentWorkLoad = 0;
                    switch (mode)
                    {
                    case 1:
                    case 5:
                        currentWorkLoad = 3;
                        break;

                    case 2:
                    case 4:
                        currentWorkLoad = 7;
                        break;

                    case 3:
                        currentWorkLoad = 10;
                        break;

                    default:
                        currentWorkLoad = 1;
                        break;
                    }

                    bool reportedMsgInWorkload = false;
                    int  workLoadForSection    = currentWorkLoad * 500;
                    while (workLoadForSection > 0)
                    {
                        if (randomWorkloadJumps)
                        {
                            int randomValue = randomGenerator.Next(21); // 0 to 20
                            if (randomValue >= 19)
                            {
                                int randomChange = randomGenerator.Next(-2, 3); // i.e. -2, -1, 0, 1, 2 (not 3)
                                if (randomChange != 0)
                                {
                                    Console.WriteLine("Changing workload from {0} -> {1}\n", currentWorkLoad, currentWorkLoad + randomChange);
                                    currentWorkLoad += randomChange;
                                }
                            }
                        }
                        timer              += 1; //tick-tock, each iteration of the loop is 1 second
                        totalCompletions   += currentThreadCount;
                        workLoadForSection -= currentThreadCount;
                        //fprintf(fp, "%d,%d\n", min(currentWorkLoad, currentThreadCount), currentThreadCount);
                        double randomNoise = randomGenerator.NextDouble() / 100.0 * 5; // [0..1) -> [0..0.01) -> [0..0.05)
                        fp.WriteLine("{0},{1},{2}", timer, (Math.Min(currentWorkLoad, currentThreadCount) * (0.95 + randomNoise)).ToString(CultureInfo.InvariantCulture), currentThreadCount);
                        // Calling HillClimbingInstance.Update(..) should ONLY happen when we need more threads, not all the time!!
                        if (currentThreadCount != currentWorkLoad)
                        {
                            // We naively assume that each work items takes 1 second (which is also our loop/timer length)
                            // So in every loop we complete 'currentThreadCount' pieces of work
                            int numCompletions = currentThreadCount;

                            // In win32threadpool.cpp it does the following check before calling Update(..)
                            // if (elapsed*1000.0 >= (ThreadAdjustmentInterval/2)) //
                            // Also 'ThreadAdjustmentInterval' is initially set like so ('INTERNAL_HillClimbing_SampleIntervalLow' = 10):
                            // ThreadAdjustmentInterval = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_HillClimbing_SampleIntervalLow);
                            double sampleDuration = (double)(timer - lastSampleTimer);
                            if (sampleDuration * 1000.0 >= (threadAdjustmentInterval / 2))
                            {
                                newMax = hc.Update(currentThreadCount, sampleDuration, numCompletions, out threadAdjustmentInterval);
                                Console.WriteLine("Mode = {0}, Num Completions = {1} ({2}), New Max = {3} (Old = {4}), threadAdjustmentInterval = {5}",
                                                  mode, numCompletions, totalCompletions, newMax, currentThreadCount, threadAdjustmentInterval);

                                if (newMax > currentThreadCount)
                                {
                                    // Never go beyound what we actually need (plus 1)
                                    int newThreadCount = Math.Min(newMax, currentWorkLoad + 1); // + 1
                                    if (newThreadCount != 0 && newThreadCount > currentThreadCount)
                                    {
                                        // We only ever increase by 1 at a time!
                                        Console.WriteLine("*** INCREASING thread count, from {0} -> {1} (CurrentWorkLoad = {2}, Hill-Climbing New Max = {3})***",
                                                          currentThreadCount, currentThreadCount + 1, currentWorkLoad, newMax);
                                        currentThreadCount += 1;
                                    }
                                    else
                                    {
                                        Console.WriteLine("*** SHOULD HAVE INCREASED thread count, but didn't, newMax = {0}, currentThreadCount = {1}, currentWorkLoad = {2}",
                                                          newMax, currentThreadCount, currentWorkLoad);
                                    }
                                }
                                else if (newMax < (currentThreadCount - 1) && newMax != 0)
                                {
                                    Console.WriteLine("*** DECREASING thread count, from {0} -> {1} (CurrentWorkLoad = {2}, Hill-Climbing New Max = {3})***",
                                                      currentThreadCount, currentThreadCount - 1, currentWorkLoad, newMax);
                                    currentThreadCount -= 1;
                                }

                                priorCompletionCount = totalCompletions;
                                lastSampleTimer      = timer;
                            }
                            else
                            {
                                Console.WriteLine("Sample Duration is too small, current = {0}, needed = {1} (threadAdjustmentInterval = {2})",
                                                  sampleDuration, (threadAdjustmentInterval / 2) / 1000.0, threadAdjustmentInterval);
                            }
                        }
                        else
                        {
                            if (reportedMsgInWorkload == false)
                            {
                                Console.WriteLine("Enough threads to carry out current workload, currentThreadCount = {0}, currentWorkLoad= {1}\n",
                                                  currentThreadCount, currentWorkLoad);
                            }

                            reportedMsgInWorkload = true;
                        }
                    }

                    fp.Flush();
                }
            }
        }
예제 #9
0
        private static void Main()
        {
            Parameters.Verbosity = VerbosityLevels.Normal;
            // this next line is to set the Debug statements from OOOT to the Console.
            Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));

            /* In this example, we first present how the details of an optimzation
             * problem can be saved to an XML-file so that it can be read in
             * and solved as opposed to defining all the details in an imperative
             * (code line by code line) way. In the first function, the xml file
             * name "test1.xml" is created. */
            makeAndSaveProblemDefinition();

            /* now we create a series of different optimization methods and test
             * them on the problem. The problem is now opened from the file and
             * the details are stored in an object of class "Problem Definition".*/
            var stream = new FileStream(filename, FileMode.Open);

            double[] xStar;

            ProblemDefinition probTest1 = ProblemDefinition.OpenprobFromXml(stream);
            abstractOptMethod opty;

            /******************Exhaustive Search ***********************/
            //SearchIO.output("******************Exhaustive Search ***********************");
            //Console.ReadKey();
            //opty = new ExhaustiveSearch(probTest1.SpaceDescriptor, optimize.minimize);
            //opty.Add(probTest1);
            ///* No convergence criteria is needed as the process concludes when all
            // * states have been visited but for this problem that is 4 trillion states.*/
            //opty.ConvergenceMethods.Clear();
            ///* if you DID KNOW the best, you can include a criteria like...*/
            //opty.ConvergenceMethods.Add(new ToKnownBestXConvergence(new[] { 3.0, 3.0 }, 0.0000001));
            //var timer = Stopwatch.StartNew();
            //var fStar = opty.Run(out xStar);

            ///* you probably will never see this process complete. Even with the added
            // * convergence criteria (which is not factored into the estimated time of
            // * completion), you are probably looking at 1 to 2 years. */
            //printResults(opty, xStar, fStar, timer);

            /***********Gradient Based Optimization with Steepest Descent****************/
            //SearchIO.output("***********Gradient Based Optimization with Steepest Descent****************");
            //Console.ReadKey();
            //opty = new GradientBasedOptimization();
            //opty.Add(probTest1);
            //abstractSearchDirection searchDirMethod = new SteepestDescent();
            //opty.Add(searchDirMethod);
            ////abstractLineSearch lineSearchMethod = new ArithmeticMean(0.0001, 1, 100);
            ////abstractLineSearch lineSearchMethod = new DSCPowell(0.0001, 1, 100);
            //abstractLineSearch lineSearchMethod = new GoldenSection(0.0001, 1);
            //opty.Add(lineSearchMethod);
            //opty.Add(new squaredExteriorPenalty(opty, 10));
            ///* since this is not a population-based optimization method, we need to remove the MaxSpan criteria. */
            //opty.ConvergenceMethods.RemoveAll(a => a is MaxSpanInPopulationConvergence);

            //timer = Stopwatch.StartNew();
            //fStar = opty.Run(out xStar);
            //printResults(opty, xStar, fStar, timer);

            ///***********Gradient Based Optimization with Fletcher-Reeves****************/
            //SearchIO.output("***********Gradient Based Optimization with Fletcher-Reeves****************");
            //Console.ReadKey();
            ///* we don't need to reset (invoke the constructor) for GradientBasedOptimization since we are only
            // * change the seaach direction method. */
            //searchDirMethod = new FletcherReevesDirection();
            ///* you could also try the remaining 3 search direction methods. */
            ////searchDirMethod = new CyclicCoordinates();
            ////searchDirMethod = new BFGSDirection();
            ////searchDirMethod = new PowellMethod(0.001, 6);
            //opty.Add(searchDirMethod);

            //timer = Stopwatch.StartNew();
            //opty.ResetFunctionEvaluationDatabase();
            //fStar = opty.Run(out xStar);
            //printResults(opty, xStar, fStar, timer);
            ///******************Generalized Reduced Gradient***********************/
            //SearchIO.output("******************Generalized Reduced Gradient***********************");
            //Console.ReadKey();
            //opty = new GeneralizedReducedGradientActiveSet();
            //opty.Add(probTest1);
            //opty.Add(new squaredExteriorPenalty(opty, 10));
            //opty.ConvergenceMethods.RemoveAll(a => a is MaxSpanInPopulationConvergence);

            //timer = Stopwatch.StartNew();
            //fStar = opty.Run(out xStar);
            //printResults(opty, xStar, fStar, timer);

            /* GRG is the ONLY one here that handles constraints explicity. It find the
             * optimal very quickly and accurately. However, many of the other show a
             * better value of f*, this is because they are using an imperfect penalty
             * function (new squaredExteriorPenalty(opty, 10)). While it seems that GRG
             * includes it as well, it is only used in the the line search method. */


            /******************Random Hill Climbing ***********************/
            probTest1.SpaceDescriptor = new DesignSpaceDescription(new[] { new VariableDescriptor(-5000, 5000, 0.1),
                                                                           new VariableDescriptor(-5000, 5000, 0.1) });
            SearchIO.output("******************Random Hill Climbing ***********************");
            Console.ReadKey();
            opty = new HillClimbing();
            opty.Add(probTest1);
            opty.Add(new squaredExteriorPenalty(opty, 8));
            opty.Add(new RandomNeighborGenerator(probTest1.SpaceDescriptor));
            opty.Add(new KeepSingleBest(optimize.minimize));
            opty.ConvergenceMethods.RemoveAll(a => a is MaxSpanInPopulationConvergence);

            /* the deltaX convergence needs to be removed as well, since RHC will end many iterations
             * at the same point it started. */
            opty.ConvergenceMethods.RemoveAll(a => a is DeltaXConvergence);

            var timer = Stopwatch.StartNew();
            var fStar = opty.Run(out xStar);

            printResults(opty, xStar, fStar, timer);



            /******************Exhaustive Hill Climbing ***********************/
            SearchIO.output("******************Exhaustive Hill Climbing ***********************");
            Console.ReadKey();
            /* Everything else about the Random Hill Climbing stays the same. */
            opty.Add(new ExhaustiveNeighborGenerator(probTest1.SpaceDescriptor));

            timer = Stopwatch.StartNew();
            fStar = opty.Run(out xStar);
            printResults(opty, xStar, fStar, timer);



            /******************Simulated Annealing***********************/
            SearchIO.output("******************Simulated Annealing***********************");
            Console.ReadKey();
            opty = new SimulatedAnnealing(optimize.minimize);
            opty.Add(probTest1);
            opty.Add(new squaredExteriorPenalty(opty, 10));
            opty.Add(new RandomNeighborGenerator(probTest1.SpaceDescriptor, 100));
            opty.Add(new SACoolingSangiovanniVincentelli(100));
            opty.ConvergenceMethods.RemoveAll(a => a is MaxSpanInPopulationConvergence);

            /* the deltaX convergence needs to be removed as well, since RHC will end many iterations
             * at the same point it started. */
            opty.ConvergenceMethods.RemoveAll(a => a is DeltaXConvergence);


            timer = Stopwatch.StartNew();
            fStar = opty.Run(out xStar);
            printResults(opty, xStar, fStar, timer);
        }
예제 #10
0
        /// <summary>
        /// This constructor creates a default network to work with.
        /// </summary>
        /// <param name="aoe2Directory">Directory of your age of empires game.</param>
        /// <param name="aiScript">Name of your ai script that you want to generate.</param>
        public AITrainingModule(string aoe2Directory, string aiScript)
        {
            _logger = Program.Logger;
            _logger.Info("Initializing Training module.");

            _aoe2Directory = aoe2Directory;
            _aiScript      = aiScript;

            _numberOfInitialCycles    = 100000;
            _numberOfContinuousCycles = 10000;
            _numberOfNeuronRefreshes  = 0;

            // Keep track of random number of neurons here.
            int numberOfInputNeurons  = 10;
            int numberOfHiddenNeurons = 10;
            int numberOfOutputNeurons = 8;

            double learningRate = 0.25;

            _errorList = new LinkedList <double>();

            LinearLayer  inputLayer  = new LinearLayer(numberOfInputNeurons);
            SigmoidLayer hiddenLayer = new SigmoidLayer(numberOfHiddenNeurons);
            SigmoidLayer outputLayer = new SigmoidLayer(numberOfOutputNeurons);

            // Wow, how hidden is really hidden. So that I think these connectors do is
            // insert themselves as part of the various layers. This really hides the hidden
            // layer from the network, as only the connectors then modify the hidden layer.
            // In other words "trained".
            var conn1 = new BackpropagationConnector(inputLayer, hiddenLayer);
            var conn2 = new BackpropagationConnector(hiddenLayer, outputLayer);

            _nueralNetwork = new BackpropagationNetwork(inputLayer, outputLayer);
            _nueralNetwork.SetLearningRate(learningRate);
            _nueralNetwork.EndEpochEvent += BackgroundTasks;             // hehe call back methods.

            // Needs to make initial configuration of AI.
            _logger.Warn("Begining initial training cycle...");

            // If this module is being instantiated for the first time, create a comprehensive
            // knowledge base/ network so it can continue where it last left off. Tweak the
            // query to filter outliers.
            _rawMgxStats = StreamUtilities.GetAiDataSet();

            _nueralNetwork.EndEpochEvent +=
                (object networkInput, TrainingEpochEventArgs args) =>
            {
                if (_percent % (_numberOfInitialCycles / 100) == 0 && _percent > 0)
                {
                    _logger.Info(string.Format("Precent completed {0}%", _percent / (_numberOfInitialCycles / 100)));
                }

                _percent++;
            };

            _nueralNetwork.Learn(CompileTrainingSet(_rawMgxStats), _numberOfInitialCycles);
            _logger.Warn("Finished initial training cycle.");

            // Get the latest dataset so we can generate some kind of graph and push the data set to database.
            var knowledgeBase = StreamUtilities.GetLatestAiEntry().ToList();
            var aiTrainingSet = CompileTrainingSet(knowledgeBase);

            _currentStats = knowledgeBase[knowledgeBase.Count - 1];

            // push data, hacked to show simple output
            //double[] veryFirstInput
            //	 =
            //{
            //	0.2,0.2,0.2,0.2,0.2,
            //	0.2,0.2,0.2,0.2,0.2
            //};

            _climber = new HillClimbing(aiTrainingSet[0].InputVector, _nueralNetwork);
            // _climber = new HillClimbing(veryFirstInput, _nueralNetwork);


            // Hardcoding these dimensions
            int ordinalTracker = 1;

            for (int i = 0; i < 4; i++)
            {
                for (int j = i + 1; j < 5; j++)
                {
                    //write normalized data
                    StreamUtilities.SubmitPlotableData(_climber.GenerateTopologyData(i, j), ordinalTracker);

                    //write unnormalized data.
                    StreamUtilities.SubmitPlotableUnnormailizedData(_climber.GenerateUnormalizedTopologyData(i, j), ordinalTracker);
                    _logger.Debug(string.Format("Writing Axis{0} and Axis{1} with ordinal {2}.", i, j, ordinalTracker));
                    ordinalTracker++;
                }
            }

            // If input table == output, then a new game is needed
            if (StreamUtilities.CheckIfNewGameIsNeeded())
            {
                TriggerNewGame();
            }
        }
예제 #11
0
        private void ManipulatorProperties(Manipulator manipulator)
        {
            ImGui.Checkbox($"Show collider", ref manipulator.ShowCollider);
            ImGui.InputFloat3("Goal", ref manipulator.Goal);

            ImGui.Separator();

            if (ImGui.BeginTabBar("ManipulatorTabs"))
            {
                if (ImGui.BeginTabItem("Solver"))
                {
                    int currType = (int)manipulator.Controller.InverseKinematicsSolver.Type;  // TODO: refactor?
                    int newType  = currType;
                    ImGui.Combo("Type", ref newType, InverseKinematicsSolver.Types, InverseKinematicsSolver.Types.Length);

                    // change inverse kinematics solver if queried
                    if (newType != currType)
                    {
                        switch ((InverseKinematicsSolverType)newType)
                        {
                        case InverseKinematicsSolverType.JacobianTranspose:
                            manipulator.Controller.InverseKinematicsSolver = JacobianTranspose.Default();
                            break;

                        case InverseKinematicsSolverType.JacobianPseudoinverse:
                            manipulator.Controller.InverseKinematicsSolver = JacobianPseudoinverse.Default();
                            break;

                        case InverseKinematicsSolverType.DampedLeastSquares:
                            manipulator.Controller.InverseKinematicsSolver = DampedLeastSquares.Default();
                            break;

                        case InverseKinematicsSolverType.HillClimbing:
                            manipulator.Controller.InverseKinematicsSolver = HillClimbing.Default();
                            break;
                        }
                    }

                    ImGui.Separator();

                    // inverse kinematics solver properties
                    ImGui.InputFloat("Threshold", ref manipulator.Controller.InverseKinematicsSolver.Threshold);
                    ImGui.InputInt("Max iterations", ref manipulator.Controller.InverseKinematicsSolver.MaxIterations);

                    if (manipulator.Controller.InverseKinematicsSolver is JacobianTranspose jacobianTranspose)
                    {
                        ImGui.InputFloat("Base damping coefficient", ref jacobianTranspose.Damping);
                    }
                    else if (manipulator.Controller.InverseKinematicsSolver is JacobianPseudoinverse jacobianInverse)
                    {
                        // TODO: input something here?
                    }
                    else if (manipulator.Controller.InverseKinematicsSolver is DampedLeastSquares dampedLeastSquares)
                    {
                        ImGui.InputFloat("Damping coefficient", ref dampedLeastSquares.Damping);
                    }
                    else if (manipulator.Controller.InverseKinematicsSolver is HillClimbing hillClimbing)
                    {
                        ImGui.InputFloat("Max step size", ref hillClimbing.MaxStepSize);
                    }

                    ImGui.EndTabItem();
                }

                if (ImGui.BeginTabItem("Planner"))
                {
                    int currType = (int)manipulator.Controller.PathPlanner.Type;
                    int newType  = currType;
                    ImGui.Combo("Type", ref newType, PathPlanner.Types, PathPlanner.Types.Length);

                    // change path planner if queried
                    if (newType != currType)
                    {
                        switch ((PathPlannerType)newType)
                        {
                        case PathPlannerType.RRT:
                            manipulator.Controller.PathPlanner = RRT.Default();
                            break;

                        case PathPlannerType.ARRT:
                            manipulator.Controller.PathPlanner = ARRT.Default(manipulator);
                            break;

                        case PathPlannerType.GeneticAlgorithm:
                            manipulator.Controller.PathPlanner = GeneticAlgorithm.Default();
                            break;
                        }
                    }

                    ImGui.Separator();

                    // path planner properties
                    ImGui.Checkbox("Collision check", ref manipulator.Controller.PathPlanner.CollisionCheck);
                    ImGui.InputInt("Max iterations", ref manipulator.Controller.PathPlanner.MaxIterations);
                    ImGui.InputFloat("Threshold", ref manipulator.Controller.PathPlanner.Threshold);

                    if (manipulator.Controller.PathPlanner is RRT rrt)
                    {
                        ImGui.Checkbox($"Show tree", ref rrt.ShowTree);
                        ImGui.InputFloat("Step", ref rrt.Step);
                        ImGui.Checkbox("Enable trimming", ref rrt.EnableTrimming);
                        ImGui.InputInt("Trim period", ref rrt.TrimPeriod);

                        if (rrt is ARRT arrt)
                        {
                            ImGui.InputInt("Attractors count", ref arrt.AttractorsCount);
                        }
                        else
                        {
                            ImGui.InputInt("Goal bias period", ref rrt.GoalBiasPeriod);
                        }
                    }
                    else if (manipulator.Controller.PathPlanner is GeneticAlgorithm geneticAlgorithm)
                    {
                        // TODO: add genetic algorithm related properties
                        ImGui.InputInt("Offspring size", ref geneticAlgorithm.OffspringSize);
                        ImGui.InputInt("Survival size", ref geneticAlgorithm.SurvivalSize);
                        ImGui.InputInt("Bezier control points", ref geneticAlgorithm.BezierControlPointsCount);
                        ImGui.InputFloat("Bezier step", ref geneticAlgorithm.BezierStep);
                    }

                    ImGui.EndTabItem();
                }

                if (ImGui.BeginTabItem("Controller"))
                {
                    // TODO: add motion control related properties

                    ImGui.EndTabItem();
                }

                ImGui.EndTabBar();
            }
        }
예제 #12
0
        static void Main(string[] args)
        {
            //State state = new State();

            //Stack<string> inp = new Stack<string>();
            //inp.Push("C");
            //inp.Push("B");
            //inp.Push("D");
            //inp.Push("A");
            //inp.Push("E");

            //Stack<string> goal = new Stack<string>();
            //goal.Push("E");
            //goal.Push("D");
            //goal.Push("C");
            //goal.Push("B");
            //goal.Push("A");

            //var result = state.GetRouteWithHillClimbng(inp, goal);


            List <WorkToDo> workToDos = new List <WorkToDo>()
            {
                new WorkToDo()
                {
                    Name = "A", Complexity = 9
                },
                new WorkToDo()
                {
                    Name = "B", Complexity = 7
                },
                new WorkToDo()
                {
                    Name = "C", Complexity = 16
                },
                new WorkToDo()
                {
                    Name = "D", Complexity = 21
                },
                new WorkToDo()
                {
                    Name = "E", Complexity = 15
                }
            };


            List <WorkerMan> workerMens = new List <WorkerMan>()
            {
                new WorkerMan()
                {
                    Name = "1", Quality = 2, WorkingMinutes = 50
                },
                new WorkerMan()
                {
                    Name = "2", Quality = 1, WorkingMinutes = 30
                },
                new WorkerMan()
                {
                    Name = "3", Quality = 2, WorkingMinutes = 70
                },
                new WorkerMan()
                {
                    Name = "4", Quality = 2, WorkingMinutes = 50
                },
                new WorkerMan()
                {
                    Name = "5", Quality = 3, WorkingMinutes = 70
                },
                new WorkerMan()
                {
                    Name = "6", Quality = 2, WorkingMinutes = 32
                },
                new WorkerMan()
                {
                    Name = "7", Quality = 1, WorkingMinutes = 44
                },
                new WorkerMan()
                {
                    Name = "8", Quality = 1, WorkingMinutes = 90
                }
            };

            // OptimalizationTransform optimalizationTransform = new OptimalizationTransform(workToDos, workerMens, 1000000, 155);
            // var solution = optimalizationTransform.HillClimbing();

            IHillClimbProblem problem  = new HillClimbingProblem(workToDos, workerMens, 100);
            ISolver           solver   = new HillClimbing(problem, 155);
            ISolution         solution = solver.Start();



            IGeneticAlgorithmProblem geneticAlgorithmProblem = new GeneticAlgorithmProblem(workToDos, workerMens, 100);
            ISolver   genSolver   = new GeneticAlgorithm.GeneticAlgorithm(geneticAlgorithmProblem);
            ISolution genSolution = genSolver.Start();

            IParticleSwarmProblem particleSwarmProblem = new ParticleSwarmProblem(workToDos, workerMens, 100, 150);
            ISolver   psSolver = new ParticleSwarmOptimaziation(particleSwarmProblem);
            ISolution psSol    = psSolver.Start();


            Console.ReadLine();
        }