Esempio n. 1
0
        public override void Ejecutar(Knapsack theProblem, Random myRandom)
        {
            EFOs = 0;

            var population = new List <PSOSolution>();

            for (var i = 0; i < PopulationSize; i++)
            {
                var s = new PSOSolution(theProblem, this);
                s.RandomInitialization(myRandom);
                population.Add(s);
            }
            population.Sort((x, y) => - 1 * x.Fitness.CompareTo(y.Fitness));
            BestSolution = new PSOSolution(population[0]);

            if (population[0].IsOptimalKnown())
            {
                return;
            }

            for (var g = 1; g < MaxGenerations; g++)
            {
                for (var i = 0; i < PopulationSize; i++)
                {
                    population[i].UpdateVelocity((PSOSolution)BestSolution, W, C1, C2, myRandom);
                    population[i].UpdatePosition(myRandom);
                    population[i].Repare(myRandom);
                    population[i].Complete(myRandom, new List <int>());
                    population[i].Evaluate();
                    population[i].UpdateHistory();
                }

                population.Sort((x, y) => - 1 * x.Fitness.CompareTo(y.Fitness));

                population[0].LocalOptimizer(LocalIterations, myRandom);


                if (BestSolution.Fitness < population[0].Fitness)
                {
                    BestSolution = new PSOSolution(population[0]);
                }

                if (EFOs >= MaxEFOs)
                {
                    break;
                }
                if (population[0].IsOptimalKnown())
                {
                    break;
                }
            }
        }
Esempio n. 2
0
 public PSOSolution(PSOSolution original) : base(original)
 {
     LocalBestObjects = new int[MyProblem.TotalItems];
     for (var i = 0; i < MyProblem.TotalItems; i++)
     {
         LocalBestObjects[i] = original.LocalBestObjects[i];
     }
     LocalBestFitness = original.LocalBestFitness;
     Velocity         = new double[MyProblem.TotalItems];
     for (var i = 0; i < MyProblem.TotalItems; i++)
     {
         Velocity[i] = original.Velocity[i];
     }
 }
Esempio n. 3
0
 public void UpdateVelocity(PSOSolution bestSolution, double w,
                            double c1, double c2, Random myRandom)
 {
     for (var i = 0; i < MyProblem.TotalItems; i++)
     {
         Velocity[i] = w * Velocity[i] +
                       c1 * myRandom.NextDouble() * (LocalBestObjects[i] - Objects[i]) +
                       c2 * myRandom.NextDouble() * (bestSolution.Objects[i] - Objects[i]);
         if (Velocity[i] > 4)
         {
             Velocity[i] = 4;
         }
         if (Velocity[i] < -4)
         {
             Velocity[i] = -4;
         }
     }
 }