Ejemplo n.º 1
0
        private void SolveMultiple100()
        {
            KnapsackInput input;

            for (int i = 0; i < 100; i++)
            {
                input = new KnapsackInput();
                input.GenerateRandomItems();
                var stopwatch     = new Stopwatch();
                var solverBaB     = new BranchAndBoundSolver(input.Items, input.Capacity);
                var solverRand    = new RandomSolver(input.Items, input.Capacity);
                var solverGreedy  = new GreedySolver(input.Items, input.Capacity);
                var solverDynamic = new DynamicProgrammingSolver(input.Items, input.Capacity);
                stopwatch.Start();
                solverBaB.Solve();
                stopwatch.Stop();
                timeResultsBaB.Add(new DataPoint(i, stopwatch.Elapsed.TotalMilliseconds));
                stopwatch.Restart();
                solverRand.Solve();
                stopwatch.Stop();
                timeResultsRand.Add(new DataPoint(i, stopwatch.Elapsed.TotalMilliseconds));
                stopwatch.Restart();
                solverGreedy.Solve();
                stopwatch.Stop();
                timeResultsGreedy.Add(new DataPoint(i, stopwatch.Elapsed.TotalMilliseconds));
                stopwatch.Restart();
                solverDynamic.Solve();
                stopwatch.Stop();
                timeResultsDynamic.Add(new DataPoint(i, stopwatch.Elapsed.TotalMilliseconds));
            }
            timeAverageGreedy  = Math.Round((timeResultsGreedy.Sum(x => x.Y) / 100), 4);
            timeAverageRand    = Math.Round((timeResultsRand.Sum(x => x.Y) / 100), 4);
            timeAverageBaB     = Math.Round((timeResultsBaB.Sum(x => x.Y) / 100), 4);
            timeAverageDynamic = Math.Round((timeResultsDynamic.Sum(x => x.Y) / 100), 4);
        }
Ejemplo n.º 2
0
        public void run_szenario(int times, String sz, String s)
        {
            int render_every = 5120; //model evaluations

            //n mal laufen lassen für empirische Auswertung
            //(bei den direkten Heuristiken (greedy,insertion,savings nicht nötig, daher n = 1)
            for (int i = 0; i < times; i++)
            {
                //solange ein Prozess läuft mache nichts!
                while (optimizer_running)
                {
                    Thread.Sleep(5000);
                }

                String problemInstance = File.ReadAllText(sz + ".json");
                model = new MEPModel.MEP();
                model.LoadModelString(problemInstance);
                scenario = sz + "_" + s + "_" + i;
                Console.WriteLine("Starting Szenario:" + scenario);
                //setze Kontext
                model.AllowTripContinuation     = true;
                model.PermutateOptions          = false;
                model.AllowUnprofitableRequests = true;
                model.AvgTravelSpeed            = 400;
                model.HotelCostPerNight         = -100;
                model.HourlyWage          = -60;
                model.MilageAllowance     = -0.1;
                model.RevenuePerDayOnsite = 2000;

                Solver.Solver so = null;
                switch (s)
                {
                case "Greedy":
                    so = new GreedySolver(model);
                    break;

                case "SA":
                    so = new SimulatedAnnealingSolver(model, 10000, 1600, render_every, 64);    //somit maximal 10.000*16 = 160.000 modell evaluationen!
                    break;

                case "GA":
                    so = new GeneticSolver(model, 19, 5120, 5, render_every);     //somit maximal 100 * 1.600 = 160.000 modell evaluationen!
                    break;

                case "Insertion":
                    so = new NearestInsertionSolver(model);
                    break;

                case "Savings":
                    so = new SavingsSolver(model);
                    break;
                }
                start = DateTime.Now;
                Start_Optimizer(so);
            }
        }
Ejemplo n.º 3
0
        private void RunGreedyVsNoGreedy()
        {
            var resultsFile = $"{ResultsFolder}greedy_vs_ilp_{DateTime.Now.ToString("yyyy-dd-M-HH-mm-ss")}.csv";

            using (var writer = new StreamWriter(resultsFile))
                using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
                {
                    csv.WriteHeader(typeof(GreedyVsILPResult));
                    csv.NextRecord();
                }

            for (int i = 1; i <= NumberOfInstances; i++)
            {
                using (var stream = File.Open(resultsFile, FileMode.Append))
                    using (var writer = new StreamWriter(stream))
                        using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
                        {
                            csv.Configuration.HasHeaderRecord = false;

                            var instanceFile = $"{InstancesFolder}/Exact{i}.txt";
                            var configFile   = $"{ConfigsFolder}tune_Exact{i}_0.prm";

                            var cinemaILP    = CinemaReader.Read(instanceFile);
                            var cinemaGreedy = CinemaReader.Read(instanceFile);;

                            var solverILP = new ILPSolver(cinemaILP);
                            var timesILP  = solverILP.Solve(false, Options.Debug, paramFile: configFile);

                            var greedySolver = new GreedySolver(cinemaGreedy);
                            var timesGreedy  = greedySolver.Solve();

                            var result = new GreedyVsILPResult
                            {
                                InstanceFile        = instanceFile,
                                ConfigFile          = configFile,
                                TotalNumberOfGroups = cinemaILP.TotalNumberOfGroups,
                                TotalNumberOfPeople = cinemaILP.TotalNumberOfPeople,

                                ILPTime    = timesILP["Total"],
                                GreedyTime = timesGreedy["Total"],

                                SeatedGreedy = cinemaGreedy.CountSeated(),
                                SeatedILP    = cinemaILP.CountSeated(),

                                ValidGreedy = cinemaGreedy.Verify(),
                                ValidILP    = cinemaILP.Verify(),

                                Capacity = cinemaGreedy.InitialCapacity
                            };

                            csv.WriteRecord(result);
                            csv.NextRecord();
                        }
            }
        }
        public ActionResult MatrixGenerated(DataMatrix problem2, [FromQuery] string myMethod = null)
        {
            bool sym     = true;
            var  problem = problem2;

            for (int i = 0; i < problem.Dimension; i++)
            {
                for (int j = 0; j < problem.Dimension; j++)
                {
                    if (problem.Distances[i][j] != problem.Distances[j][i])
                    {
                        sym = false;
                    }
                }
            }
            for (int i = 0; i < problem.Dimension; i++)
            {
                for (int j = 0; j < problem.Dimension; j++)
                {
                    if (problem.Flows[i][j] != problem.Flows[j][i])
                    {
                        sym = false;
                    }
                }
            }
            if (sym != true)
            {
                return(RedirectToAction("Report"));
            }

            if (myMethod == "Greedy")
            {
                SolutionMatrix solution = new SolutionMatrix();
                solution.SolutionArray = new int[problem.Flows.Count()];
                var greedySolver = new GreedySolver(problem);
                solution = greedySolver.GetSolution();
                return(RedirectToAction("GreedySolutionGenerated", solution));
            }
            else if (myMethod == "Steepest")
            {
                SolutionMatrix solution = new SolutionMatrix();
                solution.SolutionArray = new int[problem.Flows.Count()];
                var steepestSolver = new SteepestSolver(problem);
                solution.SolutionArray = steepestSolver.GetSolution().SolutionArray;
                solution.Score         = steepestSolver.GetSolution().Score;
                return(RedirectToAction("SteepestSolutionGenerated", solution));
            }
            else
            {
                return(View(problem));
            }
        }
Ejemplo n.º 5
0
        private void btnRunAsync_Click(object sender, RoutedEventArgs e)
        {
            output_to_file = false;
            tokensource    = new CancellationTokenSource();
            if (model != null && model.Requests.Count > 0)
            {
                btnRunAsync.IsEnabled = false;
                set_model_parameter();
                //clear optimizer Output:
                txtOptimizerOutput.Text = "";

                Solver.Solver s = null;
                if (rbGeneticAlgorithm.IsChecked == true)
                {
                    s = new GeneticSolver(model, Convert.ToInt32(txtGenerations.Text), Convert.ToInt32(txtPopulationSize.Text), Convert.ToInt32(txtMutationProbability.Text), Convert.ToInt32(txtReportProgress.Text));
                }
                if (rbBruteForce.IsChecked == true)
                {
                    if (model.GetNumberOfElements() > 11)
                    {
                        MessageBox.Show("I´m sorry Dave, I`m afraid I can`t do that!");
                    }
                    else
                    {
                        s = new BruteForceSolver(model);
                    }
                }
                if (rbSimulatedAnnealing.IsChecked == true)
                {
                    s = new SimulatedAnnealingSolver(model, Convert.ToInt32(txtStartTemp.Text), Convert.ToInt32(txtSteps.Text), Convert.ToInt32(txtReportProgress.Text), Convert.ToInt32(txtParallelAnnealings.Text));
                }
                if (rbGreedy.IsChecked == true)
                {
                    s = new GreedySolver(model);
                }
                if (rbInsertion.IsChecked == true)
                {
                    s = new NearestInsertionSolver(model);
                }
                if (rbSavings.IsChecked == true)
                {
                    s = new SavingsSolver(model);
                }

                if (s != null)
                {
                    Start_Optimizer(s);
                }
            }
        }
Ejemplo n.º 6
0
 private void Greedy_Click(object sender, RoutedEventArgs e)
 {
     if (input == null)
     {
         MessageBox.Show("You should choose data first", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
     }
     else
     {
         var stopwatch = new Stopwatch();
         var solver    = new GreedySolver(input.Items, input.Capacity);
         stopwatch.Start();
         var solution = solver.Solve();
         stopwatch.Stop();
         itemsGrid.DataContext    = solution.Items;
         allItemsGrid.DataContext = input.Items;
         resultTextBlock.Text     = "Capacity: " + solution.Capacity + ". Total value = " + solution.Value + ". Total weight = "
                                    + solution.TotalWeight + "." + " Time: " + stopwatch.Elapsed;
     }
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Processes a TSP and reports errors.
        /// </summary>
        /// <param name="file">File name of TSP being processed.</param>
        private void ProcessTsp(string file)
        {
            System.Diagnostics.Debug.WriteLine($"Loading TSP at path {file} ...\n");

            // Try convert text to TSP
            var success = Interface.TryTextToTsp(file, out var tsp);

            // If conversion was a success
            if (success)
            {
                // Print TSP info to debug console
                tsp.Print();

                // Update name of problem on graph
                this.problemName.Text = tsp.Name;

                // Create solver and event handlers
                Solver solver = null;
                ProgressChangedEventHandler    updateHandler     = null;
                RunWorkerCompletedEventHandler completionHandler = null;
                int drawDelay = 0;

                // Set solvers and event handlers based on the chosen setting
                if (bruteForceRadioButton.IsChecked == true)
                {
                    solver = new BruteForceSolver();

                    MessageBox.Show("Solution method not yet implemented after refactoring.");
                    return;
                }
                else if (bfsRadioButton.IsChecked == true || dfsRadioButton.IsChecked == true)
                {
                    var goal = Convert.ToInt32(searchGoal.Text);

                    if (bfsRadioButton.IsChecked == true)
                    {
                        solver = new BfsSolver();
                    }
                    else
                    {
                        solver = new DfsSolver();
                    }

                    MessageBox.Show("Solution method not yet implemented after refactoring.");
                    return;
                }
                else if (greedyRadioButton.IsChecked == true)
                {
                    solver            = new GreedySolver();
                    updateHandler     = GreedyProgressChanged;
                    completionHandler = GreedyCompletion;
                    drawDelay         = GREEDY_DRAW_DELAY;
                }
                else if (geneticRadioButton.IsChecked == true)
                {
                    solver            = new GeneticSolver();
                    updateHandler     = GeneticProgressChanged;
                    completionHandler = GreedyCompletion;
                    drawDelay         = GREEDY_DRAW_DELAY;
                }
                else
                {
                    MessageBox.Show("No solution method was selected.");
                    return;
                }

                if (progressCheckBox.IsChecked == true)
                {
                    // Update continously
                    solver.ProgressChanged += updateHandler;
                }
                else
                {
                    // Update only at the end
                    solver.RunWorkerCompleted += completionHandler;
                }

                var workerArgs = new Tuple <Tsp, int>(tsp, progressCheckBox.IsChecked == true ? drawDelay : 0);

                // Run solver and draw output
                solver.RunWorkerAsync(workerArgs);
            }
            // If conversion failed
            else
            {
                MessageBox.Show($"Could not convert TSP from text file: \n\n{file}");
            }
        }
Ejemplo n.º 8
0
        public ActionResult DataFile(IFormFile postedFile, [FromQuery] string myMethod = null)
        {
            _ = this.Environment.WebRootPath;
            _ = this.Environment.ContentRootPath;

            string path = Path.Combine(this.Environment.WebRootPath, "UploadedFiles");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string fileName = Path.GetFileName(postedFile.FileName);


            var problem = new DataMatrix();

            using (var sr = new StreamReader(System.IO.File.OpenRead(Path.Combine(path, fileName))))
            {
                string data     = sr.ReadToEnd();
                var    splitted = data.Split((char[])null, StringSplitOptions.RemoveEmptyEntries)
                                  .ToList()
                                  .Select(x => Convert.ToInt32(x))
                                  .ToList();

                int matrixSize = splitted[0];
                problem.Dimension = matrixSize;
                if (problem.Dimension != 0)
                {
                    problem.Distances = new int[problem.Dimension][];
                    for (int i = 0; i < problem.Dimension; i++)
                    {
                        problem.Distances[i] = new int[problem.Dimension];
                    }
                    problem.Flows = new int[problem.Dimension][];
                    for (int i = 0; i < problem.Dimension; i++)
                    {
                        problem.Flows[i] = new int[problem.Dimension];
                    }
                }
                var qapDataFlow     = new int[matrixSize][];
                var qapDataDistance = new int[matrixSize][];

                var chunked = splitted.Skip(1).Chunk(matrixSize).ToList();

                for (int i = 0; i < matrixSize; ++i)
                {
                    problem.Distances[i] = chunked[i].ToArray();
                }

                for (int i = matrixSize; i < 2 * matrixSize; ++i)
                {
                    problem.Flows[i - matrixSize] = chunked[i].ToArray();
                }
            }
            bool sym = true;

            for (int i = 0; i < problem.Dimension; i++)
            {
                for (int j = 0; j < problem.Dimension; j++)
                {
                    if (problem.Distances[i][j] != problem.Distances[j][i])
                    {
                        sym = false;
                    }
                }
            }
            for (int i = 0; i < problem.Dimension; i++)
            {
                for (int j = 0; j < problem.Dimension; j++)
                {
                    if (problem.Flows[i][j] != problem.Flows[j][i])
                    {
                        sym = false;
                    }
                }
            }
            if (sym != true)
            {
                return(RedirectToAction("Report"));
            }

            var problemResult = new DataMatrix()
            {
                Dimension = problem.Dimension,
                Distances = problem.Distances,
                Flows     = problem.Flows
            };

            if (myMethod == "Greedy")
            {
                SolutionMatrix solution = new SolutionMatrix();
                solution.SolutionArray = new int[problem.Flows.Count()];
                var greedySolver = new GreedySolver(problem);
                solution = greedySolver.GetSolution();
                return(RedirectToAction("GreedySolutionFile", solution));
            }
            else if (myMethod == "Steepest")
            {
                SolutionMatrix solution = new SolutionMatrix();
                solution.SolutionArray = new int[problem.Flows.Count()];
                var steepestSolver = new SteepestSolver(problem);
                solution.SolutionArray = steepestSolver.GetSolution().SolutionArray;
                solution.Score         = steepestSolver.GetSolution().Score;
                return(RedirectToAction("SteepestSolutionFile", solution));
            }
            else
            {
                return(View());
            }
        }
Ejemplo n.º 9
0
        private void RunTryGreedyFirst()
        {
            var resultsFile = $"{ResultsFolder}greedy_first_{DateTime.Now.ToString("yyyy-dd-M-HH-mm-ss")}.csv";

            using (var writer = new StreamWriter(resultsFile))
                using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
                {
                    csv.WriteHeader(typeof(TryGreedyFirstResult));
                    csv.NextRecord();
                }

            for (int i = 1; i <= NumberOfInstances; i++)
            {
                using (var stream = File.Open(resultsFile, FileMode.Append))
                    using (var writer = new StreamWriter(stream))
                        using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
                        {
                            csv.Configuration.HasHeaderRecord = false;

                            var instanceFile = $"{InstancesFolder}/Exact{i}.txt";
                            var configFile   = $"{ConfigsFolder}tune_Exact{i}_0.prm";

                            var cinema = CinemaReader.Read(instanceFile);

                            var greedyCinema = CinemaReader.Read(instanceFile);
                            var greedySolver = new GreedySolver(greedyCinema);

                            var totalTime = Utils.TimeAction(() =>
                            {
                                var times = greedySolver.Solve();

                                if (cinema.TotalNumberOfPeople != greedyCinema.CountSeated())
                                {
                                    var ilpCinema = CinemaReader.Read(instanceFile);
                                    var ilpSolver = new ILPSolver(ilpCinema);

                                    times = ilpSolver.Solve(Options.Tune, Options.Debug, Options.TuneOutputFile, configFile);

                                    cinema = ilpCinema;
                                }
                                else
                                {
                                    cinema = greedyCinema;
                                }
                            }, "Time");

                            var result = new TryGreedyFirstResult
                            {
                                InstanceFile = instanceFile,
                                ConfigFile   = configFile,

                                TotalNumberOfGroups = cinema.TotalNumberOfGroups,
                                TotalNumberOfPeople = cinema.TotalNumberOfPeople,

                                TotalTime = totalTime,

                                Seated   = cinema.CountSeated(),
                                Valid    = cinema.Verify(),
                                Capacity = cinema.InitialCapacity
                            };

                            csv.WriteRecord(result);
                            csv.NextRecord();
                        }
            }
        }
Ejemplo n.º 10
0
        public void Run()
        {
            var totalTime = Utils.TimeAction(() =>
            {
                var cinema = CinemaReader.Read(Options.InstanceConfig.InstanceFile);
                Dictionary <string, string> times = new Dictionary <string, string>();

                Console.WriteLine("Solving: " + Options.InstanceConfig.InstanceFile);
                Console.WriteLine(cinema);

                if (Options.GreedyOnly)
                {
                    var solver = new GreedySolver(cinema);

                    if (Options.Debug)
                    {
                        Console.WriteLine("Solving via Greedy only");
                    }

                    times = solver.Solve();
                }
                else if (Options.ILPOnly)
                {
                    var solver = new ILPSolver(cinema);

                    if (Options.Debug)
                    {
                        Console.WriteLine("Solving via ILP only");
                    }

                    times = solver.Solve(Options.Tune, Options.Debug, Options.TuneOutputFile, Options.InstanceConfig.ConfigFile);
                }
                else
                {
                    if (Options.Debug)
                    {
                        Console.WriteLine("Solving via both");
                    }

                    var greedyCinema = CinemaReader.Read(Options.InstanceConfig.InstanceFile);
                    var greedySolver = new GreedySolver(greedyCinema);

                    times = greedySolver.Solve();

                    if (cinema.TotalNumberOfPeople != greedyCinema.CountSeated())
                    {
                        var ilpCinema = CinemaReader.Read(Options.InstanceConfig.InstanceFile);
                        var ilpSolver = new ILPSolver(ilpCinema);

                        times = ilpSolver.Solve(Options.Tune, Options.Debug, Options.TuneOutputFile, Options.InstanceConfig.ConfigFile);

                        cinema = ilpCinema;
                    }
                    else
                    {
                        cinema = greedyCinema;
                    }
                }

                Console.WriteLine(cinema);
                Console.WriteLine("People seated:" + cinema.CountSeated() + " out of " + cinema.TotalNumberOfPeople);
                Console.WriteLine($"Valid cinema:{cinema.Verify()}");
            }, "Time");

            Console.WriteLine($"Total Solving Time: {totalTime}");
        }