Create a genotype map.

@param str the string
@param alleles the list of alleles
@return a mapping of sample name to genotype object
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());
    }
673965
def _covert_to_diploid(in_file, data):
    
    sample = dd.get_sample_name(data)
    out_file = "%s-diploid.vcf" % utils.splitext_plus(in_file)[0]
    in_vcf = pysam.VariantFile(in_file)
    out_vcf = pysam.VariantFile(out_file, 'w', header=in_vcf.header)
    for record in in_vcf:
        gt = list(record.samples[sample]['GT'])
        if 'SOMATIC' in record.info:
            for allele in set(gt):
                if allele != gt[0]:
                    record.samples[sample]['GT'] = gt[0], allele
                    out_vcf.write(record)
        else:
            if len(gt) == 1:
                record.samples[sample]['GT'] = gt
            else:
                record.samples[sample]['GT'] = gt[0], gt[1]
            out_vcf.write(record)
    in_vcf.close()
    out_vcf.close()
    return vcfutils.bgzip_and_index(out_file, data["config"])
464789
static HashMap<String, BlastResults> readBlast(final int alleleCutoff, final File inputBlastFile) throws IOException{
    	
        BufferedReader reader = null;
        HashMap<String, BlastResults> blast = new HashMap<String, BlastResults>();
        
        try {
            reader = new BufferedReader(new FileReader(inputBlastFile));

            for (HighScoringPair hsp : HspReader.read(reader)) {

            	//id	allele 
            	List<String> BlastnParts = Splitter.on("\t").splitToList(hsp.toString());
            	String sequenceId        = BlastnParts.get(0);
            	String allele            = BlastnParts.get(1);
            
               BlastResults blastResults    = blast.get(sequenceId);
               if(blastResults == null){
            	   blastResults  = new BlastResults(alleleCutoff);
               	   blast.put(sequenceId, blastResults);
               }
               
               blastResults.addTyping(allele);
            }
            
        }finally {
            try {
            	reader.close();
            }
            catch (Exception e) {
            	 e.printStackTrace();
            	 System.exit(1);
            }
        }
    
        
        return blast;
    	
    }
312260
def model_name(allele, num):
        
        random_string = hashlib.sha1(
            str(time.time()).encode()).hexdigest()[:16]
        return "%s-%d-%s" % (allele.upper(), num, random_string)
674589
public boolean stringIsCompilableUnit(String str) {
        DimIProxy action = new DimIProxy(this, IPROXY_STRING_IS_COMPILABLE);
        action.text = str;
        action.withContext();
        return action.booleanResult;
    }
1072342
def make_V_and_J_mask_mapping(self, genV, genJ):
        
        #construct mapping between allele/gene names and index for custom V_usage_masks
        V_allele_names = [V[0] for V in genV]
        V_mask_mapping = {}
        for v in set([x.split('*')[0] for x in V_allele_names]):
            V_mask_mapping[v] = []
        for v in set(['V'.join((x.split('*')[0]).split('V')[1:]) for x in V_allele_names]):
            V_mask_mapping[v] = []
        for i, v in enumerate(V_allele_names):
            V_mask_mapping[v] = [i]
            V_mask_mapping['V'.join((v.split('*')[0]).split('V')[1:])].append(i)
            V_mask_mapping[v.split('*')[0]].append(i)      
        
        #construct mapping between allele/gene names and index for custom J_usage_masks
        J_allele_names = [J[0] for J in genJ]
        J_mask_mapping = {}
        for j in set([x.split('*')[0] for x in J_allele_names]):
            J_mask_mapping[j] = []
        for j in set(['J'.join((x.split('*')[0]).split('J')[1:]) for x in J_allele_names]):
            J_mask_mapping[j] = []
        for i, j in enumerate(J_allele_names):
            J_mask_mapping[j] = [i]
            J_mask_mapping['J'.join((j.split('*')[0]).split('J')[1:])].append(i)
            J_mask_mapping[j.split('*')[0]].append(i)
            
        self.V_allele_names = V_allele_names
        self.V_mask_mapping = V_mask_mapping
        self.J_allele_names = J_allele_names
        self.J_mask_mapping = J_mask_mapping
693993
public static String encodeXML( final String    str )
    {
        if ( str == null )
        {
            return null;
        }

        StringCharacterIterator    iterator = new StringCharacterIterator( str );
        StringBuilder              result   = new StringBuilder();
        char                       c;

        for( c  = iterator.current();
             c != CharacterIterator.DONE;
             c  = iterator.next() )
        {
            if ( c == '>' )
            {
                result.append( "&gt;" );
            }
            else if ( c == '<' )
            {
                result.append( "&lt;" );
            }
            else if ( c == '&' )
            {
                result.append( "&amp;" );
            }
            else if ( c == '"' )
            {
                result.append( "&quot;" );
            }
            else if ( c == '\'' )
            {
                result.append( "&#39;" );
            }
            else
            {
                result.append( c );
            }
        }

        return result.toString();
    }
138082
def get_alt(self, individual=0, nucleotides_only=True):
        """"""
        #not i.startswith(',') is put in to handle cases like <DEL:ME:ALU> where we have no alternate allele
        #but some reference
        if isinstance(individual, str):
            individual = self.individuals[individual]
        if nucleotides_only:
            return [self.alt[i-1].replace('.', '') for i in self.genotype[individual] if i > 0 and not self.alt[i-1].startswith('<')]
        else:
            return [self.alt[i-1].replace('.', '') for i in self.genotype[individual] if i > 0]
431360
public void setAllIdsString(String v) {
    if (LinnaeusSpecies_Type.featOkTst && ((LinnaeusSpecies_Type)jcasType).casFeat_allIdsString == null)
      jcasType.jcas.throwFeatMissing("allIdsString", "ch.epfl.bbp.uima.types.LinnaeusSpecies");
    jcasType.ll_cas.ll_setStringValue(addr, ((LinnaeusSpecies_Type)jcasType).casFeatCode_allIdsString, v);}
1073366
private String formatDnaAllele() {

//        We are not considering this case since would mean there's no variant
//        if self.mutation_type == '=':
//            #No change.
//            #example:
//        101 A =
//        return self.ref_allele + '='

        if (">".equals(mutationType)) {
            // SNP.
            // example:
            // 101 A > C
            return reference + '>' + alternate;
        } else if ("delins".equals(mutationType)) {
            // Indel.
            // example:
            // 112_117d elAGGTCAinsTG, 112_117d elinsTG
            return "del" + reference + "ins" + alternate;
        } else if ("del".equals(mutationType)) {
            // Delete, duplication.
            // example:
            // 1000_1003d elATG, 1000_1003d upATG
            return mutationType + reference;
        } else if ("dup".equals(mutationType)) {
            // Insertion normalized as duplication
            // example:
            // "ENST00000382869.3:c.1735+32dupA"
            return mutationType + alternate;
        } else if ("ins".equals(mutationType)) {
            // Insert.
            // example:
            // 1000_1001 insATG
            return mutationType + alternate;
        } else {
            throw new AssertionError("unknown mutation type: '" + mutationType + "'");
        }
    }
457146
def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params=None):
    
    if params is None:
        params = {}

    if moltype == DNA or moltype == RNA:
        params['-nt'] = True
    elif moltype == PROTEIN:
        params['-nt'] = False
    else:
        raise ValueError, \
                "FastTree does not support moltype: %s" % moltype.label

    if best_tree:
        params['-slow'] = True

    #Create mapping between abbreviated IDs and full IDs
    int_map, int_keys = aln.getIntMap()
    #Create SequenceCollection from int_map.
    int_map = SequenceCollection(int_map,MolType=moltype)

    app = FastTree(params=params)

    result = app(int_map.toFasta())
    tree = DndParser(result['Tree'].read(), constructor=PhyloNode)
    #remap tip names
    for tip in tree.tips():
        tip.Name = int_keys[tip.Name]

    return tree
83840
def complement_alleles(self):
        
        self.alleles = self._encode_alleles(
            [complement_alleles(i) for i in self.alleles]
        )
898122
public static LinkedHashMap<String, RNASequence> readGenbankRNASequence(
			InputStream inStream) throws Exception {
		GenbankReader<RNASequence, NucleotideCompound> GenbankReader = new GenbankReader<RNASequence, NucleotideCompound>(
				inStream,
				new GenericGenbankHeaderParser<RNASequence, NucleotideCompound>(),
				new RNASequenceCreator(RNACompoundSet.getRNACompoundSet()));
		return GenbankReader.process();
	}
452538
private static RNASequence getRNASequence(String str) {
		try {
			RNASequence s = new RNASequence(str);
			return s;
		} catch (CompoundNotFoundException e) {

			logger.error("Unexpected error when creating RNASequence ",e);
		}
		return null;
	}
682110
def get_variants_in_region(self, chrom, start, end):
        """"""
        region = self.get_vcf()(
            "{}:{}-{}".format(chrom, start, end)
        )
        for v in region:
            for coded_allele, g in self._make_genotypes(v.ALT, v.genotypes):
                variant = Variant(
                    v.ID, v.CHROM, v.POS, [v.REF, coded_allele]
                )
                yield Genotypes(variant, g, v.REF, coded_allele,
                                multiallelic=len(v.ALT) > 1)
347745
def iter_genotypes(self):
        
        # Parsing each column of the dataframe
        for variant in self.df.columns:
            genotypes = self.df.loc[:, variant].values
            info = self.map_info.loc[variant, :]

            yield Genotypes(
                Variant(info.name, info.chrom, info.pos, [info.a1, info.a2]),
                genotypes,
                reference=info.a2,
                coded=info.a1,
                multiallelic=False,
            )
171059
public static AbstractType<?> parse(String str) throws SyntaxException, ConfigurationException
    {
        if (str == null)
            return BytesType.instance;

        AbstractType<?> type = cache.get(str);

        if (type != null)
            return type;

        // This could be simplier (i.e. new TypeParser(str).parse()) but we avoid creating a TypeParser object if not really necessary.
        int i = 0;
        i = skipBlank(str, i);
        int j = i;
        while (!isEOS(str, i) && isIdentifierChar(str.charAt(i)))
            ++i;

        if (i == j)
            return BytesType.instance;

        String name = str.substring(j, i);
        i = skipBlank(str, i);

        if (!isEOS(str, i) && str.charAt(i) == '(')
            type = getAbstractType(name, new TypeParser(str, i));
        else
            type = getAbstractType(name);

        // We don't really care about concurrency here. Worst case scenario, we do some parsing unnecessarily
        cache.put(str, type);
        return type;
    }