public void BuildRepresentation_NoDominant(string a1r, string a2r, string expected)
 {
     var a1 = new Allele(a1r, false);
     var a2 = new Allele(a2r, false);
     var gene = new Gene(a1, a2, Guid.NewGuid());
     Assert.AreEqual(expected, gene.Representation);
 }
 public void BuildRepresentation_OneDominant(string a1r, bool a1d, string a2r, bool a2d)
 {
     var a1 = new Allele(a1r, a1d);
     var a2 = new Allele(a2r, a2d);
     var gene = new Gene(a1, a2, Guid.NewGuid());
     Assert.AreEqual(a1r, gene.Representation);
 }
Beispiel #3
0
        //krizenie mnichov
        public Monk(Monk mother, Monk father)
        {
            if(mother.Length != father.Length)
                throw new ArgumentException("Parents must be of the same length");

            Random rand = new Random();
            Chromosome = new List<Gene>();
            Length = father.Length;
            Treshold = father.Treshold;
            Fitness = 0;

            //polovica z matky
            Chromosome.AddRange(mother.Chromosome.Take(Length / 2));
            //z otca to, co tam este nie je
            var remains = father.Chromosome.Except(Chromosome);
            Chromosome.AddRange(remains.Take(Length / 2));
            //ak treba dotvorim nove
            if (Chromosome.Count < Length)
            {
                int i = Chromosome.Count;

                while (i <= Length)
                {
                    bool tr = (rand.Next(2) == 1) ? true : false;
                    var g = new Gene(rand.Next(father.Treshold), tr);
                    if ((null != Chromosome.Where(t => t.Start == g.Start).FirstOrDefault()))
                        continue;
                    else
                    {
                        ++i;
                        Chromosome.Add(g);
                    }
                }
            }
        }
	public static List<Gene> GetGenesOfType(List<Gene> geneList, Gene.Type t)
	{
		List<Gene> genesOfTheSameType = new List<Gene>();
		foreach(Gene g in geneList)
			if(g.type == t)
				genesOfTheSameType.Add(g);
		return genesOfTheSameType;
	}
Beispiel #5
0
        public void ToString_NoArgs_Value()
        {
            var target = new Gene();
            Assert.AreEqual("", target.ToString());

            target = new Gene(1);
            Assert.AreEqual("1", target.ToString());
        }
 // --- functions:
 /**
  * Creates the starting population of Gene classes, whose chromosome contents are random
  * @param size: The size of the popultion is passed as an argument from the main class
  */
 public GeneticAlgorithm(int size)
 {
     // initialize the arraylist and each gene's initial weights HERE
     mPopulation = new List<Gene>();
     for(int i = 0; i < size; i++){
         Gene entry = new Gene();
         entry.randomizeChromosome();
         mPopulation.Add(entry);
     }
 }
Beispiel #7
0
	public void Show(Gene gene)
	{
		string rarityString = Gene.RarityStringFromrarity(gene.rarity);
		string colorString = Gene.HexColorStringFromRarity(gene.rarity);

		base.Show("Gene Info", gene.description);
		nameLabel.text = gene.geneName;
		rarityLabel.text = colorString + rarityString + "[-]";
		gameObject.SetActive(true);
	}
 public void SelectAllele_ReturnSecondAllele()
 {
     var random = new Falsy();
     var factory = new PersonFactory(random);
     var first = new Allele();
     var second = new Allele();
     var gene = new Gene(first, second, Guid.NewGuid());
     var bob = factory.SelectAllele(gene);
     Assert.AreEqual(bob, second.Id);
 }
Beispiel #9
0
        public void CopyTest()
        {
            IGene gene       = new Gene(new Node(NodeType.Hidden), new Node(NodeType.Hidden), 1);
            IGene copiedGene = gene.Copy();

            Assert.AreEqual(gene.Innovation, copiedGene.Innovation);
            Assert.AreEqual(gene.IsExpressed, copiedGene.IsExpressed);
            Assert.AreEqual(gene.NodeIn.Id, copiedGene.NodeIn.Id);
            Assert.AreEqual(gene.NodeOut.Id, copiedGene.NodeOut.Id);
            Assert.AreEqual(gene.Weight, copiedGene.Weight);
        }
        /// <summary>
        /// parses the database cache file and populates the specified lists and interval trees
        /// </summary>
        public TranscriptCacheData Read(IDictionary <ushort, IChromosome> refIndexToChromosome)
        {
            var genes             = ReadItems(_reader, () => Gene.Read(_reader, refIndexToChromosome));
            var transcriptRegions = ReadItems(_reader, () => TranscriptRegion.Read(_reader));
            var mirnas            = ReadItems(_reader, () => Interval.Read(_reader));
            var peptideSeqs       = ReadItems(_reader, () => _reader.ReadAsciiString());
            var regulatoryRegions = ReadIntervals(_reader, () => RegulatoryRegion.Read(_reader, refIndexToChromosome));
            var transcripts       = ReadIntervals(_reader, () => Transcript.Read(_reader, refIndexToChromosome, genes, transcriptRegions, mirnas, peptideSeqs));

            return(new TranscriptCacheData(Header, genes, transcriptRegions, mirnas, peptideSeqs, transcripts, regulatoryRegions));
        }
        public void AddGene()
        {
            var gene = new Gene()
            {
                Name = "NEW GENE",
            };

            chromosome.Genes.Add(gene);
            Genes.Add(new GeneViewModel(gene, context));
            context.Genes.Add(gene);
        }
Beispiel #12
0
 public LoadLikeDataTest()
 {
     _insertedGeneWithSymbol          = GeneTestData.Genes[0];
     _insertedGeneWithOutSymbol       = GeneTestData.Genes[1];
     _insertedGeneWithOutKnowFunction = GeneTestData.Genes[7];
     Context.Gene.Add(_insertedGeneWithSymbol);
     Context.Gene.Add(_insertedGeneWithOutSymbol);
     Context.Gene.Add(_insertedGeneWithOutKnowFunction);
     Context.Symbol.Add(SymbolTestData.Symbols[0]);
     Context.SaveChanges();
 }
 public void RemoveColumn(Gene gene)
 {
     if (grid != null)
     {
         var col = grid.Columns.Where(c => string.Equals(c.Header, gene.Name)).FirstOrDefault();
         if (col != null)
         {
             grid.Columns.Remove(col);
         }
     }
 }
Beispiel #14
0
        private GeneDetailedResult GetGeneResult(TowerState towerState, Gene gene, int pathLength, int maximumTurns)
        {
            var simulator = new Simulator(pathLength, maximumTurns, towerState.Cannons, towerState.Archers);
            var result    = simulator.Simulate(new MyGeneParser(gene));

            return(new GeneDetailedResult
            {
                Gene = gene,
                NormalizedGene = gene.GenomesList.Select(x => MyGeneParser.GeneToTroopCount(x)).ToArray(),
                Result = result,
            });
        }
 public void AddColumn(Gene gene)
 {
     if (grid != null)
     {
         var col = new DataGridTextColumn() { Header = gene.Name };
         grid.Columns.Add(col);
         var binding = new Binding();
         binding.Converter = mouseToAllelesConverter ?? (mouseToAllelesConverter = new MouseToAllelesConverter());
         binding.ConverterParameter = gene;
         col.Binding = binding;
     }
 }
Beispiel #16
0
        private string DemandPathFlowList(Gene gene)
        {
            string output = "";

            output += DemandPathFlow(0, gene.ValueOnPath[0]);
            for (int i = 1; i < gene.ValueOnPath.Length; i++)
            {
                output += Environment.NewLine;
                output += DemandPathFlow(i, gene.ValueOnPath[i]);
            }
            return(output);
        }
Beispiel #17
0
        public GeneScore Evaluate(Gene gene)
        {
            for (var i = 0; i < gene.Chromosomes.Count; i++)
            {
                // NT needs everything to be doubles
                _strategy.Parameters[_strategyParameterIndices[i]].Value = Convert.ToDouble(gene.Chromosomes[i]);
            }

            _strategy.RunIteration();

            return(new GeneScore(gene, FitnessFunctionWrapper.LastPerformanceValue));
        }
Beispiel #18
0
        public async Task <IActionResult> PostGene([FromBody] Gene gene)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.Gene.Add(gene);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetGene", new { id = gene.Id }, gene));
        }
Beispiel #19
0
    public DNA PerfectDuplicate()
    {
        List <Gene> newGenes = new List <Gene>();
        List <Gene> Genes    = GetGenes();

        foreach (Gene gene in Genes)
        {
            Gene newGene = gene.Clone(0);
            newGenes.Add(newGene);
        }
        return(new DNA(newGenes));
    }
Beispiel #20
0
        public void CrossoverTest()
        {
            UInt32 sequence = Convert.ToUInt32("01010101010101010101010101010101", 2);

            Gene gene1 = new Gene(sequence);
            Gene gene2 = new Gene(Convert.ToUInt32("10101010101010101010101010101010", 2));

            Gene newGene = gene1.Crossover(gene2);

            Assert.AreNotEqual(gene1.Sequence, newGene.Sequence);
            Assert.AreNotEqual(gene2.Sequence, newGene.Sequence);
        }
Beispiel #21
0
    public static Genome CreateRandom(int genomeLength, int geneLength)
    {
        Genome genome = new Genome();

        genome.genes = new Gene[genomeLength];
        for (int i = 0; i < genome.genes.Length; i++)
        {
            genome.genes[i] = Gene.CreateRandom(geneLength);
        }
        genome.score = 0;
        return(genome);
    }
Beispiel #22
0
        public async Task ReadAndWriteAllGenesToDataBase(string filePath)
        {
            base.Initialize(filePath);
            using (var reader = new StreamReader(FilePath))
            {
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    if (line != null)
                    {
                        var values  = line.Split('\t');
                        var isValid = (!string.IsNullOrEmpty(values[19]) && !string.IsNullOrEmpty(values[2]));

                        var isProteinCoding = (!string.IsNullOrEmpty(values[3]) &&
                                               values[3].Equals("protein-coding gene")) &&
                                              (!string.IsNullOrEmpty(values[5]) &&
                                               values[5].Equals("Approved"));
                        if (!isProteinCoding || !isValid)
                        {
                            continue;
                        }

                        var gene = new Gene
                        {
                            DisplayName     = values[2],
                            EntrezId        = values[18],
                            RefSeqAccession = values[23],
                            EnsembleGeneId  = values[19],
                            Symbol          = values[1],
                            AliasSymbol     = string.IsNullOrEmpty(values[8]) ? "Not defined yet" : values[8],
                            AliasName       = string.IsNullOrEmpty(values[9]) ? "Not defined yet" : values[9],
                            Location        = string.IsNullOrEmpty(values[6]) ? "Not defined yet" : values[6],
                        };
                        DbContext.Genes.AddOrUpdate(g => g.EnsembleGeneId, gene);
                    }
                }
            }
            await DbContext.SaveChangesAsync();

            //}
            //catch (DbEntityValidationException dbEx)
            //{
            //    foreach (var validationErrors in dbEx.EntityValidationErrors)
            //    {
            //        foreach (var validationError in validationErrors.ValidationErrors)
            //        {
            //            Trace.TraceInformation("Property: {0} Error: {1}",
            //                validationError.PropertyName,
            //                validationError.ErrorMessage);
            //        }
            //    }
            //}
        }
Beispiel #23
0
        public void TryMutationTest()
        {
            Gene gene = new Gene(0x00);

            // 3%あるので300回も繰り返せば大抵当たるだろうというテストに似たなにか。
            for (int i = 0; i <= 300; i++)
            {
                gene.TryMutation();
            }

            Assert.AreNotEqual(gene.Sequence, 0x00);
        }
        public void ctor_Value_ShouldNotThrowWhenValueAlleleRangeUpperBoundary()
        {
            var sut = new Gene
            {
                Allele = { ValueRange = new AlleleValueRange(3, 5) },
                Value  = 5
            };
            var minimumValue = sut.Allele.ValueRange.MinValue;
            var maximumValue = sut.Allele.ValueRange.MaxValue;

            sut.Value.Should().BeInRange(minimumValue, maximumValue);
        }
Beispiel #25
0
 /*Метод проверки на вхождение точки центра окружности в область прямоугольника*/
 private static bool checkOfCoverageOfRoom(Gene gene, List <RectangleRoom> rooms)
 {
     foreach (RectangleRoom room in rooms)
     {
         if (gene.OX > room.X1 && gene.OX < room.X2 && gene.OY > room.Y1 && gene.OY < room.Y4)
         {
             rooms.Remove(room);
             return(true);
         }
     }
     return(false);
 }
Beispiel #26
0
        /// <summary>
        /// Make sure that gene is just replaced only if replaced one does not contain the same gene
        /// Ex: R(1,2,3) will ignore 3 and accept 4
        /// </summary>
        /// <param name="replacedOne"></param>
        /// <param name="index"></param>
        /// <param name="gene"></param>
        /// <returns></returns>
        private bool SafeReplace(IChromosome replacedOne, int index, Gene gene)
        {
            bool hasAlreadyExist = replacedOne.GetGenes().Any(x => (x.Value as EmpScore).EmpId == (gene.Value as EmpScore).EmpId);

            if (!hasAlreadyExist)
            {
                replacedOne.ReplaceGene(index, gene);
                return(true);
            }

            return(false);
        }
Beispiel #27
0
    private Gene CreateSpecimen()
    {
        Gene gene = new Gene();

        gene.strength  = rng.Next(1, 10);
        gene.vitality  = rng.Next(1, 10);
        gene.dexterity = rng.Next(1, 10);
        gene.awareness = rng.Next(1, 10);
        gene.courage   = rng.Next(7, 15);

        return(gene);
    }
        private Gene GetGeneNotInMappingSection(Gene candidateGene, Gene[] mappingSection, Gene[] otherParentMappingSection)
        {
            var indexOnMappingSection = mappingSection
                .Select ((item, index) => new  { Gene = item, Index = index })
                .FirstOrDefault (g => g.Gene.Equals (candidateGene));

            if (indexOnMappingSection != null) {
                return GetGeneNotInMappingSection(otherParentMappingSection [indexOnMappingSection.Index], mappingSection, otherParentMappingSection);
            }

            return candidateGene;
        }
Beispiel #29
0
 void MutateGene(Gene gene)
 {
     for (int i = 0; i < geneSize; i++)
     {
         var rnd = Random.Range(0, 100);
         if (rnd <= MUTATION_CHANCE)
         {
             Debug.Log("Mutated");
             gene.values[i] = Random.Range(-1f, 1f);
         }
     }
 }
    private static Chromosome Modification(Chromosome chromosome)
    {
        String tracker = "";

        Gene[] newGenes = new Gene[chromosome.Genes.Length];

        for (int i = 0; i < newGenes.Length; i++)
        {
            newGenes[i] = new Gene(chromosome.Genes[i]);
        }

        int        pos          = r.Next(newGenes.Length);
        Gene       gene         = newGenes[pos];
        int        startingCell = gene.StartingCell;
        Vector3    relPos       = gene.RelativePosition;
        GameObject type         = gene.Type;
        int        number       = gene.Number;

        double     rVal        = r.NextDouble();
        List <int> cellNumbers = GetCellsNumbers(chromosome.Genes);

        if (rVal < 0.25)
        {
            startingCell = GetRandomStartingCell(cellNumbers);
            tracker      = "M1";
        }
        else
        {
            if (rVal < 0.5)
            {
                relPos  = GetRandomRelativePosition();
                tracker = "M2";
            }
            else
            {
                if (rVal < 0.75)
                {
                    type    = GetRandomCellType();
                    tracker = "M3";
                }
                else
                {
                    number  = GetRandomCellNumber(cellNumbers);
                    tracker = "M4";
                }
            }
        }

        newGenes[pos] = new Gene(startingCell, relPos, type, number);

        return(new Chromosome(newGenes, chromosome.neuralChromosome, chromosome.MutationTracker + tracker, chromosome.Parameters));
    }
    public static void Head(List <Gene> appearance, int[,] pixel, int w, int h, int x, int y)
    {
        for (int i = x; i < x + w; i++)
        {
            for (int j = y - h; j < y; j++)
            {
                pixel[i, j] = (int)coloration.PRIMARY;
            }
            if (Gene.GetGene(appearance, "Head Type").value == 1 || Gene.GetGene(appearance, "Head Type").value == 2)
            {
                pixel[i, y - h] = (int)coloration.SECONDARY;
            }
            else if (Gene.GetGene(appearance, "Head Type").value == 3 && i % 2 == 0)
            {
                pixel[i, y - h] = (int)coloration.SECONDARY;
            }
            else if (Gene.GetGene(appearance, "Head Type").value == 5 && i != x + w - 1)
            {
                pixel[i, y - h] = (int)coloration.BLACK;
            }
        }

        if (Gene.GetGene(appearance, "Head Type").value == 2)
        {
            pixel[x, y - 1] = (int)coloration.SECONDARY;
        }
        pixel[x, y - 2] = (int)coloration.WHITE;
        pixel[x, y - 3] = (int)coloration.BLACK;
        if (Gene.GetGene(appearance, "Head Type").value == 4)
        {
            pixel[x, y - 4] = (int)coloration.SECONDARY;
        }
        if (Gene.GetGene(appearance, "Head Type").value == 6)
        {
            pixel[x, y - h] = (int)coloration.WHITE;
        }

        if (Gene.GetGene(appearance, "Head Type").value == 2)
        {
            pixel[x + w - 2, y - 1] = (int)coloration.SECONDARY;
        }
        pixel[x + w - 2, y - 2] = (int)coloration.WHITE;
        pixel[x + w - 2, y - 3] = (int)coloration.BLACK;
        if (Gene.GetGene(appearance, "Head Type").value == 4)
        {
            pixel[x + w - 2, y - 4] = (int)coloration.SECONDARY;
        }
        if (Gene.GetGene(appearance, "Head Type").value == 6)
        {
            pixel[x + w - 2, y - h] = (int)coloration.WHITE;
        }
    }
    public static IEnumerator SolveCannon()
    {
        pop = new Population(10, 5);

        yield return(CalcFitness());

        while (pop.generation < pop.genLimit)
        {
            foreach (Gene g in pop.individuals)
            {
                Debug.Log("p " + g.power + " a " + g.angle + " f " + g.fitness);
            }

            Gene g1 = pop.individuals[0];
            Gene g2 = pop.individuals[1];

            if (pop.individuals[0].fitness < 9)
            {
                Gene g = pop.individuals[0];
                CannonMaster.CurrentCannon.SetAim(g.angle, g.power);
                Debug.Log("Winner " + g.power + " " + g.angle);
                break;
            }

            System.Random r = new System.Random((int)Time.time);
            if (r.Next(1, 101) <= pop.crossbreed)
            {
                Gene.Crossbreed(ref g1, ref g2);
                pop.individuals.RemoveAt(pop.individuals.Count - 1);
                pop.individuals.RemoveAt(pop.individuals.Count - 1);
                pop.individuals.Add(g1);
                pop.individuals.Add(g2);
            }

            foreach (Gene g in pop.individuals)
            {
                System.Random rand = new System.Random((int)Time.time);
                if (rand.Next(1, 101) <= pop.mutate)
                {
                    Gene.Mutate(g, r.Next(70, 101), true);
                }
                if (r.Next(1, 101) <= pop.mutate)
                {
                    Gene.Mutate(g, r.Next(40, 91), false);
                }
            }

            pop.generation++;
            Debug.Log(pop.generation);
            yield return(CalcFitness());
        }
    }
        protected override IList <IGenome> PerformCross(IList <IGenome> parents)
        {
            var genesLen = parents[0].Genes.Length;

            var rnd    = GARandomManager.Random;
            var index1 = rnd.Next(0, genesLen);
            var len    = rnd.Next(1, genesLen - index1);

            var targetParent = rnd.NextDouble() > 0.5d ? parents[0] : parents[1];
            var otherParent  = parents[0] == targetParent ? parents[1] : parents[0];

            var selectedGenes = targetParent.Genes
                                .Skip(index1)
                                .Take(len)
                                .ToArray();

            foreach (var gene in selectedGenes)
            {
                indexes.Add((gene.Value as ClonableIndex).index);
            }

            var offspringGenes = new Gene[genesLen];
            var j = 0;

            for (var i = 0; i < genesLen; i++)
            {
                Gene resultingGene;

                if (i >= index1 && i <= index1 + len - 1)
                {
                    resultingGene = targetParent.Genes[i];
                }
                else
                {
                    while (ContainsGene(selectedGenes, otherParent.Genes[j]))
                    {
                        j++;
                    }
                    resultingGene = otherParent.Genes[j];
                    j++;
                }

                offspringGenes[i] = new Gene(resultingGene);
            }

            return(new IGenome[]
            {
                new GenomeBase {
                    Genes = offspringGenes
                }
            });
        }
Beispiel #34
0
    public static string GenerateName(List <Gene> composition)
    {
        string[] syllable = { "ra", "ja", "za", "kar", "ro",  "ma", "dy",  "mar", "lex", "lo",
                              "be", "mi", "su", "lu",  "sau", "pi", "rex", "zor", "bla", "dur" };
        string   name = "";

        for (int i = 0; i < Gene.GetGene(composition, "Syllable Number").value; i++)
        {
            name += syllable[Gene.GetGene(composition, "Syllable " + i).value];
        }

        return(char.ToUpper(name[0]) + name.Substring(1));;
    }
    public static Chromosome GetRandom(int chromoLenght, int genesLenght)
    {
        Chromosome chromosome = new Chromosome
        {
            Genes = new List <Gene>()
        };

        for (int index = 0; index < chromoLenght; index++)
        {
            chromosome.Genes.Add(Gene.GetRandom(genesLenght));
        }
        return(chromosome);
    }
Beispiel #36
0
 private Gene[] CrossGenes(Gene[] parentGenes1, Gene[] parentGenes2, int crossPoint)
 {
     Gene[] newGenes = new Gene[StaticUtils.GenomeLength];
     for (int i = 0; i < crossPoint; i++)
     {
         newGenes[i] = parentGenes1[i];
     }
     for (int i = crossPoint; i < newGenes.Length; i++)
     {
         newGenes[i] = parentGenes2[i];
     }
     return(newGenes);
 }
Beispiel #37
0
 /// <summary>
 /// 根据id查询基因字典
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 public Gene Get(string id)
 {
     using (EFGeneRepository repository = new EFGeneRepository())
     {
         GN_GENE entity = repository.Get(id);
         if (entity == null)
         {
             throw new KeyNotFoundException();
         }
         Gene model = EntityToModel(entity);
         return(model);
     }
 }
        private Gene GetGeneNotInMappingSection(Gene candidateGene, Gene[] mappingSection, Gene[] otherParentMappingSection)
        {
            var indexOnMappingSection = mappingSection
                                        .Select((item, index) => new { Gene = item, Index = index })
                                        .FirstOrDefault(g => g.Gene.Equals(candidateGene));

            if (indexOnMappingSection != null)
            {
                return(GetGeneNotInMappingSection(otherParentMappingSection[indexOnMappingSection.Index], mappingSection, otherParentMappingSection));
            }

            return(candidateGene);
        }
Beispiel #39
0
        private IEnumerable <int> GetIncludedItems(Gene gene)
        {
            List <int> indices = new List <int>();

            for (int i = 0; i < gene.Bits.Count; i++)
            {
                if (gene.Bits[i] == 1)
                {
                    indices.Add(i);
                }
            }
            return(indices);
        }
Beispiel #40
0
    public static Gene readGene(string path)
    {
        Gene gene = new Gene(1, new Random());

        if (File.Exists(path))
        {
            Stream          stream       = File.OpenRead(path);
            BinaryFormatter deserializer = new BinaryFormatter();
            gene = (Gene)deserializer.Deserialize(stream);
            stream.Close();
        }
        return(gene);
    }
Beispiel #41
0
        public void AddGene(Gene gene)
        {
            var genesAffected = new EvolutionHistoryBuilder();

            genesAffected.Append(gene);
            string[] rollbackSql = gene.GenerateRollbackSql(genesAffected, this);
            var      mementos    = genesAffected.EvolutionHistory.GetMementos().ToList();

            string[] deleteStatements = GenerateDeleteStatements(_databaseName, mementos);
            _sql   = _sql.InsertRange(0, deleteStatements);
            _sql   = _sql.InsertRange(0, rollbackSql);
            _ahead = _ahead.Subtract(genesAffected.EvolutionHistory);
        }
Beispiel #42
0
    public bool requestMate(GameObject partner)
    {
        canReproduce = GetComponent <Agent>().canMate;
        float desire = partner.GetComponent <Agent>().desireable;

        if (Random.Range(0.0f, 100.0f) < desire && canReproduce && matingPartner == null)
        {
            this.matingPartner = partner;
            partnersGene       = matingPartner.GetComponent <Agent>().GetGene();
            return(true);
        }
        return(false);
    }
        internal void setGenes(Gene[] genes)
        {
            this.genes = new BitGene[genes.Length];

            for (int n = 0; n < genes.Length; n++)
            {
                Gene gene = genes[n];

                if (!(gene is BitGene)) throw new WrongGeneTypeException("BitGeneStrings only accept BitGenes");

                this.genes[n] = (BitGene)(gene.copy());
            }
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Crossing Aa and Aa");
            Gene<char> AA = new Gene<char>("Example", 'A', 1, 'A', 1);
            Gene<char> Aa = new Gene<char>("Example", 'A', 1, 'a', 0);
            Gene<char> aa = new Gene<char>("Example", 'a', 0, 'a', 0);

            Blob Mom = new Blob(Aa);
            Blob Dad = new Blob(Aa);

            for (int i = 0; i < 20; i++)
            {
              Blob child = Punnett.cross(Mom, Dad);
              Console.WriteLine(child.getGene<char>("Example").alleleA.value.ToString() + child.getGene<char>("Example").alleleB.value.ToString());
            }

            Console.ReadLine();
        }
Beispiel #45
0
    public static Gene cross(Gene g1, Gene g2)
    {
        if (g1.type != g2.type)
            {
                Debug.Log("Genes don't match up!");
                return null; //Error: Names don't match
            }

            //TODO: When you make a game controller, put it there so we get real, reliable results
            //random

            int randomNumber = random.Next(1, 5);
            Gene offspring;

            if (randomNumber == 1)
                    if (g1.firstDominance >= g2.firstDominance)
                            offspring = new Gene(g1.type, g1.firstAllele, g1.firstDominance, g2.firstAllele, g2.firstDominance);
                    else
                            offspring = new Gene(g1.type, g2.firstAllele, g2.firstDominance, g1.firstAllele, g1.firstDominance);

            else if (randomNumber == 2)
                    if (g1.firstDominance >= g2.secondDominance)
                            offspring = new Gene(g1.type, g1.firstAllele, g1.firstDominance, g2.secondAllele, g2.secondDominance);
                    else
                            offspring = new Gene(g1.type, g2.secondAllele, g2.secondDominance, g1.firstAllele, g1.firstDominance);

            else if (randomNumber == 3)
                    if (g1.secondDominance >= g2.firstDominance)
                            offspring = new Gene(g1.type, g1.secondAllele, g1.secondDominance, g2.firstAllele, g2.firstDominance);
                    else
                            offspring = new Gene(g1.type, g2.firstAllele, g2.firstDominance, g1.secondAllele, g1.secondDominance);

            else
                    if (g1.secondDominance >= g2.secondDominance)
                            offspring = new Gene(g1.type, g1.secondAllele, g1.secondDominance, g2.secondAllele, g2.secondDominance);
                    else
                            offspring = new Gene(g1.type, g2.secondAllele, g2.secondDominance, g1.secondAllele, g1.secondDominance);

            return offspring;
    }
Beispiel #46
0
 public void Equals_OtherNotGene_False()
 {
     var target = new Gene(1);
     var other = 1;
     Assert.IsFalse(target.Equals(other));
 }
        private int GetEquationResult(Gene[] genes)
        {
            var variableValues = new Dictionary<string, double>();

            for (int i = 0; i < m_variables.Count; i++)
            {
                variableValues.Add(m_variables[i], (int)genes[i].Value);
            }

            var engine = new CalculationEngine();
            var result = engine.Calculate(m_equationLeftPart, variableValues);

            return (int)result;
        }
Beispiel #48
0
        /// <summary>
        /// Copies the cycle index pair.
        /// </summary>
        /// <param name="cycle">The cycle.</param>
        /// <param name="fromParent1Genes">From parent1 genes.</param>
        /// <param name="toOffspring1">To offspring1.</param>
        /// <param name="fromParent2Genes">From parent2 genes.</param>
        /// <param name="toOffspring2">To offspring2.</param>
        private static void CopyCycleIndexPair(IList<int> cycle, Gene[] fromParent1Genes, IChromosome toOffspring1, Gene[] fromParent2Genes, IChromosome toOffspring2)
        {
            int geneCycleIndex = 0;

            for (int j = 0; j < cycle.Count; j++)
            {
                geneCycleIndex = cycle[j];
                toOffspring1.ReplaceGene(geneCycleIndex, fromParent1Genes[geneCycleIndex]);
                toOffspring2.ReplaceGene(geneCycleIndex, fromParent2Genes[geneCycleIndex]);
            }
        }
        /// <summary>
        /// Replaces the gene in the specified index.
        /// </summary>
        /// <param name="index">The gene index to replace.</param>
        /// <param name="gene">The new gene.</param>
        /// <exception cref="System.ArgumentOutOfRangeException">index;There is no Gene on index {0} to be replaced..With(index)</exception>
        public void ReplaceGene(int index, Gene gene)
        {
            if (index < 0 || index >= m_length)
            {
                throw new ArgumentOutOfRangeException("index", "There is no Gene on index {0} to be replaced.".With(index));
            }

            m_genes[index] = gene;
            Fitness = null;
        }
Beispiel #50
0
 public void Equals_OtherValue_False()
 {
     var target = new Gene(1);
     var other = new Gene(2);
     Assert.IsFalse(target.Equals(other));
 }
Beispiel #51
0
 public void Equals_OtherAsObjectOtherValue_False()
 {
     var target = new Gene(1);
     var other = new Gene(2); ;
     Assert.IsFalse(target.Equals(other as object));
 }
 public BitGeneString(Gene[] genes)
 {
     setGenes(genes);
 }
Beispiel #53
0
 public void Equals_OtherAsObjectSameValue_True()
 {
     var target = new Gene(1);
     var other = new Gene(1); ;
     Assert.IsTrue(target.Equals(other as object));
 }
Beispiel #54
0
 public void GetHashCode_NoValue_Zero()
 {
     var target = new Gene();
     Assert.AreEqual(0, target.GetHashCode());
 }
Beispiel #55
0
 public void Equals_SameValue_True()
 {
     var target = new Gene(1);
     var other = new Gene(1);
     Assert.IsTrue(target.Equals(other));
 }
Beispiel #56
0
 public void OperatorEquals_DiffValue_False()
 {
     var target = new Gene(1);
     var other = new Gene(2);
     Assert.IsFalse(target == other);
 }
Beispiel #57
0
 public void OperatorEquals_SameValue_True()
 {
     var target = new Gene(1);
     var other = new Gene(1);
     Assert.IsTrue(target == other);
 }
        /// <summary>
        /// Replaces the genes starting in the specified index.
        /// </summary>
        /// <param name="startIndex">Start index.</param>
        /// <param name="genes">The genes.</param>
        /// <remarks>
        /// The genes to be replaced can't be greater than the available space between the start index and the end of the chromosome.
        /// </remarks>
        public void ReplaceGenes(int startIndex, Gene[] genes)
        {
            ExceptionHelper.ThrowIfNull("genes", genes);

            if (genes.Length > 0)
            {
                if (startIndex < 0 || startIndex >= m_length)
                {
                    throw new ArgumentOutOfRangeException("index", "There is no Gene on index {0} to be replaced.".With(startIndex));
                }

                var genesToBeReplacedLength = genes.Length;

                var availableSpaceLength = m_length - startIndex;

                if (genesToBeReplacedLength > availableSpaceLength)
                {
                    throw new ArgumentException(
                        "genes", "The number of genes to be replaced is greater than available space, there is {0} genes between the index {1} and the end of chromosome, but there is {2} genes to be replaced.".With(availableSpaceLength, startIndex, genesToBeReplacedLength));
                }

                Array.Copy(genes, 0, m_genes, startIndex, genes.Length);

                Fitness = null;
            }
        }
Beispiel #59
0
 public void OperatorDiff_Diff_True()
 {
     var target = new Gene(1);
     var other = new Gene(2);
     Assert.IsTrue(target != other);
 }
Beispiel #60
0
        /// <summary>
        /// Creates the cycle recursively.
        /// </summary>
        /// <param name="parent1Genes">The parent one's genes.</param>
        /// <param name="parent2Genes">The parent two's genes.</param>
        /// <param name="geneIndex">The current gene index.</param>
        /// <param name="cycle">The cycle.</param>
        private void CreateCycle(Gene[] parent1Genes, Gene[] parent2Genes, int geneIndex, List<int> cycle)
        {
            if(!cycle.Contains(geneIndex))
            {
                var parent2Gene = parent2Genes[geneIndex];
                cycle.Add(geneIndex);
                var newGeneIndex = parent1Genes.Select((g, i) => new { Value = g.Value, Index = i }).First(g => g.Value.Equals(parent2Gene.Value));

                if (geneIndex != newGeneIndex.Index)
                {
                    CreateCycle(parent1Genes, parent2Genes, newGeneIndex.Index, cycle);
                }
            }
        }