Exemplo n.º 1
0
        public void LocalRandomSolveHour3ChannelInstance()
        {
            var file   = Properties.Resources.hour_DS_D_DH_inst;
            var reader = new InstanceJsonSerializer
            {
                Reader = new StreamReader(new MemoryStream(file), Encoding.UTF8)
            };
            Instance         instance     = reader.DeserializeInstance();
            RandomFastSolver randomSolver = new RandomFastSolver()
            {
                Instance = instance,
                Seed     = 10,
            };
            LocalSearch solver = new LocalSearch()
            {
                Instance            = instance,
                Solution            = randomSolver.Solution,
                PropagateRandomSeed = true,
                Seed              = 10,
                ScoringFunction   = new Scorer(),
                StopWhenCompleted = true,
                TimeLimit         = new TimeSpan(0, 0, 60),
            };

            solver.InitialSolvers.Add(randomSolver);
            solver.Solve();
            InstanceJsonSerializer serializer = new InstanceJsonSerializer()
            {
                Path = @"results\hour_DS_D_DH_sol_localrandom.json"
            };

            serializer.SerializeSolution(solver.Solution, SolutionSerializationMode.DebugTaskData);
        }
Exemplo n.º 2
0
        private static ISolver LocalSearchNewStopConditions()
        {
            GreedyFastHeuristic randomSolver = new GreedyFastHeuristic()
            {
                MaxOverfillUnits = 0,
            };
            CompoundSolver compundSolver = new CompoundSolver()
            {
                MaxLoops           = 7,
                DiagnosticMessages = true,
            };
            LocalSearch solver = new LocalSearch()
            {
                ScoringFunction             = new Scorer(),
                DiagnosticMessages          = true,
                PropagateRandomSeed         = true,
                NumberOfNoGoodActionsToStop = 10,
                TimeLimit = new TimeSpan(0, 1, 0),
                BestFactoryAdjustmentParam  = 0.2,
                NeighberhoodAdjustmentParam = 0.2,
                ImprovementOverNarrowNeighb = 2,
                Description = "local_search_new_stop_condition_1",
            };

            solver.InitialSolvers.Add(randomSolver);
            solver.InitialSolvers.Add(compundSolver);
            return(solver);
        }
Exemplo n.º 3
0
        public override IList <KeyValuePair <int, int[]> > CalculateRoutes(IDictionary <int, int>[] distances)
        {
            Distances = distances;
            var result = new List <KeyValuePair <int, int[]> >();

            _random = new Random();
            var algorithm = new RandomRoutes {
                RouteLengthLimit = 50
            };

            algorithm.Distances = distances;

            var algorithmLocalSearch = new LocalSearch(algorithm);

            algorithmLocalSearch.Distances = distances;

            for (var i = 0; i < CountRoutes; i++)
            {
                var routeStart     = algorithm.CalculateRoutesFromCity(_random.Next(distances.Length));
                var optimizedRoute = algorithmLocalSearch.OptimizeRouteFromCity(i, routeStart);

                result.Add(new KeyValuePair <int, int[]>(i, optimizedRoute));
            }
            IsCalculated     = true;
            CalculatedRoutes = result;

            return(result);
        }
Exemplo n.º 4
0
        private void RunLocalSearch()
        {
            LocalSearch localSearch = new LocalSearch();
            Route       bestRoute   = localSearch.RunLocalSearch(graph, randomRouteGenerator.GenerateSingleRandomRoute(graph.GraphOfNodes.Count));

            DataDisplay.PrintRouteAndCalculation(bestRoute.RouteIds, bestRoute.RouteCost);
        }
Exemplo n.º 5
0
 public LocalSearchBeam(LocalSearch other, int beamsize)
     : base()
 {
     this.DB = other.DB;
     this.Neighbors = other.Neighbors;
     this.Vertices = other.Vertices;
     this.BeamSize = beamsize;
 }
Exemplo n.º 6
0
 public MultipleStartLocalSearch(INonDeterministicAlgorithm algorithmNonDeterministic)
 {
     _algorithmNonDeterministic = algorithmNonDeterministic;
     RouteLengthLimit           = ((TspAlgorithmBase)_algorithmNonDeterministic).RouteLengthLimit;
     ((TspAlgorithmBase)_algorithmNonDeterministic).RouteLengthLimit = RouteLengthLimit;
     _algorithmLocalSearch = new LocalSearch((TspAlgorithmBase)_algorithmNonDeterministic)
     {
         RouteLengthLimit = RouteLengthLimit
     };
 }
Exemplo n.º 7
0
        private static ISolver LocalSearchEvolutionaryInitial()
        {
            GreedyFastHeuristic randomSolver = new GreedyFastHeuristic()
            {
                MaxOverfillUnits = 0,
            };
            CompoundSolver compundSolver = new CompoundSolver()
            {
                MaxLoops = 3,
            };
            LocalSearch solver = new LocalSearch()
            {
                PropagateRandomSeed         = true,
                NumberOfNoGoodActionsToStop = 7,
                BestFactoryAdjustmentParam  = 0.1,
                NeighberhoodAdjustmentParam = 0.1,
                ImprovementOverNarrowNeighb = 1.5,
                TimeLimit          = new TimeSpan(0, 5, 0),
                DiagnosticMessages = true,
                ReportTimeouts     = true,
            };

            solver.MoveFactories = new List <ITransformationFactory>
            {
                new InsertFactory()
                {
                    MildlyRandomOrder   = true,
                    PositionsCountLimit = 3,
                    MaxTasksChecked     = 1,
                    MaxBreaksChecked    = 1,
                    IgnoreBreaksWhenUnitOverfillAbove = 60,
                    IgnoreCompletedTasks          = true,
                    IgnoreTasksWithCompletedViews = false,
                    AlwaysReturnStartsAndEnds     = true,
                },
                new RandomDeleteFactory()
                {
                    MovesReturned = 20,
                    RampUpSpeed   = 3.0,
                },
                new RandomInsertFactory()
                {
                    MovesReturned = 20,
                    RampUpSpeed   = 3.0,
                },
                new RandomSwapFactory()
                {
                    MovesReturned = 40,
                    RampUpSpeed   = 4.0,
                },
            };
            solver.InitialSolvers.Add(randomSolver);
            solver.InitialSolvers.Add(compundSolver);
            return(solver);
        }
Exemplo n.º 8
0
        private static ISolver LocalSearchNewStopConditions2()
        {
            GreedyFastHeuristic randomSolver = new GreedyFastHeuristic()
            {
                MaxOverfillUnits   = 0,
                DiagnosticMessages = true,
            };
            CompoundSolver compundSolver = new CompoundSolver()
            {
                MaxLoops           = 7,
                DiagnosticMessages = true,
            };
            LocalSearch solver = new LocalSearch()
            {
                ScoringFunction             = new Scorer(),
                DiagnosticMessages          = true,
                PropagateRandomSeed         = true,
                NumberOfNoGoodActionsToStop = 15,
                BestFactoryAdjustmentParam  = 0.2,
                NeighberhoodAdjustmentParam = 0.2,
                ImprovementOverNarrowNeighb = 2,
                TimeLimit   = new TimeSpan(0, 5, 0),
                Description = "local_search_new_stop_condition_15rs4",
            };

            solver.MoveFactories = new List <ITransformationFactory>
            {
                new InsertFactory()
                {
                    MildlyRandomOrder   = true,
                    PositionsCountLimit = 4,
                    MaxTasksChecked     = 3,
                    MaxBreaksChecked    = 3,
                    IgnoreBreaksWhenUnitOverfillAbove = 60,
                    IgnoreCompletedTasks          = true,
                    IgnoreTasksWithCompletedViews = false,
                    AlwaysReturnStartsAndEnds     = true,
                },
                new RandomDeleteFactory()
                {
                    MovesReturned = 20,
                },
                new RandomInsertFactory()
                {
                    MovesReturned = 30,
                },
                new RandomSwapFactory()
                {
                    MovesReturned = 30,
                },
            };
            solver.InitialSolvers.Add(randomSolver);
            solver.InitialSolvers.Add(compundSolver);
            return(solver);
        }
Exemplo n.º 9
0
        private ISolver LocalSearchFinal2()
        {
            RandomFastSolver randomSolver = new RandomFastSolver()
            {
            };
            CompoundSolver compundSolver = new CompoundSolver()
            {
                MaxLoops  = 5,
                TimeLimit = new TimeSpan(0, 3, 0),
            };
            LocalSearch solver = new LocalSearch()
            {
                ScoringFunction             = new Scorer(),
                DiagnosticMessages          = true,
                PropagateRandomSeed         = true,
                NumberOfNoGoodActionsToStop = 20,
                BestFactoryAdjustmentParam  = 0.2,
                NeighberhoodAdjustmentParam = 0.2,
                ImprovementOverNarrowNeighb = 2,
                TimeLimit   = new TimeSpan(0, 6, 0),
                Description = "base_popualtion_ls_random_oneforall",
            };

            solver.MoveFactories = new List <ITransformationFactory>
            {
                new InsertFactory()
                {
                    MildlyRandomOrder   = true,
                    PositionsCountLimit = 4,
                    MaxTasksChecked     = 3,
                    MaxBreaksChecked    = 3,
                    IgnoreBreaksWhenUnitOverfillAbove = 60,
                    IgnoreCompletedTasks          = true,
                    IgnoreTasksWithCompletedViews = false,
                    AlwaysReturnStartsAndEnds     = true,
                },
                new RandomDeleteFactory()
                {
                    MovesReturned = 20,
                },
                new RandomInsertFactory()
                {
                    MovesReturned = 30,
                },
                new RandomSwapFactory()
                {
                    MovesReturned = 30,
                },
            };
            solver.InitialSolvers.Add(randomSolver);
            solver.InitialSolvers.Add(compundSolver);
            return(solver);
        }
Exemplo n.º 10
0
        private void searchThread(int pID, int max, int seed, INeighborhood <GraphGenome> neighborhood, bool silent = false)
        {
            Console.WriteLine("Thread {0} started...", pID);

            Random random = new Random(seed);

            // TODO: Resultaten (dus CPU computational time) opslaan in bestand.
            LocalSearch <GraphGenome> local_search =
                new LocalSearch <GraphGenome>(500,
                                              neighborhood,
                                              new GraphComparer <GraphGenome>(), random);

            // Dit wil ik eigenlijk static doen, maar dan komen we in de knoei met data_size.
            GraphGenome graph = new GraphGenome(500);

            graph.CreateGraph("Graph500.txt");

            GraphGenome optimum = null;

            for (int i = 0; i < ExperimentAmount; ++i)
            {
                AssignmentTwoResults <GraphGenome> inner_results = new AssignmentTwoResults <GraphGenome>();
                for (int j = 0; j < max; j++)
                {
                    graph = new GraphGenome(500);
                    graph.Generate(ref random);
                    Stopwatch   sw            = Stopwatch.StartNew();
                    GraphGenome inner_optimum = local_search.Search(graph);
                    sw.Stop();
                    inner_results.Add(inner_optimum, sw.ElapsedTicks);

                    if (!silent)
                    {
                        Console.WriteLine("Found {0} in {1} ticks or {2}ms. ({3}/{4}), pID: {5}", inner_optimum.Fitness, sw.ElapsedTicks,
                                          sw.ElapsedMilliseconds, j, max, pID);
                    }

                    if (optimum == null || optimum.Fitness >= inner_optimum.Fitness)
                    {
                        optimum = inner_optimum;
                    }
                }
                lock (solutionsThreads)
                {
                    solutionsThreads[pID] = optimum;
                }
                lock (elapsedMilisecondsThreads)
                {
                    elapsedMilisecondsThreads[pID].Add(inner_results);
                }
            }
        }
Exemplo n.º 11
0
        public static void Report2(IDictionary <int, int>[] data)
        {
            var gc = new GreedyCycle {
                RouteLengthLimit = 50
            };

            RunAlgorithm(gc, data);

            var gcg = new GreedyCycleGrasp {
                RouteLengthLimit = 50
            };

            RunAlgorithm(gcg, data);

            var nn = new NN {
                RouteLengthLimit = 50
            };

            RunAlgorithm(nn, data);

            var nng = new NNGrasp {
                RouteLengthLimit = 50
            };

            RunAlgorithm(nng, data);

            var rr = new RandomRoutes {
                RouteLengthLimit = 50
            };

            RunAlgorithm(rr, data);

            var lsGc = new LocalSearch(gc);

            RunAlgorithm(lsGc, data);

            var lsGcg = new LocalSearch(gcg);

            RunAlgorithm(lsGcg, data);

            var lsNn = new LocalSearch(nn);

            RunAlgorithm(lsNn, data);

            var lsNng = new LocalSearch(nng);

            RunAlgorithm(lsNng, data);

            var lsRr = new LocalSearch(rr);

            RunAlgorithm(lsRr, data);
        }
Exemplo n.º 12
0
        public void GLocalSearch()
        {
            IConstructiveHeuristic grasp = new SCPGRASP(0.9, 1e-9);
            double cost = grasp.Execute(scpParser.Problem);

            LocalSearch scpLS = new LocalSearch();

            cost = scpLS.Execute(grasp.Problem.Clone());
            ((SCP)scpParser.Problem).Solution = scpLS.OptimumSultion;
            TimeSpan elapsed  = scpLS.Elapsed;
            bool     validity = SolutionValidity();

            Assert.AreEqual(validity, true);
        }
Exemplo n.º 13
0
        private static ISolver LocalSearchForEvolutionaryImprovement()
        {
            CompoundSolver compundSolver = new CompoundSolver()
            {
                MaxLoops  = 1,
                TimeLimit = new TimeSpan(0, 0, 15),
            };
            LocalSearch localSearch = new LocalSearch()
            {
                NumberOfNoGoodActionsToStop = 15,
                BestFactoryAdjustmentParam  = 0.2,
                NeighberhoodAdjustmentParam = 0.2,
                ImprovementOverNarrowNeighb = 1.5,
                TimeLimit = new TimeSpan(0, 0, 15),
            };

            localSearch.MoveFactories = new List <ITransformationFactory>
            {
                new InsertFactory()
                {
                    MildlyRandomOrder   = true,
                    PositionsCountLimit = 3,
                    MaxTasksChecked     = 1,
                    MaxBreaksChecked    = 1,
                    IgnoreBreaksWhenUnitOverfillAbove = 60,
                    IgnoreCompletedTasks          = true,
                    IgnoreTasksWithCompletedViews = false,
                    AlwaysReturnStartsAndEnds     = true,
                },
                new RandomDeleteFactory()
                {
                    MovesReturned = 20,
                    RampUpSpeed   = 3.0,
                },
                new RandomInsertFactory()
                {
                    MovesReturned = 20,
                    RampUpSpeed   = 3.0,
                },
                new RandomSwapFactory()
                {
                    MovesReturned = 50,
                    RampUpSpeed   = 4.0,
                },
            };
            localSearch.InitialSolvers.Add(compundSolver);
            return(localSearch);
        }
        private LocalSearch CreateLocalSearchKnapsackSample()
        {
            LocalSearch ls = new LocalSearch();

            #region Problem Configuration
            KnapsackProblem problem = new KnapsackProblem();
            problem.BestKnownQuality  = new DoubleValue(362);
            problem.BestKnownSolution = new HeuristicLab.Encodings.BinaryVectorEncoding.BinaryVector(new bool[] {
                true, false, false, true, true, true, true, true, false, true, true, true, true, true, true, false, true, false, true, true, false, true, true, false, true, false, true, true, true, false, true, true, false, true, true, false, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, false, false, true, true, false, true, true, true, true, true, true, true, true, false, true, false, true, true, true, true, false, true, true, true, true, true, true, true, true
            });
            problem.EvaluatorParameter.Value       = new KnapsackEvaluator();
            problem.SolutionCreatorParameter.Value = new RandomBinaryVectorCreator();
            problem.KnapsackCapacity.Value         = 297;
            problem.Maximization.Value             = true;
            problem.Penalty.Value = 1;
            problem.Values        = new IntArray(new int[] {
                6, 1, 1, 6, 7, 8, 7, 4, 2, 5, 2, 6, 7, 8, 7, 1, 7, 1, 9, 4, 2, 6, 5, 3, 5, 3, 3, 6, 5, 2, 4, 9, 4, 5, 7, 1, 4, 3, 5, 5, 8, 3, 6, 7, 3, 9, 7, 7, 5, 5, 7, 1, 4, 4, 3, 9, 5, 1, 6, 2, 2, 6, 1, 6, 5, 4, 4, 7, 1, 8, 9, 9, 7, 4, 3, 8, 7, 5, 7, 4, 4, 5
            });
            problem.Weights = new IntArray(new int[] {
                1, 9, 3, 6, 5, 3, 8, 1, 7, 4, 2, 1, 2, 7, 9, 9, 8, 4, 9, 2, 4, 8, 3, 7, 5, 7, 5, 5, 1, 9, 8, 7, 8, 9, 1, 3, 3, 8, 8, 5, 1, 2, 4, 3, 6, 9, 4, 4, 9, 7, 4, 5, 1, 9, 7, 6, 7, 4, 7, 1, 2, 1, 2, 9, 8, 6, 8, 4, 7, 6, 7, 5, 3, 9, 4, 7, 4, 6, 1, 2, 5, 4
            });
            problem.Name        = "Knapsack Problem";
            problem.Description = "Represents a Knapsack problem.";
            #endregion
            #region Algorithm Configuration
            ls.Name                    = "Local Search - Knapsack";
            ls.Description             = "A local search algorithm that solves a randomly generated Knapsack problem";
            ls.Problem                 = problem;
            ls.MaximumIterations.Value = 1000;
            ls.MoveEvaluator           = ls.MoveEvaluatorParameter.ValidValues
                                         .OfType <KnapsackOneBitflipMoveEvaluator>()
                                         .Single();
            ls.MoveGenerator = ls.MoveGeneratorParameter.ValidValues
                               .OfType <ExhaustiveOneBitflipMoveGenerator>()
                               .Single();
            ls.MoveMaker = ls.MoveMakerParameter.ValidValues
                           .OfType <OneBitflipMoveMaker>()
                           .Single();
            ls.SampleSize.Value      = 100;
            ls.Seed.Value            = 0;
            ls.SetSeedRandomly.Value = true;
            #endregion
            ls.Engine = new ParallelEngine.ParallelEngine();
            return(ls);
        }
Exemplo n.º 15
0
        public IList <KeyValuePair <int, int[]> > CalculateRoutes(IDictionary <int, int>[] distances,
                                                                  TimeSpan durationLimit)
        {
            Distances = distances;

            ((TspAlgorithmBase)_algorithmNonDeterministic).Distances = distances;
            _algorithmLocalSearch = new LocalSearch((TspAlgorithmBase)_algorithmNonDeterministic)
            {
                RouteLengthLimit = RouteLengthLimit
            };
            _algorithmLocalSearch.Distances = distances;

            var result = GenerateRoutes(durationLimit);

            IsOptimized      = true;
            IsCalculated     = true;
            CalculatedRoutes = result;

            return(result);
        }
Exemplo n.º 16
0
        public void IterativeLocalSearch()
        {
            List <Tuple <double, SCPSolution> > history = new List <Tuple <double, SCPSolution> >();
            bool validity = false;
            int  iteratin = 0;

            while (iteratin++ < 5)
            {
                IConstructiveHeuristic grasp = new SCPGRASP(0.9, 1e-9);
                double      cost             = grasp.Execute((SCP)((SCP)scpParser.Problem).Clone());
                LocalSearch scpLS            = new LocalSearch();
                cost = scpLS.Execute(grasp.Problem);
                TimeSpan elapsed = scpLS.Elapsed;
                history.Add(new Tuple <double, SCPSolution>(cost, scpLS.OptimumSultion.Clone()));
            }

            ((SCP)scpParser.Problem).Solution = history.OrderBy(h => h.Item1).ToList().FirstOrDefault().Item2;
            validity = SolutionValidity();

            Assert.AreEqual(validity, true);
        }
        /// <summary>
        /// Reads the parameter from the parameter list using the
        /// <code>getInputParameter</code> method.
        /// </summary>
        public void InitParam()
        {
            //Read the parameters
            JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref solutionSetSize);
            JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "refSet1Size", ref refSet1Size);
            JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "refSet2Size", ref refSet2Size);
            JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "archiveSize", ref archiveSize);
            JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxEvaluations", ref maxEvaluations);

            //Initialize the variables
            solutionSet = new SolutionSet(solutionSetSize);
            archive     = new CrowdingArchive(archiveSize, this.Problem.NumberOfObjectives);
            refSet1     = new SolutionSet(refSet1Size);
            refSet2     = new SolutionSet(refSet2Size);
            subSet      = new SolutionSet(solutionSetSize * 1000);
            evaluations = 0;

            numberOfSubranges = 4;

            dominance                   = new DominanceComparator();
            equal                       = new EqualSolutions();
            fitness                     = new FitnessComparator();
            crowdingDistance            = new CrowdingDistanceComparator();
            distance                    = new Distance();
            sumOfFrequencyValues        = new int[this.Problem.NumberOfVariables];
            sumOfReverseFrequencyValues = new int[this.Problem.NumberOfVariables];
            frequency                   = new int[numberOfSubranges][];
            reverseFrequency            = new int[numberOfSubranges][];

            for (int i = 0; i < numberOfSubranges; i++)
            {
                frequency[i]        = new int[this.Problem.NumberOfVariables];
                reverseFrequency[i] = new int[this.Problem.NumberOfVariables];
            }

            // Read the operators of crossover and improvement
            crossoverOperator   = this.Operators["crossover"];
            improvementOperator = (LocalSearch)this.Operators["improvement"];
            improvementOperator.SetParameter("archive", archive);
        }
Exemplo n.º 18
0
    public static void Main(String[] args)
    {
        Network net = new Network();

        ft06(net);

        String solverName = "ibb";
        int    opt        = Solver.Minimize;
        long   timeout    = 180000;

        if (args.Length >= 1)
        {
            solverName = args[0];
        }

        Solver solver;

        if (solverName.Equals("bb"))
        {
            solver = new DefaultSolver(net, opt, "bb");
        }
        else if (solverName.Equals("random"))
        {
            solver = new LocalSearch(net, opt, "rs");
        }
        else if (solverName.Equals("sa"))
        {
            solver = new SimulatedAnneallingSearch(net, opt, "sa");
        }
        else if (solverName.Equals("ibb"))
        {
            solver = new IterativeBranchAndBoundSearch(net, opt, "ibb");
        }
        else if (solverName.Equals("taboo"))
        {
            solver = new TabooSearch(net, opt, "taboo");
        }
        else
        {
            Solver sa  = new SimulatedAnneallingSearch((Network)net.Clone(), opt, "sa");
            Solver ibb = new IterativeBranchAndBoundSearch((Network)net.Clone(), opt, "ibb");
            solver = new ParallelSolver(new Solver[] { sa, ibb });
        }
        solver.SolverStrategy = Solver.StrategyMethod.Bisect;
        //Cream.Monitor monitor = new Monitor();
        //monitor.setX(0, (int)(timeout / 1000));
        //solver.setMonitor(monitor);

        Console.Out.WriteLine("Start " + solver + ", timeout = " + timeout + " msecs");

        Solution bestSolution;
        int      c = 0;

        if (true)
        {
            for (solver.Start(timeout); solver.WaitNext(); solver.Resume())
            {
                Solution solution = solver.Solution;
                Console.Out.WriteLine(++c);
                Console.Out.WriteLine(solution);
                int value_Renamed = solution.ObjectiveIntValue;
                Console.Out.WriteLine(value_Renamed);
                Console.Out.WriteLine("=======================");
            }
            solver.Stop();
            bestSolution = solver.BestSolution;
        }
        else
        {
            bestSolution = solver.FindBest(timeout);
        }

        Console.Out.WriteLine("Best = " + bestSolution.ObjectiveIntValue);
        Console.Out.WriteLine("Best = " + bestSolution);
        Console.In.ReadLine();
    }
 public LocalSearchProcreator(ICrossover <T> crossover, LocalSearch <T> _local_search, Random _random, AssignmentTwoResults <T> _results) : base(crossover, "LS")
 {
     random       = _random;
     local_search = _local_search;
     results      = _results;
 }
Exemplo n.º 20
0
        private AssignmentTwoResultList <GraphGenome> IteratedLocalSearch(INeighborhood <GraphGenome> neighborhood, bool silent = false)
        {
            LocalSearch <GraphGenome> local_search =
                new LocalSearch <GraphGenome>(500,
                                              neighborhood,
                                              new GraphComparer <GraphGenome>(), main_random_source);
            IMutation <GraphGenome> pertubation = new ILSPertubation <GraphGenome>(main_random_source);

            GraphGenome graph = new GraphGenome(500);

            graph.CreateGraph("Graph500.txt");

            GraphGenome optimum = null;

            List <long> elapsedMilisecondsList = new List <long>();

            AssignmentTwoResultList <GraphGenome> results = new AssignmentTwoResultList <GraphGenome>("$ILS_{" + neighborhood.Name + "}$");

            for (int i = 0; i < ExperimentAmount; ++i)
            {
                AssignmentTwoResults <GraphGenome> res = new AssignmentTwoResults <GraphGenome>();
                for (int j = 0; j < OptimaAmount; j++)
                {
                    if (optimum == null)
                    {
                        graph = new GraphGenome(500);
                        graph.Generate(ref main_random_source);
                    }
                    else
                    {
                        graph = pertubation.Mutate(optimum);
                    }

                    Stopwatch   sw            = Stopwatch.StartNew();
                    GraphGenome inner_optimum = local_search.Search(graph);
                    sw.Stop();
                    elapsedMilisecondsList.Add(sw.ElapsedMilliseconds);

                    res.Add(inner_optimum, sw.ElapsedTicks);

                    if (!silent)
                    {
                        Console.WriteLine("Found {0} in {1} ticks or {2}ms. ({3}/{4})", inner_optimum.Fitness, sw.ElapsedTicks,
                                          sw.ElapsedMilliseconds, j, OptimaAmount);
                    }

                    if (optimum == null || optimum.Fitness >= inner_optimum.Fitness)
                    {
                        optimum = inner_optimum;
                    }

                    optimum.FunctionEvaluations = 0;
                }
                results.Add(res);
            }
            //Console.WriteLine("Best solution found: {0} in an average of {1} ms", optimum.Fitness, cpu_ticks.Average());
            Console.WriteLine("Best solution found: {0} in an average of {1} ms", optimum.Fitness, elapsedMilisecondsList.Sum() / OptimaAmount);
            //Console.WriteLine("Total time: {0} sec", sw.ElapsedMilliseconds / 1000f);

            optimum.ToImage(String.Format("results/ILS[{0}]-{1}.bmp", neighborhood.Name, optimum.Fitness), 3000, 3000);

            //Console.ReadLine();
            return(results);
        }
Exemplo n.º 21
0
 public LocalSearchPopulationGenerator(Random random, LocalSearch <T> _local_search) : base(random, "LS")
 {
     local_search = _local_search;
 }
Exemplo n.º 22
0
    public static void Main(String[] args)
    {
        String problem = "ft10";
        long   timeout = 1000 * 60 * 10;

        String[] solverNames = new String[] { "sa", "ibb", "taboo" };
        int      i           = 0;

        if (i < args.Length)
        {
            problem = args[i++];
        }
        if (i < args.Length)
        {
            timeout = Int32.Parse(args[i++]) * 1000;
        }
        if (i < args.Length)
        {
            solverNames = new String[args.Length - i];
            int j = 0;
            for (; i < args.Length; i++)
            {
                solverNames[j++] = args[i];
            }
        }
        Network network = (new JSSPProblem(problem)).network();

        if (network == null)
        {
            return;
        }
        //int opt = Solver.MINIMIZE | Solver.BETTER;
        int opt = Solver.Default;

        Solver[] solvers = new Solver[solverNames.Length];
        for (i = 0; i < solvers.Length; i++)
        {
            String name = solverNames[i];
            if (name.Equals("sa"))
            {
                solvers[i] = new SimulatedAnneallingSearch((Network)network.Clone(), opt, name);
            }
            else if (name.Equals("ibb"))
            {
                solvers[i] = new IterativeBranchAndBoundSearch((Network)network.Clone(), opt, name);
            }
            else if (name.Equals("taboo") || name.Equals("tabu"))
            {
                solvers[i] = new TabooSearch((Network)network.Clone(), opt, name);
            }
            else if (name.Equals("rw"))
            {
                solvers[i] = new LocalSearch((Network)network.Clone(), opt, name);
            }
            else
            {
                Console.Out.WriteLine("Unknown solver name " + name);
                solvers[i] = null;
            }
        }
        Solver all = new ParallelSolver(solvers);

        //Monitor monitor = new Monitor();
        //monitor.setX(0, (int)(timeout/1000));
        //all.setMonitor(monitor);
        //SolutionHandler sh=null;
        Solution solution = all.FindBest(timeout);

        Console.Out.WriteLine(solution);
        Console.In.ReadLine();
    }
Exemplo n.º 23
0
        private AssignmentTwoResultList <GraphGenome> GeneticLocalSearch(INeighborhood <GraphGenome> neighborhood)
        {
            AssignmentTwoResultList <GraphGenome> results = new AssignmentTwoResultList <GraphGenome>("$GLS_{" + neighborhood.Name + "}$");

            GraphGenome graph = new GraphGenome(500);

            graph.CreateGraph("Graph500.txt");

            GraphGenome optimum = null;

            for (int i = 0; i < ExperimentAmount; ++i)
            {
                AssignmentTwoResults <GraphGenome> res = new AssignmentTwoResults <GraphGenome>();
                int population_size = 50;
                int data_size       = 500;

                LocalSearch <GraphGenome> local_search =
                    new LocalSearch <GraphGenome>(data_size,
                                                  neighborhood,
                                                  new GraphComparer <GraphGenome>(), main_random_source);

                LocalSearchProcreator <GraphGenome> lsp = new LocalSearchProcreator <GraphGenome>(
                    new UniformSymmetricCrossover <GraphGenome>(main_random_source),
                    local_search,
                    main_random_source,
                    res);

                GeneticAlgorithm <GraphGenome> ga = new GeneticAlgorithm <GraphGenome>(
                    data_size,
                    lsp,
                    new DefaultSelector <GraphGenome>(
                        new GraphComparer <GraphGenome>()),
                    new LocalSearchPopulationGenerator <GraphGenome>(main_random_source, local_search),
                    new Goal(100, 0),
                    main_random_source,
                    "GLS");

                InnerResult ir = ga.start(population_size, OptimaAmount / (population_size / 2));
                // Eventueel nog een keer uitvoeren om tot 2500 optima te komen.
                while (res.Count < OptimaAmount)
                {
                    ir = ga.start(population_size, OptimaAmount / (population_size / 2));
                }

                // Als we er teveel hebben gekregen door de GLS run meerdere keren uit te voeren,
                // pak enkel hoeveel we nodig hebben.
                res = res.TakeFirstN(OptimaAmount);
                results.Add(res);

                if (optimum == null || res.BestResult.Optimum.Fitness < optimum.Fitness)
                {
                    optimum = new GraphGenome(res.BestResult.Optimum.Data, res.BestResult.Optimum.Fitness);
                }
            }



            // We maken iedere keer population_size / 2 optima.
            // We willen OptimaAmount optima. Dus we gaan OptimaAmount / (population_size / 2) generaties uitvoeren.

            //IteratedLocalSearch();

            optimum.ToImage(String.Format("results/GLS[{0}]-{1}.bmp", neighborhood.Name, optimum.Fitness), 3000, 3000);

            return(results);
        }
Exemplo n.º 24
0
        static void Main()
        {
            DAL.Instance.ReadFromFile();
            //DAL.Instance.PrepareFileToWrite();

            var sessionExecutionEngine = new AlgorithmExecutionEngine();

            var nearestNeighbourExecutionSession         = new AlgorithmExecutionSession(new NearestNeighbour(), new LocalSearch());
            var greedyCycleExecutionSession              = new AlgorithmExecutionSession(new GreedyCycle(), new LocalSearch());
            var nearestNeighbourGraspExecutionSession    = new AlgorithmExecutionSession(new NearestNeighbourGrasp(), new LocalSearch());
            var greedyCycleGraspExecutionSession         = new AlgorithmExecutionSession(new GreedyCycleGrasp(), new LocalSearch());
            var randomSolutionExecutionSession           = new AlgorithmExecutionSession(new RandomSolution(), new LocalSearch());
            var multipleStartLocalSearchExecutionSession = new AlgorithmExecutionSession(new NearestNeighbourGrasp(), new MultipleStartLocalSearch());
            var iteratedLocalSearchExecutionSession      = new AlgorithmExecutionSession(new NearestNeighbourGrasp(), new IteratedLocalSearch());
            //var multipleStartLocalSearchExecutionSession = new AlgorithmExecutionSession(new RandomSolution(), new MultipleStartLocalSearch());
            //var iteratedLocalSearchExecutionSession = new AlgorithmExecutionSession(new RandomSolution(), new IteratedLocalSearch());

            //sessionExecutionEngine.ExecuteDefaultSession(nearestNeighbourExecutionSession);
            //sessionExecutionEngine.ExecuteDefaultSession(greedyCycleExecutionSession);
            //sessionExecutionEngine.ExecuteDefaultSession(nearestNeighbourGraspExecutionSession);
            //sessionExecutionEngine.ExecuteDefaultSession(greedyCycleGraspExecutionSession);
            //sessionExecutionEngine.ExecuteDefaultSession(randomSolutionExecutionSession);
            //sessionExecutionEngine.ExecuteMultipleStartLocalSearchSession(multipleStartLocalSearchExecutionSession);
            //sessionExecutionEngine.ExecuteIteratedLocalSearchSession(iteratedLocalSearchExecutionSession);

            var drawer = new Drawer();

            //Console.WriteLine(Constants.NearestNeighbourText);
            //DAL.Instance.WriteToFile(nearestNeighbourExecutionSession, Constants.NearestNeighbourText);
            //drawer.DrawChart(Constants.NearestNeighbourFilename, nearestNeighbourExecutionSession.ConstructionStatisticsData.BestRoute);
            //drawer.DrawChart(Constants.NearestNeighbourOptimalizedFilename, nearestNeighbourExecutionSession.OptimalizationStatisticsData.BestRoute);

            //Console.WriteLine(Constants.GreedyCycleText);
            //DAL.Instance.WriteToFile(greedyCycleExecutionSession, Constants.GreedyCycleText);
            //drawer.DrawChart(Constants.GreedyCycleFilename, greedyCycleExecutionSession.ConstructionStatisticsData.BestRoute);
            //drawer.DrawChart(Constants.GreedyCycleOptimalizedFilename, greedyCycleExecutionSession.OptimalizationStatisticsData.BestRoute);

            //Console.WriteLine(Constants.NearestNeighboutGraspText);
            //DAL.Instance.WriteToFile(nearestNeighbourGraspExecutionSession, Constants.NearestNeighboutGraspText);
            //drawer.DrawChart(Constants.NearestNeighbourGraspFilename, nearestNeighbourGraspExecutionSession.ConstructionStatisticsData.BestRoute);
            //drawer.DrawChart(Constants.NearestNeighbourGraspOptimalizedFilename, nearestNeighbourGraspExecutionSession.OptimalizationStatisticsData.BestRoute);

            //Console.WriteLine(Constants.GreedyCycleGraspText);
            //DAL.Instance.WriteToFile(greedyCycleGraspExecutionSession, Constants.GreedyCycleGraspText);
            //drawer.DrawChart(Constants.GreedyCycleGraspFilename, greedyCycleGraspExecutionSession.ConstructionStatisticsData.BestRoute);
            //drawer.DrawChart(Constants.GreedyCycleGraspOptimalizedFilename, greedyCycleGraspExecutionSession.OptimalizationStatisticsData.BestRoute);

            //Console.WriteLine(Constants.RandomSolutionText);
            //DAL.Instance.WriteToFile(randomSolutionExecutionSession, Constants.RandomSolutionText);
            //drawer.DrawChart(Constants.RandomSolutionFilename, randomSolutionExecutionSession.ConstructionStatisticsData.BestRoute);
            //drawer.DrawChart(Constants.RandomSolutionOptimalizedFilename, randomSolutionExecutionSession.OptimalizationStatisticsData.BestRoute);

            //Console.WriteLine(Constants.MultipleStartLocalSearchText);
            //DAL.Instance.WriteToFile(multipleStartLocalSearchExecutionSession, Constants.MultipleStartLocalSearchText);
            //drawer.DrawChart(Constants.MultipleStartLocalSearchFilename, multipleStartLocalSearchExecutionSession.OptimalizationStatisticsData.BestRoute);

            //Console.WriteLine(Constants.IteratedLocalSearchText);
            //DAL.Instance.WriteToFile(iteratedLocalSearchExecutionSession, Constants.IteratedLocalSearchText);
            //drawer.DrawChart(Constants.IteratedLocalSearchFilename, iteratedLocalSearchExecutionSession.OptimalizationStatisticsData.BestRoute);

            //var LsExecutionSession = new AlgorithmExecutionSession(new RandomSolution(), new LocalSearch());

            var localSearchesResults = new List <AlgorithmOperatingData>();
            //var bestLocalSearchResult = new AlgorithmOperatingData {Distance = int.MaxValue};
            var bestLocalSearchDistance = int.MaxValue;
            var bestLocalSearchIndex    = 0;
            var localSearch             = new LocalSearch {
                ConstructionAlgorithm = new RandomSolution()
            };

            for (var i = 0; i < 10; i++)
            {
                localSearch.ConstructionAlgorithm.ResetAlgorithm();
                localSearch.ResetAlgorithm();
                localSearch.ConstructionAlgorithm.FindRoute(localSearch.ConstructionAlgorithm.OperatingData.UnusedNodes[0]);
                localSearch.OperatingData = localSearch.ConstructionAlgorithm.OperatingData.CloneData();
                localSearch.Optimize();
                var temporaryList = localSearch.OperatingData.CloneData();
                localSearchesResults.Add(temporaryList);
                if (localSearch.OperatingData.Distance >= bestLocalSearchDistance)
                {
                    continue;
                }
                bestLocalSearchDistance = localSearch.OperatingData.Distance;
                bestLocalSearchIndex    = i;
            }

            var averangeSimilarityToOthersBySharedVertices = new List <double>(new double[localSearchesResults.Count]);
            var averangeSimilarityToOthersBySharedEdges    = new List <double>(new double[localSearchesResults.Count]);
            var similarityToBestBySharedVertices           = new List <double>(new double[localSearchesResults.Count]);
            var similarityToBestBySharedEdges = new List <double>(new double[localSearchesResults.Count]);

            for (var i = 0; i < localSearchesResults.Count; i++)
            {
                for (var j = 0; j < localSearchesResults.Count; j++)
                {
                    if (i == j)
                    {
                        continue;
                    }
                    averangeSimilarityToOthersBySharedVertices[i] += Comparer.SharedVertices(localSearchesResults[i].PathNodes, localSearchesResults[j].PathNodes);
                    averangeSimilarityToOthersBySharedEdges[i]    += Comparer.SharedEdges(localSearchesResults[i].PathNodes, localSearchesResults[j].PathNodes);
                }
                if (i == bestLocalSearchIndex)
                {
                    continue;
                }
                similarityToBestBySharedVertices[i] = Comparer.SharedVertices(localSearchesResults[i].PathNodes, localSearchesResults[bestLocalSearchIndex].PathNodes);
                similarityToBestBySharedEdges[i]    = Comparer.SharedEdges(localSearchesResults[i].PathNodes, localSearchesResults[bestLocalSearchIndex].PathNodes);
            }

            averangeSimilarityToOthersBySharedVertices = averangeSimilarityToOthersBySharedVertices.Select(avg => avg / localSearchesResults.Count - 1) as List <double>;
            averangeSimilarityToOthersBySharedEdges    = averangeSimilarityToOthersBySharedEdges.Select(avg => avg / localSearchesResults.Count - 1) as List <double>;



            //DAL.Instance.CloseFileToWrite();

            Console.ReadKey();
        }