public Organism(Neat neat, IBody body, Phenotype phenotype) { _neat = neat; _body = body; Phenotype = phenotype; FitnessModifier = 1.0; }
public PandaStats CreateChildStats(PandaStats father, PandaStats mother) { _random = new Random(_createdPandasCount++); Assert.IsTrue(father.Genotype.Count == mother.Genotype.Count); var newGenotype = DrawSingleValuesAndMutate(father.Genotype) .Join(DrawSingleValuesAndMutate(mother.Genotype), c => c.Trait, c => c.Trait, (fatherGene, motherGene) => new Gene() { FatherGene = fatherGene.Value, MotherGene = motherGene.Value, Trait = fatherGene.Trait }) .ToList(); Phenotype newPhenotype = CreatePhenotype(newGenotype); var gender = _random.NextBool() ? Gender.Male : Gender.Female; return(new PandaStats() { name = $"Panda No:{_createdPandasCount}", birthdate = _createdPandasCount, gender = gender, Genotype = newGenotype, Phenotype = newPhenotype }); }
// Declare member variables here. Examples: // private int a = 2; // private string b = "text"; // Called when the node enters the scene tree for the first time. public override void _Ready() { double[] data = new double[] { 3, 3, 3 }; Counter counter = new Counter(); Genome master = new Genome(); GenesisPhenotype gp = new GenesisPhenotype(counter, master, 3, 3); List <Neuron> inputNeurons = gp.InputNeurons; List <Neuron> outputNeurons = gp.OutputNeurons; List <Synapse> synapses = gp.Synapses; Phenotype new_pheno = new Phenotype(master, synapses, inputNeurons, outputNeurons, new List <Neuron>(), counter); Phenotype clone = new_pheno.Clone(); for (int i = 0; i < 1; i++) { new_pheno.Mutate(); clone.Mutate(); } double[] output = new_pheno.Forward(data); double[] output2 = clone.Forward(data); PrintOutput(output); PrintOutput(output2); Phenotype mate = new_pheno.Mate(clone); double[] output3 = mate.Forward(data); PrintOutput(output3); }
// Starts constructing the wing static public void AttachWing(GameObject body, Phenotype type) { int wingParts = type.TypeChromosomes.Count + 1; // Create wing segments Rigidbody[] wingSegments = new Rigidbody[2 * wingParts]; HingeJoint[] wingJoints = new HingeJoint[2 * wingParts]; segmentPos = 0; nextChrom = -1; leftWing = true; attachNextSegment(body, type, type.rootChromL, 0, wingSegments, wingJoints); // Left wing nextChrom = -1; leftWing = false; attachNextSegment(body, type, type.rootChromR, 0, wingSegments, wingJoints); // Right wing // Add the wing to the global set via the WingFactory WingSetFactory.AddWing(body, type, wingSegments, wingJoints); // Attach the second bone of the wings, to the body (the second bone is always one parallel to the body, simulating the length where the wing is connected to the body) addBoneJoint(body, wingSegments[1].gameObject, type.rootChromL.boneOffset, type.rootChromL.boneOffset.magnitude, 0, 0, type.rootChromL.muscleForce / 3); addBoneJoint(body, wingSegments[wingParts + 1].gameObject, type.rootChromR.boneOffset, type.rootChromR.boneOffset.magnitude, 0, 0, type.rootChromR.muscleForce / 3); }
private Phenotype CreatePhenotype(List <Gene> newGenotype) { var newPhenotype = new Phenotype(); foreach (var aGene in newGenotype) { var fatherQueryResult = TraitUtils.QueryTraitValue(aGene.Trait, aGene.FatherGene); var motherQueryResult = TraitUtils.QueryTraitValue(aGene.Trait, aGene.MotherGene); TraitValueQueryResult strongerQueryResult; if (fatherQueryResult.Strength > motherQueryResult.Strength) { strongerQueryResult = fatherQueryResult; } else if (fatherQueryResult.Strength < motherQueryResult.Strength) { strongerQueryResult = motherQueryResult; } else { strongerQueryResult = _random.NextBool() ? fatherQueryResult : motherQueryResult; } TraitUtils.SetQueryValue(strongerQueryResult.QuantisizedEnumValue, newPhenotype); } return(newPhenotype); }
protected override Factory <EvolutionResult <DoubleGene, double> > Factory() { return(() => { var random = RandomRegistry.GetRandom(); return EvolutionResult.Of( random.NextBoolean() ? Optimize.Maximum : Optimize.Minimum, new Population <DoubleGene, double>(100) .Fill(() => Phenotype.Of( Genotype.Of(DoubleChromosome.Of(0, 1)), 1, a => a.Gene.Allele), 100 ), random.NextInt(1000), random.NextInt(1000), EvolutionDurations.Of( TimeSpan.FromMilliseconds(random.NextInt(1000000)), TimeSpan.FromMilliseconds(random.NextInt(1000000)), TimeSpan.FromMilliseconds(random.NextInt(1000000)), TimeSpan.FromMilliseconds(random.NextInt(1000000)), TimeSpan.FromMilliseconds(random.NextInt(1000000)), TimeSpan.FromMilliseconds(random.NextInt(1000000)), TimeSpan.FromMilliseconds(random.NextInt(1000000)) ), random.NextInt(100), random.NextInt(100), random.NextInt(100) ); }); }
public static Phenotype <TGene, TAllele> ToBestPhenotype <TGene, TAllele>( this IEnumerable <EvolutionResult <TGene, TAllele> > source) where TGene : IGene <TGene> where TAllele : IComparable <TAllele>, IConvertible { Phenotype <TGene, TAllele> bestPhenotype = null; foreach (var result in source) { if (Interlocked.CompareExchange(ref bestPhenotype, result.GetBestPhenotype(), null) != null) { var oldValue = bestPhenotype; Phenotype <TGene, TAllele> newValue; do { if (result.GetOptimize().Compare(result.GetBestPhenotype().GetFitness(), oldValue.GetFitness()) > 0) { newValue = result.GetBestPhenotype(); } else { break; } } while (ReferenceEquals(Interlocked.CompareExchange(ref bestPhenotype, newValue, oldValue), oldValue)); } } return(bestPhenotype); }
public override Phenotype Clone(Phenotype otherParent) { DenseLayer newLayer = new DenseLayer(neurons, activationFunction); newLayer.Deploy(inputShape); return(newLayer); }
public static List <Gene> CreateGenotypeFromPhenotype(Phenotype phenotype, List <Gene> oldGenotype) { var newGenotype = new List <Gene>(); var allTraitTypes = ReflectionUtils.GetTypesWithHelpAttribute(Assembly.GetCallingAssembly(), typeof(SingleTraitAttribute)) .Select(c => new { c = c, ata = c.GetCustomAttribute <SingleTraitAttribute>() }) .ToList(); foreach (var fieldInfo in phenotype.GetType().GetFields()) { var currentQuantisizedValue = fieldInfo.GetValue(phenotype); var name = Enum.GetName(fieldInfo.FieldType, currentQuantisizedValue); var attribute = fieldInfo.FieldType.GetField(name).GetCustomAttributes(false).OfType <TraitSingleValueCharacteristic>().SingleOrDefault(); var traitWeAreLookingFor = allTraitTypes.SingleOrDefault(c => c.c == fieldInfo.FieldType); Assert.IsNotNull(traitWeAreLookingFor, "Cannot find enum with SingleTraitAttribute of type " + fieldInfo.FieldType); newGenotype.Add(new Gene() { FatherGene = attribute.ContinuousValue, MotherGene = attribute.ContinuousValue, Trait = traitWeAreLookingFor.ata.Trait }); } return(newGenotype); }
// Constructor public EvaluatedPhenotype(Phenotype phenotype, float reachedHeight, float wingSurface, float[] fitnessOfChromosomes) { this.reachedHeight = reachedHeight; // Height in this case this.phenotype = phenotype; this.wingSurface = wingSurface; this.fitnessOfChromosomes = fitnessOfChromosomes; this.life = GlobalSettings.phenotypeLife; this.totalFitness = 0; this.totalFitness = CalculateTotalFitness(); }
[TestMethod]//NEED TO: Add more tests public void TestCalculatePhenotypicRatio1() { var rng = new PredictableRandomNumberGenerator(); var gt = new Genotype('C', Dominance.Dominant, Dominance.Recessive, rng); //Cc var otherGt = new Genotype('C', Dominance.Recessive, Dominance.Recessive, rng); //cc Phenotype p = new Phenotype(null, null, null); // TO DO: fill in string phenotypicRatio = p.CalculatePhenotypicRatio(otherGt, gt, 2); //Aa Bb Assert.AreEqual("1:3", phenotypicRatio); }
public void Update() { if (!_body.HasFinished()) { var inputs = _body.GetInputs(); var outputs = Phenotype.Compute(inputs); _body.Activate(outputs); _isFitnessUpdated = false; } }
// Create new Phenotype with "lowest" Chromosomes, based on the array "fitnessOfChromosomes" static public Phenotype MIN_PHENOTYPE(EvaluatedPhenotype[] P) { EvaluatedPhenotype chosen; chosen = P[0]; foreach (EvaluatedPhenotype ePhen in P) { if (ePhen.fitnessOfChromosomes[0] <= chosen.fitnessOfChromosomes[0]) { chosen = ePhen; } } Chromosome rootL = chosen.phenotype.rootChromL; Chromosome rootR = chosen.phenotype.rootChromR; List <Chromosome> minChromosomes = new List <Chromosome>(); int len = P[0].phenotype.TypeChromosomes.Count; for (int ind = 1; ind <= len; ind++) { chosen = P[0]; foreach (EvaluatedPhenotype ePhen in P) { if (ePhen.fitnessOfChromosomes[ind] <= chosen.fitnessOfChromosomes[ind]) { chosen = ePhen; } } minChromosomes.Add(chosen.phenotype.TypeChromosomes[ind - 1]); } float strengthDistr; int maxFlapSteps; chosen = P[0]; foreach (EvaluatedPhenotype ePhen in P) { if (ePhen.totalFitness <= chosen.totalFitness) { chosen = ePhen; } } strengthDistr = chosen.phenotype.muscleStrengthDistribution; maxFlapSteps = chosen.phenotype.maxFlapSteps; Phenotype newPhen = new Phenotype(rootL, rootR, minChromosomes, strengthDistr, maxFlapSteps); return(newPhen); }
// Asexual reproduction constructor public Entity(string objType, string id, Genome motherGenome, Vector3 spawn, bool isAnimal) { species = objType; index = id; name = (species + " " + index.ToString()); displayName = name; this.isAnimal = isAnimal; genome = new Genome(motherGenome); phenotype = new Phenotype(this); }
// Adds a new wingset and keeps track of it static public void AddWing(GameObject body, Phenotype phenotype, Rigidbody[] wingSegments, HingeJoint[] wingJoints) { Rigidbody[] wingPolygons = createWingPolygons(wingSegments, GlobalSettings.standardWingDesignIndices); WingSet wingSet = new WingSet(body, phenotype, wingPolygons, wingJoints); body.GetComponent <DragonScript>().wingSet = wingSet; wingSet.RenderVisualisation(((activeWings.Count < GlobalSettings.maxRenderedMembranes) && GlobalSettings.renderingMembranes)); activeWings.Add(wingSet); }
public void Evolve() { //Evolve pop var newPopulation = new List <Genotype>(); //Breed using routlette wheel selection for (int i = 0; i < Population.Count / 2; ++i) { var parent1 = RouletteWheelSelection(Population); var parent2 = RouletteWheelSelection(Population); //Crossover Genotype offspring1 = parent1, offspring2 = parent2; OnePointCrossover(parent1, parent2, ref offspring1, ref offspring2); //Mutate offspring offspring1.Mutate(mutationRate); offspring2.Mutate(mutationRate); offspring1.FixEndPoints(); offspring2.FixEndPoints(); newPopulation.Add(offspring1); newPopulation.Add(offspring2); } //Maintain fittest from previous population. newPopulation[0] = FittestGenotype(); //Regenerate lower portion of the population to preserve diversity for (int i = newPopulation.Count - newPopulation.Count / 6; i < newPopulation.Count; i++) { newPopulation[i] = new Genotype(); } Population = newPopulation; foreach (Genotype g in Population) { Phenotype.CreatePhenotype(g); } currentGeneration++; generationLabel.text = "Generation " + currentGeneration; if (autosaveToggle && currentGeneration % autosaveGenerationInterval == 0) { string json = SavePopulation(); FileInfo file = new FileInfo(Application.persistentDataPath + "/" + sessionNameInputField.text + "/" + "autosavePopulation" + currentGeneration / autosaveGenerationInterval + ".json"); file.Directory.Create(); File.WriteAllText(file.FullName, json); } results.Clear(); internalTimer = 0.0f; }
protected override List <Phenotype <Vector3> > DoMutations(List <Phenotype <Vector3> > generation) { var newPhenotypes = new List <Phenotype <Vector3> >(); foreach (var phenotype in generation) { var newPhenotype = new Phenotype <Vector3>(phenotype.Data + new Vector3(CurrentGeneration % 3, (CurrentGeneration + 1) % 3, (CurrentGeneration + 2) % 3)); newPhenotypes.Add(newPhenotype); } return(newPhenotypes); }
public static void SetQueryValue(object enumValue, Phenotype phenotype) { foreach (var prop in phenotype.GetType().GetFields()) { if (prop.FieldType == enumValue.GetType()) { prop.SetValue(phenotype, enumValue); return; } } Assert.IsTrue(false, $"Fail: In Phenotype class i cannot find field of enum type {enumValue}"); }
public PopulationManager(int popSize, int nInputs, int nOutputs) { this.popSize = popSize; GenesisPhenotype proto = new GenesisPhenotype(this.counter, this.MasterGenome, nInputs, nOutputs); Phenotype Adam = new Phenotype(MasterGenome, proto.Synapses, proto.InputNeurons, proto.OutputNeurons, new List <Neuron>(), counter); for (int i = 0; i < popSize; i++) { Phenotype newClone = Adam.Clone(); // newClone.Mutate(); Population.Add(newClone); } }
// Use this for initialization void Awake() { //Construct population. Involves generating initial genotypes and constructing Phenotypes from the genotypes. for (int i = 0; i < PopulationSize; i++) { Population.Add(new Genotype()); } foreach (Genotype g in Population) { Phenotype.CreatePhenotype(g); } }
public override Phenotype Clone(Phenotype otherParent) { //Assume to be another phenotype group SequentialModel modelParent = (SequentialModel)otherParent; ComputationModel[] modelClones = new ComputationModel[computationModels.Length]; for (int i = 0; i < modelClones.Length; i++) { modelClones[i] = (ComputationModel)computationModels[i].Clone(modelParent.ComputationModels[i]); } return(new SequentialModel(modelClones)); }
// Create new Phenotype with "lowest" Chromosomes, based on the array "fitnessOfChromosomes" public static Phenotype operator -(EvaluatedPhenotype P1, EvaluatedPhenotype P2) { Chromosome rootL, rootR; if (P1.fitnessOfChromosomes[0] <= P2.fitnessOfChromosomes[0]) { rootL = P1.phenotype.rootChromL; rootR = P1.phenotype.rootChromR; } else { rootL = P2.phenotype.rootChromL; rootR = P2.phenotype.rootChromR; } List <Chromosome> minChromosomes = new List <Chromosome>(); int ind = 1; foreach (Chromosome chrom in P1.phenotype.TypeChromosomes) { if (P1.fitnessOfChromosomes[ind] <= P2.fitnessOfChromosomes[ind]) { minChromosomes.Add(chrom); } else { minChromosomes.Add(P2.phenotype.TypeChromosomes[ind - 1]); } ind++; } float strengthDistr; int maxFlapSteps; if (P1.totalFitness <= P2.totalFitness) { strengthDistr = P1.phenotype.muscleStrengthDistribution; maxFlapSteps = P1.phenotype.maxFlapSteps; } else { strengthDistr = P2.phenotype.muscleStrengthDistribution; maxFlapSteps = P2.phenotype.maxFlapSteps; } Phenotype newPhen = new Phenotype(rootL, rootR, minChromosomes, strengthDistr, maxFlapSteps); return(newPhen); }
public void BeginTrial(Orientations orientation, float startTime) { this.startTime = startTime; this.orientation = orientation; SetRotation(orientation); currentTrial = new Trial(orientation, startTime); if (Phenotype != null) { Phenotype.AddTrial(currentTrial); } }
// Use the prefab to instantiate an actual body of the sample (the block at the middle) static public GameObject CreateDragon(Phenotype type, Vector3 startPosition, Quaternion startRotation, int index) { // Create new body GameObject body = (GameObject)Instantiate(DragonBody, startPosition, startRotation); DragonScript scr = body.gameObject.GetComponent <DragonScript>(); scr.index = index; // Create and atatch a wing AttachWing(body, type); return(body); }
/// <summary> /// Construct evaluator with the provided task arguments/variables. /// </summary> public MapClusteringEvaluator(IMapClusteringDataset dataset, int nbClusters, Phenotype phenotype) { this.nbClusters = nbClusters; this.phenotype = phenotype; // Build input layers (samples matrices) nbInputs = dataset.InputCount; samples = dataset.GetSamplesMatrix(); // Extract useful values n = samples.GetLength(1); // layers width m = samples.GetLength(2); // layers height nbInputsNN = samples.Length; nbOutputsNN = nbClusters * n * m; }
private Phenotype findTop(Dictionary <Phenotype, double> pop) { Phenotype alpha = null; double score = double.MinValue; foreach (KeyValuePair <Phenotype, double> kv in pop) { if (kv.Value > score) { score = kv.Value; alpha = kv.Key; } } return(alpha); }
public static OmimAnnotation Read(ExtendedBinaryReader reader) { var hgnc = reader.ReadAsciiString(); var description = reader.ReadAsciiString(); var mimNumber = reader.ReadOptInt64(); var phenotypeCount = reader.ReadOptInt32(); var phenotypes = new List <Phenotype>(); for (var i = 0; i < phenotypeCount; i++) { phenotypes.Add(Phenotype.ReadPhenotype(reader)); } return(new OmimAnnotation(hgnc, description, mimNumber, phenotypes)); }
void ResetGeneration() { //Destroy all current Phenotypes var livePhenotypes = GameObject.FindObjectsOfType <Phenotype>(); foreach (var pheno in livePhenotypes) { Destroy(pheno.gameObject); } //Clear any results results.Clear(); //Recreate phenotypes from population foreach (var geno in Population) { Phenotype.CreatePhenotype(geno); } }
// Attaches the wing segments recursively static public void attachNextSegment(GameObject obj, Phenotype type, Chromosome chrom, int el, Rigidbody[] segments, HingeJoint[] joints) { el++; nextChrom++; if (chrom.numOfJoints == 0) { obj = attachBone(obj, chrom.boneOffset, chrom.boneAddRot, chrom.boneLength, chrom.boneThickness, chrom, el, joints); obj.name = (nextChrom).ToString(); segments[segmentPos++] = obj.GetComponent <Rigidbody>(); } else { if (chrom.numOfJoints == 1) { obj = attachBone(obj, chrom.boneOffset, chrom.boneAddRot, chrom.boneLength, chrom.boneThickness, chrom, el, joints); obj.name = (nextChrom - 1).ToString(); segments[segmentPos++] = obj.GetComponent <Rigidbody>(); attachNextSegment(obj, type, type.TypeChromosomes[nextChrom], el, segments, joints); } else { obj = attachBone(obj, chrom.boneOffset, chrom.boneAddRot, chrom.boneLength, chrom.boneThickness, chrom, el, joints); obj.name = (nextChrom).ToString(); segments[segmentPos++] = obj.GetComponent <Rigidbody>(); for (int b = chrom.numOfJoints; b > 0; b--) { attachNextSegment(obj, type, type.TypeChromosomes[nextChrom], el, segments, joints); } } } // Normally bones are uncolored when not visible if (el > 0) { if (GlobalSettings.renderingBodyAndBones) { ColorizeBone(obj, chrom); } } }
static public Phenotype MUTATE_BONELENGTH(Phenotype P, float prob) { if (Random.value <= prob) { P.rootChromL.boneLength = (P.rootChromL.boneLength * VARIANCE_FACTOR()); P.rootChromR.boneLength = P.rootChromL.boneLength; } foreach (Chromosome chrom in P.TypeChromosomes) { if (Random.value <= prob) { chrom.boneLength = (chrom.boneLength * VARIANCE_FACTOR()); } } return(P); }
IEnumerator EvaluateBatch(int batchIndex, Phenotype[] batch, Orientations orientation) { IList<EvaluationBehaviour> evaluations = new List<EvaluationBehaviour>(); var layout = new TransformLayout(28.0f, 18.0f, batchSize, Mathf.FloorToInt(Mathf.Sqrt(batchSize))) .GetEnumerator(); foreach (var phenotype in batch) { layout.MoveNext(); var t = PoolManager.Pools["Evaluations"].Spawn(prefab, layout.Current, Quaternion.identity, transform); var controllerBehaviour = t.GetComponent<ControllerBehaviour>(); controllerBehaviour.Network = NetworkPorts.FromGenotype(phenotype.Genotype); var evaluationBehaviour = t.GetComponent<EvaluationBehaviour>(); evaluationBehaviour.Phenotype = phenotype; evaluationBehaviour.BeginTrial(orientation, Time.time); evaluations.Add(evaluationBehaviour); } // Wait for evaluations to complete while (evaluations.Any(ev => !ev.IsComplete)) { if (BestEvaluation != null) { var ordered = evaluations.OrderByDescending(ev => ev.CurrentTrial.Fitness); var best = ordered.First(); BestEvaluation(best); } yield return new WaitForFixedUpdate(); } // Cleanup List<Transform> children = new List<Transform>(transform.childCount); foreach (Transform child in transform) { if (child.gameObject.activeInHierarchy) { children.Add(child); } } foreach (Transform child in children) { PoolManager.Pools["Evaluations"].Despawn(child, null); } }
/// <summary> /// Construct evaluator with the provided task arguments/variables. /// </summary> public WindowMapClusteringEvaluator(IMapClusteringDataset dataset, int nbClusters, Phenotype phenotype, bool[,] filter) { this.nbClusters = nbClusters; this.phenotype = phenotype; this.filter = filter; Debug.Assert(filter.GetLength(0) % 2 != 0 && filter.GetLength(1) % 2 != 0); // Build input layers (samples matrices) nbInputs = dataset.InputCount; samples = dataset.GetSamplesMatrix(); // Extract useful values f = filter.GetLength(0); // filter width f2 = filter.Length; // f^2 t = (f - 1) / 2; // filter thickness nbInputsNN = nbInputs * f2; nbOutputsNN = nbClusters * f2; n = samples.GetLength(1); // layers width m = samples.GetLength(2); // layers height }
public ClassificationEvaluator(IClassificationDataset dataset, Phenotype phenotype, IEnumerable<double> weights) { this.dataset = dataset; this.phenotype = phenotype; this._weights = weights; }
/// <summary> /// Construct evaluator with the provided task arguments/variables. /// IMPORTANT : only for use with Test ! /// </summary> public ClassificationEvaluator(IClassificationDataset dataset, Phenotype phenotype) { this.dataset = dataset; this._weights = null; this.phenotype = phenotype; }
/// <summary> /// Construct evaluator with the provided task arguments/variables. /// </summary> public ClusteringEvaluator(IClusteringDataset dataset, int nbClusters, Phenotype phenotype) { this.dataset = dataset; this.nbClusters = nbClusters; this.phenotype = phenotype; }
IEnumerator EvaluateBatches(Phenotype[][] batches) { int batchIndex = 0; foreach (var batch in batches) { yield return StartCoroutine(EvaluateBatch(batchIndex, batch, Orientations.SoftLeft)); yield return StartCoroutine(EvaluateBatch(batchIndex, batch, Orientations.SoftRight)); yield return StartCoroutine(EvaluateBatch(batchIndex, batch, Orientations.MediumLeft)); yield return StartCoroutine(EvaluateBatch(batchIndex, batch, Orientations.MediumRight)); batchIndex++; } }