コード例 #1
0
ファイル: Mutation.cs プロジェクト: BarakUgav61/Scratch
 private static void VerifyGeneLength(GeneSequence parent, ICollection<char> childGenes)
 {
     if (childGenes.Count != parent.Genes.Length)
     {
         throw new ArgumentException("result is different length from parent");
     }
 }
コード例 #2
0
    public IEnumerator Log(int[] type, bool?wonGame)
    {
        trialsMasterCount++;
        while (reportLockout)
        {
            yield return(null);
        }
        reportLockout = true;
        GeneSequence ret = population.Find((GeneSequence gs) => gs.Compare((GeneSequence)type) && gs.returned < gs.sent);

        //If the returned game was null, that means it did not happen properly, lower this sent amount by one.
        if (wonGame == null)
        {
            ret.sent--;
        }
        else
        {
            //The sequence may have been discarded. (This may no longer be necessary since we wait for trials to complete)
            if (ret != null)
            {
                if ((bool)wonGame)
                {
                    ret.successes++;
                }
                ret.returned++;
                //Debug.Log("Log: " + ret.ToString());
            }
        }
        reportLockout = false;
    }
コード例 #3
0
        private static void ExtractBeginningMinimizers(List <Minimizer> minimizers, GeneSequence sequence, int w, int k)
        {
            string minimal    = sequence.Body.Substring(0, k);
            int    posMinimal = 0;

            if (minimizers.Count == 0 || posMinimal > minimizers[minimizers.Count - 1].Position)
            {
                minimizers.Add(new Minimizer(minimal, sequence, posMinimal));
            }

            // since the first kmer is certainly added (it is the only kmer in a size 1 window),
            // we can start at position 1, rather than 0,
            // and since k has to be at least 1, we can set windowEnd to 2 for beginning
            for (int windowEnd = 2; windowEnd < Math.Min(w, sequence.Body.Length - k + 2); windowEnd++)
            {
                // iterate through all substrings (k-mers) inside a window
                for (int i = posMinimal + 1; i < windowEnd; i++)
                {
                    string kmer = sequence.Body.Substring(i, k);

                    if (String.Compare(kmer, minimal) < 0)
                    {
                        minimal    = kmer;
                        posMinimal = i;
                    }
                }

                if (minimizers.Count == 0 || posMinimal > minimizers[minimizers.Count - 1].Position)
                {
                    minimizers.Add(new Minimizer(minimal, sequence, posMinimal));
                }
            }
        }
コード例 #4
0
        private static void ExtractInteriorMinimizers(List <Minimizer> minimizers, GeneSequence sequence, int w, int k)
        {
            string minimal    = sequence.Body.Substring(0, k);
            int    posMinimal = 0;

            // moving a window, so last iteration has just enough space to fill w kmers
            for (int windowStart = 0; windowStart < (sequence.Body.Length + 2 - w - k); windowStart++)
            {
                if (posMinimal < windowStart)
                {
                    minimal = null;
                }

                // iterate through all substrings (k-mers) inside a window
                for (int j = windowStart; j < windowStart + w; j++)
                {
                    string kmer = sequence.Body.Substring(j, k);

                    if (minimal == null || String.Compare(kmer, minimal) < 0)
                    {
                        minimal    = kmer;
                        posMinimal = j;
                    }
                }

                if (minimizers.Count == 0 || posMinimal > minimizers[minimizers.Count - 1].Position)
                {
                    minimizers.Add(new Minimizer(minimal, sequence, posMinimal));
                }
            }
        }
コード例 #5
0
        private static void ExtractEndingMinimizers(List <Minimizer> minimizers, GeneSequence sequence, int w, int k)
        {
            int l = sequence.Body.Length;

            string minimal    = null;
            int    posMinimal = l - k;

            for (int windowStart = Math.Max(l - k - w, 0) + 1; windowStart <= l - k; windowStart++)
            {
                if (posMinimal < windowStart)
                {
                    minimal = null;
                }

                // iterate through all substrings (k-mers) inside a window
                for (int i = windowStart; i <= l - k; i++)
                {
                    string kmer = sequence.Body.Substring(i, k);

                    if (minimal == null || String.Compare(kmer, minimal) < 0)
                    {
                        minimal    = kmer;
                        posMinimal = i;
                    }
                }

                if (minimizers.Count == 0 || posMinimal > minimizers[minimizers.Count - 1].Position)
                {
                    minimizers.Add(new Minimizer(minimal, sequence, posMinimal));
                }
            }
        }
コード例 #6
0
 public bool Compare(GeneSequence other)
 {
     for (int i = 0; i < genes.Length; i++)
     {
         if (other[i] != genes[i])
         {
             return(false);
         }
     }
     return(true);
 }
コード例 #7
0
        /// <summary>
        /// Static function that extracts minimizers from a given sequence
        /// </summary>
        /// <param name="sequence">Sequence from which to extract minimizers</param>
        /// <param name="w">Number of k-mers in one batch (window) of minimizer extraction</param>
        /// <param name="k">Minimizer size (character length of substrings (k-mers))</param>
        /// <returns>List of extracted minimizers</returns>
        public static List <Minimizer> Extract(GeneSequence sequence, int w, int k)
        {
            if (w < 0 || k < 0 || sequence == null || sequence.Body.Length < k)
            {
                throw new ArgumentException("Given arguments not valid");
            }

            List <Minimizer> minimizers = new List <Minimizer>();

            ExtractBeginningMinimizers(minimizers, sequence, w, k);
            ExtractInteriorMinimizers(minimizers, sequence, w, k);
            ExtractEndingMinimizers(minimizers, sequence, w, k);

            return(minimizers);
        }
コード例 #8
0
        private void SetupNodeList(GeneSequence <NodeGene> nodeGenes)
        {
            var seenBefore = new List <int>();

            foreach (var node in nodeGenes)
            {
                if (!seenBefore.Contains(node.nodeID))
                {
                    seenBefore.Add(node.nodeID);
                }
                else
                {
                    Console.WriteLine();
                    foreach (var n in nodeGenes)
                    {
                        Console.Write("nID:{0} ", n.nodeID);
                    }
                    Console.WriteLine();
                    throw new Exception("network same nodeID in network!");
                }
            }

            int representedState = 0;

            foreach (NodeGene gene in nodeGenes)
            {
                var nodeID = gene.nodeID;
                switch (gene.type)
                {
                case NodeType.Sensor:
                    inputNodes.Add(nodeID, new InputNetworkNode(nodeID));
                    break;

                case NodeType.Hidden:
                    var hnode = new InternalNetworkNode(nodeID, ((InternalNodeGene)gene).Function) as INetworkNode;
                    awaitingNotificationsNodes[nodeID] = hnode;
                    hiddenNodes.Add(nodeID, hnode);
                    break;

                case NodeType.Output:
                    var onode = new OutputNetworkNode(nodeID, representedState++, ((InternalNodeGene)gene).Function) as INetworkNode;
                    outputNodes.Add(nodeID, onode);
                    break;
                }
            }
        }
コード例 #9
0
ファイル: Swap.cs プロジェクト: BarakUgav61/Scratch
        public GeneSequence Generate(IList<GeneSequence> parents, int numberOfGenesToUse, Func<char> getRandomGene, int numberOfGenesInUnitOfMeaning, decimal slidingMutationRate, Func<int, int> getRandomInt, int freezeGenesUpTo)
        {
            var parent = parents[getRandomInt(parents.Count)];

            bool useHint = getRandomInt(2) == 0 &&
                parent.Fitness != null &&
                parent.Fitness.UnitOfMeaningIndexHint != null &&
                parent.Fitness.UnitOfMeaningIndexHint.Value >= freezeGenesUpTo;

            int pointA = useHint
                ? parent.Fitness.UnitOfMeaningIndexHint.Value * numberOfGenesInUnitOfMeaning
                : getRandomInt(numberOfGenesToUse - freezeGenesUpTo) + freezeGenesUpTo;
            int pointB = getRandomInt(numberOfGenesToUse - freezeGenesUpTo) + freezeGenesUpTo;
            if (pointA == pointB)
            {
                return parent.Clone();
            }

            var childGenes = parent.Genes.ToArray();

            IChildGenerationStrategy type = this;
            if (numberOfGenesInUnitOfMeaning == 1 ||
                numberOfGenesToUse - freezeGenesUpTo == numberOfGenesInUnitOfMeaning ||
                getRandomInt(2) == 0)
            {
                SwapTwoGenes(childGenes, pointA, pointB);
                type = new SwapMidUnitOfMeaning();
            }
            else
            {
                pointA /= numberOfGenesInUnitOfMeaning;
                pointB /= numberOfGenesInUnitOfMeaning;
                SwapTwoUnitsOfMeaning(childGenes, pointA, pointB, numberOfGenesInUnitOfMeaning);
            }

            VerifyGeneLength(parent, childGenes);

            var child = new GeneSequence(childGenes, type);

            return child;
        }
コード例 #10
0
    public IEnumerator GetSpread(System.Action <int[]> callback)
    {
        while (getLockout)
        {
            yield return(null);
        }
        getLockout = true;

        if (population == null)
        {
            population = new List <GeneSequence>();
            //Generate initial spread
            while (population.Count < initPopSize * 2)
            {
                //Randomly generate one
                int[] spread        = new int[geneSize];
                int[] defaultSpread = (int[])GameManager.DefaultPointSpread;
                //Fill with random values
                for (int i = 0; i < spread.Length; i++)
                {
                    spread[i] = Mathf.Max(0, defaultSpread[i] + Random.Range(-fluctationRange - 1, fluctationRange + 1));
                }
                //Check if it is the same as one already in there, if so, ditch it.
                bool isDuplicate = false;
                foreach (GeneSequence sequence in population)
                {
                    if (isDuplicate == false)
                    {
                        isDuplicate = sequence.Compare((GeneSequence)spread);
                    }
                }
                if (isDuplicate == false)
                {
                    //Debug override always use default point spread
                    //population.Add((GeneSequence)defaultSpread);
                    population.Add((GeneSequence)spread);
                }
            }
            timeStamp       = Time.time;
            originTimeStamp = Time.time;
            Debug.Log("Simulation start");
            for (int i = 0; i < population.Count; i++)
            {
                Debug.Log("Init: " + population[i].ToString());
            }
        }
        GeneSequence ret = population.Find((GeneSequence gs) => gs.sent < trials);

        if (ret == null)
        {
            Debug.LogWarning("All trials sent." + (Time.time - timeStamp));

            //Wait for all trials to complete
            foreach (GeneSequence item in population)
            {
                while (item.returned < item.sent)
                {
                    yield return(null);
                }
            }

            Debug.LogWarning("Trial Complete." + (Time.time - timeStamp));
            timeStamp = Time.time;


            //Sort the old population by how well they performed
            population.Sort((GeneSequence a, GeneSequence b) => {
                float aVal = (float)a.successes / (float)a.returned;
                float bVal = (float)b.successes / (float)b.returned;
                if (aVal < bVal)
                {
                    return(-1);
                }
                else if (aVal == bVal)
                {
                    return(0);
                }
                else
                {
                    return(1);
                }
            });
            //Trim the worst ones
            while (population.Count > initPopSize)
            {
                population.RemoveAt(0);
            }
            float lowest  = population[0].successes / (float)population[0].returned;
            float highest = population[population.Count - 1].successes / (float)population[population.Count - 1].returned;
            population.Reverse();
            for (int i = 0; i < population.Count; i++)
            {
                Debug.Log("C Result: " + population[i].ToString());
            }

            int diffCount = 0;
            for (int i = 0; i < population.Count; i++)
            {
                for (int k = 0; k < population.Count; k++)
                {
                    if (population[i].Compare(population[k]) == false)
                    {
                        diffCount++;
                    }
                }
            }


            if (diffCount < convergenceThreshold * initPopSize)
            {
                //We have converged
                Debug.LogError("Convergence " + diffCount + ". Total Time: " + (Time.time - originTimeStamp));
                Debug.Break();
                Application.Quit();
            }
            else
            {
                //Randomize the population
                int n = population.Count;
                while (n > 1)
                {
                    n--;
                    int          k     = Random.Range(0, n + 1);
                    GeneSequence value = population[k];
                    population[k] = population[n];
                    population[n] = value;
                }

                List <GeneSequence> children = new List <GeneSequence>();
                //Go in pairs and breed new children.
                for (int i = 0; i < population.Count; i += 2)
                {
                    if (i + 1 < population.Count)
                    {
                        GeneSequence a          = population[i];
                        GeneSequence b          = population[i + 1];
                        int[]        childArray = new int[a.genes.Length];
                        //Get a random value from each parent
                        for (int k = 0; k < childArray.Length; k++)
                        {
                            childArray[k] = (Random.value < 0.5f) ? a.genes[k] : b.genes[k];
                        }
                        //Mutate
                        if (Random.value < mutationRate)
                        {
                            Debug.Log("Mutation");
                            //Get a random position
                            int pos = Random.Range(0, childArray.Length);
                            //Shift it up or down
                            if (Random.value < 0.5f)
                            {
                                childArray[pos]++;
                            }
                            else
                            {
                                childArray[pos]--;
                            }
                        }
                        children.Add((GeneSequence)childArray);
                    }
                }
                //Add t he children to the population
                foreach (GeneSequence child in children)
                {
                    population.Add(child);
                }
            }

            for (int i = 0; i < population.Count; i++)
            {
                population[i].sent      = 0;
                population[i].returned  = 0;
                population[i].successes = 0;
            }

            //select the first thing
            ret = population[0];
        }
        ret.sent++;
        //Select an sequence with not enough trials.
        callback(ret.genes);
        getLockout = false;
    }
コード例 #11
0
ファイル: Splice.cs プロジェクト: BarakUgav61/Scratch
        public GeneSequence Generate(IList<GeneSequence> parents, int numberOfGenesToUse, Func<char> getRandomGene, int numberOfGenesInUnitOfMeaning, decimal slidingMutationRate, Func<int, int> getRandomInt, int freezeGenesUpTo)
        {
            var indexes = Enumerable.Range(0, parents.Count)
                .Shuffle().Take(2).ToArray();

            int i1 = indexes.First();
            int i2 = indexes.Last();
            int sliceIndex = getRandomInt(numberOfGenesToUse - freezeGenesUpTo) + freezeGenesUpTo;
            var parentA = parents[i1];

            IChildGenerationStrategy type = this;
            if (numberOfGenesInUnitOfMeaning > 1 &&
                numberOfGenesToUse - freezeGenesUpTo != numberOfGenesInUnitOfMeaning &&
                getRandomInt(2) == 1)
            {
                bool useHint = getRandomInt(2) == 0 &&
                    parentA.Fitness != null &&
                    parentA.Fitness.UnitOfMeaningIndexHint != null &&
                    parentA.Fitness.UnitOfMeaningIndexHint.Value >= freezeGenesUpTo;

                sliceIndex = useHint
                    ? parentA.Fitness.UnitOfMeaningIndexHint.Value * numberOfGenesInUnitOfMeaning
                    : sliceIndex - sliceIndex % numberOfGenesInUnitOfMeaning;
            }
            else
            {
                type = new SpliceMidUnitOfMeaning();
            }

            if (sliceIndex == 0)
            {
                return parentA.Clone();
            }

            var parentB = parents[i2];

            var childGenes = parentA.Genes.Take(sliceIndex).Concat(parentB.Genes.Skip(sliceIndex)).ToArray();
            VerifyGeneLength(parentA, childGenes);
            var child = new GeneSequence(childGenes, type);
            return child;
        }