Пример #1
0
 public Pseudocodigo(IIndividuoFactory inFactory, int inTamanioPoblacion)
 {
     this.poblacion        = new List <Individuo>();
     this.factory          = inFactory;
     this.tamanioPoblacion = inTamanioPoblacion;
     busquedaTabu          = new TabuSearch();
 }
Пример #2
0
        static void Main(string[] args)
        {
            var      dataSource = Config.GetDataSource();
            var      dataset    = new DataPreparer(dataSource).GetCustomerAndVehicleData();
            Solution solution   = new Solution();

            switch (Config.GetSolverType())
            {
            case "GurobiSolver":
                solution = new GSolver(dataset).Run();
                break;

            case "BendersSolver":
                solution = new BSolver(dataset).Run();
                break;

            case "IterativeLocalSearch":
                solution = new IterativeLocalSearch(dataset).Run();
                break;

            case "TabuSearch":
                solution = new TabuSearch(dataset).Run();
                break;
            }

            var outputPathString = Config.GetFileOperation().OutputPath +
                                   Config.GetFileOperation().OutputName;

            using StreamWriter file = File.CreateText(outputPathString);
            JsonSerializer serializer = new JsonSerializer();

            serializer.Serialize(file, solution);
        }
Пример #3
0
        /// <summary>
        /// Metoda wykonuje testy zależności czasowej
        /// </summary>
        /// <param name="cities"></param>
        /// <param name="timestamp"></param>
        /// <param name="maxNumberOfIterations"></param>
        /// <param name="numberOfTrials"></param>
        /// <param name="path"></param>
        public static void RunTimeTest(Cities cities, int timestamp, int maxNumberOfIterations, int numberOfTrials, string path)
        {
            string output        = "|ZALEŻNOŚĆ CZASOWA|" + Environment.NewLine,
                   elapsedTime   = "",
                   relativeError = "";

            int tempDistance,
                bestDistance = cities.BestDistance;

            Stopwatch stopWatch = new Stopwatch();

            for (int i = 0; i <= numberOfTrials; i++)
            {
                Console.WriteLine("Próba: " + i.ToString());

                stopWatch.Start();
                /////          DO DOBRANIA + wyłącz wyświetlanie wyniku
                tempDistance = Int32.Parse(TabuSearch.RunAlgorithm(cities.AdjacencyMatrix, timestamp, maxNumberOfIterations));
                stopWatch.Stop();

                if (i != 0)
                {
                    relativeError = ((tempDistance - bestDistance) / bestDistance).ToString();
                    elapsedTime   = stopWatch.Elapsed.TotalMilliseconds.ToString();
                    output       += cities.AdjacencyMatrix.GetLength(0).ToString() + ";" + elapsedTime + ";" + relativeError + Environment.NewLine;
                }

                stopWatch.Reset();
            }
            WriteOutputToFile(path, output);
        }
Пример #4
0
        static void Main(string[] args)
        {
            TabuSearch busqueda = new TabuSearch();

            //Problema del Flow Shop
            //CIUDADES
            //        Individual seed = new IndividualViajeroProblem();
            //        IndividualViajeroProblem best = (IndividualViajeroProblem) busqueda.tabuSearch(configuracion, seed);
            int[,] mat =
            {
                { 5, 5, 3, 6, 3,  3 },
                { 4, 4, 2, 4, 4,  1 },
                { 4, 4, 2, 4, 1,  3 },
                { 3, 6, 3, 2, 5, 10 },
                { 3, 6, 3, 2, 5,  1 }
            };
            int[]      vec  = { 2, 3, 4, 5, 1, 0 };
            Individual seed = new IndividuoMaquinas(mat, vec);

            Console.Write("Evaluación: " + seed.getEvaluacion() + "   Individuo: " + seed.ToString());
            IndividuoMaquinas best = (IndividuoMaquinas)busqueda.tabuSearch(seed);

            Console.Write("Evaluación: " + best.getEvaluacion() + "   Individuo: " + best.GetToString());
            Console.ReadKey();
        }
Пример #5
0
        public Individuo empezar()
        {
            inicializarPoblacion();
            ordenarPoblacion();
            Console.WriteLine("**************Mejor individuo en la primera vuelta: "
                              + poblacion[0] + "Evaluacion: " + poblacion[0].Fitness);
            int i = 1000;
            //poblacion[0]
            Random r = new Random();

            while (i > 0)
            {
                busquedaTabu = new TabuSearch();
                Individuo hijo
                    = cruce(poblacion[0],
                            poblacion[r.Next(tamanioPoblacion)]);
                hijo = (Individuo)busquedaTabu.tabuSearch(hijo);
                poblacion.Add(hijo);
                ordenarPoblacion();
                Console.WriteLine($"Gen: #{i} - " +
                                  $"Eval: {poblacion[0].Fitness}");
                i--;
            }
            return(poblacion[0]);
        }
Пример #6
0
        static void Main(string[] args)
        {
            IntelligentRandom      intelligentRandom = new IntelligentRandom();
            BasicFitnessCalculator basicCalculator   = new BasicFitnessCalculator();

            var simulatedAnnealing = new SimulatedAnnealing();

            simulatedAnnealing.Simulate(
                startTemperature: 10000,
                boardSize: 10,
                generator: intelligentRandom,
                calculator: basicCalculator
                );
            Console.WriteLine(simulatedAnnealing.Result);

            var tabuSearch = new TabuSearch();

            tabuSearch.Simulate(
                maxTabuListCount: 1500,
                boardSize: 10,
                generator: intelligentRandom,
                calculator: basicCalculator
                );
            Console.WriteLine(tabuSearch.Result);
        }
Пример #7
0
        public static void allMIT(RcpspSolver solve)
        {
            solve.generateAllPossiblePartation();
            string comb1 = "(1,2,5)";
            string comb2 = "(4)";
            string comb3 = "(3)";

            solve.EveryCombBestProj[comb1] = RcpspSolver.calCombBestScoreByTabuSearch(comb1, solve.EveryComb[comb1], true);
            solve.EveryCombBestProj[comb2] = RcpspSolver.calCombBestScoreByTabuSearch(comb2, solve.EveryComb[comb2], true);
            solve.EveryCombBestProj[comb3] = RcpspSolver.calCombBestScoreByTabuSearch(comb3, solve.EveryComb[comb3], true);
            foreach (string str in solve.EveryCombBestProj.Keys)
            {
                RcspspProject proj = solve.EveryCombBestProj[str];
                Console.WriteLine("comb core " + str + "is " + proj.BestSocre + " and list is : ");
                Console.Write("             ");
                foreach (RcpspJob job in proj.Jobs)
                {
                    Console.Write("(" + job.id + "__" + job.project + "__" + job.duration + ")");
                }
                Console.WriteLine();
            }
            List <List <RcspspProject> > projectPartition = new List <List <RcspspProject> >();

            projectPartition.Add(solve.EveryComb[comb1]);
            projectPartition.Add(solve.EveryComb[comb2]);
            projectPartition.Add(solve.EveryComb[comb3]);
            RcspspProject bestproj = RcpspSolver.calPartitionBestScoreByTabuSearch(projectPartition, solve.EveryCombBestProj, true);

            Console.WriteLine("best core is " + bestproj.BestSocre + " and partition is " + bestproj.BestCombStr);
            foreach (RcpspJob job in bestproj.Jobs)
            {
                //Console.Write("[" + job.id + "__" + job.project + "__" + job.startTime+"__"+job.duration + "]");
                if (job.isWX)
                {
                    RcspspProject wxProject = solve.EveryCombBestProj[job.project];
                    foreach (RcpspJob wxJob in wxProject.Jobs)
                    {
                        addJob2Dic(solve.ProjectList, wxJob, job.startTime);
                    }
                }
                else
                {
                    addJob2Dic(solve.ProjectList, job);
                }
            }
            //TabuSearch.printGUI(bestproj.Jobs);
            Console.WriteLine("total time is " + TabuSearch.calScheduleCore(bestproj.Jobs, false));
            foreach (RcspspProject proj in solve.ProjectList)
            {
                Console.WriteLine("Project " + proj.ProjectId);
                foreach (RcpspJob projJob in proj.Jobs)
                {
                    Console.WriteLine(projJob.id + "\t" + projJob.startTime + "\t" + (projJob.startTime + projJob.duration));
                }
            }
        }
Пример #8
0
        /// <summary>
        /// Create the concrete instance of the Algorithm with a specified Neighborhood as parameter.
        /// </summary>
        /// <param name="currentAlgorithm"> Algorithm type to create. </param>
        /// <param name="neighborhood"> Neighborhood type to pass to the Algorithm. </param>
        /// <returns> The Algorithm's instance to run. </returns>
        internal static Algorithm CreateAlgorithm(AlgorithmType algorithmType, Neighborhood <ToSolution> neighborhood)
        {
            Algorithm algorithm = default;

            switch (algorithmType)
            {
            case AlgorithmType.None:
                break;

            case AlgorithmType.NearestNeighbor:
                algorithm = new NearestNeighbor();
                break;

            case AlgorithmType.NearestNeighborKnapsack:
                algorithm = new NearestNeighborKnapsack();
                break;

            case AlgorithmType.CheapestInsertion:
                algorithm = new CheapestInsertion();
                break;

            case AlgorithmType.TwoOpt:
                if (neighborhood == null)
                {
                    neighborhood = NeighborhoodFactory.CreateNeighborhood(algorithmType);
                }
                algorithm = new LocalSearchTemplate(neighborhood);
                break;

            case AlgorithmType.LinKernighan:
                algorithm = new LinKernighan();
                break;

            case AlgorithmType.HybridCustomInsertion:
                algorithm = new HybridCustomInsertion();
                break;

            case AlgorithmType.HybridCustomUpdate:
                algorithm = new HybridCustomUpdate();
                break;

            case AlgorithmType.TabuSearch:
                if (neighborhood == null)
                {
                    neighborhood = NeighborhoodFactory.CreateNeighborhood(algorithmType);
                }
                algorithm = new TabuSearch(neighborhood);
                break;

            // Add new Algorithm types here ...
            default:
                throw new ArgumentOutOfRangeException(nameof(algorithmType), algorithmType, null);
            }
            return(algorithm);
        }
Пример #9
0
        public void SetUp()
        {
            this.neighbourFinderMock    = new Mock <INeighbourFinder>();
            this.tabuListMock           = new Mock <ITabuList>();
            this.longTermMemoryMock     = new Mock <ILongTermMemory>();
            this.costFinderMock         = new Mock <ICostFinder>();
            this.aspirationCriteriaMock = new Mock <IAspirationCriteria>();
            this.stopCriteriaMock       = new Mock <IStopCriteria>();

            tabuSearch = new TabuSearch(this.neighbourFinderMock.Object, this.tabuListMock.Object, this.longTermMemoryMock.Object, this.costFinderMock.Object, this.aspirationCriteriaMock.Object, this.stopCriteriaMock.Object, this.stopCriteriaMock.Object, this.stopCriteriaMock.Object);
        }
Пример #10
0
        /// <summary>
        /// Funkcja wykonująca test - badanie przebiegu algorytmu w zależności od czasu
        /// </summary>
        /// <param name="cities"></param>
        /// <param name="path"></param>
        public static void RunImprovementByTimeTest(Cities cities, string path)
        {
            StringBuilder algorithmResultsSB = new StringBuilder();

            algorithmResultsSB.Append("|BADANIE PRZEBIEGU ALGORYTMU W ZALEŻNOŚCI OD CZASU|" + Environment.NewLine);
            LinkedList <Pair <int, int> > algorithmResults = TabuSearch.AnalyzeAlgorithm(cities.AdjacencyMatrix, 120000);

            foreach (var result in algorithmResults)
            {
                algorithmResultsSB.Append(result.First + ";" + result.Second + Environment.NewLine);
            }
            WriteOutputToFile(path, algorithmResultsSB.ToString());
        }
Пример #11
0
        public void Test3()
        {
            _factory = new IIndividuoFactory_Universidad();

            TabuSearch busqueda = new TabuSearch();

            Pseudocodigo memetico = new Pseudocodigo(_factory, 10);

            var m = memetico.empezar();

            Console.WriteLine(m);

            Console.ReadKey();
        }
Пример #12
0
        private TabuSearch CreateTabuSearchTspSample()
        {
            TabuSearch ts = new TabuSearch();

            #region Problem Configuration
            var provider = new TSPLIBTSPInstanceProvider();
            var instance = provider.GetDataDescriptors().Where(x => x.Name == "ch130").Single();
            TravelingSalesmanProblem tspProblem = new TravelingSalesmanProblem();
            tspProblem.Load(provider.LoadData(instance));
            tspProblem.UseDistanceMatrix.Value = true;
            #endregion
            #region Algorithm Configuration
            ts.Name        = "Tabu Search - TSP";
            ts.Description = "A tabu search algorithm that solves the \"ch130\" TSP (imported from TSPLIB)";
            ts.Problem     = tspProblem;

            ts.MaximumIterations.Value = 1000;
            // move generator has to be set first
            var moveGenerator = ts.MoveGeneratorParameter.ValidValues
                                .OfType <StochasticInversionMultiMoveGenerator>()
                                .Single();
            ts.MoveGenerator = moveGenerator;
            var moveEvaluator = ts.MoveEvaluatorParameter.ValidValues
                                .OfType <TSPInversionMoveRoundedEuclideanPathEvaluator>()
                                .Single();
            ts.MoveEvaluator = moveEvaluator;
            var moveMaker = ts.MoveMakerParameter.ValidValues
                            .OfType <InversionMoveMaker>()
                            .Single();
            ts.MoveMaker             = moveMaker;
            ts.SampleSize.Value      = 750;
            ts.Seed.Value            = 0;
            ts.SetSeedRandomly.Value = true;

            var tabuChecker = ts.TabuCheckerParameter.ValidValues
                              .OfType <InversionMoveSoftTabuCriterion>()
                              .Single();
            tabuChecker.UseAspirationCriterion.Value = true;
            ts.TabuChecker = tabuChecker;

            var tabuMaker = ts.TabuMakerParameter.ValidValues
                            .OfType <InversionMoveTabuMaker>()
                            .Single();
            ts.TabuMaker        = tabuMaker;
            ts.TabuTenure.Value = 60;

            #endregion
            ts.Engine = new ParallelEngine.ParallelEngine();
            return(ts);
        }
Пример #13
0
        private TabuSearch CreateTabuSearchVrpSample()
        {
            TabuSearch ts = new TabuSearch();

            #region Problem Configuration
            var provider = new AugeratInstanceProvider();
            var instance = provider.GetDataDescriptors().Where(x => x.Name == "A-n62-k8").Single();
            VehicleRoutingProblem vrpProblem = new VehicleRoutingProblem();
            vrpProblem.Load(provider.LoadData(instance));
            #endregion
            #region Algorithm Configuration
            ts.Name        = "Tabu Search - VRP";
            ts.Description = "A tabu search algorithm that solves the \"A-n62-k8\" VRP (imported from Augerat)";
            ts.Problem     = vrpProblem;

            ts.MaximumIterations.Value = 200;
            // move generator has to be set first
            var moveGenerator = ts.MoveGeneratorParameter.ValidValues
                                .OfType <PotvinCustomerRelocationExhaustiveMoveGenerator>()
                                .Single();
            ts.MoveGenerator = moveGenerator;
            var moveEvaluator = ts.MoveEvaluatorParameter.ValidValues
                                .OfType <PotvinCustomerRelocationMoveEvaluator>()
                                .Single();
            ts.MoveEvaluator = moveEvaluator;
            var moveMaker = ts.MoveMakerParameter.ValidValues
                            .OfType <PotvinCustomerRelocationMoveMaker>()
                            .Single();
            ts.MoveMaker             = moveMaker;
            ts.SampleSize.Value      = 1000;
            ts.Seed.Value            = 0;
            ts.SetSeedRandomly.Value = true;

            var tabuChecker = ts.TabuCheckerParameter.ValidValues
                              .OfType <PotvinCustomerRelocationMoveTabuCriterion>()
                              .Single();
            tabuChecker.UseAspirationCriterion.Value = false;
            ts.TabuChecker = tabuChecker;

            var tabuMaker = ts.TabuMakerParameter.ValidValues
                            .OfType <PotvinCustomerRelocationMoveTabuMaker>()
                            .Single();
            ts.TabuMaker        = tabuMaker;
            ts.TabuTenure.Value = 6;

            #endregion
            ts.Engine = new ParallelEngine.ParallelEngine();
            return(ts);
        }
Пример #14
0
        public void TabuTest1()
        {
            file = root + "\\bays29.xml";

            XDocument       tspFile    = XDocument.Load(file);
            AdjacencyMatrix testMatrix = new AdjacencyMatrix(tspFile);
            TabuSearch      test       = new TabuSearch(testMatrix, 10000, 3);



            test = new TabuSearch(testMatrix, 10000, 8);
            test.Solve();
            float Result7 = test.lowestCost;
            float errRat7 = (Result7 - 2020) / 2020;
        }
Пример #15
0
        public static void Main(string[] args)
        {
            Utils.Parse.CSV <Category>(FILE_CATEGORY);
            Utils.Parse.CSV <Location>(FILE_LOCATION);
            Distances.Parse(FILE_DISTANCES);

            GRASP GRASP = new GRASP(Location.Instance("Plaza del Adelantado"));
            SimulatedAnnealing         SA  = new SimulatedAnnealing(50, .05, Location.Instance("Plaza del Adelantado"));
            TabuSearch                 TS  = new TabuSearch(7, Location.Instance("Plaza del Adelantado"));
            VariableNeighborhoodSearch VNS = new VariableNeighborhoodSearch(5, Location.Instance("Plaza del Adelantado"));

            Console.WriteLine("GRASP:");
            Run(GRASP, 20);
            Console.WriteLine("\nSA:");
            //Run(SA, 20);
            Console.WriteLine("\nTS:");
            Run(TS, 20);
            //Console.WriteLine("\nVNS:");
            //Run(VNS, 20);
        }
Пример #16
0
        /// <summary>
        /// Metoda odpowiedzialna za uruchomienie testów z zadanymi parametrami
        /// </summary>
        /// <param name="cities"></param> Obiekt reprezentujący dany przypadek TSP
        /// <param name="timestamp"></param> Pojemność tabu
        /// <param name="maxNumberOfIterations"></param> Maksymalna liczba iteracji
        /// <param name="numberOfTrials"></param> Liczba prób
        /// <param name="path"></param> Ścieżka dla danych wyjściowych
        public static void RunTimestampTest(Cities cities, int timestamp, int maxNumberOfIterations, int numberOfTrials, string path)
        {
            string output        = "|ZALEŻNOŚĆ OD TIMESTAMP|" + Environment.NewLine,
                   relativeError = "";
            float bestDistance   = (float)cities.BestDistance,
                  tempDistance;

            for (int i = 0; i <= numberOfTrials; i++)
            {
                Console.WriteLine("Próba: " + i.ToString());
                //Ilosc iteracji do dobrania
                tempDistance = float.Parse(TabuSearch.RunAlgorithm(cities.AdjacencyMatrix, timestamp, maxNumberOfIterations));

                if (i != 0)
                {
                    relativeError = (((tempDistance - bestDistance) / bestDistance) * 100.0f).ToString();
                    output       += relativeError + Environment.NewLine;
                }
            }
            WriteOutputToFile(path, output);
        }
Пример #17
0
        static void Main(string[] args)
        {
            #region Parametry poczatkowe
            int liczbaIteracji          = 5000;
            int nrInstancji             = 1;
            int liczbaBadanychInstancji = 20;
            #endregion

            Parser      parser      = new Parser("neh_data.txt");
            Stopwatch[] stopwatches = new Stopwatch[4] {
                new Stopwatch(), new Stopwatch(), new Stopwatch(), new Stopwatch()
            };
            #region Badanie algorytmow - poszczegolne algorytmy
            for (int i = nrInstancji; i < liczbaBadanychInstancji + 1; i++)
            {
                int[,] taskMatrix = parser.LoadTasks(i);

                #region Generowanie poczatkowej kolejnosci - natural
                int[] startingPointN = new int[taskMatrix.GetLength(0)];
                for (int j = 0; j < startingPointN.Length; j++)
                {
                    startingPointN[j] = j + 1;
                }
                #endregion

                //Tabu Search - natural, neighbourhood 1
                stopwatches[0].Start();
                int[] seqTsN1 = TabuSearch.tabuSearch(taskMatrix, startingPointN, 1, liczbaIteracji);
                stopwatches[0].Stop();
                int cMaxTsN1 = Algorithms.calculateTotalspan(taskMatrix, seqTsN1);

                //Tabu Search - natural, neighbourhood 2
                stopwatches[1].Start();
                int[] seqTsN2 = TabuSearch.tabuSearch(taskMatrix, startingPointN, 2, liczbaIteracji);
                stopwatches[1].Stop();
                int cMaxTsN2 = Algorithms.calculateTotalspan(taskMatrix, seqTsN2);

                //Tabu Search - natural, neighbourhood 3
                stopwatches[2].Start();
                int[] seqTsN3 = TabuSearch.tabuSearch(taskMatrix, startingPointN, 3, liczbaIteracji);
                stopwatches[2].Stop();
                int cMaxTsN3 = Algorithms.calculateTotalspan(taskMatrix, seqTsN3);

                //Tabu Search - natural, neighbourhood 4
                stopwatches[3].Start();
                int[] seqTsN4 = TabuSearch.tabuSearch(taskMatrix, startingPointN, 4, liczbaIteracji);
                stopwatches[3].Stop();
                int cMaxTsN4 = Algorithms.calculateTotalspan(taskMatrix, seqTsN4);

                //Zapisywanie wynikow
                int[]    cMaxes = { cMaxTsN1, cMaxTsN2, cMaxTsN3, cMaxTsN4 };
                string[] aNames = { "Method1", "Method2", "Method3", "Method4" };
                Parser.SaveTimeScore("result.txt", stopwatches, i, cMaxes, taskMatrix, aNames, i);

                //Resetowanie stoperow
                foreach (Stopwatch sw in stopwatches)
                {
                    sw.Reset();
                }
            }
            #endregion
        }
Пример #18
0
        public void NelderOtherHeuristics()
        {
            int thinningPeriod = 4;
            int treeCount      = 75;

            #if DEBUG
            treeCount = 25;
            #endif

            PlotsWithHeight      nelder        = PublicApi.GetNelder();
            OrganonConfiguration configuration = OrganonTest.CreateOrganonConfiguration(new OrganonVariantNwo());
            configuration.Treatments.Harvests.Add(new ThinByIndividualTreeSelection(thinningPeriod));
            OrganonStand stand = nelder.ToOrganonStand(configuration, 20, 130.0F, treeCount);
            stand.PlantingDensityInTreesPerHectare = TestConstant.NelderReplantingDensityInTreesPerHectare;

            Objective landExpectationValue = new Objective()
            {
                IsLandExpectationValue = true,
                PlanningPeriods        = 9
            };
            Objective volume = new Objective()
            {
                PlanningPeriods = landExpectationValue.PlanningPeriods
            };
            HeuristicParameters defaultParameters = new HeuristicParameters()
            {
                UseScaledVolume = false
            };

            GeneticParameters geneticParameters = new GeneticParameters(treeCount)
            {
                PopulationSize     = 7,
                MaximumGenerations = 5,
                UseScaledVolume    = defaultParameters.UseScaledVolume
            };
            GeneticAlgorithm genetic        = new GeneticAlgorithm(stand, configuration, landExpectationValue, geneticParameters);
            TimeSpan         geneticRuntime = genetic.Run();

            GreatDeluge deluge = new GreatDeluge(stand, configuration, volume, defaultParameters)
            {
                RainRate        = 5,
                LowerWaterAfter = 9,
                StopAfter       = 10
            };
            deluge.RandomizeTreeSelection(TestConstant.Default.SelectionPercentage);
            TimeSpan delugeRuntime = deluge.Run();

            RecordTravel recordTravel = new RecordTravel(stand, configuration, landExpectationValue, defaultParameters)
            {
                StopAfter = 10
            };
            recordTravel.RandomizeTreeSelection(TestConstant.Default.SelectionPercentage);
            TimeSpan recordRuntime = recordTravel.Run();

            SimulatedAnnealing annealer = new SimulatedAnnealing(stand, configuration, volume, defaultParameters)
            {
                Iterations = 100
            };
            annealer.RandomizeTreeSelection(TestConstant.Default.SelectionPercentage);
            TimeSpan annealerRuntime = annealer.Run();

            TabuParameters tabuParameters = new TabuParameters()
            {
                UseScaledVolume = defaultParameters.UseScaledVolume
            };
            TabuSearch tabu = new TabuSearch(stand, configuration, landExpectationValue, tabuParameters)
            {
                Iterations = 7,
                //Jump = 2,
                MaximumTenure = 5
            };
            tabu.RandomizeTreeSelection(TestConstant.Default.SelectionPercentage);
            TimeSpan tabuRuntime = tabu.Run();

            ThresholdAccepting thresholdAcceptor = new ThresholdAccepting(stand, configuration, volume, defaultParameters);
            thresholdAcceptor.IterationsPerThreshold.Clear();
            thresholdAcceptor.Thresholds.Clear();
            thresholdAcceptor.IterationsPerThreshold.Add(10);
            thresholdAcceptor.Thresholds.Add(1.0F);
            thresholdAcceptor.RandomizeTreeSelection(TestConstant.Default.SelectionPercentage);
            TimeSpan acceptorRuntime = thresholdAcceptor.Run();

            RandomGuessing random = new RandomGuessing(stand, configuration, volume, defaultParameters)
            {
                Iterations = 4
            };
            TimeSpan randomRuntime = random.Run();

            configuration.Treatments.Harvests.Clear();
            configuration.Treatments.Harvests.Add(new ThinByPrescription(thinningPeriod));
            PrescriptionParameters prescriptionParameters = new PrescriptionParameters()
            {
                Maximum         = 60.0F,
                Minimum         = 50.0F,
                Step            = 10.0F,
                UseScaledVolume = defaultParameters.UseScaledVolume
            };
            PrescriptionEnumeration enumerator = new PrescriptionEnumeration(stand, configuration, landExpectationValue, prescriptionParameters);
            TimeSpan enumerationRuntime        = enumerator.Run();

            // heuristics assigned to volume optimization
            this.Verify(deluge);
            this.Verify(annealer);
            this.Verify(thresholdAcceptor);
            this.Verify(random);

            // heuristics assigned to net present value optimization
            this.Verify(genetic);
            this.Verify(enumerator);
            this.Verify(recordTravel);
            this.Verify(tabu);

            HeuristicSolutionDistribution distribution = new HeuristicSolutionDistribution(1, thinningPeriod, treeCount);
            distribution.AddRun(annealer, annealerRuntime, defaultParameters);
            distribution.AddRun(deluge, delugeRuntime, defaultParameters);
            distribution.AddRun(thresholdAcceptor, acceptorRuntime, defaultParameters);
            distribution.AddRun(genetic, geneticRuntime, defaultParameters);
            distribution.AddRun(enumerator, enumerationRuntime, defaultParameters);
            distribution.AddRun(recordTravel, recordRuntime, defaultParameters);
            distribution.AddRun(tabu, tabuRuntime, defaultParameters);
            distribution.AddRun(random, randomRuntime, defaultParameters);
            distribution.OnRunsComplete();
        }
Пример #19
0
        static void Main(string[] args)
        {
            #region Parametry poczatkowe
            int nrMetodySasiedztwa      = 1;
            int liczbaIteracji          = 5000;
            int nrInstancji             = 1;
            int liczbaBadanychInstancji = 20;
            #endregion

            Parser      parser      = new Parser("neh_data.txt");
            Stopwatch[] stopwatches = new Stopwatch[3] {
                new Stopwatch(), new Stopwatch(), new Stopwatch()
            };
            #region Badanie algorytmow - poszczegolne algorytmy
            for (int i = nrInstancji; i < liczbaBadanychInstancji + 1; i++)
            {
                int[,] taskMatrix = parser.LoadTasks(i);

                #region Generowanie poczatkowej kolejnosci
                int[] startingPoint = new int[taskMatrix.GetLength(0)];
                for (int j = 0; j < startingPoint.Length; j++)
                {
                    startingPoint[j] = j + 1;
                }
                #endregion

                //Neh
                List <Tuple <int, int> > pP = Algorithms.ZwrocPosortowanePriorytety(taskMatrix);

                stopwatches[0].Start();
                int[] seqNeh = Neh.NehBasic(taskMatrix, pP);
                stopwatches[0].Stop();

                int cMaxNeh = Algorithms.calculateTotalspan(taskMatrix, seqNeh);

                //Tabu Search
                stopwatches[1].Start();
                int[] seqTs = TabuSearch.tabuSearch(taskMatrix, startingPoint, nrMetodySasiedztwa, liczbaIteracji);
                stopwatches[1].Stop();

                int cMaxTs = Algorithms.calculateTotalspan(taskMatrix, seqTs);

                //Johnson
                stopwatches[2].Start();
                int[] seqJohn = Johnson.AlgorytmJohnsona(taskMatrix);
                stopwatches[2].Stop();

                int cMaxJohn = Algorithms.calculateTotalspan(taskMatrix, seqJohn);

                //Zapisywanie wynikow
                int[]    cMaxes = { cMaxNeh, cMaxTs, cMaxJohn };
                string[] aNames = { "Neh", "TS", "Johnson" };
                Parser.SaveTimeScore("result.txt", stopwatches, i, cMaxes, taskMatrix, aNames, i);

                //Resetowanie stoperow
                foreach (Stopwatch sw in stopwatches)
                {
                    sw.Reset();
                }
            }
            #endregion
        }
Пример #20
0
        static void Main(string[] args)
        {
            //Dictionary<string, int> did = new Dictionary<string, int>();
            //did.Add("sad", 11);
            //Console.WriteLine("d is " + did["sad"] + " and d1 is " + did["sad1"]);
            //int i = 1023;
            //int j = i / 100;
            //int k = i % 100;
            //Console.WriteLine("d is " + i / 100 + " and d1 is " + k);
            //string fileName = args[0];
            string      fileName = "G:\\Projects\\VS2012\\算例\\000.mp";//args[0];
            RcpspSolver solve    = new RcpspSolver();

            solve = RcpspParser.parseMultiProjFile(fileName);
            allMIT(solve);
            return;

            //solve.TotalWuWeight = 30;
            ////产生所有可行划分和所有划分组合
            solve.generateAllPossiblePartation();
            ////计算所有组合的最优时间和最优分组
            solve.calcAllCombMultiProcess();
            foreach (string str in solve.EveryCombBestProj.Keys)
            {
                RcspspProject proj = solve.EveryCombBestProj[str];
                Console.WriteLine("comb core " + str + "is " + proj.BestSocre + " and list is : ");
                Console.Write("             ");
                foreach (RcpspJob job in proj.Jobs)
                {
                    Console.Write("(" + job.id + "__" + job.project + "__" + job.duration + ")");
                }
                Console.WriteLine();
            }

            RcspspProject bestproj = solve.calAllPartitionScore();

            Console.WriteLine("all project end time is  ");
            foreach (RcspspProject proj in solve.ProjectList)
            {
                if (proj.Jobs.Count > 1)
                {
                    RcpspJob lastJob = proj.Jobs.Last.Previous.Value;
                    Console.Write("   " + (lastJob.startTime + lastJob.duration));
                }
            }
            Console.WriteLine();
            Console.WriteLine("best core is " + bestproj.BestSocre + " and partition is " + bestproj.BestCombStr);
            Console.Write("this List is : ");
            foreach (RcpspJob job in bestproj.Jobs)
            {
                //Console.Write("[" + job.id + "__" + job.project + "__" + job.startTime+"__"+job.duration + "]");
                if (job.isWX)
                {
                    RcspspProject wxProject = solve.EveryCombBestProj[job.project];
                    foreach (RcpspJob wxJob in wxProject.Jobs)
                    {
                        addJob2Dic(solve.ProjectList, wxJob, job.startTime);
                    }
                }
                else
                {
                    addJob2Dic(solve.ProjectList, job);
                }
            }
            //TabuSearch.printGUI(bestproj.Jobs);
            Console.WriteLine("total time is " + TabuSearch.calScheduleCore(bestproj.Jobs, true));
            foreach (RcspspProject proj in solve.ProjectList)
            {
                Console.WriteLine("Project " + proj.ProjectId);
                foreach (RcpspJob projJob in proj.Jobs)
                {
                    Console.WriteLine(projJob.id + "\t" + projJob.startTime + "\t" + (projJob.startTime + projJob.duration));
                }
            }

            return;
        }
Пример #21
0
        static void Main(string[] args)
        {
            #region Parametry poczatkowe
            int liczbaIteracji          = 5000;
            int nrInstancji             = 1;
            int liczbaBadanychInstancji = 20;
            #endregion

            Parser      parser      = new Parser("neh_data.txt");
            Stopwatch[] stopwatches = new Stopwatch[3] {
                new Stopwatch(), new Stopwatch(), new Stopwatch()
            };
            #region Badanie algorytmow - poszczegolne algorytmy
            for (int i = nrInstancji; i < liczbaBadanychInstancji + 1; i++)
            {
                int[,] taskMatrix = parser.LoadTasks(i);

                #region Generowanie poczatkowej kolejnosci - natural
                int[] startingPointN = new int[taskMatrix.GetLength(0)];
                for (int j = 0; j < startingPointN.Length; j++)
                {
                    startingPointN[j] = j + 1;
                }
                #endregion

                #region Generowanie poczatkowej kolejnosci - randShuffle
                int[] startingPointR = Algorithms.shuffleOrder(startingPointN);
                #endregion

                #region Generowanie poczatkowej kolejnosci - neh
                List <Tuple <int, int> > pP = Algorithms.ZwrocPosortowanePriorytety(taskMatrix);
                int[] startingPointNe       = Neh.NehBasic(taskMatrix, pP);
                #endregion

                //Tabu Search - natural, neighbourhood 1
                stopwatches[0].Start();
                int[] seqTsN1 = TabuSearch.tabuSearch(taskMatrix, startingPointN, 1, liczbaIteracji);
                stopwatches[0].Stop();
                int cMaxTsN1 = Algorithms.calculateTotalspan(taskMatrix, seqTsN1);

                //Tabu Search - randShuffle, neighbourhood 1
                stopwatches[1].Start();
                int[] seqTsR1 = TabuSearch.tabuSearch(taskMatrix, startingPointR, 1, liczbaIteracji);
                stopwatches[1].Stop();
                int cMaxTsR1 = Algorithms.calculateTotalspan(taskMatrix, seqTsR1);

                //Tabu Search - neh, neighbourhood 1
                stopwatches[2].Start();
                int[] seqTsNe1 = TabuSearch.tabuSearch(taskMatrix, startingPointNe, 1, liczbaIteracji);
                stopwatches[2].Stop();
                int cMaxTsNe1 = Algorithms.calculateTotalspan(taskMatrix, seqTsNe1);

                //Zapisywanie wynikow
                int[]    cMaxes = { cMaxTsN1, cMaxTsR1, cMaxTsNe1 };
                string[] aNames = { "Natural_1", "RandShuffle_1", "Neh_1" };
                Parser.SaveTimeScore("result.txt", stopwatches, i, cMaxes, taskMatrix, aNames, i);

                //Resetowanie stoperow
                foreach (Stopwatch sw in stopwatches)
                {
                    sw.Reset();
                }
            }
            #endregion
        }