示例#1
0
        //int maxLength;    // maximum length of string to invert.

        /// <summary>
        /// Reorders the genes in the chromosome.
        /// </summary>
        /// <param name="c">The chromosome to be reordered.</param>
        public static void Reorder(Chromosome c)
        {
            // This is like two-point crossover, in that we pick two
            // random points on the chromosome.  We then reverse the order
            // of the genes contained between those two points.
            int NumberOfGenes;

            NumberOfGenes = c.Genes.Length;
            int CrossoverPoint1 = Utils.Rand.Next( NumberOfGenes );
            int CrossoverPoint2 = Utils.Rand.Next( NumberOfGenes );
            if ( CrossoverPoint1 > CrossoverPoint2 )
            {
                int tmp = CrossoverPoint1;
                CrossoverPoint1 = CrossoverPoint2;
                CrossoverPoint2 = tmp;
            }
 
            for (
                int i=CrossoverPoint1, j=CrossoverPoint2; 
                (i - CrossoverPoint1) < (CrossoverPoint2-CrossoverPoint1)/2;
                i++,j--
                )
            {
                Gene g = c.Genes[i];
                c.Genes[i] = c.Genes[j];
                c.Genes[j] = g;
            }
        }
示例#2
0
 void SpawnNeutralCell()
 {
     Chromosome outputChromosome = new Chromosome(NeutralType);
     Vector2 RandomPosition = Random.insideUnitCircle * SpawnDistanceScale;
     Vector3 spawnLocation = new Vector3(transform.position.x + RandomPosition.x, 0, transform.position.z + RandomPosition.y);
     manager.SpawnNeutral(spawnLocation, outputChromosome);
 }
示例#3
0
        public void Population_GetBestChromosome()
        {
            List<City> cities = new List<City>();
            cities.Add(new City(1, 1, "A"));
            cities.Add(new City(2, 2, "B"));
            cities.Add(new City(3, 3, "C"));
            cities.Add(new City(4, 4, "D"));
            cities.Add(new City(5, 5, "E"));

            List<City> cities2 = new List<City>();
            cities2.Add(new City(1, 1, "A"));
            cities2.Add(new City(5, 5, "B"));
            cities2.Add(new City(3, 3, "C"));
            cities2.Add(new City(4, 4, "D"));
            cities2.Add(new City(2, 2, "E"));

            Population p = new Population();
            Chromosome c = new Chromosome(cities);
            Chromosome c2 = new Chromosome(cities2);

            p.Add(c);
            p.Add(c2);

            Chromosome best = p.GetBestChromosome();

            Assert.AreEqual(c, best);
        }
        public void Test_CompareTo()
        {
            Chromosome c1 = new Chromosome("Hello, world!");
            Assert.AreEqual(0, c1.GetFitness());

            Chromosome c2 = new Chromosome("H5p&J;!l<X\\7l");
            Assert.AreEqual(399, c2.GetFitness());

            Chromosome c3 = new Chromosome("Vc;fx#QRP8V\\$");
            Assert.AreEqual(297, c3.GetFitness());

            Chromosome c4 = new Chromosome("t\\O`E_Jx$n=NF");
            Assert.AreEqual(415, c4.GetFitness());

            Assert.AreEqual(0, c1.CompareTo(c1));
            Assert.IsTrue(c1.CompareTo(c2) < 0);
            Assert.IsTrue(c1.CompareTo(c3) < 0);
            Assert.IsTrue(c1.CompareTo(c4) < 0);

            Assert.AreEqual(0, c2.CompareTo(c2));
            Assert.IsTrue(c2.CompareTo(c1) > 0);
            Assert.IsTrue(c2.CompareTo(c3) > 0);
            Assert.IsTrue(c2.CompareTo(c4) < 0);

            Assert.AreEqual(0, c3.CompareTo(c3));
            Assert.IsTrue(c3.CompareTo(c1) > 0);
            Assert.IsTrue(c3.CompareTo(c2) < 0);
            Assert.IsTrue(c3.CompareTo(c4) < 0);

            Assert.AreEqual(0, c4.CompareTo(c4));
            Assert.IsTrue(c4.CompareTo(c1) > 0);
            Assert.IsTrue(c4.CompareTo(c2) > 0);
            Assert.IsTrue(c4.CompareTo(c3) > 0);
        }
示例#5
0
 public void EqualsObj_xEqualsy_and_yEqualsx_returns_xEqualsz()
 {
     var x = new Chromosome();
       var y = new Chromosome();
       var z = new Chromosome();
       Assert.IsTrue(!(x.Equals((object)y) && y.Equals((object)z)) || x.Equals((object)z));
 }
示例#6
0
        public void ChromosomePair_CreateCrossoverChild()
        {
            List<City> cities = new List<City>();
            cities.Add(new City(1, 1, "A"));
            cities.Add(new City(2, 2, "B"));
            cities.Add(new City(3, 3, "C"));
            cities.Add(new City(4, 4, "D"));
            cities.Add(new City(5, 5, "E"));

            List<City> cities2 = new List<City>();
            cities2.Add(new City(1, 1, "A"));
            cities2.Add(new City(5, 5, "B"));
            cities2.Add(new City(3, 3, "C"));
            cities2.Add(new City(4, 4, "D"));
            cities2.Add(new City(2, 2, "E"));

            Chromosome c = new Chromosome(cities);
            Chromosome c2 = new Chromosome(cities2);

            ChromosomePair pair = new ChromosomePair(c, c2);

            Chromosome child = pair.CreateCrossoverChild();

            Assert.AreNotEqual(c, child);
        }
        public Tuple<Chromosome, Chromosome> Crossover(Chromosome c1, Chromosome c2)
        {
            var locus = random.Next(0, c1.Value.Length + 1); // Locus: http://en.wikipedia.org/wiki/Locus_(genetics)
            string ch1 = c1.Value.Substring(0, locus) + c2.Value.Substring(locus),
                   ch2 = c2.Value.Substring(0, locus) + c1.Value.Substring(locus);

            return new Tuple<Chromosome, Chromosome>(new Chromosome(ch1, fitnessCalculator), new Chromosome(ch2, fitnessCalculator));
        }
示例#8
0
        public void TestFitnessNoMatch()
        {
            Chromosome.SetTargetGene("ABCF");

            Chromosome first = new Chromosome("ABCE");

            System.Diagnostics.Debug.Assert(first.Fitness == 1);
        }
示例#9
0
 public Population(float target, IEnumerable<Chromosome> chromos, Random random, Chromosome solution, int generation)
 {
     this.target = target;
     this.chromos = chromos.ToList();
     this.solution = solution;
     this.generation = generation;
     this.random = random;
 }
        public Chromosome Mutate(Chromosome ch)
        {
            var sb = new StringBuilder(ch.Value);
            var randomPositon = random.Next(0, ch.Value.Length);
            sb[randomPositon] = generator.GenerateCharacter();

            return new Chromosome(sb.ToString(), fitnessCalculator);
        }
        public override double CalculateFitness(Chromosome ch)
        {
            var score = game.Start(ch.Replay);
            //var filledSpaces = game.FilledSpaces();

            // TODO: find a way to calculate a fitness based on the score and filledSpaces
            return score;// (score + 1) * filledSpaces;
        }
        public Chromosome Mutate(Chromosome ch)
        {
            var replay = ch.Replay.ToString();
            var sb = new StringBuilder(replay);
            var randomPositon = random.Next(0, replay.Length);
            sb[randomPositon] = characterSet.GetRandomCharacter();

            return new Chromosome(new Replay(sb.ToString()), fitnessCalculator);
        }
示例#13
0
    public void CreateInfectedCell(Chromosome _inputChromosome, Vector3 _location)
    {
        GameObject newCell = (GameObject)Instantiate(cell, _location, transform.rotation);
        CellScript script = newCell.GetComponent<CellScript>();
        script.manager = this;
        script.CreateInfected(_inputChromosome);

        infectedList.Add(script);
    }
 // Use this for initialization
 void Start()
 {
     infected = false;
     myRenderer = GetComponent<Renderer>();
     colourBlend = 0.0f;
     parentScript = GetComponentInParent<CellScript>();
     type = parentScript.infectedType;
     cellGenes = parentScript.GetChromosome();
 }
 public Population RandomPopulation()
 {
     var chromosomes = new Chromosome[ChromosomeCount];
     for (int i = 0; i < ChromosomeCount; i++)
     {
         chromosomes[i] = RandomChromosome();
     }
     return new Population(chromosomes);
 }
示例#16
0
        public void Chromosome_Calculate_Fitness()
        {
            List<City> cities = new List<City>();
            cities.Add(new City(1, 2, "A"));
            cities.Add(new City(5, 5, "B"));

            Chromosome c = new Chromosome(cities);
            Assert.AreEqual<double>(5, c.Fitness());
        }
示例#17
0
 // Converts a chromosome to its respective sequence of cities' indexes.
 public static string chromosomeToString(Chromosome chromosome)
 {
     string str = "";
     foreach (var gene in chromosome.Genes)
     {
         str += ((int)gene.RealValue).ToString() + " ";
     }
     return str;
 }
示例#18
0
 protected double CalculateFitness(Chromosome solution)
 {
     int totWaste = 0, totStock = 0;
     foreach (var gene in solution.Genes)
     {
         totWaste += (gene.ObjectValue as CutPlan).Waste;
         totStock += (gene.ObjectValue as CutPlan).StockLength;
     }
     return (totWaste / totStock)*100+1/totWaste;
 }
示例#19
0
        public Tuple<Chromosome, Chromosome> Crossover(Chromosome c1, Chromosome c2)
        {
            string replay1 = c1.Replay.ToString(), replay2 = c2.Replay.ToString();

            var locus = random.Next(0, replay1.Length + 1); // Locus: http://en.wikipedia.org/wiki/Locus_(genetics)
            string ch1 = replay1.Substring(0, locus) + replay2.Substring(locus),
                   ch2 = replay2.Substring(0, locus) + replay1.Substring(locus);

            return new Tuple<Chromosome, Chromosome>(new Chromosome(new Replay(ch1), fitnessCalculator), new Chromosome(new Replay(ch2),fitnessCalculator));
        }
示例#20
0
 private static bool IsSuccess(BulldozerAlgorithm<double> algorithm, double threshold, out Chromosome chromosome)
 {
     var chromosomes = algorithm.ChromosomePool
                                .Union(algorithm.ChromosomeBank)
                                .OfType<TreeChromosome>()
                                .ToList();
     var maxValue = chromosomes.Max(c => c.Metrics[2]);
     chromosome = chromosomes.FirstOrDefault(c => c.Metrics[2] == maxValue);
     return maxValue >= threshold;
 }
        public Tuple<Chromosome, Chromosome> Crossover(Chromosome c1, Chromosome c2)
        {
            int locus1 = random.Next(0, c1.Value.Length),
                locus2 = random.Next(locus1, c1.Value.Length),
                distance = locus2 - locus1;

            string ch1 = c1.Value.Substring(0, locus1) + c2.Value.Substring(locus1, distance) + c1.Value.Substring(locus2),
                   ch2 = c2.Value.Substring(0, locus1) + c1.Value.Substring(locus1, distance) + c2.Value.Substring(locus2);

            return new Tuple<Chromosome, Chromosome>(new Chromosome(ch1, fitnessCalculator), new Chromosome(ch2, fitnessCalculator));
        }
示例#22
0
        public void Population_AddChromoSome()
        {
            List<City> cities = new List<City>();
            cities.Add(new City(1, 1, "A"));

            Population p = new Population();
            Chromosome c = new Chromosome(cities);
            p.Add(c);

            Assert.AreEqual(c, p.Chromosomes[0]);
        }
示例#23
0
        // Converts a chromosome into a list of cities.
        public static List<City> fittestToCitiesList(List<City> cities, Chromosome fittest)
        {
            List<City> TSPSequence = new List<City>();

            foreach (var gene in fittest.Genes)
            {
                TSPSequence.Add(cities[(int)gene.RealValue]);
            }

            return TSPSequence;
        }
        private int CalculateFitness(Chromosome item)
        {
            int fitness = 0;

            char[] data = item.data;
            for (int i = 0; i < ChromosomeLength; i++) {
                fitness += Math.Abs((int)data[i] - (int)Target[i]);
            }

            return fitness;
        }
示例#25
0
文件: Spawner.cs 项目: clomax/evosim
	public void spawn (Vector3 pos, Vector3 rot, double energy, Chromosome chromosome) {
		GameObject clone = new GameObject();
		clone.transform.localPosition = pos;
		clone.transform.eulerAngles = Utility.RandomRotVec();
		Creature crt_script = clone.AddComponent<Creature>();
		clone.tag = "Creature";
	
		crt_script.invokechromosome(chromosome);
		
		crt_script.setEnergy(energy);
		crt_count.number_of_creatures += 1;
	}
示例#26
0
        public void TestMutate()
        {
            Chromosome.SetTargetGene("ADE");

            Chromosome first = new Chromosome("ABC");
            Chromosome second = new Chromosome("DEF");

            var children = first.Mate(second);

            Console.WriteLine(children.First().Gene);
            Console.WriteLine(children.Last().Gene);
        }
示例#27
0
        public void Chromosome_Calculate_Fitness_5Nodes()
        {
            List<City> cities = new List<City>();
            cities.Add(new City(1, 1, "A"));
            cities.Add(new City(5, 5, "B"));
            cities.Add(new City(10, 10, "C"));
            cities.Add(new City(20, 20, "D"));
            cities.Add(new City(30, 30, "E"));

            Chromosome c = new Chromosome(cities);
            Assert.AreEqual<double>(41.01219331, Math.Round(c.Fitness(), 8));
        }
示例#28
0
        public void addCreature(float x, float y, Chromosome chromosome = null)
        {
            Creature creature = null;
            if (type == CreatureType.Carnivore)
                creature = new Carnivore(this, x, y, chromosome);
            else if (type == CreatureType.Herbivore)
                creature = new Herbivore(this, x, y, chromosome);
            else
                creature = new Omnivore(this, x, y, chromosome);

            creatures.Add(creature);
            gameWorld.EntityManager.AddEntity(creature);
        }
        public void CrossOver_CallsEvaluatorComputeFitness()
        {
            var random = new Random();
            var parent1 = new Chromosome<string>("Parent1");
            var parent2 = new Chromosome<string>("Parent2");

            var fitnessEvaluatorMock = new Mock<IFitnessEvaluator<string>>();
            fitnessEvaluatorMock.Verify();

            var stringSinglePointCrossOver = new StringSinglePointCrossOver(random, fitnessEvaluatorMock.Object);

            Action action = () => stringSinglePointCrossOver.CrossOver(parent1, parent2);
        }
示例#30
0
        public Tuple<Chromosome, Chromosome> Crossover(Chromosome c1, Chromosome c2)
        {
            string replay1 = c1.Replay.ToString(), replay2 = c2.Replay.ToString();

            int locus1 = random.Next(0, replay1.Length),
                locus2 = random.Next(locus1, replay1.Length),
                distance = locus2 - locus1;

            string ch1 = replay1.Substring(0, locus1) + replay2.Substring(locus1, distance) + replay1.Substring(locus2),
                   ch2 = replay2.Substring(0, locus1) + replay1.Substring(locus1, distance) + replay2.Substring(locus2);

            return new Tuple<Chromosome, Chromosome>(new Chromosome(new Replay(ch1), fitnessCalculator), new Chromosome(new Replay(ch2), fitnessCalculator));
        }
示例#31
0
 public SolutionFoundEventArgs(int iteration_count, Chromosome solution)
 {
     IterationCount = iteration_count;
     Solution       = solution;
 }
示例#32
0
        public TranscriptPositionalEffectTests()
        {
            var       chromosome = new Chromosome("chr1", "1", 0);
            const int start      = 874655;
            const int end        = 879639;

            _otherTranscriptRegions = new ITranscriptRegion[]
            {
                new TranscriptRegion(TranscriptRegionType.Exon, 1, 200, 300, 1, 186),
                new TranscriptRegion(TranscriptRegionType.Intron, 1, 301, 400, 186, 187),
                new TranscriptRegion(TranscriptRegionType.Exon, 2, 401, 699, 187, 349),
                new TranscriptRegion(TranscriptRegionType.Intron, 2, 700, 709, 359, 360),
                new TranscriptRegion(TranscriptRegionType.Exon, 3, 710, 800, 350, 465)
            };

            var forwardTranscriptRegions = new ITranscriptRegion[]
            {
                new TranscriptRegion(TranscriptRegionType.Exon, 1, 874655, 874840, 1, 186),
                new TranscriptRegion(TranscriptRegionType.Intron, 1, 874841, 876523, 186, 187),
                new TranscriptRegion(TranscriptRegionType.Exon, 2, 876524, 876686, 187, 349),
                new TranscriptRegion(TranscriptRegionType.Intron, 2, 876687, 877515, 349, 350),
                new TranscriptRegion(TranscriptRegionType.Exon, 3, 877516, 877631, 350, 465),
                new TranscriptRegion(TranscriptRegionType.Intron, 3, 877632, 877789, 465, 466),
                new TranscriptRegion(TranscriptRegionType.Exon, 4, 877790, 877868, 466, 544),
                new TranscriptRegion(TranscriptRegionType.Intron, 4, 877869, 877938, 544, 545),
                new TranscriptRegion(TranscriptRegionType.Exon, 5, 877939, 878438, 545, 1044),
                new TranscriptRegion(TranscriptRegionType.Intron, 5, 878439, 878632, 1044, 1045),
                new TranscriptRegion(TranscriptRegionType.Exon, 6, 878633, 878757, 1045, 1169),
                new TranscriptRegion(TranscriptRegionType.Intron, 6, 878758, 879077, 1169, 1170),
                new TranscriptRegion(TranscriptRegionType.Exon, 7, 879078, 879639, 1170, 1731)
            };

            var reverseTranscriptRegions = new ITranscriptRegion[]
            {
                new TranscriptRegion(TranscriptRegionType.Exon, 1, 3477259, 3477354, 1, 96)
            };

            var translation = new Mock <ITranslation>();

            translation.SetupGet(x => x.CodingRegion).Returns(new CodingRegion(874655, 879533, 1, 1625, 1625));

            var gene = new Mock <IGene>();

            gene.SetupGet(x => x.OnReverseStrand).Returns(false);

            _forwardTranscript = new Mock <ITranscript>();
            _forwardTranscript.SetupGet(x => x.Chromosome).Returns(chromosome);
            _forwardTranscript.SetupGet(x => x.Start).Returns(start);
            _forwardTranscript.SetupGet(x => x.End).Returns(end);
            _forwardTranscript.SetupGet(x => x.Gene).Returns(gene.Object);
            _forwardTranscript.SetupGet(x => x.TranscriptRegions).Returns(forwardTranscriptRegions);
            _forwardTranscript.SetupGet(x => x.Translation).Returns(translation.Object);
            _forwardTranscript.SetupGet(x => x.TotalExonLength).Returns(1731);

            _reverseTranscript = new Mock <ITranscript>();
            _reverseTranscript.SetupGet(x => x.Chromosome).Returns(chromosome);
            _reverseTranscript.SetupGet(x => x.Start).Returns(3477259);
            _reverseTranscript.SetupGet(x => x.Start).Returns(3477354);
            _reverseTranscript.SetupGet(x => x.Gene.OnReverseStrand).Returns(true);
            _reverseTranscript.SetupGet(x => x.Translation).Returns((ITranslation)null);
            _reverseTranscript.SetupGet(x => x.BioType).Returns(BioType.miRNA);
            _reverseTranscript.SetupGet(x => x.TranscriptRegions).Returns(reverseTranscriptRegions);
            _reverseTranscript.SetupGet(x => x.MicroRnas).Returns(new IInterval[] { new Interval(61, 81) });
        }
示例#33
0
        private void listener_OnPacketReceived(object sender, PacketEventArgs e)
        {
            try {
                Log.Debug(string.Format("Packet Received, PacketId:{0} ObjectId:{1} Data Bytes:{2}",
                                        e.Packet.Header.PacketId,
                                        e.Packet.Header.ObjectId,
                                        e.Packet.Data.Length));

                switch ((PacketId)e.Packet.Header.PacketId)
                {
                case PacketId.Data: {
                    if (e.Packet.Header.DataLength > 0)
                    {
                        //deserialise to get the genes, create a new chromosome from these
                        //this saves having to send the whole chromosome
                        var genes      = Binary.DeSerialize <List <Gene> > (e.Packet.Data, _fitnessAssembly.KnownTypes);
                        var chromosome = new Chromosome(genes);

                        e.Result = chromosome.Evaluate(_fitnessAssembly.FitnessFunction);

                        if (OnEvaluationComplete != null)
                        {
                            var eventArgs = new RemoteEvaluationEventArgs(chromosome);
                            this.OnEvaluationComplete(this, eventArgs);
                        }
                    }

                    break;
                }

                case PacketId.Init: {
                    Log.Info("Initialisation initiated.");

                    if (e.Packet.Header.DataLength > 0)
                    {
                        Log.Info("Writing Fitness Assembly to filesystem.");

                        File.WriteAllBytes(_fitnessAssemblyName, e.Packet.Data);

                        //check for fitness file
                        if (File.Exists(_fitnessAssemblyName))
                        {
                            Log.Info("Loading the Fitness Assembly.");
                            _fitnessAssembly = new FitnessAssembly(_fitnessAssemblyName);
                        }
                        else
                        {
                            Log.Error("Fitness Assembly not accesible or missing.");
                        }
                    }

                    break;
                }

                case PacketId.Status: {
                    var result = 0x0;

                    //check for fitness file
                    if (File.Exists(_fitnessAssemblyName))
                    {
                        result = result | (int)ServerStatusFlags.Initialised;
                    }

                    if (_serverDefinedFitness)
                    {
                        result = result | (int)ServerStatusFlags.ServerDefinedFitness;
                    }

                    e.Result = (double)result;

                    break;
                }
                }
            } catch (Exception ex) {
                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }
                Log.Error(ex);
            }
        }
 public SelectionTournament(List <Chromosome> population, int tournamentSize)
 {
     Population      = population;
     NewPopulation   = new Chromosome[population.Count];
     _tournamentSize = tournamentSize;
 }
示例#35
0
 private void WriteChomosome(Chromosome chr, string comment = "")
 {
     richTextBox1.Text += chr.GId + "." + chr.Id + "\t" + chr.X1 + "\t" + chr.X2 + "\t" + chr + "\t" + Math.Round(chr.F, 4) + comment + "\n";
 }
示例#36
0
        private ICollection <Chromosome <BitArray> > CreateChildren(Chromosome <BitArray> parent1, Chromosome <BitArray> parent2)
        {
            // Determine a random point within the gene sequence
            var crossOverPoint = _random.Next(0, parent1.GeneSequence.Count);

            // Create two new gene sequences. 1 for each child
            var child1GeneSequence = new BitArray(parent1.GeneSequence.Count);
            var child2GeneSequence = new BitArray(parent1.GeneSequence.Count);

            // Set the genes on the left side of the crossover point
            for (var geneIndex = 0; geneIndex < crossOverPoint; geneIndex++)
            {
                // Child #1 gets the left part of parent #1
                child1GeneSequence[geneIndex] = parent1.GeneSequence[geneIndex];

                // Child #2 gets the left part of parent #2
                child2GeneSequence[geneIndex] = parent2.GeneSequence[geneIndex];
            }

            // Set the genes on the right side of the crossover point
            for (var geneIndex = crossOverPoint; geneIndex < parent1.GeneSequence.Length; geneIndex++)
            {
                // Child #1 gets the right part of parent #2
                child1GeneSequence[geneIndex] = parent2.GeneSequence[geneIndex];

                // Child #2 gets the right part of parent #1
                child2GeneSequence[geneIndex] = parent1.GeneSequence[geneIndex];
            }

            // Create the children
            var child1 = new Chromosome <BitArray>(child1GeneSequence);
            var child2 = new Chromosome <BitArray>(child2GeneSequence);

            return(new[] { child1, child2 });
        }
示例#37
0
        public void local_search_alg(Tasks tsk, string local_Search_Method_Name, int max_Genens, Random rnd, ref Chromosome ind, ref int func_call)
        {
            func_call = 1;
            switch (local_Search_Method_Name)
            {
            case "PRIM_2nd_TASK":
                #region áp dụng giải thuật PRIM tìm cây khung nhỏ nhất cho cluster
                int      idx_Max_Clus          = 0;
                int      num_Vertex_In_Cluster = 0;
                Evaluate eva = new Evaluate();
                eva.find_Largest_Cluster(tsk, ref idx_Max_Clus, ref num_Vertex_In_Cluster);

                double[,] cluster_Weight           = init_Chrome.create_Weight_Matrix_for_Cluster(max_Genens, num_Vertex_In_Cluster, tsk.Weight_Matrix, tsk.Vertex_In_Cluster[idx_Max_Clus]);
                double[,] spanning_Tree_of_Cluster = graph_Method_Class.prim(cluster_Weight, num_Vertex_In_Cluster, rnd);

                //Chuyen ra cay khung cua do thi G
                for (int k = 0; k < num_Vertex_In_Cluster; k++)
                {
                    for (int j = 0; j < num_Vertex_In_Cluster; j++)
                    {
                        if (spanning_Tree_of_Cluster[k, j] > 0)
                        {
                            ind.Edges_Matrix[tsk.Vertex_In_Cluster[idx_Max_Clus][k], tsk.Vertex_In_Cluster[idx_Max_Clus][j]] = spanning_Tree_of_Cluster[k, j];
                        }
                    }
                }

                //int[,] aaa = new int[max_Genens, max_Genens];
                //for (int i = 0; i < max_Genens; i++)
                //{
                //    for (int j = 0; j < max_Genens; j++)
                //    {
                //        aaa[i, j] = (int)ind.Edges_Matrix[i, j];
                //    }
                //}
                //ioFile.draw_Plot_in_Matlab("Local_Search_GA" + @".m", max_Genens, aaa);

                //Evaluate???

                #endregion
                break;

            case "1":
                #region 1
                //11111;
                #endregion
                break;
            }
        }
        /// <summary>
        /// Perform a cross over.
        /// </summary>
        /// <param name="mom">The mother genome.</param>
        /// <param name="dad">The father genome.</param>
        /// <returns></returns>
        public new NEATGenome Crossover(NEATGenome mom, NEATGenome dad)
        {
            NEATParent best;

            // first determine who is more fit, the mother or the father?
            if (mom.Score == dad.Score)
            {
                if (mom.NumGenes == dad.NumGenes)
                {
                    if (ThreadSafeRandom.NextDouble() > 0)
                    {
                        best = NEATParent.Mom;
                    }
                    else
                    {
                        best = NEATParent.Dad;
                    }
                }

                else
                {
                    if (mom.NumGenes < dad.NumGenes)
                    {
                        best = NEATParent.Mom;
                    }
                    else
                    {
                        best = NEATParent.Dad;
                    }
                }
            }
            else
            {
                if (Comparator.IsBetterThan(mom.Score, dad.Score))
                {
                    best = NEATParent.Mom;
                }

                else
                {
                    best = NEATParent.Dad;
                }
            }

            var babyNeurons = new Chromosome();
            var babyGenes   = new Chromosome();

            var vecNeurons = new List <long>();

            int curMom = 0;
            int curDad = 0;

            NEATLinkGene momGene;
            NEATLinkGene dadGene;

            NEATLinkGene selectedGene = null;

            while ((curMom < mom.NumGenes) || (curDad < dad.NumGenes))
            {
                if (curMom < mom.NumGenes)
                {
                    momGene = (NEATLinkGene)mom.Links.Get(curMom);
                }
                else
                {
                    momGene = null;
                }

                if (curDad < dad.NumGenes)
                {
                    dadGene = (NEATLinkGene)dad.Links.Get(curDad);
                }
                else
                {
                    dadGene = null;
                }

                if ((momGene == null) && (dadGene != null))
                {
                    if (best == NEATParent.Dad)
                    {
                        selectedGene = dadGene;
                    }
                    curDad++;
                }
                else if ((dadGene == null) && (momGene != null))
                {
                    if (best == NEATParent.Mom)
                    {
                        selectedGene = momGene;
                    }
                    curMom++;
                }
                else if (momGene.InnovationId < dadGene.InnovationId)
                {
                    if (best == NEATParent.Mom)
                    {
                        selectedGene = momGene;
                    }
                    curMom++;
                }
                else if (dadGene.InnovationId < momGene.InnovationId)
                {
                    if (best == NEATParent.Dad)
                    {
                        selectedGene = dadGene;
                    }
                    curDad++;
                }
                else if (dadGene.InnovationId == momGene.InnovationId)
                {
                    if (ThreadSafeRandom.NextDouble() < 0.5f)
                    {
                        selectedGene = momGene;
                    }

                    else
                    {
                        selectedGene = dadGene;
                    }
                    curMom++;
                    curDad++;
                }

                if (babyGenes.Size() == 0)
                {
                    babyGenes.Add(selectedGene);
                }

                else
                {
                    if (((NEATLinkGene)babyGenes.Get(babyGenes.Size() - 1))
                        .InnovationId != selectedGene.InnovationId)
                    {
                        babyGenes.Add(selectedGene);
                    }
                }

                // Check if we already have the nodes referred to in SelectedGene.
                // If not, they need to be added.
                AddNeuronID(selectedGene.FromNeuronID, vecNeurons);
                AddNeuronID(selectedGene.ToNeuronID, vecNeurons);
            } // end while

            // now create the required nodes. First sort them into order
            vecNeurons.Sort();

            for (int i = 0; i < vecNeurons.Count; i++)
            {
                babyNeurons.Add(Innovations.CreateNeuronFromID(
                                    vecNeurons[i]));
            }

            // finally, create the genome
            var babyGenome = new NEATGenome(Population
                                            .AssignGenomeID(), babyNeurons, babyGenes, mom.InputCount,
                                            mom.OutputCount);

            babyGenome.GA         = this;
            babyGenome.Population = Population;

            return(babyGenome);
        }
        // TODO -> return more than one child always!!!
        protected override Chromosome <T> _Crossover(Chromosome <T> fatherChromosome, Chromosome <T> motherChromosome)
        {
            _cycles.Clear();
            _cycleIndexSet.Clear();
            _lookupDictionary.Clear();

            var genomeLength     = fatherChromosome.GenomeLength;
            var childChromosomeA = new Chromosome <T>(genomeLength); // TODO -> use object pooling !!
            var childChromosomeB = new Chromosome <T>(genomeLength); // TODO -> use object pooling !!

            var fatherGenome = fatherChromosome.GetGenome();
            var motherGenome = motherChromosome.GetGenome();

            // add father genes to lookup dictionary
            for (int i = 0; i < genomeLength; i++)
            {
                _lookupDictionary.Add(fatherGenome[i], i);
            }

            // find cycles between both parents
            for (int i = 0; i < genomeLength; i++)
            {
                if (!_cycleIndexSet.Contains(i))
                {
                    var newCycle = new List <int>();
                    CreateCycle(motherGenome, i, newCycle);
                    _cycles.Add(newCycle);
                }
            }

            // filling in the offsprings using alternate cycles
            for (int i = 0; i < _cycles.Count; i++)
            {
                var currentCycle = _cycles[i];
                var alternate    = i % 2 == 0; // using modulo 2 to alternate the cycles between the 2 offsprings

                var chromosomeA = alternate ? childChromosomeA : childChromosomeB;
                var chromosomeB = alternate ? childChromosomeB : childChromosomeA;

                CopyAlternateCycle(currentCycle, fatherGenome, motherGenome, chromosomeA, chromosomeB);
            }

            return(childChromosomeA);
        }
 private static void CopyAlternateCycle(IReadOnlyList <int> currentCycle, IReadOnlyList <T> fatherGenome, IReadOnlyList <T> motherGenome, Chromosome <T> childChromosomeA, Chromosome <T> childChromosomeB)
 {
     for (int j = 0; j < currentCycle.Count; j++)
     {
         var currentCycleIndex = currentCycle[j];
         childChromosomeA.InsertGene(currentCycleIndex, fatherGenome[currentCycleIndex]);
         childChromosomeB.InsertGene(currentCycleIndex, motherGenome[currentCycleIndex]);
     }
 }
 public override bool isBetterThan(Chromosome c)
 {
     return(((System.IComparable <ChromosomeSalesman>) this).CompareTo((ChromosomeSalesman)c) <= 0);
 }
 public Chromosome <T> CrossOver(Chromosome <T> parent1, Chromosome <T> parent2)
 {
     throw new NotImplementedException();
 }
示例#43
0
        public override Chromosome Crossover(Chromosome firstParent, Chromosome secondParent)
        {
            if (Probability == 0)
            {
                throw new NotImplementedException();
            }

            double probability = Utility.Rand.NextDouble();

            int sizeChromosome = firstParent.SizeChromosome;

            int[] childArray = new int[sizeChromosome];

            if (probability <= Probability)
            {
                int[] dots = GetDotCrossover(CountDot, sizeChromosome);

                int g = 0;
                for (int p = 0; p < CountDot; p++)
                {
                    for (int i = g; i < sizeChromosome; i++)
                    {
                        if (p % 2 == 0 || p == 0)
                        {
                            if (i < dots[p])
                            {
                                childArray[i] = firstParent.chromosomeArray[i];
                                g++;
                            }
                            else if (p == CountDot - 1)
                            {
                                childArray[i] = secondParent.chromosomeArray[i];
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            if (i < dots[p])
                            {
                                childArray[i] = secondParent.chromosomeArray[i];
                                g++;
                            }
                            else if (p == CountDot - 1)
                            {
                                childArray[i] = firstParent.chromosomeArray[i];
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
            Chromosome child = new Chromosome(childArray);

            return(child);
        }
示例#44
0
        public void Transcript_EndToEnd()
        {
            IChromosome   expectedChromosome       = new Chromosome("chrBob", "Bob", 1);
            const int     expectedStart            = int.MaxValue;
            const int     expectedEnd              = int.MinValue;
            const string  expectedId               = "ENST00000540021";
            const byte    expectedVersion          = 7;
            const BioType expectedBioType          = BioType.IG_J_pseudogene;
            const bool    expectedCanonical        = true;
            const Source  expectedSource           = Source.BothRefSeqAndEnsembl;
            const bool    expectedCdsStartNotFound = true;
            const bool    expectedCdsEndNotFound   = true;

            var expectedIdAndVersion = expectedId + "." + expectedVersion;

            ICodingRegion expectedCodingRegion = new CodingRegion(10001, 10200, 1, 200, 200);

            ITranscriptRegion[] expectedTranscriptRegions = GetTranscriptRegions();
            const byte          expectedNumExons          = 3;

            const int  expectedTotalExonLength = 300;
            const byte expectedStartExonPhase  = 3;
            const int  expectedSiftIndex       = 11;
            const int  expectedPolyPhenIndex   = 13;

            IInterval[] expectedMicroRnas = GetMicroRnas();

            ITranslation expectedTranslation = new Translation(expectedCodingRegion, CompactId.Convert("ENSP00000446475", 17), "VEIDSD");

            IGene expectedGene = new Gene(expectedChromosome, 100, 200, true, "TP53", 300, CompactId.Convert("7157"),
                                          CompactId.Convert("ENSG00000141510"));

            var genes = new IGene[1];

            genes[0] = expectedGene;

            var peptideSeqs = new string[1];

            peptideSeqs[0] = expectedTranslation.PeptideSeq;

            var geneIndices             = CreateIndices(genes);
            var transcriptRegionIndices = CreateIndices(expectedTranscriptRegions);
            var microRnaIndices         = CreateIndices(expectedMicroRnas);
            var peptideIndices          = CreateIndices(peptideSeqs);

            var indexToChromosome = new Dictionary <ushort, IChromosome>
            {
                [expectedChromosome.Index] = expectedChromosome
            };

            // ReSharper disable ConditionIsAlwaysTrueOrFalse
            var transcript = new Transcript(expectedChromosome, expectedStart, expectedEnd,
                                            CompactId.Convert(expectedId, expectedVersion), expectedTranslation, expectedBioType, expectedGene,
                                            expectedTotalExonLength, expectedStartExonPhase, expectedCanonical, expectedTranscriptRegions,
                                            expectedNumExons, expectedMicroRnas, expectedSiftIndex, expectedPolyPhenIndex,
                                            expectedSource, expectedCdsStartNotFound, expectedCdsEndNotFound, null, null);
            // ReSharper restore ConditionIsAlwaysTrueOrFalse

            ITranscript observedTranscript;

            using (var ms = new MemoryStream())
            {
                using (var writer = new ExtendedBinaryWriter(ms, Encoding.UTF8, true))
                {
                    transcript.Write(writer, geneIndices, transcriptRegionIndices, microRnaIndices, peptideIndices);
                }

                ms.Position = 0;

                using (var reader = new BufferedBinaryReader(ms))
                {
                    observedTranscript = Transcript.Read(reader, indexToChromosome, genes, expectedTranscriptRegions, expectedMicroRnas, peptideSeqs);
                }
            }

            Assert.NotNull(observedTranscript);
            Assert.Equal(expectedStart, observedTranscript.Start);
            Assert.Equal(expectedEnd, observedTranscript.End);
            Assert.Equal(expectedIdAndVersion, observedTranscript.Id.WithVersion);
            Assert.Equal(expectedBioType, observedTranscript.BioType);
            Assert.Equal(expectedCanonical, observedTranscript.IsCanonical);
            Assert.Equal(expectedSource, observedTranscript.Source);
            Assert.Equal(expectedTotalExonLength, observedTranscript.TotalExonLength);
            Assert.Equal(expectedStartExonPhase, observedTranscript.StartExonPhase);
            Assert.Equal(expectedSiftIndex, observedTranscript.SiftIndex);
            Assert.Equal(expectedPolyPhenIndex, observedTranscript.PolyPhenIndex);

            Assert.Equal(expectedChromosome.Index, observedTranscript.Chromosome.Index);
            Assert.Equal(expectedGene.Symbol, observedTranscript.Gene.Symbol);
            Assert.Equal(expectedTranslation.PeptideSeq, observedTranscript.Translation.PeptideSeq);
            Assert.Equal(expectedTranscriptRegions.Length, observedTranscript.TranscriptRegions.Length);
            Assert.Equal(expectedMicroRnas.Length, observedTranscript.MicroRnas.Length);
        }
示例#45
0
 protected abstract void CrossChromosomes(Chromosome parent1, Chromosome parent2, int index);
 public double[] ExpressWith(Chromosome chromosome, Func <Gene, Gene, double> expressGene)
 {
     return(Genes.Zip(chromosome.Genes, expressGene).ToArray());
 }
 // 이 식을 사용할 수 있는 이유는, Array.Sort의 인자값으로 IComparer가 들어가야하는데, 그 IComparer의 형태와 같기 때문인걸로 보입니다.
 // 1. Sort를 사용할 Array의 데이터형을 2개 받는다.
 // 2. public 접근자다.
 // 3. int형을 반환한다.
 // 아마 위의 3가지를 다 만족하는 함수형태가 IComparer로 구현할 함수와 동일한 형태이므로 변환이 가능한 것 같습니다!!!
 public int FitnessSortAlgorism(Chromosome A, Chromosome B)
 {
     return(A.fitness.CompareTo(B.fitness));
 }
 public Individual(Chromosome cA, Chromosome cB)
 {
     this.cA = cA;
     this.cB = cB;
 }
示例#49
0
 public EvaluatedChromosome(Chromosome chromosome, double fitness)
 {
     Chromosome = chromosome;
     Fitness    = fitness;
 }
示例#50
0
 public void Score(Chromosome chromosome)
 {
     fitnessAlgorithm.CalculateScore(chromosome);
 }
示例#51
0
        public static void Main(string[] args)
        {
            FileWriting.CreateTestFile("../../Data/Test.csv", "ID, Type, Minimum Time, Average Delay, Average Cost");

            rnd = new Random();

            read_configuration_files();
            int testID = 1;

            while (true)
            {
                if (_currentAirport.Radar.Count == 0)
                {
                    _radar = new Thread(() => read_radar_thread("../../Data/Airport" + Airport + "/Radar.csv"));
                    _radar.Start();
                }

                while (!_currentAirport.Ready)
                {
                }

                var selection  = new Selection();
                var crossover  = new Crossover(2, 2);
                var mutation   = new Mutation();
                var fitness    = new Fitness();
                var chromosome = new Chromosome(_currentAirport);
                var population = new Population(250, 500, chromosome);

                // FIFO
                var fifoChr = new Chromosome(_currentAirport, true);
                fitness.Evaluate(fifoChr, true);


                var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
                {
                    CrossoverProbability = 0.5f,
                    MutationProbability  = 0.2f,
                    Termination          = new TimeEvolvingTermination(TimeSpan.FromMinutes(1)),
                    Reinsertion          = new CustomReinsertion(),
                };

                var initialTimeSpan = DateTime.Now;
                Console.WriteLine("[{0}] Scheduling started", initialTimeSpan);

                Chromosome lastBest = null;
                ga.GenerationRan += (sender, e) =>
                {
                    var bestChromosome = ga.BestChromosome as Chromosome;

                    if (lastBest == null)
                    {
                        lastBest = bestChromosome;
                    }
                };


                ga.Start();
                Console.WriteLine("[{0}] New Round !", DateTime.Now);


                FileWriting.WriteToFile("../../Data/Test.csv", testID + ", FIFO, " + fifoChr.ToString());
                FileWriting.WriteToFile("../../Data/Test.csv", testID + ", --GA, " + ga.BestChromosome.ToString());
                ga.Stop();
                _radar.Interrupt();
                _currentAirport.Ready = false;
                _currentAirport.Radar.Clear();
                testID++;
            }
        }
示例#52
0
 public Timer(DateTime time, int generation, Chromosome chromosome)
 {
     Time       = time;
     Generation = generation;
     Chromosome = chromosome;
 }
        /// <summary>
        /// Updates the geometry for an input chromosome
        /// </summary>
        /// <param name="chromo">The chromosome used to get geometry from the gh canvas</param>
        /// <returns></returns>
        public int GetGeometry(Chromosome chromo)
        {
            // Collect the object at the current instance
            List <object> localObjs = new List <object>();

            // Thank you Dimitrie :)
            foreach (IGH_Param param in Params.Input[1].Sources)
            {
                foreach (Object myObj in param.VolatileData.AllData(true)) // AllData flattens the tree
                {
                    localObjs.Add(myObj);
                }
            }

            // Gets lists of different geometry
            List <Mesh>          meshGeometry = new List <Mesh>();
            List <PolylineCurve> polyGeometry = new List <PolylineCurve>();

            // Get only mesh geometry from the object list
            for (int i = 0; i < localObjs.Count; i++)
            {
                // Need to replace with a Switch

                if (localObjs[i] is GH_Mesh)
                {
                    GH_Mesh myGHMesh = new GH_Mesh();
                    myGHMesh = (GH_Mesh)localObjs[i];
                    Mesh myLocalMesh = new Mesh();
                    GH_Convert.ToMesh(myGHMesh, ref myLocalMesh, GH_Conversion.Primary);
                    myLocalMesh.Faces.ConvertQuadsToTriangles();

                    meshGeometry.Add(myLocalMesh);

                    //Mesh joinedMesh = new Mesh();
                    //joinedMesh.Append(myLocalMesh);
                }

                if (localObjs[i] is GH_Brep)
                {
                    GH_Brep myBrep = new GH_Brep();
                    myBrep = (GH_Brep)localObjs[i];

                    Mesh[] meshes = Mesh.CreateFromBrep(myBrep.Value, MeshingParameters.FastRenderMesh);

                    Mesh mesh = new Mesh();
                    mesh.Append(meshes);
                    mesh.Faces.ConvertQuadsToTriangles();

                    meshGeometry.Add(mesh);
                }

                if (localObjs[i] is GH_Box)
                {
                    GH_Box myBox  = new GH_Box((GH_Box)localObjs[i]);
                    Mesh[] meshes = Mesh.CreateFromBrep(myBox.Brep(), MeshingParameters.FastRenderMesh);

                    Mesh mesh = new Mesh();
                    mesh.Append(meshes);
                    mesh.Faces.ConvertQuadsToTriangles();

                    meshGeometry.Add(mesh);
                }

                if (localObjs[i] is GH_Surface)
                {
                    GH_Surface mySurface = (GH_Surface)localObjs[i];

                    Mesh[] meshes = Mesh.CreateFromBrep(mySurface.Value, MeshingParameters.FastRenderMesh);

                    Mesh mesh = new Mesh();
                    mesh.Append(meshes);
                    mesh.Faces.ConvertQuadsToTriangles();

                    meshGeometry.Add(mesh);
                }

                if (localObjs[i] is GH_Curve)
                {
                    GH_Curve      myGHCurve = (GH_Curve)localObjs[i];
                    PolylineCurve myPoly    = myGHCurve.Value.ToPolyline(0, 0, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0, true);
                    polyGeometry.Add(myPoly);
                }

                if (localObjs[i] is GH_Arc)
                {
                    GH_Arc        myGHArc = (GH_Arc)localObjs[i];
                    PolylineCurve myPoly  = myGHArc.Value.ToNurbsCurve().ToPolyline(0, 0, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0, true);
                    polyGeometry.Add(myPoly);
                }

                if (localObjs[i] is GH_Line)
                {
                    GH_Line        myGHLine = (GH_Line)localObjs[i];
                    List <Point3d> pts      = new List <Point3d> {
                        myGHLine.Value.From, myGHLine.Value.To
                    };
                    PolylineCurve myPoly = new PolylineCurve(pts);
                    polyGeometry.Add(myPoly);
                }
            }

            // Get performance data
            List <double> performas = new List <double>();
            List <string> criteria  = new List <string>();

            // Cap at eight criteria max.
            int pCount        = 0;
            int repeatCounter = 1;

            foreach (IGH_Param param in Params.Input[2].Sources)
            {
                foreach (Object myObj in param.VolatileData.AllData(true))
                {
                    if (myObj is GH_Number && pCount < 8)
                    {
                        GH_Number temp = (GH_Number)myObj;
                        performas.Add(temp.Value);

                        if (!criteria.Contains(param.NickName))
                        {
                            criteria.Add(param.NickName);
                        }

                        else
                        {
                            criteria.Add(param.NickName + " (" + repeatCounter + ")");
                            repeatCounter++;
                        }

                        pCount++;
                    }

                    else if (myObj is GH_Integer && pCount < 8)
                    {
                        GH_Integer temp = (GH_Integer)myObj;
                        performas.Add((double)temp.Value);

                        if (!criteria.Contains(param.NickName))
                        {
                            criteria.Add(param.NickName);
                        }

                        else
                        {
                            criteria.Add(param.NickName + " (" + repeatCounter + ")");
                            repeatCounter++;
                        }

                        pCount++;
                    }
                }
            }

            // Set the phenotype within the chromosome class
            chromo.SetPhenotype(meshGeometry, polyGeometry, performas, criteria);

            // Return the number of performance criteria
            return(performas.Count);
        }
 /// <summary>
 /// Mutates a chromosome to maintain genetic diversity in a population.
 /// </summary>
 /// <param name="childChromosome">The child <see cref="Chromosome{T}"/> which will be mutated to maintain diversity.</param>
 public void Mutate(Chromosome <T> childChromosome)
 {
     _Mutate(childChromosome);
 }
示例#55
0
 private string GetPreCrossoverSequence(Chromosome chromosome, int crossoverPoint)
 {
     return(chromosome.Sequence.Substring(0, crossoverPoint));
 }
示例#56
0
        static double fapt2d(Chromosome sol)
        {
            string[] vcurve = { "shp", "exp", "gaus" };
            double[] vsol   = bintoreal2D(sol);
            double[,] mvar = variograma2D(vsol);
            int nvar = Convert.ToInt32(mvar[0, 0]);

            double[] vvarx = new double[nvar + 1];
            double[] vvary = new double[nvar + 1];
            double   r     = 0;

            for (int i = 1; i <= nvar; i++)
            {
                vvarx[i] = mvar[i, 1];
                vvary[i] = mvar[i, 2];
            }
            double soma    = 0;
            bool   vario   = true;
            double somavar = vvary.Sum();

            if (somavar < 0.1)
            {
                vario = false;
            }
            int cont = 0;

            for (int i = 2; i <= nvar; i++)
            {
                if (vvary[i] == 0)
                {
                    cont++;
                }
            }
            if (cont > 0)
            {
                vario = false;
            }
            if (vario == false)
            {
                r = 0;
                goto fim;
            }
            double[] param = sa.simulated(vvarx, vvary);
            int      tipo  = Convert.ToInt32(param[0]);
            double   floss = param[1];
            double   C0    = param[2];
            double   C     = param[3];
            double   a     = param[4];
            //--------penalty 1
            double fp1 = 1;

            if (C0 / C > p.ga_ns)
            {
                fp1 = System.Math.Exp(2 * p.ga_ns);
            }
            //--------penalty 2
            double fp2 = 1;
            double R   = System.Math.Abs((2 * vsol[4] * (int)vsol[5] - maxdim) / maxdim);

            if (R > rp)
            {
                fp2 = 2 * System.Math.Log(30 * R);
            }
            //--------penalty 3
            //double fp3 = System.Math.Sqrt(floss / nvar);
            //------------------------
            for (int i = 1; i <= npontos; i++)
            {
                double x    = mpontos[i, 1];
                double y    = mpontos[i, 2];
                double z    = mpontos[i, 3];
                double zest = krigagem.krigagem2D(x, y, mpontos, tipo, C0, C, a);
                soma = soma + (z - zest) * (z - zest);
                //soma2 = soma2 + (z - mediaobs)* (z - mediaobs);
            }
            soma = soma / npontos;

            soma = soma * fp1 * fp2;

            //string st = vsol[1].ToString("F2")+"/"+ vsol[2].ToString("F2") + "/" + vsol[3].ToString("F2") + "/" + vsol[4].ToString("F2") + "/" + Convert.ToInt32(vsol[5]).ToString() + "/" +C0.ToString("F2")+"/"+C.ToString("F2")+ "/" + a.ToString("F2")+ "/"+vcurve[tipo-1]+"/" +floss.ToString("F2")+"/"+soma.ToString("F2");
            //string st = soma.ToString("F4") + "/" + tipo.ToString() + "/" + C0.ToString("F4") + "/" + C.ToString("F4") + "/" + a.ToString("F4");
            tag Tag = new tag();

            Tag.ns    = C0 / C;
            Tag.angle = vsol[1]; Tag.tol = vsol[2]; Tag.bwh = vsol[3]; Tag.lsd = vsol[4];
            Tag.nl    = (int)vsol[5]; Tag.C0 = C0; Tag.C = C; Tag.a = a;
            Tag.curve = vcurve[tipo - 1]; Tag.floss = floss; Tag.fobj = soma;
            Tag.vx    = vvarx; Tag.vy = vvary; Tag.curvetipo = tipo;
            sol.Tag   = Tag;



            double gama = 0.1;
            double aux1 = 1 / (1 + System.Math.Exp(-gama * soma));

            r = 2 * (1 - aux1);
fim:
            if (r < 0)
            {
                r = 0;
            }
            //Console.WriteLine(r.ToString());
            return(r);
        }
示例#57
0
 private int SelectCrossoverPosition(Chromosome source)
 {
     return(numberGenerator.Next(0, source.Sequence.Length + 1));
 }
示例#58
0
    public void EvolveNextGeneration()
    {
        Chromosome[] nextGen = new Chromosome[populationSize];

        // Find the max to use for normalisation when selecting
        float maxFitness = 0;

        foreach (Chromosome c in population)
        {
            if (c.Fitness > maxFitness)
            {
                maxFitness = c.Fitness;
            }
        }

        // Build up the next generation using roulette wheel selection
        // More likely to select chromosomes with higher fitness values
        int indFirst  = Random.Range(0, populationSize);
        int indSecond = Random.Range(0, populationSize);

        for (int i = 0; i < populationSize; i++)
        {
            // Find the first parent
            float r = Random.value;
            //Debug.Log("first r value: " + r);
            //foreach (Chromosome c in population)
            //{
            //    Debug.Log(c.Fitness / maxFitness);
            //}

            float cur = 0;
            while (cur <= r)
            {
                // Add the normalised value
                cur += population[indFirst].Fitness / maxFitness;
                indFirst++;
                indFirst %= populationSize;
            }
            indFirst -= 1;
            if (indFirst == -1)
            {
                indFirst = populationSize - 1;
            }
            Chromosome first = population[indFirst];

            // Find the second parent
            r   = Random.value;
            cur = 0;
            while (cur <= r)
            {
                if (indSecond == indFirst)
                {
                    indSecond++;
                }
                indSecond %= populationSize;
                // Add the normalised value
                cur += population[indSecond].Fitness / maxFitness;
                indSecond++;
            }
            indSecond -= 1;
            if (indSecond == -1)
            {
                indSecond = populationSize - 1;
            }
            Chromosome second = population[indSecond];

            Chromosome child = Chromosome.Crossover(first, second);
            if (InstanceData.SingleMutate)
            {
                child = Chromosome.MutateSingle(child, mutationRate);
            }
            else
            {
                child = Chromosome.Mutate(child, mutationRate);
            }
            child.SetParents(indFirst, indSecond);
            nextGen[i] = child;
        }

        population = nextGen;

        popManager.SetGenerationChromosomes(population);
    }
        /// <summary>
        /// Updates the geometry for an input chromosome
        /// </summary>
        /// <param name="chromo">The chromosome used to get geometry from the gh canvas</param>
        /// <returns></returns>
        public int GetGeometry(Chromosome chromo)
        {
            // Collect the object at the current instance
            List <object> localObjs = new List <object>();

            // Thank you Dimitrie :)
            foreach (IGH_Param param in Params.Input[1].Sources)
            {
                foreach (Object myObj in param.VolatileData.AllData(true)) // AllData flattens the tree
                {
                    localObjs.Add(myObj);
                }
            }

            // TODO: The allGeometry should not be of type Mesh.
            List <Mesh> allGeometry = new List <Mesh>();

            // Get only mesh geometry from the object list
            for (int i = 0; i < localObjs.Count; i++)
            {
                if (localObjs[i] is GH_Mesh)
                {
                    GH_Mesh myGHMesh = new GH_Mesh();
                    myGHMesh = (GH_Mesh)localObjs[i];
                    Mesh myLocalMesh = new Mesh();
                    GH_Convert.ToMesh(myGHMesh, ref myLocalMesh, GH_Conversion.Primary);
                    myLocalMesh.Faces.ConvertQuadsToTriangles();
                    //Mesh joinedMesh = new Mesh(); yes this is commented out and no I am not a software engineer. Deal with it.
                    //joinedMesh.Append(myLocalMesh);
                    allGeometry.Add(myLocalMesh);
                }
            }

            // Get performance data
            List <double> performas = new List <double>();
            List <string> criteria  = new List <string>();

            // Cap at eight criteria max.
            int pCount = 0;

            foreach (IGH_Param param in Params.Input[2].Sources)
            {
                foreach (Object myObj in param.VolatileData.AllData(true))
                {
                    if (myObj is GH_Number && pCount < 8)
                    {
                        if (!criteria.Contains(param.NickName))
                        {
                            GH_Number temp = (GH_Number)myObj;
                            performas.Add(temp.Value);
                            criteria.Add(param.NickName);
                            pCount++;
                        }
                    }

                    else if (myObj is GH_Integer && pCount < 8)
                    {
                        if (!criteria.Contains(param.NickName))
                        {
                            GH_Integer temp = (GH_Integer)myObj;
                            performas.Add((double)temp.Value);
                            criteria.Add(param.NickName);
                            pCount++;
                        }
                    }
                }
            }

            // Set the phenotype within the chromosome class
            chromo.SetPhenotype(allGeometry, performas, criteria);

            // Return the number of performance criteria
            return(performas.Count);
        }
 /// <summary>
 /// An abstract method for mutate. This must be implemented in child classes.
 /// </summary>
 /// <param name="childChromosome">The child <see cref="Chromosome{T}"/> which will be mutated to maintain diversity.</param>
 protected abstract void _Mutate(Chromosome <T> childChromosome);