public BackPackIndividual BruteForce(BackPackEnvironment environment)
        {
            var possibleIndividuals = new List<BackPackIndividual>();

            int genomeSize = environment.ComputeGenomeSize();

            var chromosome = new int[genomeSize];
            var posssibilitiesPerInt = environment.AvailableItems.Count > 31 ?
                uint.MaxValue :
                (uint)1 << environment.AvailableItems.Count; // 2^n
            
            for (uint i = 0; i < posssibilitiesPerInt; i++)
            {
                for (int j = 0; j < genomeSize; j++)
                {
                    chromosome[j] = (int)i;
                    var individual = new BackPackIndividual(environment);
                    individual.Genome.Chromosome = (int[])chromosome.Clone();

                    if (environment.Validate(individual))
                    {
                        possibleIndividuals.Add(individual);
                    }
                }
            }

            return possibleIndividuals.Aggregate((a, b) => environment.RateFitness(a) > environment.RateFitness(b) ? a : b);
        }
        public void SolveBackPackProblemWith16RandomItems()
        {
            const int tests = 10;

            double bfFitness = 0.0;
            double gsFitness = 0.0;

            for (int n = 0; n < tests; n++)
            {
                var backPack = new BackPack(2000);
                var items = BackPackEnvironmentTest.RandomItems(16, backPack.Volume, 200);

                var environment = new BackPackEnvironment(backPack, items, 100);

                var solver = new Solver<BackPackIndividual>(environment);
                solver.Start(() => solver.CurrentGeneration > 10);

                var bf = BruteForce(environment);
                var gs = solver.CurrentOptimum;

                Console.WriteLine(environment.RateFitness(bf));
                Console.WriteLine(environment.RateFitness(gs));

                bfFitness += environment.RateFitness(bf);
                gsFitness += environment.RateFitness(gs);
            }
            // Should be atleast 90% of BF'ed fitness
            Console.WriteLine(gsFitness / bfFitness);
            Assert.IsTrue(bfFitness * 0.9 
                <= gsFitness);

        }
        public void MutateIndividual()
        {
            var backPack = new BackPack(volume: 1000);
            var items = BackPackEnvironmentTest.RandomItems(8, backPack.Volume, 100);
            var environment = new BackPackEnvironment(backPack, items);

            var individual = environment.NewRandom();
            var mutatedIndividual = individual.Mutate();

            Assert.AreNotEqual(individual.Genome.Chromosome, mutatedIndividual.Genome.Chromosome);
        }
        public void CreateEnvironment()
        {
            var backPack = new BackPack(volume: 1000);
            var items = new List<BackPackItem>(
                new [] { 
                    new BackPackItem(200, 20),
                    new BackPackItem(300, 8),
                    new BackPackItem(500, 30),
                    new BackPackItem(150, 10)
                });

            var environment = new BackPackEnvironment(backPack, items);

            Assert.AreEqual(backPack, environment.BackPack);
            Assert.AreEqual(environment.AvailableItems, items);
        }
        public void CrossIndividuals()
        {
            var backPack = new BackPack(volume: 1000);
            var items = BackPackEnvironmentTest.RandomItems(8, backPack.Volume, 100);
            var environment = new BackPackEnvironment(backPack, items);

            var a = new BackPackIndividual(environment) 
                { Genome = new BackPackIndividualGenome(new[]{0xF0}) }; //0b11110000
            var b = new BackPackIndividual(environment) 
                
                { Genome = new BackPackIndividualGenome(new[]{0xF}) }; //0b00001111
            
            var child = new BackPackIndividual(environment) 
                { Genome = new BackPackIndividualGenome(new[]{0xF7}) }; //0b11110111

            Assert.AreEqual(child.Genome.Chromosome, a.Cross(b).Genome.Chromosome);
        }
        public void ValidateIndividual()
        {
            var backPack = new BackPack(volume: 1000);
            var items = new List<BackPackItem>(
                new [] { 
                new BackPackItem(200, 20),
                new BackPackItem(300, 8),
                new BackPackItem(500, 30),
                new BackPackItem(150, 10)
            });

            var environment = new BackPackEnvironment(backPack, items);

            var invalidIndividual = new BackPackIndividual(environment);
            invalidIndividual.Genome.Chromosome = new[]{0xF}; //0xF=15=0b1111

            var validIndividual = new BackPackIndividual(environment);
            validIndividual.Genome.Chromosome = new[]{0x7}; //0x7=0b0111

            Assert.IsFalse(environment.Validate(invalidIndividual));
            Assert.IsTrue(environment.Validate(validIndividual));
        }
        public void SolveBackPackProblemWith512RandomItems()
        {
            var backPack = new BackPack(2000);
            var items = BackPackEnvironmentTest.RandomItems(512, backPack.Volume, 100);

            var environment = new BackPackEnvironment(backPack, items, individualCountAtStart: 100);

            var solver = new Solver<BackPackIndividual>(environment);

            double previous = 0;
            int c = 0;
            Func<bool> terminationCondition = () =>
                {
                    if (solver.CurrentGeneration > 10)
                    {
                        double current = environment.RateFitness(solver.CurrentOptimum);
                        if (previous != current)
                        {
                            previous = current;
                            c = 0;
                        }
                        else
                        {
                            c++;
                            if (c > 3)
                            {
                                return true;
                            }
                        }
                    }
                    return false;
                };

            solver.Start(terminationCondition);

        }
        public void RateFitnessOfRandomIndividuals()
        {
            const int tests = 3;

            for (int n = 0; n < tests; n++)
            {
                var backPack = new BackPack(volume: random.Next(10000));
                var items = RandomItems(random.Next(512), backPack.Volume, 100);

                var environment = new BackPackEnvironment(backPack, items);

                for (int i = 0; i <= items.Count; i++)
                {
                    // compute chromosome
                    var chromosome = new int[environment.ComputeGenomeSize()];
                        // set every bit that encodes an Item at an index j < i
                    for (int j = 0; j < i; j++)
                    {
                        ChromosomeIndex index = environment.ComputeChromosomeIndex(j);
                        IntBitHelper.Set(ref chromosome[index.IntIndex], index.BitIndex);
                    }

                    var individual = new BackPackIndividual(environment) 
                        { Genome = new BackPackIndividualGenome(chromosome) };

                    // compute fitness with Item-List
                    double fitness = 0.0;
                    for (int j = 0; j < i; j++)
                    {
                        fitness += items[j].Value;
                    }

                    Assert.AreEqual(fitness, environment.RateFitness(individual));
                }
            }
        }
示例#9
0
		public static void Main(string[] args)
		{
            const int backPackVolume = 2000;
            const int highestItemVolume = backPackVolume;
            const int highestItemValue = 100;
            const int itemCount = 512;
            const int individualCountAtStart = 100;

            List<BackPackItem> randomItems = RandomItems(itemCount, highestItemVolume, highestItemValue);

			for (int i = 0; i < randomItems.Count; i++)
			{
				BackPackItem item = randomItems[i];
				Console.WriteLine("\n" + (i + 1));
				Console.WriteLine("Value: " + item.Value + "\n" + "Volume: " + item.Volume + "\n\n");
			}


            BackPackEnvironment environment = new BackPackEnvironment(new BackPack(backPackVolume), randomItems, individualCountAtStart);


			Stopwatch stopwatch = new Stopwatch();

			stopwatch.Start();

			double previous = 0;
			int c = 0;
            Solver<BackPackIndividual> solver = new Solver<BackPackIndividual>(environment);
            Func<bool> terminationCondition = () =>
				{
					if (solver.CurrentGeneration > 10)
					{
						double current = environment.RateFitness(solver.CurrentOptimum);
						if (previous != current)
						{
							previous = current;
							c = 0;
						}
						else
						{
							c++;
							if (c > 3)
							{
								return true;
							}
						}
					}
					return false;
				};

            solver.Start(terminationCondition);

			stopwatch.Stop();

			double gsNeeded = stopwatch.ElapsedMilliseconds;

			Console.WriteLine("Genetic Solver Needed: " + gsNeeded + "ms");

			BackPackIndividual fittest = solver.CurrentOptimum;

			Console.WriteLine("Optimum: " + fittest);

			Console.WriteLine("Optimum-Fitness: " + environment.RateFitness(fittest));
		}