Example #1
0
        public void TestRemoveOpen()
        {
            // create a new empty route.
            int count     = 100;
            var customers = new List <int>();

            while (count > 0)
            {
                customers = new List <int>(new int[] { 0, 1, 2, 3, 4 });
                var route = new Optimization.Tours.Tour(customers, null);

                // test removing first.
                Assert.Catch <InvalidOperationException>(() => { route.Remove(route.First); });

                // remove customers.
                while (customers.Count > 2)
                {
                    var customerIdx = RandomGeneratorExtensions.GetRandom().Generate(
                        customers.Count);
                    var customer = customers[customerIdx];
                    if (customer != route.First &&
                        customer != route.Last)
                    {
                        customers.Remove(customer);

                        route.Remove(customer);

                        Assert.AreEqual(customers.Count, route.Count);
                        Assert.AreEqual(0, route.First);
                        Assert.AreEqual(null, route.Last);
                    }
                }
                count--;
            }
        }
        /// <summary>
        /// Solves the given problem.
        /// </summary>
        /// <returns></returns>
        public override Tour Solve(SequenceDirectedProblem problem, SequenceDirectedObjective objective, out float fitness)
        {
            var directedTour = new int[problem.Sequence.Count];
            var i            = 0;

            foreach (var c in problem.Sequence)
            {
                directedTour[i] = DirectedHelper.BuildDirectedId(c,
                                                                 RandomGeneratorExtensions.GetRandom().Generate(4));
                i++;
            }

            Tour tour = null;

            if (problem.Sequence.First == problem.Sequence.Last)
            {
                tour = new Tour(directedTour, directedTour[0]);
            }
            else
            {
                tour = new Tour(directedTour, directedTour[directedTour.Length - 1]);
            }
            fitness = objective.Calculate(problem, tour);

            return(tour);
        }
Example #3
0
        /// <summary>
        /// Returns true if there was an improvement, false otherwise.
        /// </summary>
        /// <returns></returns>
        public bool Apply(ProblemMock problem, ObjectiveMock objective, SolutionMock solution, int level, out float delta)
        {
            var before = solution.Value;
            var after  = RandomGeneratorExtensions.GetRandom().Generate(problem.Max);

            solution.Value = after;
            delta          = before - after; // when improvement, after is lower, delta > 0
            return(delta > 0);
        }
Example #4
0
        /// <summary>
        /// Creates a new tournament base selector.
        /// </summary>
        public TournamentSelectionOperator(
            double tournamentSize,
            double tournamentProbability)
        {
            _tournamentSize        = tournamentSize;
            _tournamentProbability = tournamentProbability;

            _random = RandomGeneratorExtensions.GetRandom();
        }
 public void Init()
 {
     RandomGeneratorExtensions.Reset();
     RandomGeneratorExtensions.GetGetNewRandom = () =>
     {
         return(new NotSoRandomGenerator(
                    new float[] { 0.6f, 0.2f, 0.8f }, new int[] { 0, 2, 3 }));
     };
 }
Example #6
0
        /// <summary>
        /// Solves the given problem.
        /// </summary>
        /// <returns></returns>
        public override SolutionMock Solve(ProblemMock problem, ObjectiveMock objective, out float fitness)
        {
            var solution = new SolutionMock()
            {
                Value = RandomGeneratorExtensions.GetRandom().Generate(problem.Max)
            };

            fitness = solution.Value;
            return(solution);
        }
Example #7
0
        /// <summary>
        /// Creates a new EAX crossover.
        /// </summary>
        public EAXOperator(int maxOffspring,
                           EdgeAssemblyCrossoverSelectionStrategyEnum strategy,
                           bool nn)
        {
            _maxOffspring = maxOffspring;
            _strategy     = strategy;
            _nn           = nn;

            _random = RandomGeneratorExtensions.GetRandom();
        }
Example #8
0
        public void TestShiftOpen()
        {
            RandomGeneratorExtensions.GetGetNewRandom = () => new RandomGenerator(116542346);

            // create a new empty route.
            var testCount = 10;
            var customers = new List <int>(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
            var route     = new Optimization.Tours.Tour(customers, null);

            // remove customers.
            int testIdx = 0;

            while (testIdx < testCount)
            {
                var customerIdx = RandomGeneratorExtensions.GetRandom().Generate(
                    customers.Count);
                var insertIdx = RandomGeneratorExtensions.GetRandom().Generate(
                    customers.Count - 2);
                if (customerIdx <= insertIdx)
                {
                    insertIdx = insertIdx + 1;
                }

                var customer = customers[customerIdx];
                var insert   = customers[insertIdx];
                if (customer != route.First &&
                    customer != route.Last)
                {
                    if (customerIdx < insertIdx)
                    {
                        customers.Insert(insertIdx + 1, customer);
                        customers.RemoveAt(customerIdx);
                    }
                    else
                    {
                        customers.RemoveAt(customerIdx);
                        customers.Insert(insertIdx + 1, customer);
                    }

                    route.ShiftAfter(customer, insert);

                    Assert.AreEqual(customers.Count, route.Count);
                    Assert.AreEqual(0, route.First);
                    Assert.AreEqual(null, route.Last);

                    ExtraAssert.ItemsAreEqual(customers, route);

                    testIdx++;
                }
            }
        }
Example #9
0
 /// <summary>
 /// Applies this operator using the given solutions and produces a new solution.
 /// </summary>
 /// <returns></returns>
 public SolutionMock Apply(ProblemMock problem, ObjectiveMock objective, SolutionMock solution1, SolutionMock solution2, out float fitness)
 {
     if (solution1.Value < solution2.Value)
     {
         fitness = solution1.Value - RandomGeneratorExtensions.GetRandom().Generate(
             solution2.Value - solution1.Value);
     }
     else
     {
         fitness = solution2.Value - RandomGeneratorExtensions.GetRandom().Generate(
             solution1.Value - solution2.Value);
     }
     return(new SolutionMock()
     {
         Value = fitness
     });
 }
Example #10
0
        /// <summary>
        /// Returns true if there was an improvement, false otherwise.
        /// </summary>
        /// <returns></returns>
        public bool Apply(ProblemMock problem, ObjectiveMock objective, SolutionMock solution, out float delta)
        {
            var fitnessBefore = solution.Value;
            var reduction     = RandomGeneratorExtensions.GetRandom().Generate(problem.Max / 50);

            if (reduction < problem.Max / 1000)
            { // mock the operator failing to find better solution.
                delta = float.MaxValue;
                return(false);
            }
            if (reduction > fitnessBefore)
            { // ok reduce to zero, problem solved.
                delta          = fitnessBefore;
                solution.Value = 0;
                return(true);
            }
            solution.Value = solution.Value - reduction;
            delta          = solution.Value - fitnessBefore; // when improvement, new is lower, delta < 0
            return(delta < 0);
        }
Example #11
0
        /// <summary>
        /// Selects a new solution for reproduction.
        /// </summary>
        /// <returns></returns>
        public int Select(ProblemMock problem, ObjectiveMock objective, Individual <SolutionMock, float>[] population, ISet <int> exclude)
        {
            // try two and select the best one.
            var selected = -1;

            do
            {
                var individual1 = RandomGeneratorExtensions.GetRandom().Generate(population.Length);
                var individual2 = RandomGeneratorExtensions.GetRandom().Generate(population.Length - 1);
                if (individual1 <= individual2)
                { // make sure they are different.
                    individual2++;
                }

                selected = individual2;
                if (population[individual1].Fitness < population[individual2].Fitness)
                {
                    selected = individual1;
                }
            } while (exclude.Contains(selected));
            return(selected);
        }
Example #12
0
        private static List <WeatherForecast> GetWeatherForecastData()
        {
            var weeklyForecast = new List <WeatherForecast>();
            var rng            = new Random();

            string[] Summaries =
                new[]
            {
                "Freezing",
                "Bracing",
                "Chilly",
                "Cool",
                "Mild",
                "Warm",
                "Balmy",
                "Hot",
                "Sweltering",
                "Scorching"
            };

            for (int i = 0; i < 7; i++)
            {
                var forecast = new WeatherForecast
                {
                    Date         = DateTime.Now.AddDays(i),
                    TemperatureC = rng.Next(-20, 55),
                    Humidity     = RandomGeneratorExtensions.NextDouble(rng, 0, 100),
                    Pressure     = RandomGeneratorExtensions.NextDouble(rng, 0, 100),
                    Summary      = Summaries[rng.Next(Summaries.Length)]
                };

                weeklyForecast.Add(forecast);
            }
            ;

            return(weeklyForecast);
        }
Example #13
0
 public void Dispose()
 {
     RandomGeneratorExtensions.Reset();
 }
        /// <summary>
        /// Applies this operator.
        /// </summary>
        public bool Apply(STSProblem problem, STSPObjective objective, Tour solution, out STSPFitness delta)
        {
            var before  = objective.Calculate(problem, solution);
            var weights = problem.Weights;

            delta = objective.Zero;

            var i        = _n;
            var toInsert = new List <int>();

            if (!_insertNew)
            { // select existing customers, to reinsert.
                while (solution.Count > 1 && i > 0)
                {
                    i--;
                    var index   = RandomGeneratorExtensions.GetRandom().Generate(solution.Count);
                    var current = solution.GetCustomerAt(index);
                    if (current != Constants.NOT_SET)
                    {
                        if (current != solution.First &&
                            current != solution.Last &&
                            solution.Remove(current))
                        {
                            toInsert.Add(current);
                        }
                    }
                }
            }
            else if (solution.Count < problem.Weights.Length)
            { // select random new customer to insert.
                while (solution.Count > 1 && i > 0)
                {
                    i--;
                    var current = RandomGeneratorExtensions.GetRandom().Generate(problem.Weights.Length);
                    if (!solution.Contains(current))
                    {
                        if (current != solution.First &&
                            current != solution.Last &&
                            solution.Remove(current))
                        {
                            toInsert.Add(current);
                        }
                    }
                }
            }

            var fitness = objective.Calculate(problem, solution);

            foreach (var current in toInsert)
            {
                // insert new.
                Pair position;
                var  cost = CheapestInsertionHelper.CalculateCheapest(solution, weights, current, out position);
                if (cost + fitness.Weight < problem.Max)
                {
                    solution.InsertAfter(position.From, current);
                    fitness.Weight    = fitness.Weight + cost;
                    fitness.Customers = fitness.Customers + 1;
                }
            }

            var after = objective.Calculate(problem, solution);

            delta = objective.Subtract(problem, after, before);
            return(objective.CompareTo(problem, before, after) > 0);
        }
        /// <summary>
        /// Applies this operator.
        /// </summary>
        public bool Apply(STSProblem problem, STSPObjective objective, Tour solution, out STSPFitness delta)
        {
            var before  = objective.Calculate(problem, solution);
            var weights = problem.Weights;

            delta = objective.Zero;

            // select random new customers to insert.
            var toInsert = new List <int>();

            if (solution.Count < problem.Weights.Length &&
                _toInsert > 0)
            {
                var i = _toInsert;
                while (solution.Count > 1 && i > 0)
                {
                    i--;
                    var current    = RandomGeneratorExtensions.GetRandom().Generate(problem.Weights.Length / 2);
                    var directedId = solution.GetDirectedId(current);
                    if (directedId == Constants.NOT_SET &&
                        !toInsert.Contains(current))
                    {
                        toInsert.Add(current);
                    }
                }
            }

            // select existing customers, to reinsert.
            if (_toRemove > 0)
            {
                var i = _toRemove;
                while (solution.Count > 1 && i > 0)
                {
                    i--;
                    var index      = RandomGeneratorExtensions.GetRandom().Generate(solution.Count);
                    var directedId = solution.GetCustomerAt(index);
                    if (directedId != Constants.NOT_SET)
                    {
                        var current = DirectedHelper.ExtractId(directedId);
                        if (directedId != solution.First &&
                            directedId != solution.Last &&
                            solution.Remove(directedId) &&
                            !toInsert.Contains(current))
                        {
                            toInsert.Add(current);
                        }
                    }
                }
            }

            // shuffle the customers to insert.
            toInsert.Shuffle();

            // insert all customers without exceeding max.
            var fitness = objective.Calculate(problem, solution);

            foreach (var current in toInsert)
            {
                var cost = solution.InsertCheapestDirected(problem.Weights, problem.TurnPenalties, current,
                                                           problem.Max - fitness.Weight);
                if (cost > 0)
                {
                    fitness.Weight += cost;
                    fitness.Customers++;
                }
            }

            var after = objective.Calculate(problem, solution);

            delta = objective.Subtract(problem, after, before);
            return(objective.CompareTo(problem, before, after) > 0);
        }