Add the information of a gene

            This adds a gene dict to variant['genes']

            Args:
                gene (dict): A gene dictionary
432456
def add_gene(self, gene):
        
        logger.debug("Adding gene {0} to variant {1}".format(
            gene, self['variant_id']))
        self['genes'].append(gene)
266672
def add_variant(self, chrom, pos, rs_id, ref, alt, qual, filt, info, form=None, genotypes=[]):
        
        variant_info = [chrom, pos, rs_id, ref, alt, qual, filt, info]
        if form:
            variant_info.append(form)
        for individual in genotypes:
            variant_info.append(individual)
        
        variant_line = '\t'.join(variant_info)
        variant = format_variant(
            line = variant_line, 
            header_parser = self.metadata, 
            check_info = self.check_info
        )
        
        if not (self.split_variants and len(variant['ALT'].split(',')) > 1):
            self.variants.append(variant)
            
        # If multiple alternative and split_variants we must split the variant                 
        else:
            for splitted_variant in split_variants(
                                                    variant_dict=variant, 
                                                    header_parser=self.metadata, 
                                                    allele_symbol=self.allele_symbol):
                self.variants.append(splitted_variant)
176579
def gene_ids_of_gene_name(self, gene_name):
        
        results = self._query_gene_ids("gene_name", gene_name)
        if len(results) == 0:
            raise ValueError("Gene name not found: %s" % gene_name)
        return results
1213550
def _add_variants(self, key, value, schema):
        ''' 
        '''
        variants = schema.get('variants')
        obj = {}
        if variants:
            for _key, func in variants.iteritems():
                _value = func(value, self.store)
                obj.update({_key: _value})
        return obj
350304
def _make_variant_locus_id(gene_id, allele_id):
        

        varloci = '-'.join((gene_id, allele_id))
        varloci = '_:' + re.sub(r'(ZFIN)?:', '', varloci)

        return varloci
284044
def update(self, infos):
        """"""
        genes = [i for i in infos if isinstance(i, LearningGene)]
        for gene in genes:
            if (
                self.network.role == "experiment"
                and self.generation > 0
                and random.random() < 0.10
            ):
                self.mutate(gene)
            else:
                self.replicate(gene)
371118
static public void addGeneIDGFF2GeneFeatures(LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList, FeatureList listGenes) throws Exception {
		Collection<String> geneIds = listGenes.attributeValues("gene_id");
		for (String geneid : geneIds) {
			FeatureList gene = listGenes.selectByAttribute("gene_id", geneid);
			FeatureI geneFeature = gene.get(0);
			ChromosomeSequence seq = chromosomeSequenceList.get(geneFeature.seqname());
			geneid = geneid.replaceAll("_", ".G");
			AccessionID geneAccessionID = new AccessionID(geneid);
			GeneSequence geneSequence = null;
			Collection<String> transcriptids = gene.attributeValues("gene_id");
			for (String transcriptid : transcriptids) {
				// get all the individual features (exons, CDS regions, etc.) of this gene
				FeatureList transcriptFeature = listGenes.selectByAttribute("gene_id", transcriptid);
				transcriptid = transcriptid.replaceAll("_", ".G");




				//      String seqName = feature.seqname();
				//FeatureI startCodon = null;
				//FeatureI stopCodon = null;
				Integer startCodonBegin = null;
				Integer stopCodonEnd = null;
				//String startCodonName = "";
				//String stopCodonName = "";


				// now select only the coding regions of this gene
				FeatureList firstFeatures = transcriptFeature.selectByType("First");
				FeatureList terminalFeatures = transcriptFeature.selectByType("Terminal");
				FeatureList internalFeatures = transcriptFeature.selectByType("Internal");
				FeatureList singleFeatures = transcriptFeature.selectByType("Single");
				FeatureList cdsFeatures = new FeatureList();
				cdsFeatures.add(firstFeatures);
				cdsFeatures.add(terminalFeatures);
				cdsFeatures.add(internalFeatures);
				cdsFeatures.add(singleFeatures);
				// sort them
				cdsFeatures = cdsFeatures.sortByStart();
				Strand strand = Strand.POSITIVE;
				FeatureI feature = cdsFeatures.get(0);
				if (feature.location().isNegative()) {
					strand = Strand.NEGATIVE;
				}
				if (startCodonBegin == null) {
					FeatureI firstFeature = cdsFeatures.get(0);
					if (strand == Strand.NEGATIVE) {
						startCodonBegin = firstFeature.location().bioEnd();
					} else {
						startCodonBegin = firstFeature.location().bioStart();
					}
				}

				if (stopCodonEnd == null) {

					FeatureI lastFeature = cdsFeatures.get(cdsFeatures.size() - 1);
					if (strand == Strand.NEGATIVE) {
						stopCodonEnd = lastFeature.location().bioStart();
					} else {
						stopCodonEnd = lastFeature.location().bioEnd();
					}
				}
				//for gtf ordering can be strand based so first is last and last is first
				if (startCodonBegin > stopCodonEnd) {
					int temp = startCodonBegin;
					startCodonBegin = stopCodonEnd;
					stopCodonEnd = temp;
				}

				AccessionID transcriptAccessionID = new AccessionID(transcriptid);
				if (geneSequence == null) {
					geneSequence = seq.addGene(geneAccessionID, startCodonBegin, stopCodonEnd, strand);
					geneSequence.setSource(((Feature) feature).source());
				} else {
					//if multiple transcripts for one gene make sure the gene is defined as the min and max start/end

					if (startCodonBegin < geneSequence.getBioBegin()) {
						geneSequence.setBioBegin(startCodonBegin);
					}
					if (stopCodonEnd > geneSequence.getBioBegin()) {
						geneSequence.setBioEnd(stopCodonEnd);
					}

				}
				TranscriptSequence transcriptSequence = geneSequence.addTranscript(transcriptAccessionID, startCodonBegin, stopCodonEnd);
				/*
				if (startCodon != null) {
					if (startCodonName == null || startCodonName.length() == 0) {
						startCodonName = transcriptid + "-start_codon-" + startCodon.location().bioStart() + "-" + startCodon.location().bioEnd();
					}
					transcriptSequence.addStartCodonSequence(new AccessionID(startCodonName), startCodon.location().bioStart(), startCodon.location().bioEnd());
				}
				if (stopCodon != null) {
					if (stopCodonName == null || stopCodonName.length() == 0) {
						stopCodonName = transcriptid + "-stop_codon-" + stopCodon.location().bioStart() + "-" + stopCodon.location().bioEnd();
					}
					transcriptSequence.addStopCodonSequence(new AccessionID(stopCodonName), stopCodon.location().bioStart(), stopCodon.location().bioEnd());
				}
				*/

				for (FeatureI cdsFeature : cdsFeatures) {
					Feature cds = (Feature) cdsFeature;
					String cdsName = cds.getAttribute("transcript_name");
					if (cdsName == null || cdsName.length() == 0) {
						cdsName = transcriptid + "-cds-" + cds.location().bioStart() + "-" + cds.location().bioEnd();
					}
					AccessionID cdsAccessionID = new AccessionID(cdsName);
					//ExonSequence exonSequence = geneSequence.addExon(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd());
					CDSSequence cdsSequence = transcriptSequence.addCDS(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd(), cds.frame());
					cdsSequence.setSequenceScore(cds.score());
				}
			}
		}

	}
889743
def _add_dict_row(self, feature_dict, key=None):
        
        self._update_internal_column_state(set(feature_dict.keys()))

        # reset the row memoization
        self._row_memo = {}

        if key is not None:
            if key in self._row_name_idx:
                self._rows[self._row_name_idx[key]] = feature_dict
                return
            else:
                self._row_name_idx[key] = len(self._rows)
                self._row_name_list.append(key)

        self._rows.append(feature_dict)
328423
def unArrayify(self, gene):
        
        g = 0
        # if gene is too small an IndexError will be thrown
        for layer in self.layers:
            if layer.type != 'Input':
                for i in range(layer.size):
                    layer.weight[i] = float( gene[g])
                    g += 1
        for connection in self.connections:
            for i in range(connection.fromLayer.size):
                for j in range(connection.toLayer.size):
                    connection.weight[i][j] = gene[g]
                    g += 1
        # if gene is too long we may have a problem
        if len(gene) > g:
            raise IndexError('Argument to unArrayify is too long.', len(gene))
1313511
def parse_kegg_gene_metadata(infile):
    
    metadata = defaultdict(str)

    with open(infile) as mf:
        kegg_parsed = bs_kegg.parse(mf.read())

    # TODO: additional fields can be parsed

    if 'DBLINKS' in kegg_parsed.keys():
        if 'UniProt' in kegg_parsed['DBLINKS']:
            unis = str(kegg_parsed['DBLINKS']['UniProt']).split(' ')
            # TODO: losing other uniprot ids by doing this
            if isinstance(unis, list):
                metadata['uniprot'] = unis[0]
            else:
                metadata['uniprot'] = unis
        if 'NCBI-ProteinID' in kegg_parsed['DBLINKS']:
            metadata['refseq'] = str(kegg_parsed['DBLINKS']['NCBI-ProteinID'])
    if 'STRUCTURE' in kegg_parsed.keys():
        metadata['pdbs'] = str(kegg_parsed['STRUCTURE']['PDB']).split(' ')
    else:
        metadata['pdbs'] = None
    if 'ORGANISM' in kegg_parsed.keys():
        metadata['taxonomy'] = str(kegg_parsed['ORGANISM'])

    return metadata
689409
def get_gene(self, gene_name):
        
        if not gene_name:
            return

        gene_pk = self.genes.get(gene_name)
        if gene_pk:
            return gene_pk

        chrom = self.chromosomes[self.variants.chrom]
        gene = Gene.objects.find(gene_name, chrom, create=True)
        if gene:
            return gene.pk
1140196
def genestatus(args):
    
    p = OptionParser(genestatus.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    idsfile, = args
    data = get_tags(idsfile)
    key = lambda x: x[0].split(".")[0]
    for gene, cc in groupby(data, key=key):
        cc = list(cc)
        tags = [x[-1] for x in cc]
        if "complete" in tags:
            tag = "complete"
        elif "partial" in tags:
            tag = "partial"
        else:
            tag = "pseudogene"
        print("\t".join((gene, tag)))
492504
def add_compound(self, compound):
        
        logger.debug("Adding compound {0} to variant {1}".format(
            compound, self['variant_id']))
        self['compounds'].append(compound)
53391
def add_infos(self, *keyvals, **kwargs):
    """"""
    kv_pairs = []
    for key, val in keyvals:
      key = key.strip()
      val = str(val).strip()
      if ':' in key:
        raise ValueError('info key "{}" must not contain a colon.'.format(key))
      kv_pairs.append((key, val))

    for k, v in kv_pairs:
      if k in self._info:
        raise ValueError('info key "{}" already exists with value {}. '
                         'Cannot add it again with value {}.'.format(k, self._info[k], v))
      self._info[k] = v

    try:
      with open(self._info_file, 'a') as outfile:
        for k, v in kv_pairs:
          outfile.write('{}: {}\n'.format(k, v))
    except IOError:
      if not kwargs.get('ignore_errors', False):
        raise
809486
def _get_genes(self, variant):
        
        transcripts = variant['transcripts']
        ensembl_ids = [transcript['ensembl_id'] for transcript in
                       transcripts if transcript['ensembl_id']]
        hgnc_symbols = [transcript['hgnc_symbol'] for transcript in
                        transcripts if transcript['hgnc_symbol']]
        genes = get_gene_info(ensembl_ids, hgnc_symbols)
        return genes
1308985
def addGeneTargetingReagent(
            self, reagent_id, reagent_label, reagent_type, gene_id,
            description=None):
        

        # TODO add default type to reagent_type
        self.model.addIndividualToGraph(
            reagent_id, reagent_label, reagent_type, description)

        self.graph.addTriple(reagent_id, self.globaltt['targets_gene'], gene_id)

        return
31212
def add_info (self, s):
        
        if s not in self.info:
            self.info.append(s)