Flip the alleles of an Genotypes instance.
778840
def flip_alleles(genotypes):
    """"""
    warnings.warn("deprecated: use 'Genotypes.flip_coded'", DeprecationWarning)
    genotypes.reference, genotypes.coded = (genotypes.coded,
                                            genotypes.reference)
    genotypes.genotypes = 2 - genotypes.genotypes
    return genotypes
617503
def flip(args):
    
    p = OptionParser(flip.__doc__)
    opts, args = p.parse_args(args)

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

    fastafile, = args
    outfastafile = fastafile.rsplit(".", 1)[0] + ".flipped.fasta"
    fo = open(outfastafile, "w")
    f = Fasta(fastafile, lazy=True)
    for name, rec in f.iteritems_ordered():
        tmpfasta = "a.fasta"
        fw = open(tmpfasta, "w")
        SeqIO.write([rec], fw, "fasta")
        fw.close()

        o = overlap([tmpfasta, name])
        if o.orientation == '-':
            rec.seq = rec.seq.reverse_complement()

        SeqIO.write([rec], fo, "fasta")
        os.remove(tmpfasta)
163106
def flip(self):
        

        left = self.left._replace(red=not self.left.red)
        right = self.right._replace(red=not self.right.red)
        top = self._replace(left=left, right=right, red=not self.red)
        return top
972045
def crossover(self, gene2):
        
        assert self.key == gene2.key

        # Note: we use "a if random() > 0.5 else b" instead of choice((a, b))
        # here because `choice` is substantially slower.
        new_gene = self.__class__(self.key)
        for a in self._gene_attributes:
            if random() > 0.5:
                setattr(new_gene, a.name, getattr(self, a.name))
            else:
                setattr(new_gene, a.name, getattr(gene2, a.name))

        return new_gene
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]
1328645
def run_genotyper(bam_file, ref_file, dbsnp_file, config_file):
    
    cl = ["gatk_genotyper.py", config_file, ref_file, bam_file]
    if dbsnp_file:
        cl.append(dbsnp_file)
    subprocess.check_call(cl)
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,
            )
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
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()
465937
def _invert_all(self):
        """"""
        set = self._datastore.setbyte
        get = self._datastore.getbyte
        for p in xrange(self._datastore.byteoffset, self._datastore.byteoffset + self._datastore.bytelength):
            set(p, 256 + ~get(p))
777711
def encode_genotype(s, mindepth=3, depth_index=2, nohet=False):
    
    atoms = s.split(":")
    if len(atoms) < 3:
        return g2x[atoms[0]]

    inferred = atoms[0]
    depth = int(atoms[depth_index])
    if depth < mindepth:
        return '-'
    if inferred == '0/0':
        return 'A'
    if inferred == '0/1':
        return '-' if nohet else 'X'
    if inferred == '1/1':
        return 'B'
    return '-'
202160
def shift_or_mirror_into_invertible_domain(self, solution_genotype,
                                               copy=False):
        
        assert solution_genotype is not None
        if copy:
            y = [val for val in solution_genotype]
        else:
            y = solution_genotype
        if isinstance(y, np.ndarray) and not isinstance(y[0], float):
            y = array(y, dtype=float)
        for i in rglen(y):
            lb = self._lb[self._index(i)]
            ub = self._ub[self._index(i)]
            al = self._al[self._index(i)]
            au = self._au[self._index(i)]
            # x is far from the boundary, compared to ub - lb
            if y[i] < lb - 2 * al - (ub - lb) / 2.0 or y[i] > ub + 2 * au + (ub - lb) / 2.0:
                r = 2 * (ub - lb + al + au)  # period
                s = lb - 2 * al - (ub - lb) / 2.0  # start
                y[i] -= r * ((y[i] - s) // r)  # shift
            if y[i] > ub + au:
                y[i] -= 2 * (y[i] - ub - au)
            if y[i] < lb - al:
                y[i] += 2 * (lb - al - y[i])
        return y
616867
def clip_or_fit_solutions(self, pop, idx):
        
        for k in idx:
            self.repair_genotype(pop[k])
1243531
def cli(ctx, feature_id, organism="", sequence=""):
    
    return ctx.gi.annotations.flip_strand(feature_id, organism=organism, sequence=sequence)
474440
def normalize_alleles_left(ref, start, stop, alleles, bound, ref_step, shuffle=True):
    

    normalized_alleles = namedtuple('shuffled_alleles', 'start stop alleles')

    if len(alleles) < 2:
        return normalized_alleles(start, stop, alleles)

    # STEP 1: Trim common suffix
    trimmed, alleles = trim_common_suffixes(alleles)
    stop -= trimmed

    # STEP 2: Trim common prefix
    trimmed, alleles = trim_common_prefixes(alleles)
    start += trimmed

    # assert bound <= start,'start={:d}, left bound={:d}'.format(start, bound)

    # STEP 3: While a null allele exists, left shuffle by prepending alleles
    #         with reference and trimming common suffixes
    while shuffle and '' in alleles and start > bound:
        step = min(ref_step, start - bound)

        r = ref[start - step:start].upper()
        new_alleles = [r + a for a in alleles]

        trimmed, new_alleles = trim_common_suffixes(new_alleles)

        if not trimmed:
            break

        start -= trimmed
        stop -= trimmed

        if trimmed == step:
            alleles = new_alleles
        else:
            left = step - trimmed
            alleles = [a[left:] for a in new_alleles]
            break

    return normalized_alleles(start, stop, tuple(alleles))
606578
def flip(self, reactions):
        """"""
        for reaction in reactions:
            if reaction in self._flipped:
                self._flipped.remove(reaction)
            else:
                self._flipped.add(reaction)
706468
def flip_strand(self):
        """"""
        self.reference = complement_alleles(self.reference)
        self.coded = complement_alleles(self.coded)
        self.variant.complement_alleles()