Ejemplo n.º 1
0
        // 새로운 노드를 추가함.
        // 기존의 연결 중 무작위로 선택해서 기존의 연결은 비활성화시키고,
        // 그 사이에 새로운 노드를 추가함.
        // in ==(w₁)==> out 이었다면
        // in =(w₂)=> new =(w₃)=> out과 같이 변이가 일어남. (w₁w₂w₃는 연결의 가중치)
        // 이때 구조적 혁신이 기존 성능에 주는 영향을 최소화하기 위해서 w₂= w₁, w₃= 1로 설정함.
        public void MutateNode(Random r)
        {
            if (Genes.Count == 0)
            {
                return;
            }
            Gene gene = RandomGenes(r);

            if (gene == null || !gene.Enable)
            {
                return;
            }

            gene.Enable = false;

            Gene gene1 = gene.Clone();

            gene1.Out        = NodeIndex;
            gene1.Weight     = 1.0;
            gene1.Innovation = Pool.NewInnovation();
            gene1.Enable     = true;
            Genes.Add(gene1);

            Gene gene2 = gene.Clone();

            gene2.In         = NodeIndex;
            gene2.Innovation = Pool.NewInnovation();
            gene2.Enable     = true;
            Genes.Add(gene2);


            ++NodeIndex;
        }
Ejemplo n.º 2
0
        public void Initialize()
        {
            Genes.Clear();

            Fitness = 0;

            int genes = _settings.GenomeLength;

            // create a random bit string (random genes)
            for (int i = 0; i < genes; ++i)
            {
                var gene       = new Gene <TCombinationModel>(_settings);
                int initPasses = 0;
                // Make sure all genes are unique
                do
                {
                    gene.Initialize();
                    initPasses++;
                } while (Genes.Any(g => g.GetActivePartsString().Equals(gene.GetActivePartsString())));

                Genes.Add(gene);
                Debug.WriteLineIf(initPasses > 1, $"# Re-initialized because of duplicate gene ({initPasses})");
            }
            RebuildModelFollowingGenes();
            UpdateFitnessScore();
        }
Ejemplo n.º 3
0
        //Give birth to two children
        public Genome(Genome Father, Genome Mother, bool XY, Int64 id)
        {
            ID         = id;
            this.Genes = new List <String>();
            //Get half the length
            int HalfLength = (int)Math.Round((Father.Genes.Count / 2D), 0);

            //If XY is true then spawn first three of father and last three of mother otherwise do the opposite
            if (XY)
            {
                //Father
                for (int i = 0; i < HalfLength; i++)
                {
                    Genes.Add(Father.Genes[i]);
                }
                //Mother
                for (int i = HalfLength; i < Mother.Genes.Count; i++)
                {
                    Genes.Add(Mother.Genes[i]);
                }
            }
            else
            {
                //Mother
                for (int i = 0; i < HalfLength; i++)
                {
                    Genes.Add(Mother.Genes[i]);
                }
                //Father
                for (int i = HalfLength; i < Father.Genes.Count; i++)
                {
                    Genes.Add(Father.Genes[i]);
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Adds gene between two nodes.
        /// There cannot be two genes between same nodes.
        /// </summary>
        private void AddGene(Random rnd, ref int innovation, List <Gene> allGenes)
        {
            int latter;
            int first;

            do
            {
                first = rnd.Next(0, Nodes.Count);
            }while(Nodes[first].Type == NodeType.Output);
            Node input = Nodes[first];
            Node output;
            int  j = 0;

            do
            {
                latter = rnd.Next(0, Nodes.Count);
                output = Nodes[latter];
                ++j;
                if (j > 10 && input.Layer >= output.Layer)
                {
                    for (int i = 0; i < Nodes.Count; i++)
                    {
                        if (input.Layer < Nodes[i].Layer)
                        {
                            output = Nodes[i];
                        }
                    }
                }
            } // SHOULD NOT PICK THE SAME LAYER
            while (input.Layer >= output.Layer);

            Gene gene = null;

            foreach (var item in allGenes)
            {
                if (item.In.Number == input.Number && item.Out.Number == output.Number)
                {
                    gene      = item.ShallowCopy();
                    gene.In   = input;
                    gene.Type = GeneType.Enabled;
                    gene.Out  = output;
                    break;
                }
            }

            if (gene == null)
            {
                gene = new Gene(input, output, 0f, GeneType.Enabled, ++innovation);
                var g = gene.ShallowCopy();
                g.Type = GeneType.AddGene;
                allGenes.Add(g);
            }
            if (Genes.ContainsValue(gene))
            {
                return;
            }
            gene.Weight = gene.AssignRandomWeight(rnd);
            gene.In.OutgoingConnections.Add(gene);
            Genes.Add(gene.Innovation, gene);
        }
 public Chromosome(List <Gene> genes) //Caprazlama yapildiginda yeni kromozom olusturmak icin sadece bu metot taraginda kullanilabilir
 {
     foreach (var gene in genes)
     {
         Genes.Add(new Gene(gene.Value));
     }
     CalculateFittnesFuntion();
 }
Ejemplo n.º 6
0
        private void InitGenes()
        {
            Genes.Add(GeneHelper.CreateCooperationGene(RandomHelper.StandardGeneratorInstance.Next(1, 2)));
            Genes.Add(GeneHelper.CreateLibidoGene());

            Genes.Add(GeneHelper.CreateEconomyGeneVariations());
            Genes.Add(GeneHelper.CreateMilitaryGeneVariations());
        }
 public Chromosome() //Kromozom ilk olustugunda populasyonda belirtildigi kadar genlere sahip bir sekilde olusturuluyor.
 {
     for (int i = 0; i < Population.GenesCount; i++)
     {
         Genes.Add(new Gene());
     }
     CalculateFittnesFuntion();
 }
Ejemplo n.º 8
0
        public void Add(Gene gene)
        {
            if (!Exists)
            {
                Genes = new List <Gene>();
            }

            Genes.Add(gene);
        }
Ejemplo n.º 9
0
        public IGene MutateAddGene(IEnumerable <IGene> genePool)
        {
            // Select two nodes at random to connect
            List <INode> nodeOutCandidates = Nodes.ToList();

            if (!GenomeParameters.AllowOutputOutGenes)
            {
                nodeOutCandidates = nodeOutCandidates.Where(n => n.Type != NodeType.Output).ToList();
            }

            INode nodeOut = nodeOutCandidates[new Random().Next(nodeOutCandidates.Count)];

            // Get existing connections for this node
            List <IGene> existingConnectionsIn  = Genes.Where(cg => cg.NodeIn == nodeOut).ToList();
            List <IGene> existingConnectionsOut = Genes.Where(cg => cg.NodeOut == nodeOut).ToList();

            // Discover nodes where no connection currently exists
            List <INode> nodeInCandidates = Nodes
                                            .Except(existingConnectionsIn.Select(g => g.NodeOut))
                                            .Except(existingConnectionsOut.Select(g => g.NodeIn)).ToList();

            // Don't allow input to input or output to output connections
            if (nodeOut.Type == NodeType.Input || nodeOut.Type == NodeType.Output)
            {
                nodeInCandidates = nodeInCandidates.Where(n => n.Type != nodeOut.Type).ToList();
            }

            if (nodeOut.Type == NodeType.Hidden || nodeOut.Type == NodeType.Output)
            {
                nodeInCandidates = nodeInCandidates.Where(n => n.Type != NodeType.Input).ToList();
            }

            if (nodeInCandidates.Count > 0)
            {
                INode selectedNodeIn = nodeInCandidates[new Random().Next(nodeInCandidates.Count)];

                IGene existingGene = genePool.FirstOrDefault(gp => gp.NodeIn.Id == selectedNodeIn.Id &&
                                                             gp.NodeOut.Id == nodeOut.Id);

                // Create the connection
                IGene gene = new Gene(
                    nodeOut,
                    selectedNodeIn,
                    existingGene != null ? existingGene.Innovation : GetNextInnovation()
                    );

                Genes.Add(gene);

                return(gene);
            }

            return(null);
        }
Ejemplo n.º 10
0
        public Genome(int inputs, int outputs, double weight = 0) : this()
        {
            List <INode> inputNodes  = Enumerable.Range(0, inputs).Select <int, INode>(i => new Node(NodeType.Input, i)).ToList();
            List <INode> outputNodes = Enumerable.Range(0, outputs).Select <int, INode>(i => new Node(NodeType.Output, i)).ToList();

            Nodes = inputNodes.Concat(outputNodes).ToList();

            inputNodes.ForEach(inputNode => {
                outputNodes.ForEach(outputNode =>
                                    Genes.Add(new Gene(inputNode, outputNode, GetNextInnovation(), weight)));
            });
        }
Ejemplo n.º 11
0
        public void Crossover(ref TestCitizen mate, int slicePosA = -1, int slicePosB = -1)
        {
            Random rng = new Random();

            slicePosA = (slicePosA < 0) ? rng.Next(Genes.Count - 1) : slicePosA;
            slicePosB = (slicePosB < 0) ? rng.Next(mate.Genes.Count - 1) : slicePosB;

            // Determines if the input parameters are valid

            if (slicePosB >= mate.Genes.Count || slicePosA >= Genes.Count)
            {
                throw new InvalidOperationException("slice position is greater than the maximum index of either the mate, or the subject!");
            }

            // Initializes each cut List

            List <bool> cutA = new List <bool>(Genes.Count - (slicePosA + 1));
            List <bool> cutB = new List <bool>(mate.Genes.Count - (slicePosB + 1));

            // Removes the data from each subject at the splice Pos

            for (int i = 0; i < Genes.Count - (slicePosA + 1); i++)
            {
                cutA.Add(Genes[Genes.Count - 1]);
                Genes.RemoveAt(Genes.Count - 1);
            }

            cutA.Reverse();

            for (int i = 0; i < mate.Genes.Count - (slicePosB + 1); i++)
            {
                cutB.Add(mate.Genes[mate.Genes.Count - 1]);
                mate.Genes.RemoveAt(mate.Genes.Count - 1);
            }

            cutB.Reverse();

            // Adds the cut material back into the opposite subject

            foreach (bool b in cutA)
            {
                mate.Genes.Add(b);
            }

            foreach (bool b in cutB)
            {
                Genes.Add(b);
            }
        }
Ejemplo n.º 12
0
        public TestCitizen(List <bool> genes = null, int geneCount = -1) : base()
        {
            geneCount = (geneCount > 0) ? GeneCount : geneCount;

            // Initializes the genes list with default value
            Genes = genes ?? new List <bool>(geneCount);

            if (genes == null)
            {
                for (int i = 0; i < geneCount; i++)
                {
                    Genes.Add(false);
                }
            }
        }
Ejemplo n.º 13
0
        public void MutateLink(bool forceBias)
        {
            Neuron n1 = forceBias ? this[-66] : RandomNeuron(true);
            Neuron n2 = RandomNeuron(false);

            foreach (Gene gene in Genes)
            {
                if (gene.from == n1.Index && gene.axon.destination == n2.Index)
                {
                    return;
                }
            }

            Genes.Add(new Gene(n1.Index, n2.Index, R.NextDouble() * 4 - 2, true, innovation++));
        }
Ejemplo n.º 14
0
        private void CopyFrom(Neat parent)
        {
            lock (ThinkLock) {
                for (int i = 0; i < parent.Neurons.Count; i++)
                {
                    Neurons.Add(parent.Neurons[i].Clone(this));
                }
            }
            for (int i = 0; i < parent.Genes.Count; i++)
            {
                Gene gene = parent.Genes[i];
                Genes.Add(new Gene(gene.from, gene.axon.destination, gene.axon.weight, gene.enabled, gene.innovation));
            }

            innovation = parent.innovation;
        }
Ejemplo n.º 15
0
        public void FromParents(Neat parent, Neat other)
        {
            lock (ThinkLock) {
                OnRemove?.Invoke();
                Neurons.Clear();
                Genes.Clear();
            }

            if (other == null || R.NextDouble() > mutate_crossover)
            {
                CopyFrom(parent);
                VaryColor(parent, null);
            }
            else
            {
                Dictionary <int, Gene> genes = new Dictionary <int, Gene>();

                foreach (Gene gene in parent.Genes.Concat(other.Genes))
                {
                    if (!genes.ContainsKey(gene.innovation))
                    {
                        Gene mutate = gene;
                        if (!mutate.enabled && R.NextDouble() < mutate_enable)
                        {
                            mutate.enabled = true;
                        }
                        genes[gene.innovation] = mutate;
                    }
                }

                int max = 0;

                foreach (Gene gene in genes.Values)
                {
                    max = Max(max, Max(gene.from, gene.axon.destination));
                    Genes.Add(gene);
                }

                addNeurons(max);
                innovation = Max(parent.innovation, other.innovation);

                VaryColor(parent, other);
            }

            MutateEnable();
            Mutate();
        }
Ejemplo n.º 16
0
 public void AddGene(GeneType Gene)
 {
     #region Validations
     if (Genes == null)
     {
         Genes = new List <GeneType>();
     }
     if (Genes.Count > NumberOfGene)
     {
         throw new Exception("Violation of Maximum Number of Genes");
     }
     if (Gene == null)
     {
         throw new NullReferenceException();
     }
     #endregion Validations
     Genes.Add(Gene);
 }
Ejemplo n.º 17
0
 protected void AddRegion(string id, string typename, int start, int end, Sense sense)
 {
     try{
         if (typename.Equals("gene"))
         {
             Gene g = new Gene(id, typename, start, end, sense);
             Genes.Add(id, g);
         }
         else
         {
             Region r = new Region(id, typename, start, end, sense);
             Regions.Add(id, r);
         }
     }
     catch (Exception e) {
         MainData.ShowMessageWindow("Your Gff3 IDs are not consistent!\n " +
                                    "Change Gff3 loader options to fix them!\n Error: " + e.Message + "\n Offending id:" + id, true);
     }
 }
Ejemplo n.º 18
0
        // 새로운 연결을 추가하는 변이
        // 두 개의 노드를 무작위로 선택해 (단, out에 해당하는 node는 입력 노드가 아님)
        // 두 노드 사이를 잇는 연결이 없다면 새로운 연결을 추가함
        public void MutateConnection(Random random)
        {
            int n1 = RandomNode(false, random);
            int n2 = RandomNode(true, random);

            if (n2 < Pool.Inputs)
            {
                if (n1 < Pool.Inputs)
                {
                    return;
                }
                int _tmp = n1;

                n1 = n2;
                n2 = _tmp;
            }
            if (n1 == n2)
            {
                return;
            }
            if (n1 > n2)
            {
                int _tmp = n1;

                n1 = n2;
                n2 = _tmp;
            }

            if (ContainsLink(n1, n2))
            {
                return;
            }

            Gene gene = new Gene(n1, n2)
            {
                Weight     = random.NextDouble() * 4 - 2,
                Enable     = true,
                Innovation = Pool.NewInnovation()
            };

            Genes.Add(gene);
        }
Ejemplo n.º 19
0
        public Genome(int genomeSize, int geneSize, GenomeFunctions <T> functions, GenomeSettings settings = null)
        {
            if (settings == null)
            {
                this.settings = new GenomeSettings(genomeSize);
            }
            else
            {
                this.settings = settings;
            }
            this.Generation = 1;
            this.Genes      = new List <Gene <T> >(genomeSize);
            this.geneSize   = geneSize;
            this.functions  = functions;

            for (int i = 0; i < Genes.Capacity; i++)
            {
                Genes.Add(new Gene <T>(geneSize, functions, settings));
            }
        }
Ejemplo n.º 20
0
        public INode MutateAddNode()
        {
            int innovation = (int)RandomHelpers.GetRandomBiasingLow(
                Genes.Min(g => g.Innovation), Genes.Max(g => g.Innovation)
                );

            IGene oldGene = Genes.FirstOrDefault(g => g.Innovation <= innovation);

            if (oldGene == null)
            {
                oldGene = Genes[new Random().Next(Genes.Count)];
            }

            INode newNode = new Node(NodeType.Hidden);

            // Disable the old connection
            oldGene.IsExpressed = false;

            // Add new connections
            IGene newGeneIn = new Gene(
                oldGene.NodeOut,
                newNode,
                GetNextInnovation(),
                1
                );

            IGene newGeneOut = new Gene(
                newNode,
                oldGene.NodeIn,
                GetNextInnovation(),
                oldGene.Weight
                );

            Nodes.Add(newNode);

            Genes.Add(newGeneIn);
            Genes.Add(newGeneOut);

            return(newNode);
        }
Ejemplo n.º 21
0
        public void MutateNode()
        {
            if (Genes.Count == 0)
            {
                return;
            }

            Gene gene = Genes[R.Next(0, Genes.Count)];

            if (!gene.enabled)
            {
                return;
            }

            gene.enabled = false;

            StdNeuron neuron = new StdNeuron(this, Neurons.Count + 1);

            Neurons.Add(neuron);

            Genes.Add(new Gene(gene.from, neuron.Index, gene.axon.weight, true, innovation++));
            Genes.Add(new Gene(neuron.Index, gene.axon.destination, 1, true, innovation++));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Add nodes to random connection gene in genome
        /// </summary>
        private void AddNode(Random rnd, ref int innovation, ref int number, List <Gene> allGenes)
        {
            int  index = rnd.Next(0, Genes.Count);
            var  pair  = Genes.ElementAt(index);
            Gene gene  = pair.Value;

            gene.Type = GeneType.Disabled;
            Node node       = null;
            Gene firstGene  = null;
            Gene latterGene = null;
            bool exists     = FindExistingNode(gene, ref node, ref firstGene, ref latterGene, allGenes, ref innovation, ref number);

            if (!exists)
            {
                node       = new Node(NodeType.Hidden, gene.In.Layer + 1, ++number);
                firstGene  = new Gene(gene.In, node, 1f, GeneType.Enabled, ++innovation);
                latterGene = new Gene(node, gene.Out, gene.Weight, GeneType.Enabled, ++innovation);
            }
            // Check if the latter gene connection cannot be from the same layer to the same layer
            if (gene.Out.Layer == node.Layer)
            {
                IncrementLayer(node);
            }

            if (!Genes.ContainsKey(firstGene.Innovation)) // should always go to if branch
            {
                Genes.Add(firstGene.Innovation, firstGene);
                firstGene.In.OutgoingConnections.Add(firstGene);
                if (!exists)
                {
                    var g = firstGene.ShallowCopy();
                    g.Type = GeneType.AddNode;
                    allGenes.Add(g); // still points to nodes in this genome
                }
            }
            else
            {
                ;
            }
            if (!Genes.ContainsKey(latterGene.Innovation)) // should always go to if branch
            {
                Genes.Add(latterGene.Innovation, latterGene);
                latterGene.In.OutgoingConnections.Add(latterGene);
                if (!exists)
                {
                    var g = latterGene.ShallowCopy();
                    g.Type = GeneType.AddNode;
                    allGenes.Add(g); // still points to nodes in this genome
                }
            }
            else
            {
                ;
            }
            if (!Nodes.Contains(node)) // should always go to if branch
            {
                Nodes.Add(node);
            }
            else
            {
                for (int i = 0; i < Nodes.Count; i++)
                {
                    if (node.Number == Nodes[i].Number)
                    {
                        if (ReferenceEquals(node, Nodes[i]))
                        {
                            ;
                        }
                        else
                        {
                            ;
                        }
                    }
                }
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Processes a feature from a GTF gene model file.
        /// </summary>
        /// <param name="feature"></param>
        /// <param name="oneBasedStart"></param>
        /// <param name="oneBasedEnd"></param>
        /// <param name="chrom"></param>
        /// <param name="attributes"></param>
        public void ProcessGtfFeature(MetadataListItem <List <string> > feature, long oneBasedStart, long oneBasedEnd, Chromosome chrom, Dictionary <string, string> attributes)
        {
            bool hasGeneId       = attributes.TryGetValue("gene_id", out string geneId);
            bool hasTranscriptId = attributes.TryGetValue("transcript_id", out string transcriptId);
            bool hasProteinId    = attributes.TryGetValue("protein_id", out string proteinId);
            bool hasExonId       = attributes.TryGetValue("exon_id", out string exonId);
            bool hasSource       = feature.SubItems.TryGetValue("source", out List <string> sourceish);
            bool hasStrand       = feature.SubItems.TryGetValue("strand", out List <string> strandish);
            bool hasFrame        = feature.SubItems.TryGetValue("frame", out List <string> framey);

            string source = hasSource ? sourceish[0] : "";

            if (!hasStrand)
            {
                return;
            }                           // strand is a required to do anything in this program
            string strand = strandish[0];
            int    frame  = 0;

            if (hasFrame)
            {
                int.TryParse(framey[0], out frame);
            }

            // Trim prefixes from the IDs
            string genePrefix       = "gene:";
            string transcriptPrefix = "transcript:";

            if (hasGeneId && geneId.StartsWith(genePrefix))
            {
                string newGeneId = geneId.Substring(genePrefix.Length);
                feature.FreeText.Replace(geneId, newGeneId);
                geneId = newGeneId;
            }
            if (hasTranscriptId && transcriptId.StartsWith(transcriptPrefix))
            {
                string newTranscriptId = transcriptId.Substring(transcriptPrefix.Length);
                feature.FreeText.Replace(transcriptId, newTranscriptId);
                transcriptId = newTranscriptId;
            }
            if (hasProteinId && proteinId.StartsWith(transcriptPrefix))
            {
                proteinId = proteinId.Substring(transcriptPrefix.Length); // transcript id is used for protein id sometimes
            }

            // Catch the transcript features before they go by if available, i.e. if the file doesn't just have exons
            if (feature.Key == "transcript" && (currentTranscript == null || hasTranscriptId && transcriptId != currentTranscript.ID))
            {
                if (currentGene == null || hasGeneId && geneId != currentGene.ID)
                {
                    currentGene = new Gene(geneId, chrom, source, strand, oneBasedStart, oneBasedEnd, feature);
                    Genes.Add(currentGene);
                    GenomeForest.Add(currentGene);
                }

                currentTranscript = new Transcript(transcriptId, currentGene, source, strand, oneBasedStart, oneBasedEnd, null, null, feature);
                currentGene.Transcripts.Add(currentTranscript);
                GenomeForest.Add(currentTranscript);
            }

            if (feature.Key == "exon" || feature.Key == "CDS")
            {
                if (currentGene == null || hasGeneId && geneId != currentGene.ID)
                {
                    currentGene = new Gene(geneId, chrom, source, strand, oneBasedStart, oneBasedEnd, feature);
                    Genes.Add(currentGene);
                    GenomeForest.Add(currentGene);
                }

                if (currentTranscript == null || hasTranscriptId && transcriptId != currentTranscript.ID)
                {
                    if (currentTranscript != null)
                    {
                        Transcript.SetRegions(currentTranscript);
                        currentTranscript.FrameCorrection();
                    }
                    currentTranscript = new Transcript(transcriptId, currentGene, source, strand, oneBasedStart, oneBasedEnd, null, null, feature);
                    currentGene.Transcripts.Add(currentTranscript);
                    GenomeForest.Add(currentTranscript);
                }

                if (feature.Key == "exon")
                {
                    ISequence exon_dna = chrom.Sequence.GetSubSequence(oneBasedStart - 1, oneBasedEnd - oneBasedStart + 1);
                    Exon      exon     = new Exon(currentTranscript, currentTranscript.IsStrandPlus() ? exon_dna : exon_dna.GetReverseComplementedSequence(),
                                                  source, oneBasedStart, oneBasedEnd, chrom.Sequence.ID, strand, null, feature);
                    if (exon.Length() > 0)
                    {
                        currentTranscript.Exons.Add(exon);
                    }
                }
                else if (feature.Key == "CDS")
                {
                    CDS cds = new CDS(currentTranscript, chrom.Sequence.ID, source, strand, oneBasedStart, oneBasedEnd, null, frame);
                    if (hasProteinId)
                    {
                        currentTranscript.ProteinID = proteinId;
                    }
                    if (cds.Length() > 0)
                    {
                        currentTranscript.CodingDomainSequences.Add(cds);
                    }
                }
                else
                { // nothing to do
                }
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Processes a feature from a GFF3 gene model file.
        /// </summary>
        /// <param name="feature"></param>
        /// <param name="oneBasedStart"></param>
        /// <param name="oneBasedEnd"></param>
        /// <param name="chrom"></param>
        /// <param name="attributes"></param>
        public void ProcessGff3Feature(MetadataListItem <List <string> > feature, long oneBasedStart, long oneBasedEnd, Chromosome chrom, Dictionary <string, string> attributes)
        {
            bool hasGeneId       = attributes.TryGetValue("gene_id", out string geneId);
            bool hasTranscriptId = attributes.TryGetValue("transcript_id", out string transcriptId);
            bool hasExonId       = attributes.TryGetValue("exon_id", out string exonId);
            bool hasProteinId    = attributes.TryGetValue("protein_id", out string proteinId);
            bool hasSource       = feature.SubItems.TryGetValue("source", out List <string> sourceish); // false if empty ("." in GFF format)
            bool hasStrand       = feature.SubItems.TryGetValue("strand", out List <string> strandish); // false if empty ("." in GFF format)
            bool hasFrame        = feature.SubItems.TryGetValue("frame", out List <string> framey);     // false if empty ("." in GFF format)

            string source = hasSource ? sourceish[0] : "";

            if (!hasStrand)
            {
                return;
            }                           // strand is a required to do anything in this program
            string strand = strandish[0];
            int    frame  = 0;

            if (hasFrame)
            {
                int.TryParse(framey[0], out frame);
            }

            if (hasGeneId && (currentGene == null || hasGeneId && geneId != currentGene.ID))
            {
                currentGene = new Gene(geneId, chrom, source, strand, oneBasedStart, oneBasedEnd, feature);
                Genes.Add(currentGene);
                GenomeForest.Add(currentGene);
            }

            if (hasTranscriptId && (currentTranscript == null || hasTranscriptId && transcriptId != currentTranscript.ID))
            {
                if (currentTranscript != null)
                {
                    Transcript.SetRegions(currentTranscript);
                    currentTranscript.FrameCorrection();
                }
                currentTranscript = new Transcript(transcriptId, currentGene, source, strand, oneBasedStart, oneBasedEnd, null, null, feature);
                currentGene.Transcripts.Add(currentTranscript);
                GenomeForest.Add(currentTranscript);
            }

            if (hasExonId)
            {
                ISequence exon_dna = chrom.Sequence.GetSubSequence(oneBasedStart - 1, oneBasedEnd - oneBasedStart + 1);
                Exon      exon     = new Exon(currentTranscript, currentTranscript.IsStrandPlus() ? exon_dna : exon_dna.GetReverseComplementedSequence(),
                                              source, oneBasedStart, oneBasedEnd, chrom == null ? "" : chrom.ChromosomeID, strand, null, feature);
                if (exon.Length() > 0)
                {
                    currentTranscript.Exons.Add(exon);
                }
            }
            else if (hasProteinId)
            {
                CDS cds = new CDS(currentTranscript, chrom.Sequence.ID, source, strand, oneBasedStart, oneBasedEnd, null, frame);
                if (cds.Length() > 0)
                {
                    currentTranscript.CodingDomainSequences.Add(cds);
                    currentTranscript.ProteinID = proteinId;
                }
            }
            else // nothing to do
            {
            }
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Add a new Gene
 /// </summary>
 public void addGene()
 {
     Genes.Add(new Gene());
 }