Iterates on available markers.

        Returns:
            Genotypes instances.
978177
def iter_genotypes(self):
        
        # Seeking at the beginning of the file
        self._impute2_file.seek(0)

        # Parsing each lines of the IMPUTE2 file
        for i, line in enumerate(self._impute2_file):
            genotypes = self._parse_impute2_line(line)

            variant_info = None
            if self.has_index:
                variant_info = self._impute2_index.iloc[i, :]
            self._fix_genotypes_object(genotypes, variant_info)

            yield genotypes
1270211
def iter_methods(self):
        
        for wrkey, obj in self.iter_instances():
            f, obj_id = wrkey
            loop = self.event_loop_map[wrkey]
            m = getattr(obj, f.__name__)
            yield loop, m
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
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
533356
def get_variants(self, arch=None, types=None, recursive=False):
        
        types = types or []
        result = []

        if "self" in types:
            result.append(self)

        for variant in six.itervalues(self.variants):
            if types and variant.type not in types:
                continue
            if arch and arch not in variant.arches.union(["src"]):
                continue
            result.append(variant)
            if recursive:
                result.extend(variant.get_variants(types=[i for i in types if i != "self"], recursive=True))

        result.sort(key=lambda x: x.uid)
        return result
802141
def return_markers(self, trigger_bits=8, trigger_zero=True):
        
        nev_file = splitext(self.filename)[0] + '.nev'
        markers = _read_neuralev(nev_file, read_markers=True)

        if trigger_bits == 8:
            to8 = lambda x: str(int(x) - (256 ** 2 - 256))
            for m in markers:
                m['name'] = to8(m['name'])

        if trigger_zero:
            no_zero = (i for i, m in enumerate(markers) if m['name'] != '0')

            markers_no_zero = []
            for i in no_zero:
                if (i + 1) < len(markers) and markers[i + 1]['name'] == '0':
                    markers[i]['end'] = markers[i + 1]['start']
                markers_no_zero.append(markers[i])

        return markers_no_zero
132642
def iter_variants(self):
        """"""
        for v in self.get_vcf():
            yield Variant(v.ID, v.CHROM, v.POS, {v.REF} | set(v.ALT))
459315
def types(self):
        
        output = set()
        for var in self.values():
            if var.has_value():
                output.update(var.types())
        return list(output)
749916
def load_alleles():
    
    result = []
    path = local_path()
    etree = xml.etree.ElementTree.parse(path)
    for allele in etree.iterfind("MhcAlleleName"):
        name_element = allele.find("DisplayedRestriction")
        mhc_class_element = allele.find("Class")
        # need at least a name and an HLA class
        if name_element is None or mhc_class_element is None:
            continue
        name = name_element.text

        synonyms = set([])
        for synonym_element in allele.iterfind("Synonyms"):
            for synonym in synonym_element.text.split(","):
                synonyms.add(synonym.strip())
        mhc_class = mhc_class_element.text
        organism_element = allele.find("Organsim")
        if organism_element is None:
            organism = None
        else:
            organism = organism_element.text

        locus_element = allele.find("Locus")

        if locus_element is None:
            locus = None
        else:
            locus = locus_element.text

        allele_object = Allele(
            name=name,
            mhc_class=mhc_class,
            locus=locus,
            organism=organism,
            synonyms=synonyms)
        result.append(allele_object)
    return result
695078
def iter_instances(self):
        
        for wrkey in set(self.keys()):
            obj = self.get(wrkey)
            if obj is None:
                continue
            yield wrkey, obj
897425
def _read_current_marker(self):
        """"""
        return self._geno_values[
            np.frombuffer(self._bed.read(self._nb_bytes), dtype=np.uint8)
        ].flatten(order="C")[:self._nb_samples]
460123
private static <G extends Gene<?, G>, C extends Comparable<? super C>>
	ISeq<C> batchEval(
		final Seq<Genotype<G>> genotypes,
		final Function<? super Genotype<G>, ? extends C> function
	) {
		return genotypes.<C>map(function).asISeq();
	}
242229
def populate_iteration(self, iteration):
        """"""

        cur_idx = iteration.cur_idx
        genotypes = self.genotype_file.next().split()
        iteration.chr, iteration.rsid, junk, iteration.pos = genotypes[0:4]
        iteration.chr = int(iteration.chr)
        iteration.pos = int(iteration.pos)

        if DataParser.boundary.TestBoundary(iteration.chr, iteration.pos, iteration.rsid):
            try:
                [iteration.genotype_data,
                    iteration.major_allele,
                    iteration.minor_allele,
                    iteration.hetero_count,
                    iteration.maj_allele_count,
                    iteration.min_allele_count,
                    iteration.missing_allele_count,
                    iteration.allele_count2] = self.process_genotypes(genotypes)
                return iteration.maf >= DataParser.min_maf and iteration.maf <= DataParser.max_maf
            except TooFewAlleles:
                print "\n\n\nSkipping %s:%s %s %s" % (iteration.chr, iteration.pos, iteration.rsid, cur_idx)

        return False
1203254
def parse_args():
    """"""
    parser = argparse.ArgumentParser(
        prog="geneparse-extractor",
        description="Genotype file extractor. This tool will extract markers "
                    "according to names or to genomic locations.",
        epilog="The parser arguments (PARSER_ARGS) are the same as the one in "
               "the API. For example, the arguments for the Plink parser is "
               "'prefix:PREFIX' (where PREFIX is the prefix of the "
               "BED/BIM/FAM files).",
    )

    # The input file format
    group = parser.add_argument_group("Input Options")
    group.add_argument(
        "-f", "--format", metavar="FORMAT", required=True, type=str,
        dest="input_format", choices=set(parsers.keys()),
        help="The input file format.",
    )

    group.add_argument(
        nargs="+", dest="parser_args", type=str, metavar="PARSER_ARGS",
        help="The arguments that will be passed to the genotype parsers.",
    )

    # The extract options
    group = parser.add_argument_group("Extract Options")
    group.add_argument(
        "-e", "--extract", metavar="FILE", type=argparse.FileType("r"),
        help="The list of markers to extract (one per line, no header).",
    )
    group.add_argument(
        "-k", "--keep", metavar="FILE", type=argparse.FileType("r"),
        help="The list of samples to keep (one per line, no header).",
    )
    group.add_argument(
        "--maf", action="store_true",
        help="Check MAF and flip the allele coding if the MAF is higher "
             "than 50%%.",
    )

    # The output options
    group = parser.add_argument_group("Output Options")
    group.add_argument(
        "-o", "--output", metavar="FILE", type=str, required=True,
        help="The output file (can be '-' for STDOUT when using VCF or CSV as "
             "output format).",
    )
    group.add_argument(
        "--output-format", metavar="FORMAT", default="vcf", type=str,
        choices={"vcf", "plink", "csv"},
        help="The output file format. Note that the extension will be added "
             "if absent. Note that CSV is a long format (hence it might take "
             "more disk space).",
    )

    return parser.parse_args()
443891
public static void getGenotype(int index, Integer alleles[]) {
//        index++;
//        double value = (-3 + Math.sqrt(1 + 8 * index)) / 2;    // slower than the iterating version, right?
//        alleles[1] = new Double(Math.ceil(value)).intValue();
//        alleles[0] = alleles[1] - ((alleles[1] + 1) * (alleles[1] +2) / 2 - index);

        int cursor = 0;
        final int MAX_ALLOWED_ALLELES = 100;   // should we allow more than 100 alleles?
        for (int i = 0; i < MAX_ALLOWED_ALLELES; i++) {
            for (int j = 0; j <= i; j++) {
                if (cursor == index) {
                    alleles[0] = j;
                    alleles[1] = i;
                    return;
                }
                cursor++;
            }
        }
    }
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
1020817
def genes(self):
        
        if self._genes is None:
            self._genes = self.ensembl.genes_at_locus(
                self.contig, self.start, self.end)
        return self._genes