Iterates on available markers.

        Returns:
            Genotypes instances.
423073
def iter_genotypes(self):
        
        for info, dosage in self._bgen.iter_variants():
            yield Genotypes(
                Variant(
                    info.name, CHROM_STR_ENCODE.get(info.chrom, info.chrom),
                    info.pos, [info.a1, info.a2],
                ),
                dosage,
                reference=info.a1,
                coded=info.a2,
                multiallelic=True,
            )
1261426
def of_type(cls, iterable, types):
    

    return cls(x for x in iterable if isinstance(x, types))
1287708
def setup_markers(seqs):
    
    family2marker = {} # family2marker[family] = [marker, size]
    markers = cycle(['^', 'p', '*', '+', 'x', 'd', '|', 'v', '>', '<', '8'])
    size = 60
    families = []
    for seq in list(seqs.values()):
        for insertion in seq[2]:
            for family in list(insertion[-1].values()):
                if family not in families:
                    families.append(family)
    for family in families:
        marker = next(markers) 
        if marker == '^':
            size = size * 0.5
        family2marker[family] = [marker, size]
    return family2marker
695618
def get_all_resources(self):
        
        resources = {}
        resources[
            "genetic_map_HapMapII_GRCh37"
        ] = self.get_genetic_map_HapMapII_GRCh37()
        resources["cytoBand_hg19"] = self.get_cytoBand_hg19()
        resources["knownGene_hg19"] = self.get_knownGene_hg19()
        resources["kgXref_hg19"] = self.get_kgXref_hg19()
        for source, target in itertools.permutations(["NCBI36", "GRCh37", "GRCh38"], 2):
            resources[source + "_" + target] = self.get_assembly_mapping_data(
                source, target
            )
        return resources
447446
def _fix_genotypes_object(self, genotypes, variant_info):
        """"""
        # Checking the name (if there were duplications)
        if self.has_index and variant_info.name != genotypes.variant.name:
            if not variant_info.name.startswith(genotypes.variant.name):
                raise ValueError("Index file not synced with IMPUTE2 file")
            genotypes.variant.name = variant_info.name

        # Trying to set multi-allelic information
        if self.has_index and self._index_has_location:
            # Location was in the index, so we can automatically set the
            # multi-allelic state of the genotypes
            genotypes.multiallelic = variant_info.multiallelic

        else:
            # Location was not in the index, so we check one marker before and
            # after the one we found
            logging.warning("Multiallelic variants are not detected on "
                            "unindexed files.")
894404
def load_genotypes(self):
        


        if self.file_index < len(self.archives):
            self.current_file = self.archives[self.file_index]
            info_filename = self.current_file.replace(Parser.gen_ext, Parser.info_ext)
            if len(self.info_files) > 0:
                info_filename = self.info_files[self.file_index]
            self.info_file = open(info_filename)
            self.info_file.readline()   # Dump the header

            if DataParser.compressed_pedigree:
                self.freq_file = gzip.open("%s" % (self.current_file), 'rb')
            else:
                self.freq_file = open(self.current_file)
            self.current_chrom = self.chroms[self.file_index]
            self.file_index += 1
        else:
            raise StopIteration
1186389
def markers():
    ''' 
    '''
    print("Available markers: \n\n - " + "\n - ".join(list(MarkerType)))
    print()
    print("Shortcuts: \n\n" + "\n".join(" %r: %s" % item for item in _MARKER_SHORTCUTS.items()))
705148
public ISeq<Genotype<G>> getGenotypes() {
		return _population.stream()
			.map(Phenotype::getGenotype)
			.collect(ISeq.toISeq());
	}
1292602
def get_contained_pyversions(marker):
    

    collection = []
    if not marker:
        return set()
    marker = _ensure_marker(marker)
    # Collect the (Variable, Op, Value) tuples and string joiners from the marker
    _markers_collect_pyversions(marker._markers, collection)
    marker_str = " and ".join(sorted(collection))
    if not marker_str:
        return set()
    # Use the distlib dictionary parser to create a dictionary 'trie' which is a bit
    # easier to reason about
    marker_dict = distlib.markers.parse_marker(marker_str)[0]
    version_set = set()
    pyversions, _ = parse_marker_dict(marker_dict)
    if isinstance(pyversions, set):
        version_set.update(pyversions)
    elif pyversions is not None:
        version_set.add(pyversions)
    # Each distinct element in the set was separated by an "and" operator in the marker
    # So we will need to reduce them with an intersection here rather than a union
    # in order to find the boundaries
    versions = set()
    if version_set:
        versions = reduce(lambda x, y: x & y, version_set)
    return versions
1083947
def sequencetyper(self):
        """"""
        logging.info('Performing sequence typing')
        for sample in self.runmetadata.samples:
            if sample.general.bestassemblyfile != 'NA':
                if type(sample[self.analysistype].allelenames) == list:
                    # Initialise variables
                    header = 0
                    genome = sample.name
                    # Initialise self.bestmatch[genome] with an int that will eventually be replaced by the # of matches
                    self.bestmatch[genome] = defaultdict(int)
                    if sample[self.analysistype].profile != 'NA':
                        # Create the profiledata variable to avoid writing self.profiledata[self.analysistype]
                        profiledata = sample[self.analysistype].profiledata
                        # Calculate the number of allele matches between each sequence type and the results
                        best_seqtype = dict()
                        for sequencetype in sample[self.analysistype].profiledata:
                            # Initialise a counter
                            count = 0
                            # Iterate through each gene for the sequence type
                            for gene, refallele in sample[self.analysistype].profiledata[sequencetype].items():
                                # Use the gene to extract the calculated allele
                                allele = self.matchdict[genome][gene]
                                # Increment the count on a match
                                if refallele == allele:
                                    count += 1
                            # Add the sequence type to the set of sequence types with the number of matches as the key
                            try:
                                best_seqtype[count].add(sequencetype)
                            except KeyError:
                                best_seqtype[count] = set()
                                best_seqtype[count].add(sequencetype)
                        # Find the highest number of matches from the dictionary
                        best = sorted(best_seqtype.items(), key=operator.itemgetter(0), reverse=True)[0][1]
                        # Deal with multiple allele matches
                        for gene in sample[self.analysistype].allelenames:
                            # Clear the appropriate count and lists
                            multiallele = list()
                            multipercent = list()
                            # Go through the alleles in plusdict
                            for allele in self.plusdict[genome][gene]:
                                percentid = list(self.plusdict[genome][gene][allele].keys())[0]
                                # "N" alleles screw up the allele splitter function
                                if allele not in ['N', 'NA']:
                                    # Append as appropriate - alleleNumber is treated as an integer for proper sorting
                                    multiallele.append(int(allele))
                                    multipercent.append(percentid)
                                # If the allele is "N"
                                else:
                                    # Append "N" and a percent identity of 0
                                    multiallele.append("N")
                                    multipercent.append(0)
                            # Populate self.bestdict with genome, gene, alleles joined with a space (this was made like
                            # this because allele is a list generated by the .iteritems() above
                            try:
                                self.bestdict[genome][gene][" ".join(str(allele)
                                                                     for allele in sorted(multiallele))] = \
                                    multipercent[0]
                            except IndexError:
                                self.bestdict[genome][gene]['NA'] = 0
                            # Find the profile with the most alleles in common with the query genome
                            for sequencetype in best:
                                # The number of genes in the analysis
                                header = len(profiledata[sequencetype])
                                # refallele is the allele number of the sequence type
                                refallele = profiledata[sequencetype][gene]
                                # If there are multiple allele matches for a gene in the reference profile e.g. 10 692
                                if len(refallele.split(" ")) > 1:
                                    # Map the split (on a space) alleles as integers - if they are treated as integers,
                                    # the alleles will sort properly
                                    intrefallele = map(int, refallele.split(" "))
                                    # Create a string of the joined, sorted alleles
                                    sortedrefallele = " ".join(str(allele) for allele in sorted(intrefallele))
                                else:
                                    # Use the reference allele as the sortedRefAllele
                                    sortedrefallele = refallele
                                for allele, percentid in self.bestdict[genome][gene].items():
                                    # If the allele in the query genome matches the allele in the reference profile, add
                                    # the result to the bestmatch dictionary. Genes with multiple alleles were sorted
                                    # the same, strings with multiple alleles will match: 10 692 will never be 692 10
                                    if allele == sortedrefallele and float(percentid) == 100.00:
                                        # Increment the number of matches to each profile
                                        self.bestmatch[genome][sequencetype] += 1
                                    # Special handling of BACT000060 and BACT000065 genes for E. coli and BACT000014
                                    # for Listeria. When the reference profile has an allele of 'N', and the query
                                    # allele doesn't, set the allele to 'N', and count it as a match
                                    elif sortedrefallele == 'N' and allele != 'N':
                                        # Increment the number of matches to each profile
                                        self.bestmatch[genome][sequencetype] += 1
                                    # Consider cases with multiple allele matches
                                    elif len(allele.split(' ')) > 1:
                                        # Also increment the number of matches if one of the alleles matches the
                                        # reference allele e.g. 41 16665 will match either 41 or 16665
                                        if sortedrefallele != 'N' and allele != 'N':
                                            match = False
                                            for sub_allele in allele.split(' '):
                                                if sub_allele == refallele:
                                                    match = True
                                            if match:
                                                # Increment the number of matches to each profile
                                                self.bestmatch[genome][sequencetype] += 1
                                    elif allele == sortedrefallele and sortedrefallele == 'N':
                                        # Increment the number of matches to each profile
                                        self.bestmatch[genome][sequencetype] += 1
                        # Get the best number of matches
                        # From: https://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value
                        try:
                            sortedmatches = sorted(self.bestmatch[genome].items(), key=operator.itemgetter(1),
                                                   reverse=True)[0][1]
                        # If there are no matches, set :sortedmatches to zero
                        except IndexError:
                            sortedmatches = 0
                        # Otherwise, the query profile matches the reference profile
                        if int(sortedmatches) == header:
                            # Iterate through best match
                            for sequencetype, matches in self.bestmatch[genome].items():
                                if matches == sortedmatches:
                                    for gene in profiledata[sequencetype]:
                                        # Populate resultProfile with the genome, best match to profile, # of matches
                                        # to the profile, gene, query allele(s), reference allele(s), and % identity
                                        self.resultprofile[genome][sequencetype][sortedmatches][gene][
                                            list(self.bestdict[genome][gene]
                                                 .keys())[0]] = str(list(self.bestdict[genome][gene].values())[0])
                                    sample[self.analysistype].sequencetype = sequencetype
                                    sample[self.analysistype].matchestosequencetype = matches
                        # If there are fewer matches than the total number of genes in the typing scheme
                        elif 0 < int(sortedmatches) < header:
                            mismatches = []
                            # Iterate through the sequence types and the number of matches in bestDict for each genome
                            for sequencetype, matches in self.bestmatch[genome].items():
                                # If the number of matches for a profile matches the best number of matches
                                if matches == sortedmatches:
                                    # Iterate through the gene in the analysis
                                    for gene in profiledata[sequencetype]:
                                        # Get the reference allele as above
                                        refallele = profiledata[sequencetype][gene]
                                        # As above get the reference allele split and ordered as necessary
                                        if len(refallele.split(" ")) > 1:
                                            intrefallele = map(int, refallele.split(" "))
                                            sortedrefallele = " ".join(str(allele) for allele in sorted(intrefallele))
                                        else:
                                            sortedrefallele = refallele
                                        # Populate self.mlstseqtype with the genome, best match to profile, # of matches
                                        # to the profile, gene, query allele(s), reference allele(s), and % identity
                                        if self.analysistype == 'mlst':
                                            self.resultprofile[genome][sequencetype][sortedmatches][gene][
                                                list(self.bestdict[genome][gene]
                                                     .keys())[0]] = str(list(self.bestdict[genome][gene].values())[0])
                                        else:
                                            self.resultprofile[genome][sequencetype][sortedmatches][gene][
                                                list(self.bestdict[genome][gene].keys())[0]] \
                                                = str(list(self.bestdict[genome][gene].values())[0])
                                            #
                                            if sortedrefallele != list(self.bestdict[sample.name][gene].keys())[0]:
                                                mismatches.append(
                                                    ({gene: ('{} ({})'.format(list(self.bestdict[sample.name][gene]
                                                                                   .keys())[0], sortedrefallele))}))
                                        sample[self.analysistype].mismatchestosequencetype = mismatches
                                        sample[self.analysistype].sequencetype = sequencetype
                                        sample[self.analysistype].matchestosequencetype = matches
                        elif sortedmatches == 0:
                            for gene in sample[self.analysistype].allelenames:
                                # Populate the results profile with negative values for sequence type and sorted matches
                                self.resultprofile[genome]['NA'][sortedmatches][gene]['NA'] = 0
                            # Add the new profile to the profile file (if the option is enabled)
                            sample[self.analysistype].sequencetype = 'NA'
                            sample[self.analysistype].matchestosequencetype = 'NA'
                            sample[self.analysistype].mismatchestosequencetype = 'NA'
                        else:
                            sample[self.analysistype].matchestosequencetype = 'NA'
                            sample[self.analysistype].mismatchestosequencetype = 'NA'
                            sample[self.analysistype].sequencetype = 'NA'
                else:
                    sample[self.analysistype].matchestosequencetype = 'NA'
                    sample[self.analysistype].mismatchestosequencetype = 'NA'
                    sample[self.analysistype].sequencetype = 'NA'

            else:
                sample[self.analysistype].matchestosequencetype = 'NA'
                sample[self.analysistype].mismatchestosequencetype = 'NA'
                sample[self.analysistype].sequencetype = 'NA'
            # Clear out the reverse_profiledata attribute - frozen sets can not be .json encoded
            try:
                delattr(sample[self.analysistype], 'reverse_profiledata')
            except AttributeError:
                pass
615804
def iter_markers(self):
        
        marker_finder = _MarkerFinder.from_stream(self._stream)
        start = 0
        marker_code = None
        while marker_code != JPEG_MARKER_CODE.EOI:
            marker_code, segment_offset = marker_finder.next(start)
            marker = _MarkerFactory(
                marker_code, self._stream, segment_offset
            )
            yield marker
            start = segment_offset + marker.segment_length
481607
def _get_biallelic_variant(self, variant, info, _check_alleles=True):
        """"""
        info = info.iloc[0, :]
        assert not info.multiallelic

        # Seeking and parsing the file
        self._impute2_file.seek(info.seek)
        genotypes = self._parse_impute2_line(self._impute2_file.readline())

        variant_alleles = variant._encode_alleles([
            genotypes.reference, genotypes.coded,
        ])
        if (_check_alleles and variant_alleles != variant.alleles):
            # Variant with requested alleles is unavailable.
            logging.variant_not_found(variant)
            return []

        return [genotypes]
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
1061549
def getAllVariantSets(self):
        
        for dataset in self.getAllDatasets():
            iterator = self._client.search_variant_sets(
                dataset_id=dataset.id)
            for variantSet in iterator:
                yield variantSet
1296861
def iter_genotypes(self):
        
        for v in self.get_vcf():
            alleles = {v.REF} | set(v.ALT)

            if self.quality_field:
                variant = ImputedVariant(v.ID, v.CHROM, v.POS, alleles,
                                         getattr(v, self.quality_field))
            else:
                variant = Variant(v.ID, v.CHROM, v.POS, alleles)

            for coded_allele, g in self._make_genotypes(v.ALT, v.genotypes):
                yield Genotypes(variant, g, v.REF, coded_allele,
                                multiallelic=len(v.ALT) > 1)
819512
def supported_alleles(self):
        
        if 'supported_alleles' not in self._cache:
            result = set(self.allele_to_allele_specific_models)
            if self.allele_to_fixed_length_sequence:
                result = result.union(self.allele_to_fixed_length_sequence)
            self._cache["supported_alleles"] = sorted(result)
        return self._cache["supported_alleles"]
1071804
def iter_acgt_geno(self):
        
        # Need to iterate over itself, and modify the actual genotypes
        for i, (marker, geno) in enumerate(self.iter_geno()):
            yield marker, self._allele_encoding[i][geno]