Пример #1
0
    void Split()
    {
        if (GameObject.FindGameObjectsWithTag("Cell").Length > 1000)
        {
            return;
        }

        GameObject child1 = Instantiate(PrefabSupplier.CellPrefabReference, transform.position, transform.rotation, transform.parent);
        GameObject child2 = Instantiate(PrefabSupplier.CellPrefabReference, transform.position, transform.rotation, transform.parent);

        child1.transform.rotation *= Quaternion.Euler(0, 0, genome[CellModeIndex].SplitAngle + genome[CellModeIndex].Child1Angle);
        child2.transform.rotation *= Quaternion.Euler(0, 0, genome[CellModeIndex].SplitAngle + genome[CellModeIndex].Child2Angle);
        Rigidbody2D child1physics = child1.GetComponent <Rigidbody2D>();
        Rigidbody2D child2physics = child2.GetComponent <Rigidbody2D>();
        Cell        child1Data    = child1.GetComponent <Cell>();
        Cell        child2Data    = child2.GetComponent <Cell>();

        child1Data.Mass          = Mass / 2f;
        child2Data.Mass          = Mass / 2f;
        child1Data.genome        = genome.Clone();
        child2Data.genome        = genome.Clone();
        child1Data.CellModeIndex = genome[CellModeIndex].Child1ModeIndex;
        child2Data.CellModeIndex = genome[CellModeIndex].Child2ModeIndex;

        Vector2 splitVelocity = new Vector2(-.3f, 0).Rotate(transform.eulerAngles.z + genome[CellModeIndex].SplitAngle);

        child1physics.velocity = physics.velocity + splitVelocity;
        child2physics.velocity = physics.velocity - splitVelocity;

        //Component[] child1Components = child1.GetComponents<Component>();
        //Component[] child2Components = child2.GetComponents<Component>();

        if (genome[CellModeIndex].Child1KeepAdhesin)
        {
            ReBuildAdhesins(child1Data, genome[CellModeIndex].Child1Angle);
        }

        if (genome[CellModeIndex].Child2KeepAdhesin)
        {
            ReBuildAdhesins(child2Data, genome[CellModeIndex].Child2Angle);
        }

        if (genome[CellModeIndex].MakeAdhesin)
        {
            GameObject adhesin = Instantiate(PrefabSupplier.AdhesinPrefabReference);
            adhesin.transform.SetParent(gameObject.transform.parent);
            Adhesin adhesinData = adhesin.GetComponent <Adhesin>();
            adhesinData.Cell1 = child1Data;
            adhesinData.Cell2 = child2Data;
            child1Data.AddAdhesin(adhesinData);
            child2Data.AddAdhesin(adhesinData);
        }

        Alive = false;
        Destroy(gameObject);
    }
Пример #2
0
    public Genome[] breed(Genome g1, Genome g2, int nbChildren)
    {
        Genome[] children = new Genome[nbChildren];

        for (int i = 0; i < nbChildren; i++)
        {
            Genome        g1Clone   = g1.Clone();
            List <double> g1Weights = g1Clone.getNeuralNetwork().getWeightsList();
            List <double> g2Weights = g2.getNeuralNetwork().getWeightsList();

            // Genetic Crossover
            for (int j = 0; j < g2Weights.Count; j++)
            {
                if (MathHelpers.randomNumber() <= 0.5)
                {
                    g1Weights [j] = g2Weights [j];
                }
            }

            // Preform Mutations on random weights
            for (int k = 0; k < g1Weights.Count; k++)
            {
                if (MathHelpers.randomNumber() <= NeuroEvolution.mutationRate)
                {
                    g1Weights [k] += MathHelpers.randomNumber() * NeuroEvolution.mutationRange * 2 - NeuroEvolution.mutationRange;
                }
            }

            g1Clone.getNeuralNetwork().setNeuronsAndWeights(g1Clone.getNeuralNetwork().getNumberOfNeuronsPerLayer(), g1Weights);

            children [i] = g1Clone;
        }

        return(children);
    }
Пример #3
0
    public void EvaluateBestCreature()
    {
        List <Genome> scores = new List <Genome>();

        foreach (List <Environment> tests in environments)
        {
            // Average score
            float score = 0;
            foreach (Environment environment in tests)
            {
                score += environment.evolvable.GetScore();
            }
            score /= tests.Count;

            // Put in the scores
            Genome genome = tests[0].evolvable.genome.Clone();
            genome.score = score; // Updates with the average score
            scores.Add(genome);
        }


        scores.Sort(
            delegate(Genome a, Genome b)
        {
            return(b.score.CompareTo(a.score));     // Larger first
        }
            );



        // Sorts the already existing genomes and extract the best one
        history.bestGenomes.Sort(
            delegate(Genome a, Genome b)
        {
            return(b.score.CompareTo(a.score));    // Larger first
        }
            );
        Genome oldBest = history.bestGenomes[0].Clone();


        history.bestGenomes.Clear();
        for (int i = 0; i < keepTop; i++)
        {
            history.bestGenomes.Add(scores[i].Clone());
        }

        history.bestScore = history.bestGenomes[0].score;


        history.generations.Add(history.bestGenomes[0].Clone());

        // Add backs the best genome
        history.bestGenomes.Add(oldBest.Clone());

        // Best genome (overall best)
        history.bestGenomes.Add(GetBestGenomeIn(history.generations));

        // Best scores for gizmos draw
        history.CalculateMinMaxScore();
    }
Пример #4
0
    public Genome SelectGenome()
    {
        Genome g          = bestGenome.Clone();
        float  totalScore = 0;

        foreach (Creature creature in oldCreatures)
        {
            float score = creature.GetScore();
            //Debug.Log("score: " + score);
            totalScore += score * score;
        }

        float rand         = Random.Range(0, totalScore);
        float currentScore = 0;

        foreach (Creature creature in oldCreatures)
        {
            float score = creature.GetScore();
            currentScore += score * score;
            if (rand <= currentScore)
            {
                g = creature.genome.Clone();
                Debug.Log(score);
                //Debug.Log("Genome selected had score of " + score);
                //Debug.Log("Percentage " + (score * score / totalScore) * 100);
                break;
            }
        }
        return(g);
    }
Пример #5
0
    private void CreateCreatures()
    {
        for (int i = 0; i < variationsPerGeneration; i++)
        {
            Genome genome = bestGenome.Clone();

            int mutationNum = UnityEngine.Random.Range(minMutations, maxMutations + 1);
            for (int j = 0; j < mutationNum; j++)
            {
                genome.Mutate();
            }

            Vector3    position   = distance * i;
            GameObject simulation = Instantiate(simulationPrefab, position, Quaternion.identity) as GameObject;
            Creature   creature   = simulation.transform.Find("creature").GetComponent <Creature>();

            creature.genome = genome;
            creatures.Add(creature);
        }
    }
Пример #6
0
    public static void UniformCrossover(Genome parent1, Genome parent2, out Genome offspring1, out Genome offspring2)
    {
        offspring1 = (Genome)parent1.Clone();
        offspring2 = (Genome)parent2.Clone();

        for (int i = 0; i < parent1.Length; i++)
        {
            float rnd = Helper.Next(1.0f);
            offspring1[i] = rnd < CROSSOVER_PROBABILITY ? parent1[i] : parent2[i];
            offspring2[i] = rnd < CROSSOVER_PROBABILITY ? parent2[i] : parent1[i];
        }
    }
Пример #7
0
    public List <Environment> CreateEnvironments(Genome genome, int i)
    {
        // Variants
        List <Environment> tests = new List <Environment>();

        environments.Add(tests);
        for (int t = 0; t < testsPerMutation; t++)
        {
            CreateEnvironment(genome.Clone(), i, t);
        }
        return(tests);
    }
Пример #8
0
        /// <summary>
        /// Creates and returns a mutated version of this chromosome
        /// </summary>
        /// <param name="MutatePercentChance">The percentage chance that any given node in the chromosome will be modified</param>
        /// <returns></returns>
        public Chromosome Mutate(int MutatePercentChance)
        {
            var c     = new Chromosome(Genome.Clone() as Node);
            var nodes = c.Enumerate().ToList();

            Trace.Write("Mutating: ");
            foreach (var n in nodes)
            {
                if (Random.Next(100) < MutatePercentChance)
                {
                    //can add a child
                    if (Random.Next(100) < MutateChanceAdd && nodes.Count < MutateMaxSize)
                    {
                        Trace.Write(" add ");
                        n.AddChild(CreateNode());
                    }
                    //can lose a child
                    if ((Random.Next(100) < MutateChanceLose && nodes.Count > MutateMinSize) || nodes.Count > MutateMaxSize)
                    {
                        Trace.Write(" rem ");
                        if (n.Children.Count > 0)
                        {
                            n.RemoveChild(n.Children[Random.Next(n.Children.Count)]);
                        }
                    }
                    //can change an action (this is like add and lose) or a functor
                    if (Random.Next(100) < MutateChanceMutate)
                    {
                        Trace.Write(" mut ");
                        var a = n as Action;
                        if (a != null)
                        {
                            Mutate(a);
                        }
                        else
                        {
                            var co = n as Conditional;
                            if (co != null)
                            {
                                Mutate(co);
                            }
                        }
                        //n.GetType().GetMethod("Mutate").Invoke(n, null);
                    }
                }
            }
            Trace.WriteLine("");
            return(c);
        }
Пример #9
0
    private Genome GetBestGenomeIn(List <Genome> list)
    {
        Genome best      = list[0].Clone();
        float  bestScore = best.score;

        foreach (Genome genome in list)
        {
            if (genome.score > bestScore)
            {
                best      = genome.Clone();
                bestScore = best.score;
            }
        }
        return(best.Clone());
    }
Пример #10
0
    public void CopulateBestCreatures()
    {
        List <Genome> genomes = new List <Genome>();

        for (int i = 0; i < sexed; i++)
        {
            Genome g1 = history.bestGenomes[Random.Range(0, history.bestGenomes.Count - 1)];
            Genome g2 = history.bestGenomes[Random.Range(0, history.bestGenomes.Count - 1)];

            Genome g3 = g1.Clone();

            genomes.Add(Genome.Copulate(g1, g2));
        }

        history.bestGenomes.AddRange(genomes);
    }
Пример #11
0
    //crossover and mutate 2 pairs
    List <Genome> repopulate(List <Creature> selected)
    {
        List <Genome> ret = new List <Genome>();
        //List<Genome> pars = new List<Genome>();
        int size = selected.Count;

        while (selected.Count > 1)
        {
            int r1 = Random.Range(0, selected.Count);
            int r2 = Random.Range(0, selected.Count);
            while (r1 == r2)
            {
                r2 = Random.Range(0, selected.Count);
            }
            Genome   p1       = selected[r1].genome.Clone();
            Genome   p2       = selected[r2].genome.Clone();
            Genome[] children = Genome.crossover2Pnt(p1, p2);
            Genome   c1       = children[0];
            Genome   c2       = children[1];
            c1.Mutate(mutateRate);
            c2.Mutate(mutateRate);
            ret.Add(p1); //pars.Add(p1);
            ret.Add(p2); //pars.Add(p2);
            ret.Add(c1);
            ret.Add(c2);

            selected.RemoveAt(r1);
            if (r1 < r2)
            {
                r2--;
            }
            selected.RemoveAt(r2);
        }

        if (selected.Count == 1)
        {
            //int i = Random.Range(0, pars.Count);
            Genome p = selected[0].genome.Clone();
            Genome c = p.Clone();
            c.Mutate(mutateRate);
            ret.Add(p);
            ret.Add(c);
        }

        return(ret);
    }
Пример #12
0
    public static    Genome[] crossover(Genome a, Genome b)
    {
        Genome[] ret    = new Genome[2];
        int      startI = Random.Range(0, 8);
        Genome   n1     = a.Clone();
        Genome   n2     = b.Clone();

        for (int i = startI; i < 8 - startI; i++)
        {
            n1.genes[i] = b.genes[i];
            n2.genes[i] = a.genes[i];
        }

        n1.applyGenes();
        n2.applyGenes();
        ret[0] = n1; ret[1] = n2;

        return(ret);
    }
Пример #13
0
        public object Clone()
        {
            var c = new Chromosome(Genome.Clone() as Node);

            return(c);
        }
Пример #14
0
        public override void AddedToContainer()
        {
            base.AddedToContainer();

            var builder = new FieldBuilder();

            builder.BuildSessionStart(this);

            var genomeTemplatesComboBox = builder.AddComboBoxField("Genome: ");

            genomeTemplatesComboBox.Items.AddRange(EditorData.GenomeTemplates.Select(s => s.TemplateName));
            genomeTemplatesComboBox.Index = 0;

            var annTemplatesComboBox = builder.AddComboBoxField("ANN: ");

            annTemplatesComboBox.Items.AddRange(EditorData.ANNTemplates.Select(s => s.TemplateName));
            annTemplatesComboBox.Index = 0;

            var creatureTemplatesComboBox = builder.AddComboBoxField("Creature: ");

            creatureTemplatesComboBox.Items.AddRange(EditorData.CreatureTemplates.Select(s => s.TemplateName));
            creatureTemplatesComboBox.Index = 0;

            var mutateCheckBox = builder.AddCheckBoxField("Mutate the genome: ");

            var amountField = builder.AddIntegerField("Amount to add: ");

            amountField.MinValue = 1;

            builder.AddResizableButtonField("OK", delegate(object sender)
            {
                string name   = genomeTemplatesComboBox.Items[genomeTemplatesComboBox.Index];
                Genome genome = null;
                foreach (var g in EditorData.GenomeTemplates)
                {
                    if (g.TemplateName == name)
                    {
                        genome = g.Genome;
                    }
                }

                name = annTemplatesComboBox.Items[annTemplatesComboBox.Index];
                INeuralNetChromosome ann = null;
                foreach (var a in EditorData.ANNTemplates)
                {
                    if (a.TemplateName == name)
                    {
                        ann = a.ANN;
                    }
                }

                name = creatureTemplatesComboBox.Items[creatureTemplatesComboBox.Index];
                ICreature creature = null;
                foreach (var c in EditorData.CreatureTemplates)
                {
                    if (c.TemplateName == name)
                    {
                        creature = c.Creature;
                    }
                }

                for (int i = 0; i < amountField.Value; i++)
                {
                    var clone       = (ICreature)creature.Clone();
                    var cloneGenome = genome.Clone();
                    cloneGenome.SetNetChromosome(ann.Clone());

                    if (mutateCheckBox.Checked)
                    {
                        cloneGenome.Mutate();
                    }

                    clone.ImprintGenome(cloneGenome);

                    world.AddEntity(clone);

                    clone.Position = new EntityPosition(Globals.Random.Next(world.Width), Globals.Random.Next(world.Height));
                }
            });

            builder.BuildSessionEnd();

            X = (Parent.Width / 2) - (Width / 2);
            Y = (Parent.Height / 2) - (Height / 2);

            CanResizeFormVertically = false;
        }
Пример #15
0
        void OneTrainingIteration(int i, BackgroundWorker bw)
        {
            Genome clone    = maxgenome;
            bool   merged   = false;
            bool   commoned = false;

            if (rand.Next(3) > 0 && otherparents.Count > 0)
            {
                Genome p = otherparents.Pop();
                if (rand.Next(2) == 0 || otherparents.Count < 1)
                {
                    if (rand.Next(2) == 0 && otherparents.Count > 0)
                    {
                        Genome p2 = otherparents.Pop();

                        if (Genome.Merge(p, p2, out clone))
                        {
                            merged = true;
                        }
                    }
                    else
                    {
                        if (Genome.Merge(maxgenome, p, out clone))
                        {
                            merged = true;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Commoning attempt. {0}:{1} {2}:{3}", prevcommon.ID, Interface.GenomeExists(prevcommon.ID), p.ID, Interface.GenomeExists(p.ID));
                    if (Genome.GetCommon(prevcommon, p, out clone))
                    {
                        prevcommon = clone;
                        commoned   = true;
                        merged     = true;
                    }
                    else
                    {
                        Console.WriteLine("Commoning failed. {0}:{1} {2}:{3}", prevcommon.ID, Interface.GenomeExists(prevcommon.ID), p.ID, Interface.GenomeExists(p.ID));
                    }
                }
            }
            if (!merged)
            {
                clone = maxgenome.Clone();
                int m = mutation * (i / 500 + 1) % 20;
                clone.Mutate(m);
            }

            double[] output     = clone.GetOutput(ogInput);
            double   errorcount = currentpuzzle.CheckDenormalisedValues(output, out string t);
            //System.IO.File.WriteAllText("blep.txt", t);
            double newscore = -errorcount;
            string message  = String.Format("{0}| Name: {1}; Score: {2}; {3}", i, clone.Name, newscore, commoned);

            bw.ReportProgress(i, message);
            if (newscore > maxscore)
            {
                otherparents.Clear();
                genomechanged = true;
                maxgenome     = clone;
                prevcommon    = clone;
                maxscore      = newscore;
                maxiteration  = i;
                string update = String.Format("{0}| Name: {1}; Score: {2};", i, maxgenome.Name, maxscore);
                EmailAttempt("Sudokise Update: " + maxscore, update);
            }
            else if (newscore == maxscore && !merged)
            {
                otherparents.Push(clone);
            }
            else
            {
                DisposeGenome(clone);
            }
        }