コード例 #1
0
        //small value is good, high is bad (it is a function of time and time need to be as small as it is possible)
        public double FittnesFunctionF(SubjectTraveller subject)
        {
            int    actualWeight = 0;
            double vc           = _container.MaxSpeed;
            double f            = CalculateTimeBetweenCities(subject.FirstCity, subject.TripPlan[0], vc);
            int    itemWeight   = subject.TripPlan[0].ItemsInCity.Last().Weight;

            if (CanPickUpItem(itemWeight, actualWeight, _container.Capacity))
            {
                actualWeight += itemWeight;
            }

            for (int i = 0; i < subject.TripPlan.Count() - 1; i++)
            {
                vc         = _container.MaxSpeed - actualWeight * ((_container.MaxSpeed - _container.MinSpeed) / _container.Capacity);
                f         += CalculateTimeBetweenCities(subject.TripPlan[i], subject.TripPlan[i + 1], vc);
                itemWeight = subject.TripPlan[i + 1].ItemsInCity.Last().Weight;
                if (CanPickUpItem(itemWeight, actualWeight, _container.Capacity))
                {
                    actualWeight += itemWeight;
                }
            }

            vc = _container.MaxSpeed - actualWeight * ((_container.MaxSpeed - _container.MinSpeed) / _container.Capacity);
            f += CalculateTimeBetweenCities(subject.TripPlan[subject.TripPlan.Count() - 1], subject.FirstCity, vc);

            return(f);
        }
コード例 #2
0
        public void FixSubjectTraveller(SubjectTraveller st)
        {
            List <City> chosen = new List <City>();
            List <City> left   = new List <City>();

            foreach (City c in _container._Cities)
            {
                if (st.TripPlan.Contains(c))
                {
                    left.Remove(c);
                }
                else
                {
                    left.Add(c);
                }
            }


            for (int i = 0; i < st.TripPlan.Length; i++)
            {
                for (int j = i + 1; j < st.TripPlan.Length; i++)
                {
                    if (st.TripPlan[i].Equals(st.TripPlan[j]))
                    {
                        st.TripPlan[j] = left[left.Count];
                        left.Remove(left[left.Count]);
                    }
                }
            }
        }
コード例 #3
0
        //Generates random population(subset of chromosoms/solutions )
        public void InitPopulation(SubjectTraveller[] pop, double mutProp)
        {
            for (int j = 0; j < pop.Length; j++)
            {
                List <int> citiesIndexesLeft = new List <int>();
                //becouse count of cities - first city
                pop[j] = new SubjectTraveller(_container.Dimension - 1, mutProp, _container._Cities[0]);
                //{
                //    FirstCity =
                //};
                foreach (City c in _container._Cities)
                {
                    citiesIndexesLeft.Add(c.CityId);
                }
                //usuwamy 0 bo już jest dodane w FirstCity
                citiesIndexesLeft.RemoveAt(0);

                if (pop[j].TripPlan.Length != citiesIndexesLeft.Count)
                {
                    throw new Exception("Length of trip is not the same as Count of cities");
                }

                for (int i = 0; i < pop[j].TripPlan.Length; i++)
                {
                    //int cityNumber = _rnd.Next(citiesIndexesLeft.Count);
                    int rndNumOfCityFromCitiesIndexesLeft = ThreadSafeRandom.ThisThreadsRandom.Next(citiesIndexesLeft.Count);
                    pop[j].TripPlan[i] = _container._Cities[citiesIndexesLeft[rndNumOfCityFromCitiesIndexesLeft] - 1];
                    citiesIndexesLeft.Remove(rndNumOfCityFromCitiesIndexesLeft);
                }
            }
        }
コード例 #4
0
        public SubjectTraveller[] SelectCrossMutate(SubjectTraveller[] population, CrossingType crossType)
        {
            //SortPopulationByTravelTimeAsc();  //NIE MA TO SENSU - W TURNIEJU TO I TAK WYBIERANY JEST NAJLEPSZY POSROD KILKU
            List <SubjectTraveller> newGeneration = new List <SubjectTraveller>(Env.POP_SIZE);

            //int actualPopSize = 0;

            while (newGeneration.Count <= Env.POP_SIZE)
            {
                double           rndNum = ThreadSafeRandom.ThisThreadsRandom.NextDouble();
                SubjectTraveller child;
                SubjectTraveller mother = TournamentSelection(Env.CROSS_RATE, Env.TOURNAMENT_SIZE, population);

                if (rndNum <= Env.CROSS_RATE)
                {
                    SubjectTraveller father = TournamentSelection(Env.CROSS_RATE, Env.TOURNAMENT_SIZE, population);
                    child = crossType(mother, father);
                }
                else
                {
                    child = new SubjectTraveller(mother);
                }
                child.Mutate();
                if (!newGeneration.Contains(child))
                {
                    newGeneration.Add(child);
                }
            }

            return(newGeneration.ToArray());
        }
コード例 #5
0
        public SubjectTraveller CrossOverOX1(SubjectTraveller mother, SubjectTraveller father)
        {
            int halfOfTripLength = mother.TripPlan.Length / 2;
            int firstPoint       = ThreadSafeRandom.ThisThreadsRandom.Next(halfOfTripLength - (Convert.ToInt32(halfOfTripLength * 0.2))) + Convert.ToInt32(halfOfTripLength * 0.1);
            int secondPoint      = ThreadSafeRandom.ThisThreadsRandom.Next(halfOfTripLength - (Convert.ToInt32(halfOfTripLength * 0.2))) + Convert.ToInt32(halfOfTripLength * 0.1) + halfOfTripLength;

            SubjectTraveller child = new SubjectTraveller(mother.TripPlan.Length, mother.MutationPropability, mother.FirstCity);

            //SubjectTraveller secondChild = new SubjectTraveller(mother.TripPlan.Length, mother.MutationPropability, mother.FirstCity);

            for (int i = firstPoint; i <= secondPoint; i++)
            {
                child.TripPlan[i] = mother.TripPlan[i];
            }

            List <City> restCities = new List <City>();

            for (int i = secondPoint + 1; i < father.TripPlan.Length; i++)
            {
                restCities.Add(father.TripPlan[i]);
            }
            for (int i = 0; i < secondPoint + 1; i++)
            {
                restCities.Add(father.TripPlan[i]);
            }
            foreach (City c in child.TripPlan)
            {
                restCities.Remove(c);
            }

            bool flag = true;

            while (flag)
            {
                int numberOfGeneInFather = 0;
                for (int i = secondPoint + 1; i < child.TripPlan.Length; i++)
                {
                    child.TripPlan[i] = restCities[numberOfGeneInFather];
                    numberOfGeneInFather++;
                }
                for (int i = 0; i < firstPoint; i++)
                {
                    child.TripPlan[i] = restCities[numberOfGeneInFather];
                    numberOfGeneInFather++;
                }

                if (!child.TripPlan.Contains(null))
                {
                    flag = false;
                }
            }

            return(child);
            //return new SubjectTraveller[2] { firstChild, secondChild };
        }
コード例 #6
0
        public SubjectTraveller CrossOverInKindOfUniform(SubjectTraveller mother, SubjectTraveller father)
        {
            //HashSet<SubjectTraveller> children = new HashSet<SubjectTraveller>();
            SubjectTraveller child = new SubjectTraveller(mother.TripPlan.Length, mother.MutationPropability, mother.FirstCity);

            //double crossingImportanceMother = mother.TravelTime;
            //double crossingImportanceFather = father.TravelTime;
            double crossingImportanceMother;

            //double crossingImportanceFather;
            if (mother.TravelTime >= father.TravelTime)
            {
                crossingImportanceMother = 0.8;
                //crossingImportanceFather = 0.3;
            }
            else
            {
                crossingImportanceMother = 0.2;
                //crossingImportanceFather = 0.7;
            }

            double randomNumber = ThreadSafeRandom.ThisThreadsRandom.NextDouble();

            for (int i = 0; i < mother.TripPlan.Length; i++)
            {
                if (randomNumber < crossingImportanceMother)
                {
                    if (!child.TripPlan.Contains(mother.TripPlan[i]))
                    {
                        child.TripPlan[i] = mother.TripPlan[i];
                    }
                    else
                    {
                        child.TripPlan[i] = father.TripPlan[i];
                    }
                }
                else
                {
                    if (!child.TripPlan.Contains(father.TripPlan[i]))
                    {
                        child.TripPlan[i] = father.TripPlan[i];
                    }
                    else
                    {
                        child.TripPlan[i] = mother.TripPlan[i];
                    }
                }
            }

            return(child);
        }
コード例 #7
0
        public void FitFunctionTest()
        {
            DataContainer container = DataContainer.Instance;

            container.Capacity  = 6;
            container.Dimension = 4;
            container.MaxSpeed  = 1.5;
            container.MinSpeed  = 0.6;

            City cityA = new City(1, 1, 1);
            City cityB = new City(2, 4, 5);
            City cityC = new City(3, 8, 2);
            City cityD = new City(4, 2, -6);

            cityB.ItemsInCity.Add(new Item(1, 8, 3, 2));
            cityC.ItemsInCity.Add(new Item(2, 6, 5, 3));
            cityD.ItemsInCity.Add(new Item(3, 3, 1, 4));

            List <City> cities = new List <City>()
            {
                cityA, cityB, cityC, cityD
            };
            DataContainer dc = DataContainer.Instance;

            dc._Cities = cities;

            SubjectTraveller st = new SubjectTraveller(4, 0.4, cityA);

            st.FirstCity = cityA;
            st.TripPlan  = new City[] { cityB, cityC, cityD };


            TTP    tsp    = new TTP();
            double result = tsp.FittnesFunction(st);

            Console.WriteLine("Result is {0}", result);

            Assert.IsTrue(true);
        }
コード例 #8
0
        public void SolveTTPbyGoToNarestCity(int itemChooseMethod)
        {
            foreach (City c in _container._Cities)
            {
                c.SortItemsBy(itemChooseMethod);
            }

            SubjectTraveller _solution;
            List <int>       citiesIndexesLeft = new List <int>();

            _solution = new SubjectTraveller(_container.Dimension - 1, Env.MUT_RATE, _container._Cities[0]);

            foreach (City c in _container._Cities)
            {
                citiesIndexesLeft.Add(c.CityId);
            }
            //usuwamy 0 bo już jest dodane w FirstCity
            citiesIndexesLeft.Remove(1);

            if (_solution.TripPlan.Length != citiesIndexesLeft.Count)
            {
                throw new Exception("Length of trip is not the same as Count of cities");
            }

            int startPointIndex = 1;

            for (int i = 0; i < _solution.TripPlan.Length; i++)
            {
                startPointIndex = SearchNearestCityIndex(startPointIndex, citiesIndexesLeft);

                _solution.TripPlan[i] = _container._Cities[startPointIndex - 1];
                citiesIndexesLeft.Remove(startPointIndex);
            }

            _solution.TravelTime = FittnesFunction(_solution);

            Console.WriteLine(_solution.TravelTime.ToString());
        }
コード例 #9
0
        public void SwapTest()
        {
            City cityA = new City(1, 1, 1);
            City cityB = new City(2, 4, 5);
            City cityC = new City(3, 8, 2);
            City cityD = new City(4, 2, -6);

            cityB.ItemsInCity.Add(new Item(1, 8, 3, 2));
            cityC.ItemsInCity.Add(new Item(2, 6, 5, 3));
            cityD.ItemsInCity.Add(new Item(3, 3, 1, 4));

            SubjectTraveller st = new SubjectTraveller(4, 0.4, cityA);

            st.FirstCity = cityA;
            st.TripPlan  = new City[] { cityB, cityC, cityD };

            foreach (City c in st.TripPlan)
            {
                Console.WriteLine(c.ToString());
            }
            //st.SwapInTripPlan(0, 2);
            st.SwapInMemory(0, 2);
            Console.WriteLine("AFTER REVERSE:");
            foreach (City c in st.TripPlan)
            {
                Console.WriteLine(c.ToString());
            }
            Console.WriteLine("Cities");
            Console.WriteLine("City A: {0}", cityA.ToString());
            Console.WriteLine("City B: {0}", cityB.ToString());
            Console.WriteLine("City C: {0}", cityC.ToString());
            Console.WriteLine("City D: {0}", cityD.ToString());


            Assert.IsTrue(true);
        }
コード例 #10
0
        public void StartGeneticTTP(int sizeOfPopulation, int coutOfGenerations, int itemChooseMethod, double mutProp, int crossType)
        {
            //sort items in Cities 1- sortByBestRatio(value/weight)
            foreach (City c in _container._Cities)
            {
                c.SortItemsBy(itemChooseMethod);
            }

            //INIT POPULATION
            SubjectTraveller[] _population;
            _population = new SubjectTraveller[sizeOfPopulation];
            //SubjectTraveller[] population = new SubjectTraveller[sizeOfPopulation];
            InitPopulation(_population, mutProp);

            //CHECK POPULATION
            foreach (SubjectTraveller subTrav in _population)
            {
                //FixSubjectTraveller(subTrav); //no need to fix

                subTrav.TravelTime = FittnesFunction(subTrav);
                //jeśli FittnesFunctionF to musi być odwrotnie znak nierówności

                if (subTrav.TravelTime > _bestG)
                {
                    _bestG = subTrav.TravelTime;
                }
                if (subTrav.TravelTime < _worstG)
                {
                    _worstG = subTrav.TravelTime;
                }
                _sumG += subTrav.TravelTime;

                //Console.WriteLine(subTrav); //print to check
            }
            _avgG = _sumG / _population.Length;
            _generationMaxFittnesMap.Add(0, _bestG);
            _generationMinFittnesMap.Add(0, _worstG);
            _generationAvgFittnesMap.Add(0, _avgG);


            CrossingType ctD;

            if (crossType == 1)
            {
                ctD = new CrossingType(CrossOverInKindOfUniform);
            }
            else if (crossType == 2)
            {
                ctD = new CrossingType(CrossOverOX1);
            }
            else
            {
                ctD = new CrossingType(CrossOverOX1);
            }

            //Console.WriteLine(_bestTravelTime);

            for (int i = 0; i < Env.GENERATION_COUNT; i++)
            {
                _sumG = 0;
                double bestFittnesInGeneration  = Double.MinValue;
                double worstFittnesInGeneration = Double.MaxValue;
                //SELECT CANDIDATS TO CROSSING
                //CROSS
                //MUTATE

                _population = SelectCrossMutate(_population, ctD);

                //CHECK NEW POPULATION
                foreach (SubjectTraveller subTrav in _population)
                {
                    subTrav.TravelTime = FittnesFunction(subTrav);
                    if (subTrav.TravelTime > bestFittnesInGeneration)
                    {
                        bestFittnesInGeneration = subTrav.TravelTime;
                    }
                    if (subTrav.TravelTime < worstFittnesInGeneration)
                    {
                        worstFittnesInGeneration = subTrav.TravelTime;
                    }
                    if (subTrav.TravelTime > _bestG)
                    {
                        _bestG = subTrav.TravelTime;
                    }
                    if (subTrav.TravelTime < _worstG)
                    {
                        _worstG = subTrav.TravelTime;
                    }
                    _sumG += subTrav.TravelTime;
                }
                _avgG = _sumG / _population.Length;
                _generationMaxFittnesMap.Add(i + 1, bestFittnesInGeneration);
                _generationMinFittnesMap.Add(i + 1, worstFittnesInGeneration);
                _generationAvgFittnesMap.Add(i + 1, _avgG);
            }

            //PrintMinMaxAvgForEachGen();

            Console.WriteLine($"The Best is: {_bestG}");
            Console.WriteLine($"The Worst is: {_worstG}");
        }
コード例 #11
0
        public void StartTTP(int sizeOfPopulation, int coutOfGenerations, int itemChooseMethod, double mutProp, int crossType)
        {
            foreach (City c in _container._Cities)
            {
                c.SortItemsBy(itemChooseMethod);
            }

            SubjectTraveller[] _population;
            _population = new SubjectTraveller[sizeOfPopulation];
            InitPopulation(_population, mutProp);

            //CHECK POPULATION
            foreach (SubjectTraveller subTrav in _population)
            {
                subTrav.TravelTime = FittnesFunction(subTrav);

                if (subTrav.TravelTime > _bestG)
                {
                    _bestG = subTrav.TravelTime;
                }
                if (subTrav.TravelTime < _worstG)
                {
                    _worstG = subTrav.TravelTime;
                }
                _sumG += subTrav.TravelTime;

                //Console.WriteLine(subTrav); //print to check
            }
            _avgG = _sumG / _population.Length;


            CrossingType ctD;

            if (crossType == 1)
            {
                ctD = new CrossingType(CrossOverInKindOfUniform);
            }
            else if (crossType == 2)
            {
                ctD = new CrossingType(CrossOverOX1);
            }
            else
            {
                ctD = new CrossingType(CrossOverOX1);
            }

            for (int i = 0; i < Env.GENERATION_COUNT; i++)
            {
                _sumG = 0;
                double bestFittnesInGeneration  = Double.MinValue;
                double worstFittnesInGeneration = Double.MaxValue;
                //SELECT CANDIDATS TO CROSSING
                //CROSS
                //MUTATE

                _population = SelectCrossMutate(_population, ctD);

                //CHECK NEW POPULATION
                foreach (SubjectTraveller subTrav in _population)
                {
                    subTrav.TravelTime = FittnesFunction(subTrav);
                    if (subTrav.TravelTime > bestFittnesInGeneration)
                    {
                        bestFittnesInGeneration = subTrav.TravelTime;
                    }
                    if (subTrav.TravelTime < worstFittnesInGeneration)
                    {
                        worstFittnesInGeneration = subTrav.TravelTime;
                    }
                    if (subTrav.TravelTime > _bestG)
                    {
                        _bestG = subTrav.TravelTime;
                    }
                    if (subTrav.TravelTime < _worstG)
                    {
                        _worstG = subTrav.TravelTime;
                    }
                    _sumG += subTrav.TravelTime;
                }
                _avgG = _sumG / _population.Length;
            }
        }