// Breeding funtion that mixes the genes values ( experimental, doesn't represent nature ) public void Mix( DNA dna1, DNA dna2 ) { for( int i = 0; i < m_Genes.Length; i++ ) { m_Genes[ i ] = ( dna1.m_Genes[ i ] + dna2.m_Genes[ i ] ) / 2; } }
public static List<IAmAGene> Interprit(DNA dna) { var genes = new List<IAmAGene>(); for (int i = 0; i < dna.Data.Length; i++) { var marker = dna.Data[i]; var maker = GeneMakers.FirstOrDefault(m => m.MarkerFrom <= marker && m.MarkerTo >= marker); if (maker == null) continue; if (dna.Size >= i + maker.Size) { var gene = maker.Make(dna.GetFragment(i, maker)); if (Game1.Debug == null) Debug.WriteLine(String.Format("[{0}]", gene.GetType().Name)); genes.Add(gene); i += maker.ArgumentBytes; } } return genes; }
static void Main(string[] args) { DNA firstStep = new DNA(); spark = firstStep.Strand; bool t = false; int iteration = 0; ConsoleKeyInfo end = new ConsoleKeyInfo(); Console.WriteLine("AI solver will attempt equations after GA designs them"); NaturalSelection ns = new NaturalSelection(); IntellegentDesign id = new IntellegentDesign(); id.initialize(); ns.darwin(spark); do { if (t==false) { t = true; Root(ns,id); } ns.darwin(id.dueronomy(ns.vA)); Root(ns, id); if (iteration>100||novelAns>=cap) { end = Console.ReadKey(); iteration = 0; novelAns = 0; } iteration++; } while (end.Key != ConsoleKey.Escape); }
public void Train() { evaluator.Evaluate(population); population.Sort (); best = population[0]; this.G******g(); foreach(DNA dna in population) dna.Mutate (.10f); }
// Breeding funtion that selects a random parent to give each gene public void RandomSplice( DNA dna1, DNA dna2 ) { for( int i = 0; i < m_Genes.Length; i++ ) { if( Random.Range( 0f, 1f ) > .5f ) m_Genes[ i ] = dna1.m_Genes[ i ]; else m_Genes[ i ] = dna2.m_Genes[ i ]; } }
// Find other trees near this one, pick one at random (that should change) // and create offspring with shared DNA and possibly mutated genes. // Offspring is placed on map public override float reproduce(){ Debug.Log ("Reproducing"); List<GameObject> options = base.getNearby("Tree"); Trees offspring; float randomX, randomZ; int random; DNA offspringDNA = new DNA(numGenes); DNA chosen = new DNA(numGenes); Debug.Log ("choosing mate from " + options.Count + " options "); // Create new DNA string for offspring, mutations happen here if (options.Count > 1) { random = Random.Range(1, options.Count); chosen = options[random].GetComponent<Trees>().DNA; offspringDNA = DNA.fertilize(chosen); } else { offspringDNA = DNA; } // Run the mutations on these genes, probability of occuring is built in // so there's not a 100% chance that these will happen offspringDNA.missenseMutate(); offspringDNA.frameShiftInsert(); // Create new tree gameObject and place it on terrain without colliding // with other trees offspring = Instantiate(base.offspringPrefab) as Trees; offspring.transform.parent = gameObject.transform.parent; offspring.DNA = offspringDNA; randomX = Random.Range (-reproductiveRange, reproductiveRange); randomZ = Random.Range (-reproductiveRange, reproductiveRange); // Ensure the tree doesn't spawn inside of another's collder, allow 5 attempts // at finding a spot without another tree already there, destroy if it does Vector3 boxDimensions = new Vector3(5, 2, 5); //! warning magic numbers Vector3 spawnPosition = new Vector3(randomX, Terrain.activeTerrain.SampleHeight(new Vector3(randomX, 0, randomZ)), randomZ); int attempts = 0; while( Physics.OverlapBox(spawnPosition, boxDimensions).Length > 1 && attempts < 5) { randomX = Random.Range (-reproductiveRange, reproductiveRange); randomZ = Random.Range (-reproductiveRange, reproductiveRange); spawnPosition.x = randomX; spawnPosition.z = randomZ; attempts++; } if (attempts == 5) Destroy(offspring); else offspring.transform.position = new Vector3(this.transform.position.x + randomX, this.transform.position.y, this.transform.position.z + randomZ); return 10; }
internal static LogicalNetworEntity Create( IEnumerable<LogicalNetworkGene> dominantGeneSequence, GateTypeEvolutionMethod evolutionMethod, TruthTable truthTableToSolve, LogicGateTypes gateTypeRestrictions) { Contract.Requires(dominantGeneSequence != null); Contract.Requires(truthTableToSolve != null); Contract.Requires(gateTypeRestrictions != null); var dna = new DNA<LogicalNetworkGene>(dominantGeneSequence.ToList()); return Create(dna, dna.Genes[0], evolutionMethod, truthTableToSolve, gateTypeRestrictions); }
//creates new DNA sequence from two (this & DNA Breed(DNA Lover) { List<float> ChildGenomes = new List<float>(); // this splites the dna in half, i probaly want to do something better then this int crossover = Mathf.RoundToInt(Random.Range(1, maxDNA)); for (int i = 0; i < maxDNA; i++) { if (i > crossover) { ChildGenomes.Add(GetGene(i)); } else ChildGenomes.Add(Lover.GetGene(i)); } DNA newdna = new DNA(ChildGenomes); return newdna; }
/// <summary> /// Crossover Predicate. /// </summary> /// <param name="index"> /// The point in which crossover is made. /// </param> /// <param name="parent1"></param> /// <param name="parent2"></param> /// <returns></returns> public static DNACrossover crossover(int index, DNA parent1, DNA parent2) { DNACrossover cross = new DNACrossover(); var split1 = split(index, parent1); var split2 = split(index, parent2); cross.child1 = join(split1.front, split2.back); cross.child2 = join(split2.front, split1.back); if (cross.child1 == null || cross.child2 == null) return null; return cross; }
//Searches through DNASequence array to see if C- is in the sequence //Returns 1 if C- if found and 0 if not //Uses binary search recursively to find C- //Takes in DNASequence, 0 as the lowestIndex, the highest index minus one as the largestIndex, and C- as the value to find static int BinarySearch(DNA[] DNASequence, int lowestIndex, int largestIndex, DNA findValue) { //Gets the middle index value int middleIndex = (lowestIndex + largestIndex) / 2; //The array is empty and value to find is not in the sequence and returns 0 if (lowestIndex > largestIndex) { return 0; } //The value to find is in the first half of the array to search //Middle element is larger than C else if (DNASequence[middleIndex].CompareTo(findValue) < 0 ) { //Call BinarySearch and searches through only the first half return BinarySearch(DNASequence, 0, middleIndex - 1, findValue); } //The value to find is in the second half of the array to search //Middle element is smaller than C else if (DNASequence[middleIndex].CompareTo(findValue) > 0 ) { //Call BinarySearch and searches through only the second half return BinarySearch(DNASequence, middleIndex + 1, largestIndex, findValue); } //The value to find is in the first half of the array to search //Middle element has a C base but a + charge else if (DNASequence[middleIndex].CompareTo(findValue) == 0 && DNASequence[middleIndex].CompareChargeTo(findValue) < 0) { //Call BinarySearch and searches through only the second half in case there is a C with a - charge return BinarySearch(DNASequence, middleIndex + 1, largestIndex, findValue); } //The value you to find is the middle element else if (DNASequence[middleIndex].CompareTo(findValue) == 0 && DNASequence[middleIndex].CompareChargeTo(findValue) == 0) { //C- is in the DNA sequence return 1; } //C- is not found and returns 0 else { return 0; } }
/// <summary> /// Navigate to the view for the specified menu option /// </summary> public void NavigateTo(DNA.XForms.Sample.ViewModels.MenuItem option) { if (previousItem != null) previousItem.Selected = false; option.Selected = true; previousItem = option; var displayPage = PageForOption(option); Device.OnPlatform (WinPhone: () => Detail = new ContentPage ()); //work around to clear current page. Detail = new NavigationPage(displayPage) { BarBackgroundColor = ColorHelper.ToolbarBackground, BarTextColor = Color.White, }; IsPresented = false; }
internal static LogicalNetworEntity Create( DNA<LogicalNetworkGene> dna, IEnumerable<LogicalNetworkGene> dominantGeneSequence, GateTypeEvolutionMethod evolutionMethod, TruthTable truthTableToSolve, LogicGateTypes gateTypeRestrictions) { Contract.Requires(dna != null); Contract.Requires(dominantGeneSequence != null); Contract.Requires(truthTableToSolve != null); Contract.Requires(gateTypeRestrictions != null); LogicalNetworkFactory factory; if (evolutionMethod == GateTypeEvolutionMethod.Restrict) { factory = new LogicalNetworkFactory(truthTableToSolve.InputInterfaceLength, truthTableToSolve.OutputInterfaceLength, gateTypeRestrictions); } else // Evolve { factory = new LogicalNetworkFactory(truthTableToSolve.InputInterfaceLength, truthTableToSolve.OutputInterfaceLength); } var network = LogicalNetworkDNADecoder.CreateNetwork(factory, dominantGeneSequence); int numOfNAGates = 0; if (evolutionMethod == GateTypeEvolutionMethod.Evolve && gateTypeRestrictions != null) { foreach (var entry in network.EntryArray) { var gate = entry.NodeEntry.Node as LogicGate; if (gate != null) { var type = new LogicGateType(gate.Operation, entry.UpperConnectionEntryArray.Length); if (!gateTypeRestrictions.Contains(type)) numOfNAGates++; } } } int errors = new TruthTableComputation(network).ComputeError(truthTableToSolve); return new LogicalNetworEntity(dna, network, errors, numOfNAGates); }
// Initialization public void Start () { myTerrain = Terrain.activeTerrain; if ( !isOnTerrain () ){ Destroy(this.gameObject); } numGenes = 5; DNA = new DNA(numGenes); setYTransform (); // Place the organic on the map so it's pretty setGameObjectName (); // Rename the organic so it's easy to identify setNutrition (); // Get the organic's initial nutrition setNutritionFactor (5); // set the initial scale setScale (); timeUntilReproduce = 20; age = 0; DNA.missenseChance = 2; DNA.shiftInsertChance = 1; nextAge = 1; }
public DNA fertilize(DNA parentB){ DNA parentA = this; DNA offspring = new DNA(numGenes); string newSection = ""; for(int i = 0; i < numGenes-1; i++){ // pick each gene from one parent // this should be faster than the commented code int geneA = (int)Random.Range(1,2); int geneB = (int)Random.Range(1,2); if( geneA == 1 ) newSection += parentA.chromos[i][0]; else newSection += parentB.chromos[i][0]; if( geneB == 1 ) newSection += parentA.chromos[i][1]; else newSection += parentB.chromos[i][1]; offspring.chromos[i] = newSection; newSection = ""; } return offspring; }
public void Counts_a_nucleotide_only_once() { var dna = new DNA("GGTTGG"); dna.Count('T'); Assert.That(dna.Count('T'), Is.EqualTo(2)); }
private DNA MutateDNA(DNA dna) { int rnd_mutation = rnd.Next(3); switch (rnd_mutation) { case 0: dna.Mutation_SwapDNA(); break; case 1: dna.Mutation_MoveDNA(); break; case 2: dna.Mutation_ReverseDNARange(); break; } return dna; }
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { bool valid = DNA.ValidLetters((string)value); return(new ValidationResult(valid, "Invalid letters")); }
/// <summary> /// DNA split (crossover operation) /// </summary> /// <param name="split_index"> /// The point in the DNA where the split is made /// </param> /// <param name="parent"> /// The parent to split /// </param> /// <returns> /// DNA split into two partial DNAs /// </returns> public static DNASplit split(int split_index, DNA parent) { if (split_index > parent.Count) return null; DNASplit slices = new DNASplit(); int i; slices.front = new DNAPartial(); slices.back = new DNAPartial(); for (i = 0; i < split_index; i++ ) { slices.front.Add(parent[i]); } for (i = split_index; i < parent.Count; i++) { slices.back.Add(parent[i]); } return slices; }
void Update() { // selection // calculate fitness // float generationBest = 0; population[0] = elite; for (int i = 0; i < population.Length; i++) { population[i].CalculateFitness(); if (population[i].fitness > bestScore) { bestScore = population[i].fitness; elite = population[i]; } print("Best Fitness: " + bestScore); /* * float count = 0; * * for (int j = 0; j < target.GetLength(0); j++) * { * if (population[i].genes[j, 0] == target[j, 0] && population[i].genes[j, 1] == target[j, 1] && population[i].genes[j, 2] == target[j, 2]) * count++; * } * if (count > generationBest) * { * generationBest = count; * elite = population[i]; * } * print("Generation Best: " + generationBest); */ } // build mating pool List <DNA> matingPool = new List <DNA>(); for (int i = 0; i < population.Length; i++) { int n = (int)(population[i].fitness * 10000f); for (int j = 0; j < n; j++) { matingPool.Add(population[i]); } } // reproduction for (int i = 0; i < population.Length; i++) { int a = Random.Range(0, matingPool.Count); int b = Random.Range(0, matingPool.Count); DNA partnerA = matingPool[a]; DNA partnerB = matingPool[b]; // crossover DNA child = partnerA.Crossover(partnerB); //mutation child.Mutate(mutationRate); population[i] = child; } // display /* * for (int i = 0; i < population.Length; i++) * { * * for (int j = 0; j < target.GetLength(0); j++) * { * Vector3 temp = new Vector3(population[i].genes[j, 0] + (30 * i), population[i].genes[j, 1], population[i].genes[j, 2]); * * spheres[i, j].transform.position = temp; * spheres[i, j].GetComponent<Renderer>().material.color = colors[i]; * /* * int count = 0; * for (int k = 0; k < 3; k++) * { * if (population[i].genes[j, k] == target[j, k]) * { * count++; * // spheres[i, j].GetComponent<Renderer>().material.color = new Color(1, 0, 0); * } * else * spheres[i, j].GetComponent<Renderer>().material.color = colors[i]; * } * if (count == 0) * spheres[i, j].GetComponent<Renderer>().material.color = colors[i]; * if (count == 1) * spheres[i, j].GetComponent<Renderer>().material.color = new Color(1, 0, 0); * if (count == 2) * spheres[i, j].GetComponent<Renderer>().material.color = new Color(0.5f, 0.5f, 0); * if (count == 3) * spheres[i, j].GetComponent<Renderer>().material.color = new Color(0, 1, 0); * * } * * }*/ print("Generation: " + generation); if (bestScore > previousBest) { for (int i = 0; i < elite.genes.GetLength(0); i++) { // GameObject newSphere = CreateSphere(new Vector3(elite.genes[i, 0] + offset, elite.genes[i, 1] - 30, elite.genes[i, 2]), 1); for (int j = 0; j < elite.genes.GetLength(0); j++) { Vector3 start = new Vector3(elite.genes[i, 0] + offset, elite.genes[i, 1], elite.genes[i, 2]); Vector3 end = new Vector3(elite.genes[j, 0] + offset, elite.genes[j, 1], elite.genes[j, 2]); if (Mathf.Approximately(Vector3.Distance(start, end), 2)) { CreateCylinderBetweenPoints(start, end, 0.5f); CreateSphere(start, 1); CreateSphere(end, 1); } if (Mathf.Approximately(Vector3.Distance(start, end), 3)) { CreateCylinderBetweenPoints(start, end, 0.5f); CreateSphere(start, 1); CreateSphere(end, 1); } if (Mathf.Approximately(Vector3.Distance(start, end), 5)) { CreateCylinderBetweenPoints(start, end, 0.5f); CreateSphere(start, 1); CreateSphere(end, 1); } if (Mathf.Approximately(Vector3.Distance(start, end), 7)) { CreateCylinderBetweenPoints(start, end, 0.5f); CreateSphere(start, 1); CreateSphere(end, 1); } if (Mathf.Approximately(Vector3.Distance(start, end), 11)) { CreateCylinderBetweenPoints(start, end, 0.5f); CreateSphere(start, 1); CreateSphere(end, 1); } if (Mathf.Approximately(Vector3.Distance(start, end), 13)) { CreateCylinderBetweenPoints(start, end, 0.5f); CreateSphere(start, 1); CreateSphere(end, 1); } if (Mathf.Approximately(Vector3.Distance(start, end), 17)) { CreateCylinderBetweenPoints(start, end, 0.5f); CreateSphere(start, 1); CreateSphere(end, 1); } if (Mathf.Approximately(Vector3.Distance(start, end), 19)) { CreateCylinderBetweenPoints(start, end, 0.5f); CreateSphere(start, 1); CreateSphere(end, 1); } if (Mathf.Approximately(Vector3.Distance(start, end), 23)) { CreateCylinderBetweenPoints(start, end, 0.5f); CreateSphere(start, 1); CreateSphere(end, 1); } if (Mathf.Approximately(Vector3.Distance(start, end), 29)) { CreateCylinderBetweenPoints(start, end, 0.5f); CreateSphere(start, 1); CreateSphere(end, 1); } if (Mathf.Approximately(Vector3.Distance(start, end), 31)) { CreateCylinderBetweenPoints(start, end, 0.5f); CreateSphere(start, 1); CreateSphere(end, 1); } } } offset += 50; } previousBest = bestScore; generation++; }
public void Validates_nucleotides() { var dna = new DNA("GGTTGG"); Assert.Throws<InvalidNucleotideException>(() => dna.Count('X')); }
public void Has_no_uracil() { var dna = new DNA("GGTTGG"); Assert.That(dna.Count('U'), Is.EqualTo(0)); }
// 適応度比較 private void CompareDNA(DNA <T> a, DNA <T> b) { }
public SchwereKI(int ID) : base(ID) { dna = Genome.GetDNA(); }
//new main loop, iterates over n epochs having each population member play eachother static void NewMainLoop() { t.Interval = 1000; Console.WriteLine("Beginning Training"); Console.WriteLine("Current Generation: " + CurrentGeneration); Console.WriteLine("Quick Iteration Count: " + QuickIterationCount); Console.WriteLine("Slow Iteration Count: " + SlowIterationCount); Console.WriteLine("Starting Fast Iteration"); while (CurrentGeneration < QuickIterationCount) { time = 0; t.Start(); t.Elapsed += T_Elapsed; Console.WriteLine("Weights"); foreach (DNA dna in Population) { Console.WriteLine(dna.PrintInfo()); } List <DNA> localPopulation = new List <DNA>(Population); Population.Clear(); while (localPopulation.Count > 0) { DNA selection = localPopulation[0]; if (selection.GamesPlayed >= PopulationSize - 1) { localPopulation.Remove(selection); Population.Add(selection); continue; } localPopulation.Remove(selection); foreach (DNA k in localPopulation) { DNA opponent = k; QuickPlay(ref selection, ref opponent); } Population.Add(selection); SaveProgress(localPopulation); } Console.WriteLine("Beginning Selection"); NewSelection(); Console.WriteLine("Beginning Mutation"); NewMutate(); Console.WriteLine("Saving"); Save(CurrentGeneration); t.Stop(); int hours = (int)Math.Floor(Convert.ToDecimal(time / 3600)); if (time < 3600) { hours = 0; } int minutes = (int)Math.Floor(Convert.ToDecimal((time - (hours * 3600)) / 60)); if (time < 60) { minutes = 0; } int seconds = (time - (hours * 3600)) - (minutes * 60); Console.WriteLine("Quick Iteration Time: " + hours.ToString("D2") + ":" + minutes.ToString("D2") + ":" + seconds.ToString("D2")); CurrentGeneration++; } Console.WriteLine("Starting Slow Iteration"); for (int i = 0; i < SlowIterationCount; i++) { time = 0; t.Start(); foreach (DNA dna in Population) { Console.WriteLine(dna.PrintInfo()); } List <DNA> localPopulation = new List <DNA>(Population); Population.Clear(); while (localPopulation.Count > 0) { DNA selection = localPopulation[0]; localPopulation.Remove(selection); foreach (DNA k in localPopulation) { DNA opponent = k; Player p1 = new Player("Player 1", ref selection); Player p2 = new Player("Player 2", ref opponent); Play(ref p1, ref p2); } Population.Add(selection); } Console.WriteLine("Beginning Selection"); NewSelection(); Console.WriteLine("Beginning Mutation"); NewMutate(); Console.WriteLine("Saving"); Save(i); t.Stop(); int hours = time % 3600; if (time < 3600) { hours = 0; } int minutes = (time - hours * 3600) % 60; if (time < 60) { minutes = 0; } int seconds = (time - hours * 3600) - minutes * 60; Console.WriteLine("Slow Iteration Time: " + hours + ":" + minutes + ":" + seconds); } }
static void Main(string[] args) { Console.WriteLine("Play Game?"); if (Console.ReadLine().ToLower() == "y") { DNA smartAI = new DNA(); smartAI.BuildPredefinedAI(1); smartAI.Wins = 0; smartAI.Losses = 0; smartAI.GamesPlayed = 0; DNA randomAI = new DNA(); randomAI.BuildPredefinedAI(2); randomAI.Wins = 0; randomAI.Losses = 0; randomAI.GamesPlayed = 0; Player smartPlayer = new Player("Medium Player", ref smartAI); Player randomPlayer = new Player("Hard Player", ref randomAI); Console.WriteLine("Game Count: "); int gamecount = Convert.ToInt32(Console.ReadLine()); PlayLoop(gamecount, ref smartPlayer, ref randomPlayer, false); Console.Write("Games Played: "); Console.WriteLine(gamecount); Console.WriteLine(smartPlayer.name + " Won: " + smartPlayer.ai.Wins + " Games"); Console.WriteLine(randomPlayer.name + " Won: " + randomPlayer.ai.Wins + " Games"); Console.ReadLine(); return; } Console.WriteLine("Use Default Evolution File?"); if (Console.ReadLine().ToLower() == "n") { Console.WriteLine("Enter Path: "); EvolutionFilePath = Console.ReadLine(); } Console.WriteLine("Use Default Progress File?"); if (Console.ReadLine().ToLower() == "n") { Console.WriteLine("Enter Path: "); ProgressFilePath = Console.ReadLine(); } Console.WriteLine("Load Evolution Progress?"); if (Console.ReadLine().ToLower() == "y") { ReadEvolutionInfo(); } else { Console.WriteLine("Population Size: "); PopulationSize = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Quick Play Iteration Count: "); QuickIterationCount = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Slow Play Iteration Count: "); SlowIterationCount = Convert.ToInt32(Console.ReadLine()); CreateEvolutionFile(); } Console.WriteLine("Load Iteration Progress?"); if (Console.ReadLine().ToLower() == "y") { ReadProgressInfo(); } else { //GeneratePopulation(); NewGeneratePopulation(); } NewMainLoop(); Console.WriteLine("Finished"); Console.ReadLine(); }
public void SetDNA(DNA DNA) { this.DNA = DNA; }
internal void Combine(DNA dna1, DNA dna2) { throw new NotImplementedException(); }
public override void Optimize() { DNA dnaBestEver = null; try { // initialize the parameter definition bool fFirstRun = (_form == null); _rgParameterDefinitions = new ParameterDefinitions(this.Strategy, fFirstRun); if (fFirstRun) { _form = new GeneticOptionsDialog(); } _form.InitializeParameters(_rgParameterDefinitions); DateTime dateStartLast = _dateStartLast; _dateStartLast = Strategy.BackTestFrom; if (!_form.WalkForward || Strategy.BackTestFrom <= dateStartLast) { if (_form.ShowDialog(Form.ActiveForm) != DialogResult.OK) { #if NT7 WaitForIterationsCompleted(true); #endif return; } } #if !NT7 _nPopulationSize = _form.PopulationSize; _cMaxGenerations = _form.MaxGenerations; _mutationRate = _form.MutationRate; _mutationStrength = _form.MutationStrength; _fitnessGain = _form.FitnessGain; _percentAliens = _form.Aliens; _stabilitySize = _form.StabilitySize; _resetSize = _form.ResetSize; _nMinimumPerformce = _form.MinimumPerformance; #endif int cAliens = (int)Math.Ceiling(_nPopulationSize * _percentAliens); int nStabilitySize = (int)Math.Ceiling(_nPopulationSize * _stabilitySize); int nResetSize = _nPopulationSize - (int)Math.Ceiling(_nPopulationSize * _resetSize); DateTime timeStart = DateTime.Now; int cParams = _rgParameterDefinitions.Count; decimal cCombinationsActual = _rgParameterDefinitions.CountCombinations; long cCombinations = (long)Math.Min(cCombinationsActual, (decimal)long.MaxValue); Strategy.Print( string.Format( "{0}: PH Genetic Optimizer Start @ {1}, combinations: {2:N0}", Strategy.Instrument.FullName, timeStart, cCombinationsActual ) ); List <DNA> rgChildren = new List <DNA> (); Dictionary <DNA, bool> setChildren = new Dictionary <DNA, bool> (); // create an initial generation of aliens int cIterations = 0; double stabilityScorePrev = double.NaN; List <DNA> rgParents = new List <DNA> (); int iGeneration; for (iGeneration = 1; iGeneration <= _cMaxGenerations; iGeneration++) { // fill the rest of this generation with aliens while (rgChildren.Count < _nPopulationSize && setChildren.Count < cCombinations) { DNA child = CreateAlien(0); if (setChildren.ContainsKey(child)) { continue; } setChildren.Add(child, true); rgChildren.Add(child); } DNA dnaBestSinceReset = null; try { // score the new generation ScoreGeneration(rgChildren); //if (rgParents.Count > nPopulationSize) // rgParents.RemoveRange (nPopulationSize, rgParents.Count - nPopulationSize); rgParents.AddRange(rgChildren); rgParents.Sort(); dnaBestSinceReset = rgParents [0]; } finally { if (rgParents.Count > 0 && dnaBestSinceReset != null && (dnaBestEver == null || dnaBestEver.Performance < dnaBestSinceReset.Performance)) { dnaBestEver = dnaBestSinceReset; } } double stabilityScore = 0.0; int cStabilityIndividuals = (int)Math.Min(rgParents.Count, nStabilitySize); if (cStabilityIndividuals < 1) { cStabilityIndividuals = 1; } for (int i = 0; i < cStabilityIndividuals; i++) { double scoreParent = rgParents [i].Performance; if (scoreParent > double.NegativeInfinity) { stabilityScore += rgParents [i].Performance; } } cIterations += rgChildren.Count; TimeSpan diff = DateTime.Now - timeStart; double iterPerSec = cIterations / diff.TotalSeconds; Strategy.Print(string.Format( "{0}: gen {1}/{2}, {3:N1} ips, max PERF: {4:N2}, stability PERF: {5:N2}\t{6}", Strategy.Instrument.FullName, iGeneration, _cMaxGenerations, iterPerSec, dnaBestSinceReset.Performance, stabilityScore / cStabilityIndividuals, rgParents.Count == 0 ? "" : _rgParameterDefinitions.ToString(dnaBestSinceReset))); if (dnaBestEver != null) { Strategy.Print(dnaBestEver.Performance + ", " + _nMinimumPerformce); } if (dnaBestEver != null && dnaBestEver.Performance > _nMinimumPerformce) { Strategy.Print(string.Format("{0}: Minimum performance reached.", Strategy.Instrument.FullName)); return; } if (iGeneration == _cMaxGenerations) { break; } if (setChildren.Count >= cCombinations) { break; } if (stabilityScore == stabilityScorePrev) { //rgParents.RemoveRange (1, rgParents.Count - 1); rgParents.Clear(); rgChildren.Clear(); Strategy.Print(string.Format( "{0}: reset", Strategy.Instrument.FullName ) ); //stabilityScore = double.NaN; continue; } // get the range of PERF values double minPerformance = double.MaxValue; double maxPerformance = double.MinValue; for (int i = 0; i < rgParents.Count; i++) { double performance = rgParents [i].Performance; if (performance == double.NegativeInfinity) { continue; } if (minPerformance > performance) { minPerformance = performance; } if (maxPerformance < performance) { maxPerformance = performance; } } // weight the procreation probabilities if (maxPerformance != minPerformance) { for (int i = 0; i < rgParents.Count; i++) { DNA parent = rgParents [i]; double performance = parent.Performance; if (performance == double.NegativeInfinity) { parent.Weight = 0; } else { double weight = (parent.Performance - minPerformance) / (maxPerformance - minPerformance); #if true parent.Weight = Math.Pow(weight, _fitnessGain) + 0.001; #else parent.Weight = (Math.Pow(weight, fitnessGain / (iGeneration - parent.Generation)) + 0.001); #endif } } } double totalWeight = 0; for (int i = 0; i < rgParents.Count; i++) { totalWeight += rgParents [i].Weight; } // initialize a new generation rgChildren.Clear(); // a certain percentage of the new population are aliens: int cAliensThisGeneration; if (stabilityScore == stabilityScorePrev) { cAliensThisGeneration = nResetSize; } else { cAliensThisGeneration = cAliens; } while (rgChildren.Count < cAliensThisGeneration && setChildren.Count < cCombinations) { DNA child = CreateAlien(iGeneration); if (setChildren.ContainsKey(child)) { continue; } setChildren.Add(child, true); rgChildren.Add(child); } // fuzz each param individually for (int iParam = 0; iParam < cParams; iParam++) { int cValues = _rgParameterDefinitions [iParam].CountValues; for (int iFuzz = 0; iFuzz < 5; iFuzz++) { int [] rgParams = new int [cParams]; for (int iParamFuzz = 0; iParamFuzz < cParams; iParamFuzz++) { rgParams [iParamFuzz] = dnaBestSinceReset.GetParam(iParamFuzz); } rgParams [iParam] = MutateParam(_mutationStrength, cValues, rgParams [iParam]); DNA child = new DNA(rgParams, dnaBestSinceReset.Generation + 1); if (!setChildren.ContainsKey(child)) { setChildren.Add(child, true); rgChildren.Add(child); } } } while (rgChildren.Count < _nPopulationSize - cAliensThisGeneration && setChildren.Count < cCombinations) { if (UserAbort) { throw new AbortOptimizationException(); } // find parents rendomly according to weighted fitness double weightA = _rand.NextDouble() * totalWeight; int iParentA = 0; while (iParentA < rgParents.Count && weightA > rgParents [iParentA].Weight) { weightA -= rgParents [iParentA].Weight; iParentA++; } double weightB = _rand.NextDouble() * totalWeight; int iParentB = 0; while (iParentB < rgParents.Count && weightB > rgParents [iParentB].Weight) { weightB -= rgParents [iParentB].Weight; iParentB++; } // these are the parents: DNA parentA = rgParents [iParentA]; DNA parentB = rgParents [iParentB]; // create a new set of genes int [] rgParams = new int [cParams]; for (int iParam = 0; iParam < cParams; iParam++) { // Take an attribute from parents DNA parent = (_rand.Next(100) < 50) ? parentA : parentB; rgParams [iParam] = parent.GetParam(iParam); // Should we mutate? int cValues = _rgParameterDefinitions [iParam].CountValues; if (cValues > 1 && _rand.NextDouble() < _mutationRate) { rgParams [iParam] = MutateParam(_mutationStrength, cValues, rgParams [iParam]); } } // create the new child, and make sure it's unique //int iGenerationChild = iGeneration; //int iGenerationChild = 1 + Math.Min (parentA.Generation, parentB.Generation); int iGenerationChild = (parentA.Generation + parentB.Generation) / 2; DNA child = new DNA(rgParams, iGenerationChild); if (!setChildren.ContainsKey(child)) { setChildren.Add(child, true); rgChildren.Add(child); } } stabilityScorePrev = stabilityScore; } DateTime timeEnd = DateTime.Now; TimeSpan tsDuration = timeEnd - timeStart; Strategy.Print(string.Format( "{0}: PH Optimizer End @ {1}, duration: {2} ({3} per iteration)", Strategy.Instrument.FullName, timeEnd, tsDuration, TimeSpan.FromTicks(tsDuration.Ticks / iGeneration) ) ); } catch (AbortOptimizationException) { Strategy.Print("Optimization Aborted..."); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); Strategy.Print(e.ToString()); //throw; } finally { if (dnaBestEver != null) { Dump(dnaBestEver); } } #if NT7 WaitForIterationsCompleted(true); #endif }
public void Has_no_adenosine() { var dna = new DNA(""); Assert.That(dna.Count('A'), Is.EqualTo(0)); }
public void GenerationsPassed() { if (initialize) { gameManager.SetTargetDNA(); for (int i = 0; i < populationSize; i++) { DNA dna = new DNA(); dna.RandomDNA(); dna.CalculateFitness(gameManager.targetDNA); population.Add(dna); } population.Sort(compareDNA); population[0].fitness = Mathf.Round(population[0].fitness); // Add best gene of first generation bestGenes.Add(population[0]); generation++; for (int i = 0; i < generationsPassed - 1; i++) { NewGeneration(); population.Sort(compareDNA); // Add best gene of first generation bestGenes.Add(population[0]); } saveManager.Save(population[0], generation); saveManager.LoadSave(); initialize = false; } else { gameManager.SetTargetDNA(); for (int i = 0; i < generationsPassed; i++) { NewGeneration(); population.Sort(compareDNA); // Add best gene of first generation bestGenes.Add(population[0]); } // GenerationCheck(); saveManager.Save(population[0], generation); saveManager.LoadSave(); } //for (int i = 0; i < bestGenes.Count; i++) //{ // Debug.Log(bestGenes[i].fitness); //} }
public void Repetitive_cytidine_gets_counts() { var dna = new DNA("CCCCC"); Assert.That(dna.Count('C'), Is.EqualTo(5)); }
public override int Evaluate(DNA dna) { throw new NotImplementedException(); }
/// <summary> /// Mutation Predicate. /// Modifies a DNA string by changing one of its bases to be a random new value /// </summary> /// <param name="mut_index"> /// The point in which mutation is applied. /// </param> /// <param name="randomGene"> /// The function used to supply random Genes /// </param> public static Mutant mutate(int mut_index, DNA original, getRandomGeneFunct randomGene) { Mutant m; DNA g_dna; DNAPartial g_partial; DNAPartial rest; Gene g; g=randomGene(); while (original.Contains(g)) g = randomGene(); g_dna = new DNA(); g_dna.Add(g); var sp_mut = split(mut_index-1, original); g_partial = split(0, g_dna).back; // remove the base at the location that mutation is to occur DNA back = join(new DNAPartial(), sp_mut.back); back.RemoveAt(0); // add mutated item back = join(g_partial, split(0,back).back); DNA front = join(new DNAPartial(), sp_mut.front); // join front, mutation, and rest, lists together rest = split(0, join(split(0,front).back, split(0, back).back)).back; m = new Mutant(join(new DNAPartial(), rest)); return m; }
public void Counts_only_thymidine() { var dna = new DNA("GGGGTAACCCGG"); Assert.That(dna.Count('T'), Is.EqualTo(1)); }
internal override double DetermineFitness(DNA <Point> genotype) { return(new PointsCalculator().Roundness(genotype.Genes)); }
public void Validates_nucleotides() { var dna = new DNA("GGTTGG"); Assert.Throws <InvalidNucleotideException>(() => dna.Count('X')); }
private DNA Reproduce(DNA parentA, DNA parentB) { // Create a list with available DNA List<int> AvailabeDNA = new List<int>(); for (int i = 0; i < DNA_Size; i++) { AvailabeDNA.Add (parentA.DNA_String[i]); } // Create offspring crossover DNA DNA offspring = new DNA(DNA_Size); for (int i = 0; i < DNA_Size; i++) { // Should parentA or parentB be used for this DNA index? double rnd_parentValue = rnd.NextDouble(); if (rnd_parentValue > 0.5) { // Use parentA offspring.DNA_String[i] = parentA.DNA_String[i]; AvailabeDNA.Remove(offspring.DNA_String[i]); } else { // Use parentB offspring.DNA_String[i] = parentB.DNA_String[i]; AvailabeDNA.Remove(offspring.DNA_String[i]); } } // Correct offspring DNA - Remove duplicates for (int i = 0; i < DNA_Size; i++) { for (int j = 0; j < DNA_Size; j++) { if (i != j && offspring.DNA_String[i] == offspring.DNA_String[j]) { offspring.DNA_String[i] = AvailabeDNA[0]; AvailabeDNA.RemoveAt(0); break; } } } // Check if Mutation should be done double rnd_mutationValue = rnd.NextDouble(); if (rnd_mutationValue < mutationChance) { offspring = MutateDNA(offspring); } return offspring; }
public void Init(bool isFirstGen = false) { firstGeneration = isFirstGen; dna = new DNA(DNALength, maxDNAVal); }
// Start is called before the first frame update void Start() { dna = GetComponent <DNA>(); }
// Start is called before the first frame update void Start() { dna = gameObject.GetComponent <DNA>(); }
public void Counts_all_nucleotides() { var dna = new DNA("AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC"); var expected = new Dictionary<char, int> { { 'A', 20 }, { 'T', 21 }, { 'C', 12 }, { 'G', 17 } }; Assert.That(dna.NucleotideCounts, Is.EqualTo(expected)); }
public void Init() { dna = new DNA(DNALength, 3); timeAlive = 0; alive = true; }
private void CalculateFitness() { fitnessSum = 0; DNA firstBest = Population[0]; //DNA secondBest = Population[0]; //DNA thirdBest = Population[0]; // Debug.Log("População:" + Population.Count); for (int i = 0; i < Population.Count; i++) { fitnessSum += Population[i].CalculateFitness(i); // Debug.Log("Somatório Fitness:" + fitnessSum); if (Population[i].Fitness > firstBest.Fitness) { //thirdBest = secondBest; //secondBest = firstBest; firstBest = Population[i]; } } //Debug.Log("Printar o melhor individu, tendo fitness de: " + firstBest.Fitness); //Debug.Log("Printar o SEGUNDO melhor individu, tendo fitness de: " + secondBest.Fitness); //Debug.Log("Printar o TERCEIRO melhor individu, tendo fitness de: " + thirdBest.Fitness); /*if(firstBest.Fitness >= 120) * { *//*int spykeCount = 0; * int opossumCount = 0; * int eagleCount = 0; * int lifeCount = 0; * * for (int j = 0; j < firstBest.Genes.Count; j++) * { * switch((int)firstBest.Genes[j].GetValue(firstBest.Genes[j].Length - 1)) * { * case 0: * spykeCount++; * break; * case 1: * opossumCount++; * break; * case 2: * eagleCount++; * break; * case 3: * lifeCount++; * break; * } * } * Debug.Log("Valores do FIRST: FITNESS = " + firstBest.Fitness + " -> SPYKE: " + spykeCount + " || OPOSSUM: " + opossumCount + " || EAGLE: " + eagleCount + " || LIFE: " + lifeCount); * * spykeCount = 0; * opossumCount = 0; * eagleCount = 0; * lifeCount = 0; * * for (int j = 0; j < secondBest.Genes.Count; j++) * { * switch ((int)secondBest.Genes[j].GetValue(secondBest.Genes[j].Length - 1)) * { * case 0: * spykeCount++; * break; * case 1: * opossumCount++; * break; * case 2: * eagleCount++; * break; * case 3: * lifeCount++; * break; * } * } * Debug.Log("Valores do SECOND: FITNESS = " + secondBest.Fitness + " -> SPYKE: " + spykeCount + " || OPOSSUM: " + opossumCount + " || EAGLE: " + eagleCount + " || LIFE: " + lifeCount); * * spykeCount = 0; * opossumCount = 0; * eagleCount = 0; * lifeCount = 0; * * for (int j = 0; j < thirdBest.Genes.Count; j++) * { * switch ((int)thirdBest.Genes[j].GetValue(thirdBest.Genes[j].Length - 1)) * { * case 0: * spykeCount++; * break; * case 1: * opossumCount++; * break; * case 2: * eagleCount++; * break; * case 3: * lifeCount++; * break; * } * } * Debug.Log("Valores do THIRD: FITNESS = " + thirdBest.Fitness + " -> SPYKE: " + spykeCount + " || OPOSSUM: " + opossumCount + " || EAGLE: " + eagleCount + " || LIFE: " + lifeCount);*/ /*if ((int)secondBest.Genes[i].GetValue(secondBest.Genes[i].Length - 1) != 0) * { * Debug.Log("Segundo Elemento: " + enemyList[(int)secondBest.Genes[i].GetValue(firstBest.Genes[i].Length - 1)]); * } * if ((int)thirdBest.Genes[i].GetValue(thirdBest.Genes[i].Length - 1) != 0) * { * Debug.Log("Terceiro Elemento: " + enemyList[(int)thirdBest.Genes[i].GetValue(thirdBest.Genes[i].Length - 1)]); * }*//* * //Debug.Log("ELEMENTO: " + enemyList[(int)firstBest.Genes[i].GetValue(firstBest.Genes[i].Length - 1)]); * }*/ BestFitness = firstBest.Fitness; // Debug.Log("Best Gene: " + best.Genes.Count); // best.Genes.CopyTo(BestGenes, 0); for (int i = 0; i < BestGenes.Count; i++) { for (int j = 0; j < BestGenes[i].Length; j++) { firstBest.Genes[i].SetValue(BestGenes[i].GetValue(j), j); } } }
public void Has_no_nucleotides() { var dna = new DNA(""); var expected = new Dictionary<char, int> { { 'A', 0 }, { 'T', 0 }, { 'C', 0 }, { 'G', 0 } }; Assert.That(dna.NucleotideCounts, Is.EqualTo(expected)); }
void Begin() { joints = new GameObject[5]; bones = new GameObject[10]; muscles = new GameObject[8]; brain = new NeuralNetwork(bones.Length + muscles.Length * 2, muscles.Length, 1, 60); connectDirectory = new MuscleConnect[muscles.Length]; structurePosition = new Transform[joints.Length + bones.Length + muscles.Length]; connections = new int[bones.Length * 2 + muscles.Length * 2]; if (genome == null) { joints = CreateRandomObjects(joints, jointObject); bones = CreateRandomObjects(bones, boneObject); muscles = CreateRandomObjects(muscles, muscleObject); creatureSystem = new GameObject[][] { joints, bones, muscles }; int doubleConnection = 0; foreach (GameObject bone in bones) { HingeJoint2D boneJoint = bone.GetComponent <HingeJoint2D>(); int firstJoint = (doubleConnection < joints.Length) ? doubleConnection : Mathf.FloorToInt(Random.Range(0, joints.Length)); connections[numberOfSelectedConnections++] = firstJoint; boneJoint.connectedBody = joints[firstJoint].GetComponent <Rigidbody2D>(); if (doubleConnection < joints.Length || Random.value > 0.5f) { doubleConnection++; HingeJoint2D boneJoint2 = bone.AddComponent <HingeJoint2D>(); int secondJoint = (doubleConnection < joints.Length) ? doubleConnection : Mathf.FloorToInt(Random.Range(0, joints.Length)); while (firstJoint == secondJoint) { secondJoint = Mathf.FloorToInt(Random.Range(0, joints.Length)); } connections[numberOfSelectedConnections++] = secondJoint; boneJoint2.connectedBody = joints[secondJoint].GetComponent <Rigidbody2D>(); boneJoint2.autoConfigureConnectedAnchor = false; boneJoint2.anchor = new Vector2(0.5f, 0); boneJoint2.connectedAnchor = Vector2.zero; } else { connections[numberOfSelectedConnections++] = -1; } } int directoryCounter = 0; foreach (GameObject muscle in muscles) { MuscleConnect muscleConnection = muscle.GetComponent <MuscleConnect>(); int chosenBone1 = Mathf.FloorToInt(Random.Range(0, bones.Length)); int chosenBone2; do { chosenBone2 = Mathf.FloorToInt(Random.Range(0, bones.Length)); }while (chosenBone1 == chosenBone2); muscleConnection.SetBones(bones[chosenBone1], bones[chosenBone2]); connections[numberOfSelectedConnections++] = chosenBone1; connections[numberOfSelectedConnections++] = chosenBone2; connectDirectory[directoryCounter++] = muscleConnection; } genome = new DNA(brain, structurePosition, connections, joints.Length, bones.Length, muscles.Length); } else { brain = genome.brain; joints = CreateSpecificObject(joints.Length, jointObject); bones = CreateSpecificObject(bones.Length, boneObject); muscles = CreateSpecificObject(muscles.Length, muscleObject); foreach (GameObject bone in bones) { HingeJoint2D boneJoint = bone.GetComponent <HingeJoint2D>(); boneJoint.connectedBody = joints[genome.connections[numberOfSelectedConnections++]].GetComponent <Rigidbody2D>(); if (genome.connections[numberOfSelectedConnections] != -1) { HingeJoint2D boneJoint2 = bone.AddComponent <HingeJoint2D>(); boneJoint2.connectedBody = joints[genome.connections[numberOfSelectedConnections]].GetComponent <Rigidbody2D>(); boneJoint2.autoConfigureConnectedAnchor = false; boneJoint2.anchor = new Vector2(0.5f, 0); boneJoint2.connectedAnchor = Vector2.zero; } numberOfSelectedConnections++; } int directoryCounter = 0; foreach (GameObject muscle in muscles) { MuscleConnect muscleConnection = muscle.GetComponent <MuscleConnect>(); GameObject bone1 = bones[genome.connections[numberOfSelectedConnections++]]; GameObject bone2 = bones[genome.connections[numberOfSelectedConnections++]]; muscleConnection.SetBones(bone1, bone2); connectDirectory[directoryCounter++] = muscleConnection; } } }
public void Repetitive_sequence_has_only_guanosine() { var dna = new DNA("GGGGGGGG"); var expected = new Dictionary<char, int> { { 'A', 0 }, { 'T', 0 }, { 'C', 0 }, { 'G', 8 } }; Assert.That(dna.NucleotideCounts, Is.EqualTo(expected)); }
void Update() { //sizeTarget = (int)(sizeTarget * 1.2); //ga.NewGeneration(sizeTarget); ga.NewGeneration(); //Debug.Log("TARGET SIZE: " + sizeTarget); Debug.Log("Nova Geração"); numGenerations += 1; //numGenerationsText.text = numGenerations.ToString(); //bestFitnessText.text = ga.BestFitness.ToString(); //if (ga.BestFitness >= fitnessTarget*1) { //Debug.Log("Best fitness: " + ga.BestFitness); if (ga.Population[0].Fitness >= fitnessTarget * 1) /*&& * ga.Population[1].Fitness >= fitnessTarget * 1 && * ga.Population[2].Fitness >= fitnessTarget * 1 * )*/ { int contador = 0; for (int i = 2; i >= 0; i--) { DNA aux = ga.Population[i]; int spykeCount = 0; int opossumCount = 0; int eagleCount = 0; int lifeCount = 0; int frogCount = 0; for (int j = 0; j < aux.Genes.Count; j++) { //Debug.Log("Valor de DOUBLE: " + (double) aux.Genes[j].GetValue(aux.Genes[j].Length - 1)); contador++; //Debug.Log("Contador: " + contador); switch ((double)aux.Genes[j].GetValue(aux.Genes[j].Length - 1)) { case 0: spykeCount++; // Instantiate(enemySpyke, new Vector3(j * 1f, i * 1.5f, 0), Quaternion.identity); listOfPrefabs.Add(enemySpyke); break; case 1: opossumCount++; // Instantiate(enemyOpossum, new Vector3(j * 1.0f, i * 1.5f, 0), Quaternion.identity); listOfPrefabs.Add(enemyOpossum); break; case 2: eagleCount++; listOfPrefabs.Add(enemyEagle); // Instantiate(enemyEagle, new Vector3(j * 1.0f, i * 1.5f, 0), Quaternion.identity); break; case 3: lifeCount++; listOfPrefabs.Add(enemyLife); // Instantiate(enemyLife, new Vector3(j * 1.0f, i * 1.5f, 0), Quaternion.identity); break; case 4: frogCount++; listOfPrefabs.Add(enemyFrog); // Instantiate(enemyLife, new Vector3(j * 1.0f, i * 1.5f, 0), Quaternion.identity); break; } } Debug.Log("Valores do I = " + i + " com FITNESS = " + aux.Fitness + " : -> SPYKE: " + spykeCount + " || OPOSSUM: " + opossumCount + " || EAGLE: " + eagleCount + " || LIFE: " + lifeCount + " || FROG: " + frogCount); // Debug.Log(listOfPrefabs[1].ToString()); // Instantiate(listOfPrefabs[1], new Vector3(1 * 1.0f, i * 1.5f, 0), Quaternion.identity); } this.enabled = false; } }
public DNA Replicate(string newName) { DNA replicatedDNA = new DNA(newName, arrayOfBlocks.GetLength(0), arrayOfBlocks.GetLength(1), arrayOfBlocks.GetLength(2)); for (int i = 0; i < replicatedDNA.arrayOfBlocks.GetLength(0); i++) { for (int j = 0; j < replicatedDNA.arrayOfBlocks.GetLength(1); j++) { for (int k = 0; k < replicatedDNA.arrayOfBlocks.GetLength(2); k++) { // Copy dna block weight, and calc repDNA color replicatedDNA.arrayOfBlocks[i, j, k].SetBlockMaxWeight(arrayOfBlocks[i, j, k].GetBlockMaxWeight()); replicatedDNA.arrayOfBlocks[i, j, k].SetBlockMinWeight(arrayOfBlocks[i, j, k].GetBlockMinWeight()); replicatedDNA.arrayOfBlocks[i, j, k].SetBlockWeight(arrayOfBlocks[i, j, k].GetBlockWeight()); replicatedDNA.arrayOfBlocks[i, j, k].CalculateBlockColor(); // Position replicatedDNA.arrayOfBlocks[i, j, k].SetBlockPosition(arrayOfBlocks[i, j, k].GetBlockPosition()); // Stabilization replicatedDNA.arrayOfBlocks[i, j, k].SetBlockStabilized(arrayOfBlocks[i, j, k].GetBlockStabilized()); replicatedDNA.arrayOfBlocks[i, j, k].SetBlockStabilizedChance(arrayOfBlocks[i, j, k].GetBlockStabilizedChance()); // Type replicatedDNA.arrayOfBlocks[i, j, k].SetBlockType(arrayOfBlocks[i, j, k].GetBlockType()); // Name replicatedDNA.arrayOfBlocks[i, j, k].CalculateBlockName(newName); // Now we copy all the data from the time joints connected to the original block, to put into the new block data if (arrayOfBlocks[i, j, k].GetPosXCon().GetConType() != null) { // Copy x joint axis replicatedDNA.arrayOfBlocks[i, j, k].GetPosXCon().SetConAxis(arrayOfBlocks[i, j, k].GetPosXCon().GetConAxis()); // Copy x joint speed replicatedDNA.arrayOfBlocks[i, j, k].GetPosXCon().SetConSpeed(arrayOfBlocks[i, j, k].GetPosXCon().GetConSpeed()); replicatedDNA.arrayOfBlocks[i, j, k].GetPosXCon().SetConSpeedMax(arrayOfBlocks[i, j, k].GetPosXCon().GetConSpeedMax()); replicatedDNA.arrayOfBlocks[i, j, k].GetPosXCon().SetConSpeedMin(arrayOfBlocks[i, j, k].GetPosXCon().GetConSpeedMin()); // copy x joint strength replicatedDNA.arrayOfBlocks[i, j, k].GetPosXCon().SetConStr(arrayOfBlocks[i, j, k].GetPosXCon().GetConStr()); replicatedDNA.arrayOfBlocks[i, j, k].GetPosXCon().SetConStrMax(arrayOfBlocks[i, j, k].GetPosXCon().GetConStrMax()); replicatedDNA.arrayOfBlocks[i, j, k].GetPosXCon().SetConStrMin(arrayOfBlocks[i, j, k].GetPosXCon().GetConStrMin()); // copy x joint type replicatedDNA.arrayOfBlocks[i, j, k].GetPosXCon().SetConType(arrayOfBlocks[i, j, k].GetPosXCon().GetConType()); } else if (arrayOfBlocks[i, j, k].GetPosXCon().GetIsFixedJoint()) { replicatedDNA.arrayOfBlocks[i, j, k].GetPosXCon().SetFixedJoint(true); } if (arrayOfBlocks[i, j, k].GetPosYCon().GetConType() != null) { // Copy x joint axis replicatedDNA.arrayOfBlocks[i, j, k].GetPosYCon().SetConAxis(arrayOfBlocks[i, j, k].GetPosYCon().GetConAxis()); // Copy x joint speed replicatedDNA.arrayOfBlocks[i, j, k].GetPosYCon().SetConSpeed(arrayOfBlocks[i, j, k].GetPosYCon().GetConSpeed()); replicatedDNA.arrayOfBlocks[i, j, k].GetPosYCon().SetConSpeedMax(arrayOfBlocks[i, j, k].GetPosYCon().GetConSpeedMax()); replicatedDNA.arrayOfBlocks[i, j, k].GetPosYCon().SetConSpeedMin(arrayOfBlocks[i, j, k].GetPosYCon().GetConSpeedMin()); // copy x joint strength replicatedDNA.arrayOfBlocks[i, j, k].GetPosYCon().SetConStr(arrayOfBlocks[i, j, k].GetPosYCon().GetConStr()); replicatedDNA.arrayOfBlocks[i, j, k].GetPosYCon().SetConStrMax(arrayOfBlocks[i, j, k].GetPosYCon().GetConStrMax()); replicatedDNA.arrayOfBlocks[i, j, k].GetPosYCon().SetConStrMin(arrayOfBlocks[i, j, k].GetPosYCon().GetConStrMin()); // copy x joint type replicatedDNA.arrayOfBlocks[i, j, k].GetPosYCon().SetConType(arrayOfBlocks[i, j, k].GetPosYCon().GetConType()); } else if (arrayOfBlocks[i, j, k].GetPosYCon().GetIsFixedJoint()) { replicatedDNA.arrayOfBlocks[i, j, k].GetPosYCon().SetFixedJoint(true); } if (arrayOfBlocks[i, j, k].GetPosZCon().GetConType() != null) { // Copy x joint axis replicatedDNA.arrayOfBlocks[i, j, k].GetPosZCon().SetConAxis(arrayOfBlocks[i, j, k].GetPosZCon().GetConAxis()); // Copy x joint speed replicatedDNA.arrayOfBlocks[i, j, k].GetPosZCon().SetConSpeed(arrayOfBlocks[i, j, k].GetPosZCon().GetConSpeed()); replicatedDNA.arrayOfBlocks[i, j, k].GetPosZCon().SetConSpeedMax(arrayOfBlocks[i, j, k].GetPosZCon().GetConSpeedMax()); replicatedDNA.arrayOfBlocks[i, j, k].GetPosZCon().SetConSpeedMin(arrayOfBlocks[i, j, k].GetPosZCon().GetConSpeedMin()); // copy x joint strength replicatedDNA.arrayOfBlocks[i, j, k].GetPosZCon().SetConStr(arrayOfBlocks[i, j, k].GetPosZCon().GetConStr()); replicatedDNA.arrayOfBlocks[i, j, k].GetPosZCon().SetConStrMax(arrayOfBlocks[i, j, k].GetPosZCon().GetConStrMax()); replicatedDNA.arrayOfBlocks[i, j, k].GetPosZCon().SetConStrMin(arrayOfBlocks[i, j, k].GetPosZCon().GetConStrMin()); // copy x joint type replicatedDNA.arrayOfBlocks[i, j, k].GetPosZCon().SetConType(arrayOfBlocks[i, j, k].GetPosZCon().GetConType()); } else if (arrayOfBlocks[i, j, k].GetPosZCon().GetIsFixedJoint()) { replicatedDNA.arrayOfBlocks[i, j, k].GetPosZCon().SetFixedJoint(true); } } } } replicatedDNA.JointRenderingObject = JointRenderingObject; return(replicatedDNA); }
public Individual() { dna = new DNA(); }
public Nematode(DNA dna) : base(dna) { Normalize(); }
public void Clean() { fitness = 0; dna = new DNA(); }
/// <summary> /// DNA join (crossover operation) /// Appends front and back to form new DNA /// </summary> public static DNA join(DNAPartial front, DNAPartial back) { DNA child = new DNA(); child.AddRange(front); child.AddRange(back); return child; }
public DNAProperties(DNA dna) { InitializeComponent(); dgDNAList.DataSource = dna.dnachain; }
/// <summary> /// Mutation Predicate. /// Performs a mutation on chance. /// Mutation occurs if calculated chance is less than required probability, otherwise the DNA is not affected. /// </summary> /// <param name="probability"> /// Probability of mutation occuring. /// Value must be between 0.0 and 1.0 /// </param> /// <returns> /// Either a mutated DNA or unaffected DNA /// </returns> public static Mutant mutate_by_chance(DNA original, getRandomGeneFunct randomGene, double probability = MUTATION_RATE) { Mutant m; int mut_index; // a random point in the DNA at which mutation will occur Random rand = new Random(); if (rand.NextDouble() < probability) { mut_index = rand.Next(1, original.Count); return mutate(mut_index, original, randomGene); } else { m = new Mutant(original); } return m; }
static void Main(string[] args) { var DNALenght = int.Parse(Console.ReadLine()); var DNAs = new List <string>();//time var inputDNA = Console.ReadLine(); while (inputDNA != "Clone them!") { var splited = inputDNA .Split(new char[] { '!' }, StringSplitOptions.RemoveEmptyEntries) .ToList(); //if (splited.Count == DNALenght)//I don't know //{ // DNAs.Add(string.Join("", splited)); //} DNAs.Add(string.Join("", splited)); inputDNA = Console.ReadLine(); } var workingDNAs = new List <string>(); foreach (var DNA in DNAs) { var splited = DNA .Split(new char[] { '!' }, StringSplitOptions.RemoveEmptyEntries) .ToList(); if (string.Join("", splited).Length == DNALenght)//I don't know { workingDNAs.Add(string.Join("", splited)); } } var bestDNAs = new List <string>();//time var bestLenght = 0; foreach (var DNA in workingDNAs) { MatchCollection matchesDNA = Regex.Matches(DNA, @"(1+)"); var bestLenghtCurrnet = 0; foreach (Match item in matchesDNA) { if (item.Groups[1].Value.Length > bestLenghtCurrnet) { bestLenghtCurrnet = item.Groups[1].Value.Length; } } if (bestLenght <= bestLenghtCurrnet) { bestLenght = bestLenghtCurrnet; bestDNAs.Add(DNA); } } var moreBestDNAs = new List <string>();//empty foreach (var DNA in bestDNAs) { MatchCollection matchesDNA = Regex.Matches(DNA, @"(1+)"); var bestLenghtCurrnet = 0; foreach (Match item in matchesDNA) { if (item.Groups[1].Value.Length > bestLenghtCurrnet) { bestLenghtCurrnet = item.Groups[1].Value.Length; } } if (bestLenght == bestLenghtCurrnet) { moreBestDNAs.Add(DNA); } } if (moreBestDNAs.Count == 1) {//3 times //try //{ // string[] areYouHere = new string[1]; // var a = areYouHere[10000]; //} //catch (Exception) //{ // // throw; //} for (int i = 0; i < DNAs.Count; i++) { if (DNAs[i] == moreBestDNAs[0]) { MatchCollection matchesDNA = Regex.Matches(DNAs[i], @"(1+)"); var maxLengh = int.MinValue; foreach (Match currentDNA in matchesDNA) { if (maxLengh < currentDNA.Value.Length) { maxLengh = currentDNA.Value.Length; } } Console.WriteLine($"Best DNA sample {i + 1} with sum: {maxLengh}."); Console.WriteLine(string.Join(" ", DNAs[i].ToCharArray())); return; } } } else { var leftMoreBestDNAs = new List <string>(); var mostLeftIndex = int.MaxValue; foreach (var DNA in moreBestDNAs) { var currentIndex = DNA.IndexOf(new string('1', bestLenght)); if (mostLeftIndex > currentIndex) { mostLeftIndex = currentIndex; } } foreach (var DNA in moreBestDNAs) { var currentIndex = DNA.IndexOf(new string('1', bestLenght)); if (mostLeftIndex == currentIndex) { leftMoreBestDNAs.Add(DNA); } } if (leftMoreBestDNAs.Count == 1) {//2 times //try //{ // string[] areYouHere = new string[1]; // var a = areYouHere[10000]; //} //catch (Exception) //{ // // throw; //} for (int i = 0; i < DNAs.Count; i++) { if (DNAs[i] == leftMoreBestDNAs[0]) { MatchCollection matchesDNA = Regex.Matches(DNAs[i], @"(1+)"); var maxLengh = int.MinValue; foreach (Match currentDNA in matchesDNA) { if (maxLengh < currentDNA.Value.Length) { maxLengh = currentDNA.Value.Length; } } Console.WriteLine($"Best DNA sample {i + 1} with sum: {maxLengh}."); Console.WriteLine(string.Join(" ", DNAs[i].ToCharArray())); return; } } } else {//5 times //try //{ // string[] areYouHere = new string[1]; // var a = areYouHere[10000]; //} //catch (Exception) //{ // // throw; //} } } //var bestDNAs = new List<string>();//time //var bestLenght = 0; //foreach (var DNA in workingDNAs) //{ // MatchCollection matchesDNA = Regex.Matches(DNA, @"(1+)"); // var bestLenghtCurrnet = 0; // foreach (Match item in matchesDNA) // { // if (item.Groups[1].Value.Length > bestLenghtCurrnet) // { // bestLenghtCurrnet = item.Groups[1].Value.Length; // } // } // // if (bestLenght <= bestLenghtCurrnet) // { // bestLenght = bestLenghtCurrnet; // bestDNAs.Add(DNA); // } //} // //var moreBestDNAs = new List<string>();//empty //foreach (var DNA in bestDNAs) //{ // MatchCollection matchesDNA = Regex.Matches(DNA, @"(1+)"); // var bestLenghtCurrnet = 0; // foreach (Match item in matchesDNA) // { // if (item.Groups[1].Value.Length > bestLenghtCurrnet) // { // bestLenghtCurrnet = item.Groups[1].Value.Length; // } // } // // if (bestLenght == bestLenghtCurrnet) // { // moreBestDNAs.Add(DNA); // } //} //// if only one //if (moreBestDNAs.Count == 1) //{ // for (int i = 0; i < DNAs.Count; i++) // { // if (DNAs[i] == moreBestDNAs[0]) // { // MatchCollection matchesDNA = Regex.Matches(DNAs[i], @"(1+)"); // var maxLengh = int.MinValue; // foreach (Match currentDNA in matchesDNA) // { // if (maxLengh < currentDNA.Value.Length) // { // maxLengh = currentDNA.Value.Length; // } // } // // Console.WriteLine($"Best DNA sample {i + 1} with sum: {maxLengh}."); // Console.WriteLine(string.Join(" ", DNAs[i].ToCharArray())); // return; // } // } //} // //var leftMoreBestDNAs = new List<string>(); //var mostLeftIndex = int.MaxValue; //foreach (var DNA in moreBestDNAs) //{ // var currentIndex = DNA.IndexOf(new string('1', bestLenght)); // if (mostLeftIndex > currentIndex) // { // mostLeftIndex = currentIndex; // } //} // //foreach (var DNA in moreBestDNAs) //{ // var currentIndex = DNA.IndexOf(new string('1', bestLenght)); // if (mostLeftIndex == currentIndex) // { // leftMoreBestDNAs.Add(DNA); // } //} // //var bestSum = int.MinValue; //foreach (var DNA in moreBestDNAs) //{ // var currentSum = DNA.ToCharArray().Select(x => int.Parse(x.ToString())).ToList().Sum(); // if (bestSum < currentSum) // { // bestSum = currentSum; // } //} // //var finalyBestDNA = ""; //foreach (var DNA in moreBestDNAs) //{ // var currentSum = DNA.ToCharArray().Select(x => int.Parse(x.ToString())).ToList().Sum(); // if (bestSum == currentSum) // { // finalyBestDNA = DNA; // break; // } //} // //for (int i = 0; i < DNAs.Count; i++) //{ // if (DNAs[i] == finalyBestDNA) // { // Console.WriteLine($"Best DNA sample {i + 1} with sum: {bestSum}."); // Console.WriteLine(string.Join(" ", finalyBestDNA.ToCharArray())); // } //} // ////if (leftMoreBestDNAs.Count >= 1) ////{ //// for (int i = 0; i < DNAs.Count; i++) //// { //// if (DNAs[i] == leftMoreBestDNAs[0]) //// { //// MatchCollection matchesDNA = Regex.Matches(DNAs[i], @"(1+)"); //// var maxLengh = int.MinValue; //// foreach (Match currentDNA in matchesDNA) //// { //// if (maxLengh < currentDNA.Value.Length) //// { //// maxLengh = currentDNA.Value.Length; //// } //// } //// //// Console.WriteLine($"Best DNA sample {i + 1} with sum: {maxLengh}."); //// Console.WriteLine(string.Join(" ", DNAs[i].ToCharArray())); //// } //// } ////} ////else ////{ //// var bestSum = int.MinValue; //// foreach (var DNA in moreBestDNAs) //// { //// var currentSum = DNA.ToCharArray().Select(x => int.Parse(x.ToString())).ToList().Sum(); //// if (bestSum < currentSum) //// { //// bestSum = currentSum; //// } //// } //// //// var finalyBestDNA = ""; //// foreach (var DNA in moreBestDNAs) //// { //// var currentSum = DNA.ToCharArray().Select(x => int.Parse(x.ToString())).ToList().Sum(); //// if (bestSum == currentSum) //// { //// finalyBestDNA = DNA; //// break; //// } //// } //// //// for (int i = 0; i < DNAs.Count; i++) //// { //// if (DNAs[i] == finalyBestDNA) //// { //// Console.WriteLine($"Best DNA sample {i + 1} with sum: {bestSum}."); //// Console.WriteLine(string.Join(" ", finalyBestDNA.ToCharArray())); //// } //// } ////} }
void SetRadarMap(RadarMap map, DNA dna) { map.ResetMap(dna); }
public void NewGeneration(int numNewDNA = 0, bool crossoverNewDNA = false) { int finalCount = Population.Count + numNewDNA; if (finalCount <= 0) { return; } if (Population.Count > 0) { CalculateFitness(); Population.Sort(CompareDNA); //testando fitness /*for (int k = 0; k < 5; k++) * { * DNA test = Population[k]; * int spykeCount = 0; * int opossumCount = 0; * int eagleCount = 0; * int lifeCount = 0; * * for (int j = 0; j < test.Genes.Count; j++) * { * switch ((int)test.Genes[j].GetValue(test.Genes[j].Length - 1)) * { * case 0: * spykeCount++; * break; * case 1: * opossumCount++; * break; * case 2: * eagleCount++; * break; * case 3: * lifeCount++; * break; * } * } * Debug.Log("Valores do K = " + k + " com FITNESS = " + test.Fitness + " : -> SPYKE: " + spykeCount + " || OPOSSUM: " + opossumCount + " || EAGLE: " + eagleCount + " || LIFE: " + lifeCount); * * }*/ } newPopulation.Clear(); for (int i = 0; i < finalCount; i++) { // Debug.Log("NOVO INDIVIDUO"); if (i < Elitism && i < Population.Count) { newPopulation.Add(Population[i]); } else if (i < Population.Count || crossoverNewDNA) { DNA parent1 = ChooseParent(); DNA parent2 = ChooseParent(); DNA child = parent1.Crossover(parent2); child.Mutate(MutationRate); // for (int j = 0; j < child.Genes.Count; j++) // { // Debug.Log("Filho Mutado: {" + child.Genes[j].GetValue(0) + ", " + child.Genes[j].GetValue(1) + ", " + child.Genes[j].GetValue(2) + "}"); // } newPopulation.Add(child); } else { newPopulation.Add(new DNA(dnaSize, random, getRandomGene, fitnessFunction, shouldInitGenes: true)); } } List <DNA> tmpList = Population; Population = newPopulation; newPopulation = tmpList; Generation++; }