Highest priority effect for each unique gene ID
339699
def top_priority_effect_per_gene_id(self):
        """"""
        return OrderedDict(
            (gene_id, top_priority_effect(variant_effects))
            for (gene_id, variant_effects)
            in self.groupby_gene_id().items())
1167150
def _init_objaartall(self):
        """"""
        kws = {
            'sortgo':lambda nt: [nt.NS, nt.dcnt],
            # fmtgo=('{p_fdr_bh:8.2e} {GO} '
            # Formatting for GO terms in grouped GO list
            'fmtgo':('{hdr1usr01:2} {NS} {GO} {s_fdr_bh:8} '
                     '{dcnt:5} {childcnt:3} R{reldepth:02} '
                     '{D1:5} {GO_name} ({study_count} study genes)\n'),
            # Formatting for GO terms listed under each gene
            'fmtgo2':('{hdr1usr01:2} {NS} {GO} {s_fdr_bh:8} '
                      '{dcnt:5} R{reldepth:02} '
                      '{GO_name} ({study_count} study genes)\n'),
            # itemid2name=ensmusg2symbol}
            }
        return AArtGeneProductSetsAll(self.grprdflt, self.hdrobj, **kws)
660073
def gene_list(self, list_id):
        """"""
        return self.query(GeneList).filter_by(list_id=list_id).first()
466713
def best_match(self, seqs, scan_rc=True):
        
        self.set_threshold(threshold=0.0)
        for matches in self.scan(seqs, 1, scan_rc):
            yield [m[0] for m in matches]
1208784
def gene_by_protein_id(self, protein_id):
        
        gene_id = self.gene_id_of_protein_id(protein_id)
        return self.gene_by_id(gene_id)
1327341
def best_genomes(self, n):
        """"""
        def key(g):
            return g.fitness

        return sorted(self.most_fit_genomes, key=key, reverse=True)[:n]
56168
def _add_gene_associations(self, r_id, r_genes, gene_ids, r_tag):
        """"""
        genes = ET.SubElement(
            r_tag, _tag('geneProductAssociation', FBC_V2))
        if isinstance(r_genes, list):
            e = Expression(And(*(Variable(i) for i in r_genes)))
        else:
            e = Expression(r_genes)
        gene_stack = [(e.root, genes)]
        while len(gene_stack) > 0:
            current, parent = gene_stack.pop()
            if isinstance(current, Or):
                gene_tag = ET.SubElement(parent, _tag('or', FBC_V2))
            elif isinstance(current, And):
                gene_tag = ET.SubElement(parent, _tag('and', FBC_V2))
            elif isinstance(current, Variable):
                gene_tag = ET.SubElement(parent, _tag(
                    'geneProductRef', FBC_V2))
                if current.symbol not in gene_ids:
                    id = 'g_' + util.create_unique_id(
                        self._make_safe_id(current.symbol), gene_ids)
                    gene_ids[id] = current.symbol
                    gene_tag.set(_tag('geneProduct', FBC_V2), id)
            if isinstance(current, (Or, And)):
                for item in current:
                    gene_stack.append((item, gene_tag))
906858
def missing_representative_structure(self):
        """"""
        return [x.id for x in self.genes if not self.genes_with_a_representative_structure.has_id(x.id)]
1159976
def liftover_to_genome(pass_pos, gtf):
    """"""

    fixed_pos = []
    for pos in pass_pos:
        if pos["chrom"] not in gtf:
            continue
        db_pos = gtf[pos["chrom"]][0]
        mut = _parse_mut(pos["sv"])
        print([db_pos, pos])
        if db_pos[3] == "+":
            pos['pre_pos'] = db_pos[1] + pos["pre_pos"] + 1
        else:
            pos['pre_pos'] = db_pos[2] - (pos["pre_pos"] - 1)
        pos['chrom'] = db_pos[0]
        pos['nt'] = list(mut[0])
        fixed_pos.append(pos)

    _print_header(fixed_pos)
    for pos in fixed_pos:
        print_vcf(pos)
500920
def njsd(network, ref_gene_expression_dict, query_gene_expression_dict, gene_set):
    
    gene_jsd_dict = dict()
    reference_genes = ref_gene_expression_dict.keys()
    assert len(reference_genes) != 'Reference gene expression profile should have > 0 genes.'

    for gene in gene_set:
        if gene not in network.nodes:
            continue

        neighbors = find_neighbors(network, gene)

        query_expression_vec = get_neighbor_expression_vector(neighbors, query_gene_expression_dict)
        ref_expression_vec = get_neighbor_expression_vector(neighbors, ref_gene_expression_dict)
        assert len(query_expression_vec) == len(ref_expression_vec), 'Topology of reference network and query network differs. Please check.'

        # A gene which has non-expressed neighbors is ignored.
        if np.sum(query_expression_vec) == 0 and np.sum(ref_expression_vec) == 0:
            continue

        query_p_vec = exp2prob(query_expression_vec)
        ref_p_vec = exp2prob(ref_expression_vec)

        gene_jsd_dict[gene] = jsd(query_p_vec, ref_p_vec)

    return np.mean(list(gene_jsd_dict.values()))
254543
def get_coords(data):
    
    for category, vtypes in [("LOH", {"LOSS", "HETEROZYGOSITY"}),
                             ("amplification", {"AMPLIFICATION"})]:
        out = tz.get_in([category, dd.get_genome_build(data)], _COORDS, {})
        priority_file = dd.get_svprioritize(data)
        if priority_file:
            if os.path.basename(priority_file).find("civic") >= 0:
                for chrom, start, end, gene in _civic_regions(priority_file, vtypes, dd.get_disease(data)):
                    out[gene] = (chrom, start, end)
            elif os.path.basename(priority_file).find(".bed") >= 0:
                for line in utils.open_gzipsafe(priority_file):
                    parts = line.strip().split("\t")
                    if len(parts) >= 4:
                        chrom, start, end, gene = parts[:4]
                        out[gene] = (chrom, int(start), int(end))
        yield category, out
518077
def _do_prioritize(items):
    
    if not any("tumoronly-prioritization" in dd.get_tools_off(d) for d in items):
        if vcfutils.get_paired_phenotype(items[0]):
            has_tumor = False
            has_normal = False
            for sub_data in items:
                if vcfutils.get_paired_phenotype(sub_data) == "tumor":
                    has_tumor = True
                elif vcfutils.get_paired_phenotype(sub_data) == "normal":
                    has_normal = True
            return has_tumor and not has_normal
156058
def genes_by_name(self, gene_name):
        
        gene_ids = self.gene_ids_of_gene_name(gene_name)
        return [self.gene_by_id(gene_id) for gene_id in gene_ids]
572992
def genes_with_a_representative_structure(self):
        """"""
        tmp = DictList(x for x in self.genes if x.protein.representative_structure)
        return DictList(y for y in tmp if y.protein.representative_structure.structure_file)
230535
def gene_id_of_associated_transcript(effect):
    
    return apply_to_transcript_if_exists(
        effect=effect,
        fn=lambda t: t.gene_id,
        default=None)
173375
def best_score(self, seqs, scan_rc=True, normalize=False):
        
        self.set_threshold(threshold=0.0)
        if normalize and len(self.meanstd) == 0:
            self.set_meanstd()
            means = np.array([self.meanstd[m][0] for m in self.motif_ids])
            stds = np.array([self.meanstd[m][1] for m in self.motif_ids])

        for matches in self.scan(seqs, 1, scan_rc):
            scores = np.array([sorted(m, key=lambda x: x[0])[0][0] for m in matches if len(m) > 0])
            if normalize:
                scores = (scores - means) / stds
            yield scores
420092
def filter_missing(self):
        """"""

        missing             = None
        locus_count         = 0

        # Filter out individuals according to missingness
        self.genotype_file.seek(0)
        for genotypes in self.genotype_file:
            genotypes = genotypes.split()
            chr, rsid, junk, pos = genotypes[0:4]
            if DataParser.boundary.TestBoundary(chr, pos, rsid):
                locus_count += 1
                allelic_data = numpy.array(genotypes[4:], dtype="S2").reshape(-1, 2)
                if missing is None:
                    missing             = numpy.zeros(allelic_data.shape[0], dtype='int8')
                missing += (numpy.sum(0+(allelic_data==DataParser.missing_representation), axis=1)/2)

        max_missing = DataParser.ind_miss_tol * locus_count
        dropped_individuals = 0+(max_missing<missing)

        self.ind_mask[:,0] = self.ind_mask[:,0]|dropped_individuals
        self.ind_mask[:,1] = self.ind_mask[:,1]|dropped_individuals

        valid_individuals = numpy.sum(self.ind_mask==0)
        max_missing = DataParser.snp_miss_tol * valid_individuals

        self.locus_count = 0
        # We can't merge these two iterations since we need to know which individuals
        # to consider for filtering on MAF
        dropped_snps = []
        self.genotype_file.seek(0)
        for genotypes in self.genotype_file:
            genotypes = genotypes.split()
            chr, rsid, junk, pos = genotypes[0:4]
            chr = int(chr)
            pos = int(pos)
            if DataParser.boundary.TestBoundary(chr, pos, rsid):
                allelic_data = numpy.ma.MaskedArray(numpy.array(genotypes[4:], dtype="S2").reshape(-1, 2), self.ind_mask).compressed()
                missing = numpy.sum(0+(allelic_data==DataParser.missing_representation))
                if missing > max_missing:
                    DataParser.boundary.dropped_snps[int(chr)].add(int(pos))
                    dropped_snps.append(rsid)
                else:
                    self.locus_count += 1