A convenience method to uniformly create variant loci.
        If we want to materialize these in the monarch space,
        then we wrap with the self.make_id function.
        :param gene_id:
        :param allele_id:
        :return:
350304
def _make_variant_locus_id(gene_id, allele_id):
        

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

        return varloci
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)
52409
def variants(self, case_id, skip=0, count=1000, filters=None):
        """"""
        filters = filters or {}
        logger.debug("Fetching case with case_id: {0}".format(case_id))
        case_obj = self.case(case_id)
        plugin, case_id = self.select_plugin(case_obj)
        self.filters = plugin.filters

        gene_lists = (self.gene_list(list_id) for list_id
                      in filters.get('gene_lists', []))
        nested_geneids = (gene_list.gene_ids for gene_list in gene_lists)
        gene_ids = set(itertools.chain.from_iterable(nested_geneids))

        if filters.get('gene_ids'):
            filters['gene_ids'].extend(gene_ids)
        else:
            filters['gene_ids'] = gene_ids
        variants = plugin.variants(case_id, skip, count, filters)
        return variants
1148990
def allelefreq(args):
    
    p = OptionParser(allelefreq.__doc__)
    p.add_option("--nopanels", default=False, action="store_true",
                 help="No panel labels A, B, ...")
    p.add_option("--usereport", help="Use allele frequency in report file")
    opts, args, iopts = p.set_image_options(args, figsize="9x13")

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

    loci, = args
    fig, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = plt.subplots(ncols=2, nrows=3,
                                                 figsize=(iopts.w, iopts.h))
    plt.tight_layout(pad=4)
    if opts.usereport:
        treds, df = read_treds(tredsfile=opts.usereport)
    else:
        treds, df = read_treds()

    df = df.set_index(["abbreviation"])

    axes = (ax1, ax2, ax3, ax4, ax5, ax6)
    loci = loci.split(",")
    for ax, locus in zip(axes, loci):
        plot_allelefreq(ax, df, locus)

    # Delete unused axes
    for ax in axes[len(loci):]:
        ax.set_axis_off()

    root = fig.add_axes([0, 0, 1, 1])
    pad = .03
    if not opts.nopanels:
        panel_labels(root, ((pad / 2, 1 - pad, "A"), (.5 + pad, 1 - pad, "B"),
                        (pad / 2, 2 / 3. - pad / 2, "C"), (.5 + pad, 2 / 3. - pad / 2, "D"),
                        (pad / 2, 1 / 3. , "E"), (.5 + pad, 1 / 3. , "F"),
                        ))
    normalize_axes(root)

    image_name = "allelefreq." + iopts.format
    savefig(image_name, dpi=iopts.dpi, iopts=iopts)
860718
def _get_genes(self, variant):
        
        ensembl_ids = []
        hgnc_symbols = []
        
        for transcript in variant.transcripts:
            if transcript.ensembl_id:
                ensembl_ids.append(transcript.ensembl_id)
            if transcript.hgnc_symbol:
                hgnc_symbols.append(transcript.hgnc_symbol)
        
        genes = get_gene_info(
                        ensembl_ids=ensembl_ids, 
                        hgnc_symbols=hgnc_symbols
                        )
        return genes
800909
def process_mgi_relationship_transgene_genes(self, limit=None):
        
        if self.test_mode:
            graph = self.testgraph
        else:
            graph = self.graph
        LOG.info("getting transgene genes")
        raw = '/'.join((self.rawdir, 'mgi_relationship_transgene_genes'))
        geno = Genotype(graph)
        col = [
            'rel_key', 'allele_key', 'allele_id', 'allele_label', 'category_key',
            'category_name', 'property_key', 'property_name', 'gene_num'
        ]
        with open(raw, 'r', encoding="utf8") as csvfile:
            filereader = csv.reader(csvfile, delimiter='\t', quotechar='\"')
            header = next(filereader)
            if header != col:
                LOG.error('expected columns:  %s\n\tBut got:\n%s', col, header)
            for row in filereader:
                # rel_key,
                allele_key = int(row[col.index('allele_key')])
                allele_id = row[col.index('allele_id')]
                # allele_label,
                # category_key,
                # category_name,
                # property_key,
                # property_name,
                gene_num = int(row[col.index('gene_num')])

                if self.test_mode and allele_key not in self.test_keys.get('allele')\
                        and gene_num not in self.test_ids:
                    continue

                gene_id = 'NCBIGene:' + str(gene_num)

                # geno.addParts(gene_id, allele_id, self.globaltt['has_variant_part'])
                seqalt_id = self.idhash['seqalt'].get(allele_key)
                if seqalt_id is None:
                    seqalt_id = allele_id
                geno.addSequenceDerivesFrom(seqalt_id, gene_id)

                if not self.test_mode and limit is not None and \
                        filereader.line_num > limit:
                    break

        return
482974
def process_genotypes(self, data):
        
        # Get a list of uniq entries in the data, except for missing
        alleles = list(set(data[4:]) - set(DataParser.missing_representation))
        if len(alleles) > 2:
            raise TooManyAlleles(chr=self.chr, rsid=self.rsid, alleles=alleles)

        # We don't have a way to know this in advance, so we want to just iterate onward
        # if we encounter one of these
        if len(alleles) == 1:
            raise TooFewAlleles(chr=self.chr, rsid=self.rsid, alleles=alleles)

        # Strip out any excluded individuals
        allelic_data = numpy.ma.MaskedArray(numpy.array(data[4:], dtype="S2"), self.ind_mask).compressed().reshape(-1, 2)

        maj_allele_count = numpy.sum(allelic_data==alleles[0])

        min_allele_count = numpy.sum(allelic_data==alleles[1])

        effect_allele_count = min_allele_count
        if min_allele_count > maj_allele_count:
            alleles = [alleles[1], alleles[0]]
            allele_count = maj_allele_count
            maj_allele_count = min_allele_count
            min_allele_count = allele_count

        #genotypes = []
        major_allele       = alleles[0]
        minor_allele       = alleles[1]

        # Genotypes represent the sum of minor alleles at each sample
        genotype_data = numpy.sum(allelic_data==minor_allele, axis=1)
        missing_alleles = allelic_data[:, 0]==DataParser.missing_representation
        genotype_data[missing_alleles] = DataParser.missing_storage
        hetero_count = numpy.sum(genotype_data==1)

        return (genotype_data,
                major_allele,
                minor_allele,
                hetero_count,
                maj_allele_count,
                min_allele_count,
                numpy.sum(missing_alleles),
                effect_allele_count)
213082
def partition_loci(self,verbose=False):
    
    self.g.merge_cycles()
    #sys.stderr.write(self.g.get_report()+"\n")
    gs = self.g.partition_graph(verbose=verbose)
    tls = [] # makea list of transcript loci
    for g in gs:
      tl = TranscriptLoci()
      tl.merge_rules = self.merge_rules
      ns = g.get_nodes()
      for n in [x.payload for x in ns]:
        for tx in n:
          tl.add_transcript(tx)
      if len(tl.g.get_nodes()) > 0:
        tls.append(tl)
    #print '-----------------------' 
    #names = []
    #for tl in tls:
    #  for tx in tl.get_transcripts():
    #    names.append(tx.get_gene_name())
    #for name in sorted(names):
    #  print name
    #print '--------------------------'
    return tls
1199791
private void addHomozygousGenotype(Variant variant, int numAllele, String[] alternateAlleles, VariantStats stats, String[] homCounts) {
        if (homCounts.length == alternateAlleles.length) {
            for (int i = 0; i < homCounts.length; i++) {
                Integer alleles[] = new Integer[2];
                getHomozygousGenotype(i + 1, alleles);
                String gt = VariantVcfFactory.mapToMultiallelicIndex(alleles[0], numAllele) + "/" + VariantVcfFactory.mapToMultiallelicIndex(alleles[1], numAllele);
                Genotype genotype = new Genotype(gt, variant.getReference(), alternateAlleles[numAllele]);
                stats.addGenotype(genotype, Integer.parseInt(homCounts[i]));
            }
        }
    }
148223
def _get_other_allele_by_zygosity(allele_id, zygosity):
        
        other_allele = None
        if zygosity == 'homozygous':
            other_allele = allele_id
        elif zygosity == 'hemizygous':
            other_allele = '0'
        elif zygosity == 'unknown':  # we'll use this as a convention
            other_allele = '?'
        elif zygosity == 'complex':  # transgenics
            other_allele = '0'
        elif zygosity == 'heterozygous':
            # passing on hets until a different fxn
            pass
        else:
            LOG.warning("Unconfigured zygosity: %s", zygosity)

        return other_allele
1370937
def _set_variant_id(self, variant_id=None):
        """"""
        if not variant_id:
            variant_id = '_'.join([
                self.CHROM,
                str(self.POS),
                self.REF,
                self.ALT
                ])

        logger.debug("Updating variant id to {0}".format(
            variant_id))

        self['variant_id'] = variant_id
892685
def reads_to_dataframe(variants_and_allele_reads):
    
    df_builder = DataFrameBuilder(
        AlleleRead,
        extra_column_fns={
            "gene": lambda variant, _: ";".join(variant.gene_names),
        })
    for variant, allele_reads in variants_and_allele_reads:
        df_builder.add_many(variant, allele_reads)
    return df_builder.to_dataframe()
432456
def add_gene(self, gene):
        
        logger.debug("Adding gene {0} to variant {1}".format(
            gene, self['variant_id']))
        self['genes'].append(gene)
765746
@Override
    public LazyData createGenotypeMap(String str, List<Allele> alleles, String chr, int pos) {
        if (genotypeParts == null) {
            genotypeParts = new String[header.getColumnCount() - NUM_STANDARD_FIELDS];
        }

        int nParts = ParsingUtils.split(str, genotypeParts, VCFConstants.FIELD_SEPARATOR_CHAR);
        if (nParts != genotypeParts.length) {
            generateException("there are " + (nParts - 1)
                    + " genotypes while the header requires that " + (genotypeParts.length - 1)
                    + " genotypes be present for all records at " + chr + ":" + pos, lineNo);
        }

        ArrayList<Genotype> genotypes = new ArrayList<>(nParts);
        // get the format keys
        List<String> genotypeKeys = ParsingUtils.split(genotypeParts[0], VCFConstants.GENOTYPE_FIELD_SEPARATOR_CHAR);

        // cycle through the sample names
        Iterator<String> sampleNameIterator = header.getGenotypeSamples().iterator();

        // clear out our allele mapping
        alleleMap.clear();

        // cycle through the genotype strings
        for (int genotypeOffset = 1; genotypeOffset < nParts; genotypeOffset++) {
            List<String> genotypeValues = ParsingUtils.split(genotypeParts[genotypeOffset], VCFConstants.GENOTYPE_FIELD_SEPARATOR_CHAR);

            final String sampleName = sampleNameIterator.next();
            final GenotypeBuilder gb = new GenotypeBuilder(sampleName);

            // check to see if the value list is longer than the key list, which is a problem
            if (genotypeKeys.size() < genotypeValues.size()) {
                generateException("There are too many keys for the sample " + sampleName + ", "
                        + "keys = " + parts[8] + ", "
                        + "values = " + parts[genotypeOffset]);
            }

            int genotypeAlleleLocation = -1;
            if (!genotypeKeys.isEmpty()) {
                gb.maxAttributes(genotypeKeys.size() - 1);


                for (int i = 0; i < genotypeKeys.size(); i++) {
                    final String gtKey = genotypeKeys.get(i);
                    boolean missing = i >= genotypeValues.size();

                    // todo -- all of these on the fly parsing of the missing value should be static constants
                    if (gtKey.equals(VCFConstants.GENOTYPE_KEY)) {
                        genotypeAlleleLocation = i;
                        // opencb modification: add ALL the fields to the attributes. null for missing values!
                        gb.attribute(gtKey, genotypeValues.get(i));
                    } else if (missing) {
                        // if its truly missing (there no provided value) skip adding it to the attributes
                        // opencb modification: add ALL the fields to the attributes. null for missing values!
                        gb.attribute(gtKey, null);
                    } else if (gtKey.equals(VCFConstants.GENOTYPE_FILTER_KEY)) {
                        final List<String> filters = parseFilters(getCachedString(genotypeValues.get(i)));
                        if (filters != null) {
                            gb.filters(filters);
                        }
                        // opencb modification: add ALL the fields to the attributes. null for missing values!
                        gb.attribute(gtKey, filters);
                    } else if (genotypeValues.get(i).equals(VCFConstants.MISSING_VALUE_v4)) {
                        // don't add missing values to the map
                        // opencb modification: add ALL the fields to the attributes. null for missing values!
                        gb.attribute(gtKey, null);
                    } else {
                        if (gtKey.equals(VCFConstants.GENOTYPE_QUALITY_KEY)) {
                            if (genotypeValues.get(i).equals(VCFConstants.MISSING_GENOTYPE_QUALITY_v3)) {
                                gb.noGQ();
                            } else {
                                gb.GQ((int)Math.round(Double.valueOf(genotypeValues.get(i))));
                            }
                        } else if (gtKey.equals(VCFConstants.GENOTYPE_ALLELE_DEPTHS)) {
                            gb.AD(decodeInts(genotypeValues.get(i)));
                        } else if (gtKey.equals(VCFConstants.GENOTYPE_PL_KEY)) {
                            gb.PL(decodeInts(genotypeValues.get(i)));
                        } else if (gtKey.equals(VCFConstants.GENOTYPE_LIKELIHOODS_KEY)) {
                            gb.PL(GenotypeLikelihoods.fromGLField(genotypeValues.get(i)).getAsPLs());
                        } else if (gtKey.equals(VCFConstants.DEPTH_KEY)) {
                            gb.DP(Integer.valueOf(genotypeValues.get(i)));
                        }
                        // opencb modification: add ALL the fields to the attributes. null for missing values!
                        gb.attribute(gtKey, genotypeValues.get(i));
                    }
                }
            }

            // check to make sure we found a genotype field if our version is less than 4.1 file
            if (!version.isAtLeastAsRecentAs(VCFHeaderVersion.VCF4_1) && genotypeAlleleLocation == -1) {
                generateException("Unable to find the GT field for the record; the GT field is required before VCF4.1");
            }
            if (genotypeAlleleLocation > 0) {
                generateException("Saw GT field at position "
                        + genotypeAlleleLocation + ", but it must be at the first position for genotypes when present");
            }

            final List<Allele> gTalleles = (genotypeAlleleLocation == -1
                    ? new ArrayList<>(0)
                    : parseGenotypeAlleles(genotypeValues.get(genotypeAlleleLocation), alleles, alleleMap));
            gb.alleles(gTalleles);
            gb.phased(genotypeAlleleLocation != -1
                    && genotypeValues.get(genotypeAlleleLocation).indexOf(VCFConstants.PHASED) != -1);

            // add it to the list
            try {
                genotypes.add(gb.make());
            } catch (TribbleException e) {
                throw new TribbleException.InternalCodecException(e.getMessage() + ", at position " + chr + ":" + pos);
            }
        }

        return new LazyGenotypesContext.LazyData(genotypes, header.getSampleNamesInOrder(), header.getSampleNameToOffset());
    }
903857
def create(genome, config, time_constant):
        
        genome_config = config.genome_config
        required = required_for_output(genome_config.input_keys, genome_config.output_keys, genome.connections)

        # Gather inputs and expressed connections.
        node_inputs = {}
        for cg in itervalues(genome.connections):
            if not cg.enabled:
                continue

            i, o = cg.key
            if o not in required and i not in required:
                continue

            if o not in node_inputs:
                node_inputs[o] = [(i, cg.weight)]
            else:
                node_inputs[o].append((i, cg.weight))

        node_evals = {}
        for node_key, inputs in iteritems(node_inputs):
            node = genome.nodes[node_key]
            activation_function = genome_config.activation_defs.get(node.activation)
            aggregation_function = genome_config.aggregation_function_defs.get(node.aggregation)
            node_evals[node_key] = CTRNNNodeEval(time_constant,
                                                 activation_function,
                                                 aggregation_function,
                                                 node.bias,
                                                 node.response,
                                                 inputs)

        return CTRNN(genome_config.input_keys, genome_config.output_keys, node_evals)
62558
def runGetVariant(self, id_):
        
        compoundId = datamodel.VariantCompoundId.parse(id_)
        dataset = self.getDataRepository().getDataset(compoundId.dataset_id)
        variantSet = dataset.getVariantSet(compoundId.variant_set_id)
        gaVariant = variantSet.getVariant(compoundId)
        # TODO variant is a special case here, as it's returning a
        # protocol element rather than a datamodel object. We should
        # fix this for consistency.
        jsonString = protocol.toJson(gaVariant)
        return jsonString
249872
def from_gene_ids_and_names(cls, gene_names: Dict[str, str]):
        """"""
        genes = [ExpGene(id_, name=name) for id_, name in gene_names.items()]
        return cls.from_genes(genes)