예제 #1
0
        public async Task <IList <Individual> > HandleSelection(IList <Individual> SelectionBoxs, int capacity, Selection selectionSelected)
        {
            var totalRoulet = 0;
            var selection   = new List <Individual>();
            await Task.Run(() =>
            {
                for (int i = 0; i < SelectionBoxs.Count; i++)
                {
                    totalRoulet += SelectionBoxs[i].Fitness;
                }
            });

            await Task.Run(() =>
            {
                while (capacity-- > 0)
                {
                    //Random between 0 and sum
                    var pointer = RandomHelper.CreateRandom(0, totalRoulet);
                    for (int i = 0; i < SelectionBoxs.Count; i++)
                    {
                        if (pointer <= SelectionBoxs[i].Fitness)
                        {
                            selection.Add(SelectionBoxs[i]);
                            break;
                        }
                        pointer -= SelectionBoxs[i].Fitness;
                    }
                }
            });

            return(selection);
        }
예제 #2
0
        public Task <Individual> HandleMutation(Individual input, Mutation mutation)
        {
            //Choose one point from chromosome
            var point = RandomHelper.CreateRandom(input.Generate.Count());

            input.Generate[point] = (input.Generate[point].Equals(true)) ? false : true;
            return(Task.FromResult(new Individual(input.Generate, _items, _knapsackCapacity)));
        }
예제 #3
0
        public static void CreateInsureNum(DateTime date, int count)
        {
            if (app == null)
            {
                string appFileName = System.IO.Path.Combine(rootPath, "InsureNumApp.config");//HzIns.BasicFramework.Common.Utility.GetFilePath("\\Config\\" + "InsureNumApp.config");
                using (System.IO.FileStream steam = new System.IO.FileStream(appFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None))
                {
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(steam))
                    {
                        app = reader.ReadToEnd().Trim().Split(',');
                    }
                }
            }
            List <string> numList  = null;
            List <string> usedList = new List <string>();
            string        preNum   = date.ToString("yyMMdd");// +app[DateTime.Now.Second % app.Length];

            if (insureNumList.ContainsKey(preNum))
            {
                numList = insureNumList[preNum];
                if (numList.Count >= count)
                {
                    return;
                }
            }
            else
            {
                numList = new List <string>();
                insureNumList.Add(preNum, numList);
            }
            string filePath = System.IO.Path.Combine(rootPath, String.Format("{0}\\{1}", "InsureNum", date.ToString("yyMM")));//HzIns.BasicFramework.Common.Utility.GetFilePath(String.Format("\\Data\\{0}\\{1}", "InsureNum", date.ToString("yyMM")));

            if (!System.IO.Directory.Exists(filePath))
            {
                System.IO.Directory.CreateDirectory(filePath);
            }

            string fileName = System.IO.Path.Combine(filePath, preNum + ".dat");

            using (System.IO.FileStream steam = new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read, System.IO.FileShare.None))
            {
                using (System.IO.StreamReader reader = new System.IO.StreamReader(steam))
                {
                    usedList = reader.ReadToEnd().Split(',').ToList();
                }
            }
            while (numList.Count < count)
            {
                string insureNum = preNum + app[DateTime.Now.Second % app.Length] + RandomHelper.CreateRandom(1000000, 9999999);
                if (numList.Exists(c => c == insureNum) || usedList.Exists(c => c == insureNum))
                {
                    continue;
                }
                numList.Add(insureNum);
            }
        }
        public Task <(MinFuncIndividual first, MinFuncIndividual second)> HandleRecombination(MinFuncIndividual parent1, MinFuncIndividual parent2, Recombination recombination)
        {
            if (recombination == Recombination.Single)
            {
                var random = RandomHelper.CreateRandom(0, _chromosomeLength);
                var child1 = new MinFuncIndividual(new double[_chromosomeLength]);
                var child2 = new MinFuncIndividual(new double[_chromosomeLength]);

                child1.Generate[random] = (parent1.Generate[random] * _alfa) + (parent2.Generate[random] * (1 - _alfa));
                child2.Generate[random] = (parent1.Generate[random] * _alfa) + (parent2.Generate[random] * (1 - _alfa));

                return(Task.FromResult((child1, child2)));
            }
            return(Task.FromResult((new MinFuncIndividual(null), new MinFuncIndividual(null))));;
        }
        public Task <IList <MinFuncIndividual> > HandleSelection(IList <MinFuncIndividual> selectionBoxs, int amountOfSelection, Selection selection)
        {
            if (selection == Selection.SUS)
            {
                IList <MinFuncIndividual> selectiveIndividulas = new List <MinFuncIndividual>();
                selectionBoxs = selectionBoxs.OrderByDescending(S => S.Fitness).ToList();
                var totalfitness = ComputeCumulativeSum(selectionBoxs);

                var pointer = (RandomHelper.CreateRandom(0, totalfitness / amountOfSelection));

                double ptr = 0;

                foreach (var individual in selectionBoxs)
                {
                    ptr += individual.Fitness;
                    while ((ptr - individual.Fitness <= pointer && pointer <= ptr) || totalfitness == 0)
                    {
                        selectiveIndividulas.Add(individual);
                        pointer += totalfitness / amountOfSelection;
                        if (selectiveIndividulas.Count() == amountOfSelection)
                        {
                            break;
                        }
                    }
                    if (selectiveIndividulas.Count() == amountOfSelection)
                    {
                        break;
                    }
                }
                #region OldCode

                /*
                 * foreach (var individual in selectionBoxs)
                 * {
                 *  ptr += individual.Fitness;
                 *  if (pointer <= ptr)
                 *  {
                 *      selectiveIndividulas.Add(individual);
                 *      if (selectiveIndividulas.Count() == amountOfSelection)
                 *          break;
                 *      pointer += _totalFitness / amountOfSelection;
                 *  }
                 * }*/
                #endregion
                return(Task.FromResult(selectiveIndividulas));
            }
            return(Task.FromResult(new List <MinFuncIndividual>() as IList <MinFuncIndividual>));
        }
 public Task <IList <MinFuncIndividual> > HandleSelection(IList <MinFuncIndividual> SelectionBoxs, int chromosomeLength, Selection selection)
 {
     if (selection == Selection.SelfAdaptionRandom)
     {
         IList <MinFuncIndividual> firstPopulation = new List <MinFuncIndividual>();
         for (int i = 0; i < _numberOfEarlyPopulation; i++)
         {
             firstPopulation.Add(new MinFuncIndividual(
                                     new double[chromosomeLength].GenerateRandom(),
                                     0,
                                     RandomHelper.CreateRandom(1000, 9999) / 1000
                                     ));
         }
         return(Task.FromResult(firstPopulation));
     }
     return(Task.FromResult(new List <MinFuncIndividual>() as IList <MinFuncIndividual>));
 }
예제 #7
0
        //public static void CreateMasterOrderNum(DateTime date, int count)
        //{
        //    string webSiteType = "11";//主站
        //    string consumeType = "12";//购买

        //    CreateOrderNum(webSiteType, consumeType, date, count);
        //}

        //public static void CreateChannelOrderNum(DateTime date, int count)
        //{
        //    string webSiteType = "21";//渠道
        //    string consumeType = "12";//购买

        //    CreateOrderNum(webSiteType, consumeType, date, count);
        //}

        private static void CreateOrderNum(string webSiteType, string consumeType, DateTime date, int count)
        {
            List <string> numList  = null;
            List <string> usedList = new List <string>();
            string        preNum   = webSiteType + consumeType + app + date.ToString("yyMMdd");

            if (orderNumList.ContainsKey(preNum))
            {
                numList = orderNumList[preNum];
                if (numList.Count >= count)
                {
                    return;
                }
            }
            else
            {
                numList = new List <string>();
                orderNumList.Add(preNum, numList);
            }
            string filePath = System.IO.Path.Combine(rootPath, String.Format("{0}\\{1}", "OrderNum", date.ToString("yyMM")));

            if (!System.IO.Directory.Exists(filePath))
            {
                System.IO.Directory.CreateDirectory(filePath);
            }

            string fileName = System.IO.Path.Combine(filePath, preNum + ".dat");

            using (System.IO.FileStream steam = new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read, System.IO.FileShare.None))
            {
                using (System.IO.StreamReader reader = new System.IO.StreamReader(steam))
                {
                    usedList = reader.ReadToEnd().Split(',').ToList();
                }
            }
            while (numList.Count < count)
            {
                string orderNum = preNum + RandomHelper.CreateRandom(100000, 999999);
                if (numList.Exists(c => c == orderNum) || usedList.Exists(c => c == orderNum))
                {
                    continue;
                }
                numList.Add(orderNum);
            }
        }
예제 #8
0
        public async Task <(Individual first, Individual second)> HandleRecombination(Individual first, Individual second, Recombination recombination)
        {
            var point1 = RandomHelper.CreateRandom(1, first.Generate.Count());
            var point2 = RandomHelper.CreateRandom(point1, first.Generate.Count());

            bool[] child1Generate = new bool[first.Generate.Count()];
            bool[] child2Generate = new bool[first.Generate.Count()];

            await Task.Run(() =>
            {
                for (int i = 0; i < first.Generate.Count(); i++)
                {
                    if (point1.Equals(point2))
                    {
                        child1Generate[i] = (i < point1) ? first.Generate[i] : second.Generate[i];
                        child2Generate[i] = (i < point1) ? second.Generate[i] : first.Generate[i];
                    }
                    else
                    {
                        child1Generate[i] = (i < point1) ? first.Generate[i]
                                                         : ((i < point2) ? second.Generate[i] : first.Generate[i]);
                        child2Generate[i] = (i < point1) ? second.Generate[i]
                                                         : ((i < point2) ? first.Generate[i] : second.Generate[i]);
                    }
                }
            });

            var child1 = new Individual(child1Generate, _items, _knapsackCapacity);
            var child2 = new Individual(child2Generate, _items, _knapsackCapacity);

            //noise for mutation
            if (RandomHelper.CreateRandom(0, 100) < 35)
            {
                child1 = await _simpleMutation.HandleMutation(child1, Mutation.None);
            }
            if (RandomHelper.CreateRandom(0, 100) < 35)
            {
                child2 = await _simpleMutation.HandleMutation(child2, Mutation.None);
            }
            return(child1, child2);
        }
예제 #9
0
 public Task <IList <MinFuncIndividual> > HandleSelection(IList <MinFuncIndividual> selectionBoxs, int amountOfRandomNumber, Selection selection)
 {
     if (selection == Selection.Tournament)
     {
         IList <MinFuncIndividual> selectiveIndividulas = new List <MinFuncIndividual>();
         IList <MinFuncIndividual> tour = new List <MinFuncIndividual>();
         for (int i = 0; i < amountOfRandomNumber; i++)
         {
             for (int j = 0; j < _kInNetIndividulas; j++)
             {
                 var poiter = RandomHelper.CreateRandom(0, (selectionBoxs.Count - 1));
                 tour.Add(selectionBoxs[poiter]);
             }
             tour = tour.OrderByDescending(f => f.Fitness).ToList();
             selectiveIndividulas.Add(tour[0]);
             tour.Clear();
         }
         return(Task.FromResult(selectiveIndividulas));
     }
     return(Task.FromResult(new List <MinFuncIndividual>() as IList <MinFuncIndividual>));
 }
        public Task <IList <MinFuncIndividual> > HandleSelection(IList <MinFuncIndividual> selectionBoxs, int numberOfSelection, Selection selection)
        {
            if (selection == Selection.RouletteWheel)
            {
                IList <MinFuncIndividual> selectiveIndividulas = new List <MinFuncIndividual>();
                var camulativ = ComputeCumulativeSum(selectionBoxs);

                for (int i = 0; i < numberOfSelection; i++)
                {
                    var random = RandomHelper.CreateRandom(0, camulativ.cumulativeSumOfFitness[selectionBoxs.Count() - 1]);
                    for (int j = 0; j < camulativ.cumulativeSumOfFitness.Count() - 1; j++)
                    {
                        if ((random >= camulativ.cumulativeSumOfFitness[j] && random <= camulativ.cumulativeSumOfFitness[j + 1]) || camulativ.totalFitness == 0)
                        {
                            selectiveIndividulas.Add(selectionBoxs[j]);
                            break;
                        }
                    }
                }
                return(Task.FromResult(selectiveIndividulas));
            }
            return(Task.FromResult(new List <MinFuncIndividual>() as IList <MinFuncIndividual>));
        }
예제 #11
0
        public async Task <bool> DoTrain(MinFunGettingStarted gettingStarted)
        {
            var firstPopulation = await _selectionHandler.ProcessSelection(null, gettingStarted.ChoromosemeLenght, Selection.Random);

            var maximumChild = new MinFuncIndividual(new double[gettingStarted.ChoromosemeLenght]);

            await Task.Run(() =>
            {
                //var threadId = Thread.CurrentThread.ManagedThreadId;
                for (int i = 0; i < gettingStarted.NumberOfGenerationRepetitions; i++)
                {
                    //threadId = Thread.CurrentThread.ManagedThreadId;
                    TryChanged.Invoke(i);
                    var parent = _selectionHandler.ProcessSelection(firstPopulation, gettingStarted.NumberOfParents, gettingStarted.SelectionList).Result;
                    for (int j = 0; j < gettingStarted.NumberOfParents - 1; j++)
                    {
                        ParentChanged.Invoke(j);
                        var random = RandomHelper.CreateRandom(0, 10);
                        if (random == 5)
                        {
                            //create childs by recombination
                            var childs = _recombinationHandler.ProcessRecombinationHandler(parent[j], parent[j + 1], gettingStarted.Recombinations).Result;

                            // Compute childs fitness to function
                            var child1New = _functionHandler.ProcessHandleFitness(childs.first, gettingStarted.ChoromosemeLenght, gettingStarted.FunctionSelected).Result;
                            var child2New = _functionHandler.ProcessHandleFitness(childs.second, gettingStarted.ChoromosemeLenght, gettingStarted.FunctionSelected).Result;


                            //Choose Max Child//
                            var chooseChild = (child1New.Fitness >= child2New.Fitness) ?
                                              child1New : child2New;

                            if (chooseChild.Fitness > maximumChild.Fitness)
                            {
                                maximumChild = chooseChild;
                                //Invoke
                                MaximumChildChanged.Invoke(maximumChild, MutationOrRecombination.Recombination, j, i);
                            }

                            // میو + لاندا
                            firstPopulation.Add(child1New);
                            firstPopulation.Add(child2New);
                        }
                        else
                        {
                            //create childs by mutation
                            var mutationChild = _mutationnHandler.ProcessMutationHandler(parent[j], gettingStarted.mutationList).Result;

                            //update child fitness => by function
                            var childUpdateFitness = _functionHandler.ProcessHandleFitness(mutationChild, gettingStarted.ChoromosemeLenght, gettingStarted.FunctionSelected).Result;

                            //Choose Max Child //

                            if (childUpdateFitness.Fitness > maximumChild.Fitness)
                            {
                                maximumChild = childUpdateFitness;
                                //Invoke
                                //MaximumChildChanged.Invoke(maximumChild, MutationOrRecombination.Mutation, j, i);
                                MaximumChildChanged.Invoke(maximumChild, MutationOrRecombination.Mutation, j, i);
                            }

                            //update case positive or not
                            _mutationnHandler.ProcessUpdateCase(mutationChild, childUpdateFitness, gettingStarted.mutationList);

                            // میو + لاندا
                            firstPopulation.Add(childUpdateFitness);
                        }
                    }
                    // update sigma
                    _mutationnHandler.ProcessUpdateStatus(gettingStarted.mutationList);
                }
                ExcetedFitness = _functionHandler.ProcessHanldeExcutedFitness(maximumChild, gettingStarted.FunctionSelected).Result;
            });

            return(true);
        }