/// <summary>
 /// Constructor
 /// </summary>
 /// <param name="series1">First series to see if it crossed the second</param>
 /// <param name="series2">Second series</param>
 /// <param name="crossoverType">Crosses above or below</param>
 public CrossoverSellCondition(List <double> series1, List <double> series2, CrossoverType crossoverType)
     : base()
 {
     _series1       = series1;
     _series2       = series2;
     _crossoverType = crossoverType;
 }
Esempio n. 2
0
 public Chromosome(World world)
 {
     this.world         = world;
     this.crossoverType = world.crossoverType;
     this.dna           = new List <City>(world.cities);
     dna.ShuffleList();
 }
Esempio n. 3
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            Clear();

            int pop_size_factor = Int32.Parse(cmbPopulationSize.Items[cmbPopulationSize.SelectedIndex].ToString());

            CrossoverType crossover_type = CrossoverType.OnePointCrossover;

            switch (cmbCrossoverType.SelectedIndex)
            {
            case 0: crossover_type = CrossoverType.OnePointCrossover; break;

            case 1: crossover_type = CrossoverType.UniformCrossover; break;

            case 2: crossover_type = CrossoverType.PMX; break;
            }

            double elitism_rate = Double.Parse(cmbElitismRate.SelectedItem.ToString());

            gs = new GeneticSolver(1024 * pop_size_factor, 1000, elitism_rate / 10, 0.01, crossover_type);
            gs.GeneratorFunction   = PhraseGenerator;
            gs.FitnessFunction     = CalculateFitness;
            gs.IterationCompleted += Gs_IterationCompleted;
            gs.SolutionFound      += Gs_SolutionFound;

            gs.Evolve();
        }
Esempio n. 4
0
        public override IGenotype CrossoverWith(IGenotype other, CrossoverType crossover, IRandomNumberGenerator random)
        {
            var newgeno = new StringGenotype(null);
            var og      = other as StringGenotype;

            switch (crossover)
            {
            case CrossoverType.Uniform:
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < Math.Min(str.Length, og.str.Length); i++)
                {
                    sb.Append(random.NextBool() ? str[i] : og.str[i]);
                }
                newgeno.str = sb.ToString();
                break;

            case CrossoverType.OnePoint:
                var point = random.Next(Math.Min(str.Length, og.str.Length));
                newgeno.str = str.Substring(0, point) + og.str.Substring(point);
                break;

            default: throw new NotImplementedException(crossover.ToString());
            }
            return(newgeno);
        }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="series1">First series to see if it crossed the value</param>
 /// <param name="value">Value for the crossover</param>
 /// <param name="crossoverType">Crosses above or below</param>
 public CrossoverSellCondition(List <double> series1, double value, CrossoverType crossoverType)
     : base()
 {
     _series1       = series1;
     _series2       = null;
     _value         = value;
     _crossoverType = crossoverType;
 }
        ///// <summary>
        ///// Constructor.
        ///// </summary>
        //internal CrossoverBase ()
        //	: this (1.0)
        //{
        //}

        ///// <summary>
        ///// Constructor.
        ///// </summary>
        ///// <param name="crossOverProbability"></param>
        //public CrossoverBase (double crossOverProbability)
        //	: this (crossOverProbability, true)
        //{
        //}

        ///// <summary>
        ///// Constructor.
        ///// </summary>
        ///// <param name="crossOverProbability"></param>
        ///// <param name="allowDuplicates"></param>
        //public CrossoverBase (double crossOverProbability, bool allowDuplicates)
        //	: this (crossOverProbability, allowDuplicates, CrossoverType.SinglePoint)
        //{
        //}

        ///// <summary>
        ///// Constructor.
        ///// </summary>
        ///// <param name="crossOverProbability"></param>
        ///// <param name="allowDuplicates"></param>
        ///// <param name="crossoverType"></param>
        //public CrossoverBase (double crossOverProbability, bool allowDuplicates, CrossoverType crossoverType)
        //	: this (crossOverProbability, allowDuplicates, crossoverType, Operators.ReplacementMethod.GenerationalReplacement)
        //{
        //}

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="crossOverProbability"></param>
        /// <param name="allowDuplicates"></param>
        /// <param name="crossoverType"></param>
        /// <param name="replacementMethod"></param>
        public CrossoverBase(double crossOverProbability, bool allowDuplicates, CrossoverType crossoverType, ReplacementMethod replacementMethod)
        {
            this.CrossoverProbability = crossOverProbability;
            this.AllowDuplicates      = allowDuplicates;
            this.ReplacementMethod    = replacementMethod;
            this.CrossoverType        = crossoverType;

            Enabled = true;
        }
Esempio n. 7
0
        public GeneticSolver(int population_size = 1024, int iteration_count = 1000, double elitism_ratio = 0.1, double mutation_ratio = 0.01, CrossoverType crossover_type = CrossoverType.OnePointCrossover)
        {
            PopulationSize = population_size;
            IterationCount = iteration_count;
            ElitismRatio   = elitism_ratio;
            MutationRatio  = mutation_ratio;
            CrossoverType  = crossover_type;

            Population = new Population(population_size);
        }
Esempio n. 8
0
 public GenomeSettings(int genomeSize)
 {
     this.elitism          = Math.Max(1, genomeSize / 10);
     this.mutationRate     = 0.01f;
     this.scalingType      = FitnessScalingType.SigmaTruncation;
     this.reproductionType = ReproductionType.Generational;
     this.selectionType    = SelectionType.RouletteWheel;
     this.mutationType     = MutationType.Exchange;
     this.crossoverType    = CrossoverType.SinglePoint;
 }
Esempio n. 9
0
        public static Crossover CreateCrossover(CrossoverType type)
        {
            switch (type)
            {
            case CrossoverType.UniformWithElite:
                return(new UniformWithElite());

            default:
                return(new UniformWithElite());
            }
        }
Esempio n. 10
0
        public static Crossover GetCrossover(CrossoverType type, int populationSize, double crossoverProbability)
        {
            switch (type)
            {
            case CrossoverType.OnePoint:
                return(new OnePointCrossover(crossoverProbability, populationSize));

            case CrossoverType.TwoPoint:
            default:
                return(new TwoPointCrossover(crossoverProbability, populationSize));
            }
        }
Esempio n. 11
0
        public Genotype(int geneCount, int geneLength, float crossoverRate, float mutationRate, CrossoverType crossoverType, MutationType mutationType, GeneType geneType)
        {
            GeneType   = geneType;
            GeneCount  = geneCount;
            GeneLength = geneLength;

            CrossoverRate = crossoverRate;
            MutationRate  = mutationRate;

            CrossoverType = crossoverType;
            MutationType  = mutationType;
        }
Esempio n. 12
0
 public MultiTaskGeneticSolver(AdjacencyMatrix matrix, MutationType mutation, CrossoverType crossover, SelectionType selectionType, int populationSize, int MaxTime)
 {
     this.SolverTitle  = "Multi Thread Solver";
     this.crossover    = crossover;
     this.matrix       = matrix;
     this.mutation     = mutation;
     maxPopulationSize = populationSize;
     selector          = selectionType;
     rnd               = new Random();
     this.MaxTime      = MaxTime;
     results           = new List <Candidate>();
     time              = new Stopwatch();
     bestPerTwoMinutes = new List <Candidate>();
     result            = new Result(this);
     minutes           = 0;
 }
Esempio n. 13
0
        public static ICrossover Get(CrossoverType type)
        {
            switch (type)
            {
            case CrossoverType.Point:
                return((ICrossover) new Point());

            case CrossoverType.TwoPoint:
                return((ICrossover) new TwoPoint());

            case CrossoverType.Uniform:
                return((ICrossover) new Uniform());

            default:
                throw new NotImplementedException();
            }
        }
Esempio n. 14
0
        public GeneticAlgorithm(
            int mutatorValue,
            int generationCount,
            int populationSize,
            CrossoverType crossoverType,
            SelectionType selectionType,
            List <City> cities)
        {
            this.mutationProbability = 1.0 / (TourManager.Cities.Count * mutatorValue);
            this.generationCount     = generationCount;
            this.populationSize      = populationSize;

            this.crossover = CrossoverFactory.Get(crossoverType);
            this.selection = SelectionFactory.Get(selectionType);

            TourManager.Cities = cities;
            this.distances     = Distance.Calculate(TourManager.Cities);
        }
Esempio n. 15
0
 public GenomeSettings
 (
     int elitism,
     float mutationRate,
     FitnessScalingType scalingType,
     ReproductionType reproductionType,
     SelectionType selectionType,
     MutationType mutationType,
     CrossoverType crossoverType
 )
 {
     this.elitism          = elitism;
     this.mutationRate     = mutationRate;
     this.scalingType      = scalingType;
     this.reproductionType = reproductionType;
     this.selectionType    = selectionType;
     this.mutationType     = mutationType;
     this.crossoverType    = crossoverType;
 }
Esempio n. 16
0
        internal Replicator(ReproductionParameters reproductionParameters)
        {
            _mutationsDistribution = new DiscreteDistribution(new double[]
            {
                reproductionParameters.WeightMutations.OverallRouletteWheelShare,
                reproductionParameters.SplitConnectionRouletteWheelShare,
                reproductionParameters.AddConnectionRouletteWheelShare,
                reproductionParameters.RemoveConnectionRouletteWheelShare,
            },
                                                              new[]
            {
                (int)MutationType.Weight,
                (int)MutationType.SplitConnection,
                (int)MutationType.AddConnection,
                (int)MutationType.RemoveConnection
            });

            _weightMutationDistribution = new WeightMutationDistribution(reproductionParameters.WeightMutations, Rng);
            _crossoverType = reproductionParameters.CrossoverType;
        }
Esempio n. 17
0
 public OptimoEvolver(int PopSize, CrossoverType xType, string fileStem, bool loadFromFile = false)
 {
     ReadInCurrentGeneration = loadFromFile;
     CountFeatures           = OptoGlobals.IsDebugMode;
     Console.WriteLine("Count Features is " + (CountFeatures ? "On" : "Off"));
     generation  = 0;
     _cross      = xType;
     _popSize    = PopSize;
     _population = new List <T>(_popSize);
     FileStem    = fileStem;
     for (int i = 0; i < _popSize; ++i)
     {
         _population.Add(new T());
     }
     _outputPath     = FileStem + "OutputTable.csv";
     _currentGenPath = FileStem + "/CurrentGenPop.csv";
     _lookup         = new Dictionary <string, Tuple <Double, Double> >();
     if (File.Exists(_outputPath))
     {
         readLookupFromFile();
     }
     else
     {
         OptoGlobals.CreateDirectoryAndThenFile(_outputPath);
     }
     if (FocusOnAllColumns)
     {
         SetPopToAllCols();
     }
     if (ReadInCurrentGeneration)
     {
         if (File.Exists(_currentGenPath))
         {
             loadPopulationFromFile();
         }
         else
         {
             dumpPopulationToFile();
         }
     }
 }
        internal CrossoverData CreateCrossoverData(int chromosomeLength, CrossoverType crossoverType)
        {
            var result = new CrossoverData(chromosomeLength);

            //this is like double point except that the values are all taken from one parent
            //first the centre section of the parent selection is taken to the child
            //the remaining values of the same parent are passed to the child in the order in
            //which they appear in the second parent. If the second parent does not include the value
            //an exception is thrown.

            //these can bring back the same number, this is ok as the values will be both inclusive
            //so if crossoverPoint1 and crossoverPoint2 are the same, one gene will form the center section.
            switch (crossoverType)
            {
            case CrossoverType.SinglePoint:
                //0 is invalid, range for single point is 1 to [length]
                result.Points.Add(RandomProvider.GetThreadRandom().Next(1, chromosomeLength));
                break;

            case CrossoverType.DoublePoint:
            case CrossoverType.DoublePointOrdered:
                //0 is invalid, range for double needs to leave room for right segment and is 1 to [length]

                int point1;
                int point2;
                do
                {
                    point2 = RandomProvider.GetThreadRandom().Next(1, chromosomeLength);
                    point1 = RandomProvider.GetThreadRandom().Next(1, chromosomeLength);
                } while (point2 == point1);

                result.Points.Add(System.Math.Min(point2, point1));
                result.Points.Add(System.Math.Max(point2, point1));

                break;
            }

            return(result);
        }
Esempio n. 19
0
		private static bool Init(TspGraph input, int generations, int populationSize, int elitismSize, int tournamentSize, double mutationRate, double crossoverRate, CrossoverType cT, int limit)
		{
			try
			{
				InputGraph = input.GraphMatrix;
				numbOfCities = input.Dimension;
				Generations = generations;
				PopulationSize = populationSize;
				ElitismSize = elitismSize;
				TournamentSize = tournamentSize;
				MutationRate = mutationRate;
				CrossoverRate = crossoverRate;
				globalBestFitness = 0;
				rand1 = new Random();
				rand2 = new Random();
				cType = cT;
				timeLimit = limit;

				fitnessList = new List<double>(populationSize);
				population = new List<List<Int16>>(populationSize);

				for (int i = 0; i < population.Capacity; i++)
				{
					population.Add(new List<short>(numbOfCities + 1));
					for (Int16 j = 0; j < population[i].Capacity - 1; j++)
						population[i].Add(j);
					population[i].Add(0);
					RandomizeSolution(population[i], i);
					fitnessList.Add(CalculateFitness(population[i]));
				}
			}
			catch (Exception e)
			{
				Console.WriteLine("Błąd. Opis błędu: " + e);
				return false;
			}

			return true;
		}
        /// <summary>
        /// Constructor with parameters.
        /// </summary>
        /// <param name="populationSize">The population size.</param>
        /// <param name="encodingType">The encoding type used in the chromosome.</param>
        /// <param name="selectionType">The selection type.</param>
        /// <param name="crossoverType">The crossover type.</param>
        /// <param name="mutationType">The mutation type.</param>
        /// <param name="mutationRate">The mutation rate.</param>
        /// <param name="elitisim">The elistism rate.</param>
        /// <param name="stoppingCriteriaOptions">The stopping critieria options used to stop the algorithm from executing forever.
        /// Optional if not specified, it will use the default which is set to an iteration threshold with maximum of 1000 iterations.</param>
        public GAOptions(int populationSize, EncodingType encodingType, SelectionType selectionType, CrossoverType crossoverType, MutationType mutationType,
                         double mutationRate, double elitisim, StoppingCriteriaOptions stoppingCriteriaOptions = null)
        {
            PopulationSize = populationSize;
            EncodingType   = encodingType;
            SelectionType  = selectionType;
            CrossoverType  = crossoverType;
            MutationType   = mutationType;
            MutationRate   = mutationRate;
            Elitism        = elitisim;

            if (stoppingCriteriaOptions == null)
            {
                // if not specified the GA will use an iteration based stopping criteria, set to a maximum iteration of 1000.
                StoppingCriteriaOptions = new StoppingCriteriaOptions
                {
                    StoppingCriteriaType = StoppingCriteriaType.SpecifiedIterations,
                    MaximumIterations    = 1000
                };
                return;
            }

            StoppingCriteriaOptions = stoppingCriteriaOptions;
        }
Esempio n. 21
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="crossOverProbability"></param>
 /// <param name="allowDuplicates"></param>
 /// <param name="crossoverType"></param>
 public CrossoverIndex(double crossOverProbability, int index, bool allowDuplicates, CrossoverType crossoverType)
     : this(crossOverProbability, index, allowDuplicates, crossoverType, GAF.Operators.ReplacementMethod.GenerationalReplacement)
 {
 }
Esempio n. 22
0
        internal CrossoverData PerformCrossover(Chromosome p1, Chromosome p2, double crossoverProbability, CrossoverType crossoverType, CrossoverData crossoverData, out Chromosome c1, out Chromosome c2)
        {
            var result           = new CrossoverData();
            var chromosomeLength = p1.Genes.Count;

            if (chromosomeLength != p2.Genes.Count)
            {
                throw new ArgumentException("Parent chromosomes are not the same length.");
            }

            if (crossoverData == null)
            {
                throw new ArgumentException("The CrossoverData parameter is null.");
            }

            List <Gene> cg1 = new List <Gene>();
            List <Gene> cg2 = new List <Gene>();

            //check probability by generating a random number between zero and one and if
            //this number is less than or equal to the given crossover probability
            //then crossover takes place."
            var rd = RandomProvider.GetThreadRandom().NextDouble();

            if (rd <= crossoverProbability)
            {
                switch (crossoverType)
                {
                case CrossoverType.SinglePoint:
                {
                    if (crossoverData.Points == null || crossoverData.Points.Count < 1)
                    {
                        throw new ArgumentException(
                                  "The CrossoverData.Points property is either null or is missing the required crossover points.");
                    }

                    var crossoverPoint1 = crossoverData.Points[0];
                    result.Points.Add(crossoverPoint1);

                    //create the two children
                    cg1.AddRangeCloned(p1.Genes.Take(crossoverPoint1).ToList());
                    //cg1.AddRange(p2.Genes.Skip(crossoverPoint1).Take(chromosomeLength - crossoverPoint1));
                    cg1.AddRangeCloned(p2.Genes.Skip(crossoverPoint1).Take(chromosomeLength - crossoverPoint1));

                    cg2.AddRangeCloned(p2.Genes.Take(crossoverPoint1).ToList());
                    cg2.AddRangeCloned(p1.Genes.Skip(crossoverPoint1).Take(chromosomeLength - crossoverPoint1));

                    break;
                }

                case CrossoverType.DoublePoint:
                {
                    if (crossoverData.Points == null || crossoverData.Points.Count < 2)
                    {
                        throw new ArgumentException(
                                  "The CrossoverData.Points property is either null or is missing the required crossover points.");
                    }

                    var firstPoint  = crossoverData.Points[0];
                    var secondPoint = crossoverData.Points[1];

                    result.Points.Add(firstPoint);
                    result.Points.Add(secondPoint);

                    //first child
                    //first part of Parent 1
                    cg1.AddRangeCloned(p1.Genes.Take(firstPoint).ToList());
                    //middle part pf Parent 2
                    cg1.AddRangeCloned(p2.Genes.Skip(firstPoint).Take(secondPoint - firstPoint));
                    //last part of Parent 1
                    cg1.AddRangeCloned(p1.Genes.Skip(secondPoint).Take(chromosomeLength - secondPoint));

                    //second child
                    //first part of Parent 2
                    cg2.AddRangeCloned(p2.Genes.Take(firstPoint).ToList());
                    //middle part pf Parent 1
                    cg2.AddRangeCloned(p1.Genes.Skip(firstPoint).Take(secondPoint - firstPoint));
                    //last part of Parent 2
                    cg2.AddRangeCloned(p2.Genes.Skip(secondPoint).Take(chromosomeLength - secondPoint));

                    break;
                }

                case CrossoverType.DoublePointOrdered:
                {
                    if (crossoverData.Points == null || crossoverData.Points.Count < 2)
                    {
                        throw new ArgumentException(
                                  "The CrossoverData.Points property is either null or is missing the required crossover points.");
                    }

                    //this is like double point except that the values are all taken from one parent
                    //first the centre section of the parent selection is taken to the child
                    //the remaining values of the same parent are passed to the child in the order in
                    //which they appear in the second parent. If the second parent does not include the value
                    //an exception is thrown.

                    //these can bring back the same number, this is ok as the values will be both inclusive
                    //so if crossoverPoint1 and crossoverPoint2 are the same, one gene will form the center section.
                    var firstPoint  = crossoverData.Points[0];
                    var secondPoint = crossoverData.Points[1];

                    result.Points.Add(firstPoint);
                    result.Points.Add(secondPoint);

                    //pass the middle part of Parent 1 to child 1
                    cg1.AddRangeCloned(p1.Genes.Skip(firstPoint).Take(secondPoint - firstPoint));         //+1 make this exclusive e.g. 4-6 include 3 genes.

                    //pass the middle part of Parent 2 to child 2
                    cg2.AddRangeCloned(p2.Genes.Skip(firstPoint).Take(secondPoint - firstPoint));

                    //create hash sets for parent1 and child1
                    var p1Hash  = new HashSet <object>();
                    var cg1Hash = new HashSet <object>();

                    //populate the parent hash set with object values (not the gene itself)
                    foreach (var gene in p1.Genes)
                    {
                        p1Hash.Add(gene.ObjectValue);
                    }

                    //populate the child hash set with object values (not the gene itself)
                    //at this point only the center section of P1 will be in C1
                    foreach (var gene in cg1)
                    {
                        cg1Hash.Add(gene.ObjectValue);
                    }

                    //run through the P2 adding to C1 those that exist in P1 but not yet in C1
                    //add them in the order found in P2. This has to be done by value as the first parent
                    //is used but the order id determined by the second parent. Can't use Guid as the second
                    //parent has a different set of genes guids.
                    foreach (var gene in p2.Genes)
                    {
                        //if we have the value in P1 and it is not already in C1, then add it.
                        bool existsInP1  = p1Hash.Contains(gene.ObjectValue);
                        bool existsInCg1 = cg1Hash.Contains(gene.ObjectValue);

                        if (existsInP1 && !existsInCg1)
                        {
                            cg1.AddCloned(gene);
                        }
                    }

                    var p2Hash  = new HashSet <object>();
                    var cg2Hash = new HashSet <object>();

                    foreach (var gene in p2.Genes)
                    {
                        p2Hash.Add(gene.ObjectValue);
                    }

                    foreach (var gene in cg2)
                    {
                        cg2Hash.Add(gene.ObjectValue);
                    }


                    //run through the P1 adding to C2 those that exist in P2 but not yet in C2
                    //add them in the order found in P1. This has to be done by value as the first parent
                    //is used but the order id determined by the second parent. Can't use Guid as the second
                    //parent has a different set of genes (guids)
                    foreach (var gene in p1.Genes)
                    {
                        //if we have the value in P1 and it is not already in C1, then add it.
                        bool existsInP2  = p2Hash.Contains(gene.ObjectValue);
                        bool existsInCg2 = cg2Hash.Contains(gene.ObjectValue);

                        if (existsInP2 && !existsInCg2)
                        {
                            cg2.AddCloned(gene);
                        }
                    }

                    //if at this point we do not have a complete child, raise an exception
                    if (cg1.Count != p1.Count || cg2.Count != p2.Count)
                    {
                        throw new CrossoverTypeIncompatibleException("The parent Chromosomes were not suitable for Ordered Crossover as they do not contain the same set of values. Consider using a different crossover type, or ensure all solutions are build with the same set of values.");
                    }

                    break;
                }
                }
            }
            else
            {
                //crossover probaility dictates that these pass through to the next generation untouched (except for an ID change.
                //get the existing parent genes and treat them as the new children
                cg1.AddRangeCloned(p1.Genes);
                cg2.AddRangeCloned(p2.Genes);
            }

            if (cg1.Count != chromosomeLength || cg1.Count != chromosomeLength)
            {
                throw new ChromosomeCorruptException("Chromosome is corrupt!");
            }
            c1 = new Chromosome(cg1);
            c2 = new Chromosome(cg2);

            return(result);
        }
Esempio n. 23
0
 public FI2PopGA(int populationSize, int genomeLength, float mutationRate, bool elitism, CrossoverType crossoverType, int tournamentSize, float evaluationTime, bool testing,
                 int testRuns, int maxGeneration, LevelGenerator levelGenerator)
 {
     this.populationSize = populationSize;
     this.genomeLength   = genomeLength;
     this.levelGenerator = levelGenerator;
     this.tournamentSize = tournamentSize;
     this.testing        = testing;
     this.testRuns       = testRuns;
     this.maxGeneration  = maxGeneration;
     this.elitism        = elitism;
     this.crossoverType  = crossoverType;
     this.mutationRate   = mutationRate;
     this.evaluationTime = evaluationTime;
     Initialise();
 }
Esempio n. 24
0
        public void Crossover(Network superiorNetwork, Random rand, CrossoverType crossoverType)
        {
            switch (crossoverType)
            {
            case CrossoverType.SwapWeights:
                throw new NotImplementedException();
                break;

            case CrossoverType.SwapNeurons:
                for (int i = 0; i < Layers.Length; i++)
                {
                    Layer superiorLayer = superiorNetwork.Layers[i];
                    Layer inferiorLayer = Layers[i];

                    for (int j = 0; j < inferiorLayer.Neurons.Length; j++)
                    {
                        double swapRate = 0.4;
                        if (rand.NextDouble() > swapRate)
                        {
                            superiorLayer.Neurons[j].CopyTo(inferiorLayer.Neurons[j]);
                        }
                    }
                }
                break;

            case CrossoverType.SwapLayers:
                int   whichLayer  = rand.Next(superiorNetwork.Layers.Length);
                Layer layerToCopy = superiorNetwork.Layers[whichLayer];
                Layer newLayer    = new Layer(layerToCopy.Neurons[0].ActivationFunc, layerToCopy.Neurons[0].Weights.Length, layerToCopy.Neurons.Length);
                layerToCopy.CopyTo(newLayer);
                Layers[whichLayer] = newLayer;
                break;

            case CrossoverType.SinglePoint:
                for (int i = 0; i < Layers.Length; i++)
                {
                    Layer superiorLayer = superiorNetwork.Layers[i];
                    Layer inferiorLayer = Layers[i];

                    int  cutPoint = rand.Next(inferiorLayer.Neurons.Length + 1); //Cut point = 1 is point between Neurons[0] and Neurons[1]
                    bool flip     = rand.Next(2) == 1;                           //1 = forward

                    if (flip)
                    {
                        for (int j = cutPoint; j < inferiorLayer.Neurons.Length; j++)
                        {
                            superiorLayer.Neurons[j].CopyTo(inferiorLayer.Neurons[j]);
                        }
                    }
                    else
                    {
                        for (int j = cutPoint - 1; j >= 0; j--)
                        {
                            superiorLayer.Neurons[j].CopyTo(inferiorLayer.Neurons[j]);
                        }
                    }
                }
                break;

            case CrossoverType.DoublePoint:
                throw new NotImplementedException();
                break;
            }
        }
        internal GeneticSolver createNewSolver(bool isMultiThread)
        {
            MutationType    mutation  = null;
            CrossoverType   crossover = null;
            SelectionType   selection = null;
            GeneticSolver   solver    = null;//add parameters TO DO
            AdjacencyMatrix matrix    = new AdjacencyMatrix(tspXmlFile);

            switch (mutationIndex)
            {
            case 0:
            {
                if (!isMultiThread)
                {
                    mutation = new InversionMutation(mutationChance);
                }
                else
                {
                    mutation = new MultiThreadInversionMutation(mutationChance);
                }
                break;
            }

            case 1:
            {
                if (!isMultiThread)
                {
                    mutation = new TranspositionMutation(mutationChance);
                }
                else
                {
                    mutation = new MultiThreadTranspositionMutation(mutationChance);
                }
                break;
            }
            }

            switch (crossoverIndex)
            {
            case 0:
            {
                if (!isMultiThread)
                {
                    crossover = new PMXCrossover(crossoverChance);
                }
                else
                {
                    crossover = new MultiThreadPMXCrossover(crossoverChance);          //new PMXCrossover(crossoverChance); //
                }
                break;
            }

            case 1:
            {
                if (!isMultiThread)
                {
                    crossover = new OXCrossover(crossoverChance);
                }
                else
                {
                    crossover = new MultiThreadOXCrossover(crossoverChance);
                }
                break;
            }
            }

            switch (selectorIndex)
            {
            case 0:
            {
                if (!isMultiThread)
                {
                    selection = new TournamentSelection(selectorSize);
                }
                else
                {
                    selection = new MultiThreadTournamentSelection(selectorSize);
                }
                break;
            }

            case 1:
            {
                if (!isMultiThread)
                {
                    selection = new RouletteSelection(selectorSize);
                }
                else
                {
                    selection = new MultiThreadRouletteSelection(selectorSize);
                }
                break;
            }
            }

            if (mutation != null && selection != null && crossover != null)
            {
                if (isMultiThread)
                {
                    MultiTaskOptions.parallelOptCrossover.MaxDegreeOfParallelism = int.Parse(View.tbxLvlCrossover.Text);
                    MultiTaskOptions.parallelOptMutation.MaxDegreeOfParallelism  = int.Parse(View.tbxLvlMutation.Text);
                    MultiTaskOptions.parallelOptSelection.MaxDegreeOfParallelism = int.Parse(View.tbxLvlSelector.Text);
                    solver = new MultiTaskGeneticSolver(matrix, mutation, crossover, selection, populationSize, timeMS);
                }
                else
                {
                    solver = new SingleTaskGeneticSolver(matrix, mutation, crossover, selection, populationSize, timeMS);
                }
            }
            return(solver);
        }
Esempio n. 26
0
		public static TimeSpan TimeMeasured { get; private set; } //zmierzony czas wykonywania obliczen
		#endregion

		public static void SolveTsp(TspGraph input, int elitismSize, double crossoverRate, double mutationRate, int populationSize, CrossoverType cT, int limit = 300, int generations = 10000, int tournamentSize = 2)
		{
			if (input.Dimension > 2 && input.Name != null && input.GraphMatrix != null)
			{
				if (elitismSize % 2 == 1)
				{
					elitismSize--;
					Console.WriteLine("Ilość elit powinna być podzielna przez 2. Zmniejszono o 1.");
				}
				if (populationSize % 2 == 1)
				{
					populationSize--;
					Console.WriteLine("Wielkość populacji powinna być podzielna przez 2. Zmniejszono o 1.");
				}

				bool allright = Init(input, generations, populationSize, elitismSize, tournamentSize, mutationRate, crossoverRate, cT, limit);

				if (allright)
				{
					stopwatch = new Stopwatch();
					stopwatch.Start();
					Search();
					stopwatch.Stop();
					TimeMeasured = stopwatch.Elapsed;
				}
			}
			else Console.WriteLine("Przed uruchomieniem algorytmu wczytaj odpowiednio dane wejściowe.\n(Wciśnij dowolny klawisz aby wrócić)");
		}
Esempio n. 27
0
 public Configuration withCrossoverType(CrossoverType t)
 {
     crossoverType = t;
     return(this);
 }
Esempio n. 28
0
 public abstract IGenotype CrossoverWith(IGenotype other, CrossoverType crossover, IRandomNumberGenerator random);
        internal void PerformCrossover(Chromosome p1, Chromosome p2, double crossoverProbability, CrossoverType crossoverType, CrossoverData crossoverData, out Chromosome c1, out Chromosome c2)
        {
            this.CrossoverProbability = crossoverProbability;
            this.CrossoverType        = crossoverType;

            this.PerformCrossover(p1, p2, crossoverData, out c1, out c2);
        }
Esempio n. 30
0
 public CrossOverInfo(Random rnd, CrossoverType type)
 {
     this.rnd  = rnd;
     this.type = type;
 }