Convert AA variant to an hgvs representation

        :param variant: contains start, del, and ins
        :type variant: dict
        :param acc: protein accession
        :type acc: str
        :return hgvs string
        :rtype str
190783
def _convert_to_sequence_variants(self, variant, acc):
        
        start = variant['start']
        insertion = ''.join(variant['ins'])
        deletion = ''.join(variant['del'])

        # defaults
        is_dup = False    # assume not dup
        fsext_len = None    # fs or ext length
        is_sub = False
        is_ext = False

        if start == 1:    # initial methionine is modified
            aa_start = aa_end = AAPosition(base=start, aa=deletion)
            ref = ''
            alt = ''
            self._is_init_met = True
            self._is_ambiguous = True    # side-effect

        if insertion and insertion.find("*") == 0:    # stop codon at variant position
            aa_start = aa_end = AAPosition(base=start, aa=deletion[0])
            ref = ''
            alt = '*'
            is_sub = True

        elif start == len(self._ref_seq):    # extension
            if self._alt_seq[-1] == '*':
                fsext_len = len(insertion) - len(deletion)    # don't include the former stop codon
            else:
                fsext_len = '?'
            subst_at_stop_codon = insertion[0]

            aa_start = aa_end = AAPosition(base=start, aa='*')
            ref = ''
            alt = subst_at_stop_codon
            is_ext = True

        elif self._is_frameshift:    # frameshift
            aa_start = aa_end = AAPosition(base=start, aa=deletion[0])
            ref = ''

            try:
                fsext_len = str(
                    insertion.index("*") + 1)    # start w/ 1st change; ends w/ * (inclusive)
            except ValueError:
                fsext_len = "?"

            alt = insertion[0]

        else:    # no frameshift - sub/delins/dup
            if insertion == deletion:    # silent
                aa_start = aa_end = AAPosition(base=start, aa=deletion)
                ref = alt = ''

            elif len(insertion) == len(deletion) == 1:    # substitution
                aa_start = aa_end = AAPosition(base=start, aa=deletion)
                ref = ''
                alt = insertion
                is_sub = True

            elif len(deletion) > 0:    # delins OR deletion OR stop codon at variant position
                ref = deletion
                end = start + len(deletion) - 1
                if len(insertion) > 0:    # delins
                    aa_start = AAPosition(base=start, aa=deletion[0])
                    if end > start:
                        aa_end = AAPosition(base=end, aa=deletion[-1])
                    else:
                        aa_end = aa_start
                    alt = insertion

                else:    # deletion OR stop codon at variant position
                    if len(deletion) + start == len(
                            self._ref_seq):    # stop codon at variant position
                        aa_start = AAPosition(base=start, aa=deletion[0])
                        aa_end = AAPosition(base=start, aa=deletion[0])
                        ref = ''
                        alt = '*'
                        is_sub = True
                    else:    # deletion
                        aa_start = AAPosition(base=start, aa=deletion[0])
                        if end > start:
                            aa_end = AAPosition(base=end, aa=deletion[-1])
                        else:
                            aa_end = aa_start
                        alt = None

            elif len(deletion) == 0:    # insertion OR duplication OR extension

                is_dup, dup_start = self._check_if_ins_is_dup(start, insertion)

                if is_dup:    # duplication
                    dup_end = dup_start + len(insertion) - 1
                    aa_start = AAPosition(base=dup_start, aa=insertion[0])
                    aa_end = AAPosition(base=dup_end, aa=insertion[-1])
                    ref = alt = None

                else:    # insertion
                    start -= 1
                    end = start + 1

                    aa_start = AAPosition(base=start, aa=self._ref_seq[start - 1])
                    aa_end = AAPosition(base=end, aa=self._ref_seq[end - 1])
                    ref = None
                    alt = insertion

            else:    # should never get here
                raise ValueError("unexpected variant: {}".format(variant))

        var_p = self._create_variant(
            aa_start,
            aa_end,
            ref,
            alt,
            fsext_len=fsext_len,
            is_dup=is_dup,
            acc=acc,
            is_ambiguous=self._is_ambiguous,
            is_sub=is_sub,
            is_ext=is_ext,
            is_init_met=self._is_init_met
        )

        return var_p
398238
def getVariantId(self, gaVariant):
        
        md5 = self.hashVariant(gaVariant)
        compoundId = datamodel.VariantCompoundId(
            self.getCompoundId(), gaVariant.reference_name,
            str(gaVariant.start), md5)
        return str(compoundId)
29404
public Map<String, String> getAvailableVariantMap(Map<String, VariantSet> variants,
			Map<String, String> curVariants) {

		Map<String, String> availableVariantMap = new HashMap<>();
		for (Entry<String, VariantSet> entry : variants.entrySet()) {
			String variantType = entry.getKey();
			VariantSet variantSet = entry.getValue();
			String variant = variantSet.getDefaultVariant();
			if (curVariants.containsKey(variantType)) {
				String curVariant = curVariants.get(variantType);
				VariantResolver resolver = variantResolvers.get(variantType);
				if (resolver != null) {
					variant = resolver.getAvailableVariant(curVariant, variants.get(variantType));
					if (variant == null) {
						variant = variants.get(variantType).getDefaultVariant();
					}
				} else {
					throw new BundlingProcessException(
							"Unable to find variant resolver for variant type '" + variantType + "'");
				}
			}
			availableVariantMap.put(variantType, variant);
		}
		return availableVariantMap;
	}
532509
def getVC(self):
        
        _Cr = decompose_GxE(self.fr['Cr'])
        RV = {}
        for key in list(_Cr.keys()):
            RV['var_%s' % key] = sp.array([var_CoXX(_Cr[key], self.Xr)])
        RV['var_g'] = sp.array([var_CoXX(self.fr['Cg'], self.XXh)])
        RV['var_n'] = sp.array([var_CoXX(self.fr['Cn'], sp.eye(self.XXh.shape[0]))])
        return RV
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
466653
def getVariantSet(self, id_):
        
        if id_ not in self._variantSetIdMap:
            raise exceptions.VariantSetNotFoundException(id_)
        return self._variantSetIdMap[id_]
1188216
private static String reduceVariant(final String variant){
		if (isEmpty(variant))
			throw new AssertionError("Shouldn't happen, can't reduce non existent variant");
		
		int indexOfUnderscore = variant.lastIndexOf('_');
		if (indexOfUnderscore==-1)
			return "";
		return variant.substring(0, indexOfUnderscore);
	}
1317944
def get_variant_value(identifier)
      data = Gxapi.with_error_handling do
        Timeout::timeout(2.0) do
          Gxapi.cache.fetch(self.cache_key(identifier)) do
            @interface.get_variant(identifier).to_hash
          end
        end
      end
      Ostruct.new(
        data.is_a?(Hash) ? data : self.default_values
      )
    end
857452
def median_vaf_purity(row, cohort, **kwargs):
    
    patient_id = row["patient_id"]
    patient = cohort.patient_from_id(patient_id)
    variants = cohort.load_variants(patients=[patient], filter_fn=no_filter)
    if patient_id in variants.keys():
        variants = variants[patient_id]
    else:
        return np.nan
    def grab_vaf(variant):
        filterable_variant = FilterableVariant(variant, variants, patient)
        return variant_stats_from_variant(variant, filterable_variant.variant_metadata).tumor_stats.variant_allele_frequency
    vafs = [grab_vaf(variant) for variant in variants]
    return 2 * pd.Series(vafs).median()
1245259
def _extract_variants(address, variants_str):
  
  def entries():
    for entry in variants_str.split(','):
      key, _, value = entry.partition('=')
      if not key or not value:
        raise ValueError('Invalid variants after the @ in: {}'.format(address))
      yield (key, value)
  return tuple(entries())
691958
def translateIndelGenotypeFromVCF(vcf_genotypes, ref):
    ''''''

    # indels
    def getPrefix(s1, s2):
        '''get common prefix of strings s1 and s2.'''
        n = min(len(s1), len(s2))
        for x in range(n):
            if s1[x] != s2[x]:
                return s1[:x]
        return s1[:n]

    def getSuffix(s1, s2):
        '''get common sufix of strings s1 and s2.'''
        n = min(len(s1), len(s2))
        if s1[-1] != s2[-1]:
            return ""
        for x in range(-2, -n - 1, -1):
            if s1[x] != s2[x]:
                return s1[x + 1:]
        return s1[-n:]

    def getGenotype(variant, ref):

        if variant == ref:
            return "*", 0

        if len(ref) > len(variant):
            # is a deletion
            if ref.startswith(variant):
                return "-%s" % ref[len(variant):], len(variant) - 1
            elif ref.endswith(variant):
                return "-%s" % ref[:-len(variant)], -1
            else:
                prefix = getPrefix(ref, variant)
                suffix = getSuffix(ref, variant)
                shared = len(prefix) + len(suffix) - len(variant)
                # print "-", prefix, suffix, ref, variant, shared, len(prefix), len(suffix), len(ref)
                if shared < 0:
                    raise ValueError()
                return "-%s" % ref[len(prefix):-(len(suffix) - shared)], len(prefix) - 1

        elif len(ref) < len(variant):
            # is an insertion
            if variant.startswith(ref):
                return "+%s" % variant[len(ref):], len(ref) - 1
            elif variant.endswith(ref):
                return "+%s" % variant[:len(ref)], 0
            else:
                prefix = getPrefix(ref, variant)
                suffix = getSuffix(ref, variant)
                shared = len(prefix) + len(suffix) - len(ref)
                if shared < 0:
                    raise ValueError()

                return "+%s" % variant[len(prefix):-(len(suffix) - shared)], len(prefix)
        else:
            assert 0, "snp?"

    # in pileup, the position refers to the base
    # after the coordinate, hence subtract 1
    # pos -= 1

    genotypes, offsets = [], []
    is_error = True

    for variant in vcf_genotypes:
        try:
            g, offset = getGenotype(variant, ref)
        except ValueError:
            break

        genotypes.append(g)
        if g != "*":
            offsets.append(offset)

    else:
        is_error = False

    if is_error:
        raise ValueError()

    assert len(set(offsets)) == 1, "multiple offsets for indel"
    offset = offsets[0]

    genotypes = "/".join(genotypes)
    return genotypes, offset
50586
def build_hgvsp(self):
        

        variants = []

        if not self._is_ambiguous and len(self._alt_seq) > 0:

            do_delins = True
            if self._ref_seq == self._alt_seq:
                # Silent p. variant
                start = self._alt_data.variant_start_aa
                if start - 1 < len(self._ref_seq):
                    deletion = self._ref_seq[start - 1]
                    insertion = deletion
                else:
                    start = ""
                    deletion = ""
                    insertion = ""
                    self._is_frameshift = False
                variants.append({"start": start, "ins": insertion, "del": deletion})
                do_delins = False
            elif self._is_substitution:
                if len(self._ref_seq) == len(self._alt_seq):
                    diff_pos = [(i, self._ref_seq[i], self._alt_seq[i])
                                for i in range(len(self._ref_seq))
                                if self._ref_seq[i] != self._alt_seq[i]]
                    if len(diff_pos) == 1:
                        (start, deletion, insertion) = diff_pos[0]
                        variants.append({"start": start + 1, "ins": insertion, "del": deletion})
                        do_delins = False

            if do_delins:
                if self._alt_data.is_frameshift:
                    start = self._alt_data.variant_start_aa - 1
                    while self._ref_seq[start] == self._alt_seq[start]:
                        start += 1
                    insertion = list(self._alt_seq[start:])
                    deletion = list(self._ref_seq[start:])
                    variants.append({"start": start + 1, "ins": insertion, "del": deletion})

                else:    # non-frameshifting delins or dup
                    # get size diff from diff in ref/alt lengths
                    start = self._alt_data.variant_start_aa - 1
                    delta = len(self._alt_seq) - len(self._ref_seq)
                    while self._ref_seq[start] == self._alt_seq[start]:
                        start += 1
                    offset = start + abs(delta)

                    if delta > 0:    # net insertion
                        insertion = list(self._alt_seq[start:offset])
                        deletion = []
                        ref_sub = self._ref_seq[start:]
                        alt_sub = self._alt_seq[offset:]
                    elif delta < 0:    # net deletion
                        insertion = []
                        deletion = list(self._ref_seq[start:offset])
                        ref_sub = self._ref_seq[offset:]
                        alt_sub = self._alt_seq[start:]
                    else:
                        insertion = []
                        deletion = []
                        ref_sub = self._ref_seq[start:]
                        alt_sub = self._alt_seq[start:]

                    # from start, get del/ins out to last difference
                    diff_indices = [i for i in range(len(ref_sub)) if ref_sub[i] != alt_sub[i]]
                    if not diff_indices and not deletion and insertion[0] == '*':
                        diff_indices.append(0)
                    if diff_indices:
                        max_diff = diff_indices[-1] + 1
                        insertion.extend(list(alt_sub[:max_diff]))
                        deletion.extend(list(ref_sub[:max_diff]))

                    variants.append({"start": start + 1, "ins": insertion, "del": deletion})

            if DBG:
                print(variants)

        if self._is_ambiguous:
            var_ps = [
                self._create_variant(
                    None,
                    None,
                    '',
                    '',
                    acc=self._protein_accession,
                    is_ambiguous=self._is_ambiguous)
            ]
        elif len(self._alt_seq) == 0:
            var_ps = [
                self._create_variant(
                    None,
                    None,
                    '',
                    '',
                    acc=self._protein_accession,
                    is_ambiguous=self._is_ambiguous,
                    is_no_protein=True)
            ]
        else:
            var_ps = [
                self._convert_to_sequence_variants(x, self._protein_accession) for x in variants
            ]

        if len(var_ps) > 1:
            raise HGVSError("Got multiple AA variants - not supported")
        return var_ps[0]
245124
def _add_exac(self, variant_obj, info_dict):
        
        exac = None
        exac_keys = ['ExAC', 'EXAC', 'ExACAF', 'EXACAF']
        for key in exac_keys:
            if info_dict.get(key):
                exac = float(info_dict[key])
        #If not found in vcf search transcripts
        if not exac:
            for transcript in variant_obj.transcripts:
                exac_raw = transcript.ExAC_MAF
                if exac_raw:
                    exac = float(exac_raw.split(':')[-1])
        
        if exac:
            variant_obj.add_frequency('ExAC', exac)
128022
def get_variant_id(variant_dict=None, variant_line=None):
    
    
    if variant_dict:
        chrom = variant_dict['CHROM']
        position = variant_dict['POS']
        ref = variant_dict['REF']
        alt = variant_dict['ALT']
    elif variant_line:
        splitted_line = variant_line.rstrip().split('\t')
        chrom = splitted_line[0]
        position = splitted_line[1]
        ref = splitted_line[3]
        alt = splitted_line[4]
    else:
        raise Exception("Have to provide variant dict or variant line")
    
    return '_'.join([
        chrom,
        position,
        ref,
        alt,
    ])
1085960
def export(ctx, outfile, variant_type):
    
    adapter = ctx.obj['adapter']
    version = ctx.obj['version']
    
    LOG.info("Export the variants from {0}".format(adapter))
    nr_cases = 0

    is_sv = variant_type == 'sv'
    existing_chromosomes = set(adapter.get_chromosomes(sv=is_sv))
    
    ordered_chromosomes = []
    for chrom in CHROMOSOME_ORDER:
        if chrom in existing_chromosomes:
            ordered_chromosomes.append(chrom)
            existing_chromosomes.remove(chrom)
    for chrom in existing_chromosomes:
        ordered_chromosomes.append(chrom)
    
    nr_cases = adapter.cases().count()
    LOG.info("Found {0} cases in database".format(nr_cases))

    head = HeaderParser()
    head.add_fileformat("VCFv4.3")
    head.add_meta_line("NrCases", nr_cases)
    head.add_info("Obs", '1', 'Integer', "The number of observations for the variant")
    head.add_info("Hom", '1', 'Integer', "The number of observed homozygotes")
    head.add_info("Hem", '1', 'Integer', "The number of observed hemizygotes")
    head.add_version_tracking("loqusdb", version, datetime.now().strftime("%Y-%m-%d %H:%M"))
    
    if variant_type == 'sv':
        head.add_info("END", '1', 'Integer', "End position of the variant")
        head.add_info("SVTYPE", '1', 'String', "Type of structural variant")
        head.add_info("SVLEN", '1', 'Integer', "Length of structural variant")
        
        
    for chrom in ordered_chromosomes:
        length = adapter.get_max_position(chrom)
        head.add_contig(contig_id=chrom, length=str(length))

    print_headers(head, outfile=outfile)
    
    for chrom in ordered_chromosomes:
        if variant_type == 'snv':
            LOG.info("Collecting all SNV variants")
            variants = adapter.get_variants(chromosome=chrom)
        else:
            LOG.info("Collecting all SV variants")
            variants = adapter.get_sv_variants(chromosome=chrom)
        LOG.info("{} variants found".format(variants.count()))
        for variant in variants:
            variant_line = format_variant(variant, variant_type=variant_type)
            # chrom = variant['chrom']
            # pos = variant['start']
            # ref = variant['ref']
            # alt = variant['alt']
            # observations = variant['observations']
            # homozygotes = variant['homozygote']
            # hemizygotes = variant['hemizygote']
            # info = "Obs={0}".format(observations)
            # if homozygotes:
            #     info += ";Hom={0}".format(homozygotes)
            # if hemizygotes:
            #     info += ";Hem={0}".format(hemizygotes)
            # variant_line = "{0}\t{1}\t.\t{2}\t{3}\t.\t.\t{4}\n".format(
            #     chrom, pos, ref, alt, info)
            print_variant(variant_line=variant_line, outfile=outfile)
552495
def convertVariant(self, record, callSetIds):
        
        variant = self._createGaVariant()
        variant.reference_name = record.contig
        if record.id is not None:
            variant.names.extend(record.id.split(';'))
        variant.start = record.start          # 0-based inclusive
        variant.end = record.stop             # 0-based exclusive
        variant.reference_bases = record.ref
        if record.alts is not None:
            variant.alternate_bases.extend(list(record.alts))
        filterKeys = record.filter.keys()
        if len(filterKeys) == 0:
            variant.filters_applied = False
        else:
            variant.filters_applied = True
            if len(filterKeys) == 1 and filterKeys[0] == 'PASS':
                variant.filters_passed = True
            else:
                variant.filters_passed = False
                variant.filters_failed.extend(filterKeys)
        # record.qual is also available, when supported by GAVariant.
        for key, value in record.info.iteritems():
            if value is None:
                continue
            if key == 'SVTYPE':
                variant.variant_type = value
            elif key == 'SVLEN':
                variant.svlen = int(value[0])
            elif key == 'CIPOS':
                variant.cipos.extend(value)
            elif key == 'CIEND':
                variant.ciend.extend(value)
            elif isinstance(value, str):
                value = value.split(',')
            protocol.setAttribute(
                variant.attributes.attr[key].values, value)
        for callSetId in callSetIds:
            callSet = self.getCallSet(callSetId)
            pysamCall = record.samples[str(callSet.getSampleName())]
            variant.calls.add().CopyFrom(
                self._convertGaCall(callSet, pysamCall))
        variant.id = self.getVariantId(variant)
        return variant
938234
def conv_variant(self, column, name, **kwargs):
        """"""
        return self.convert(str(column.type), column, name, **kwargs)