Format conversion

Format conversion#

vcztools converts a configured vcztools.VczReader to three output formats from Python, so any sample or variant selection on the reader (see Reading VCZ) flows through to the output. Each writer is documented in full in the API reference; the linked file-format pages describe the output semantics (allele conventions, missingness, multi-allelic handling).

write_vcf streams records and filters on the fly, so a configured variant filter and a sample subset are honoured as-is. write_plink and write_bgen are fixed-width per variant: they are biallelic-only and cannot consume a still-configured filter, which must first be resolved into a fixed selection with materialise_variant_filter().

The examples below run against the example dataset data/sample.vcz.zip (9 variants across 3 samples; see Reading VCZ).

Writing VCF#

A sample subset and a vcztools.BcftoolsFilter can be set on the reader and passed straight to write_vcf:

import vcztools

root = vcztools.open_zarr("data/sample.vcz.zip")
with vcztools.VczReader(root) as reader:
    reader.set_samples(["NA00001", "NA00003"])
    reader.set_variant_filter(vcztools.BcftoolsFilter(reader, include="QUAL>10"))
    vcztools.write_vcf(reader, "subset.vcf")

The output reflects both the sample subset and the filter. The #CHROM line lists only the two selected samples, and every record that survives has QUAL > 10 (4 of the 9 variants):

records = []
for line in open("subset.vcf"):
    if line.startswith("#CHROM"):
        print("samples:", line.split()[9:])
    elif not line.startswith("#"):
        records.append(line.split())

quals = [float(record[5]) for record in records]
print("records written:", len(records))
print("QUAL values:", quals)
print("all QUAL > 10:", all(qual > 10 for qual in quals))
samples: ['NA00001', 'NA00003']
records written: 4
QUAL values: [29.0, 67.0, 47.0, 50.0]
all QUAL > 10: True