Read a VCF file

VCF lists the variants found on a reference genome. This file is the example of the VCF 4.3 specification. The 8 fixed columns are read; the genotypes of the samples (FORMAT and the following columns) are ignored. The type of each alternate allele is worked out by comparing it with the reference.

1

Starting code

This is the PHP code used by this example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public function readVcf(VcfReaderInterface $vcfReader)
{
    // The example file of the VCF 4.3 specification
    $oResult = $vcfReader->read(file($this->getParameter('kernel.project_dir') . '/public/data/sample.vcf'));
    $aVariants = $oResult->getVariants();
 
    // Only the variants that passed every filter
    $aPassing = array_filter($aVariants, fn(VcfVariant $oVariant) => $oVariant->isPass());
 
    // Malformed lines are reported and skipped, the others are read
    $oFaulty = $vcfReader->read([
        "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO",
        "20\t14370\trs6054257\tG\tA\t29\tPASS\tDP=14",
        "20\tabc\t.\tT\tA\t3\tq10\tDP=11",
        "20\t17330\t.\tT\tA\t3\tq10",
    ]);
 
    return $this->render('default/variantsReadVcf.html.twig', [
        'variants'  => $this->describe($aVariants), // type of each alternate allele (SNV, insertion...)
        'passing'   => count($aPassing),
        'faulty'    => $oFaulty,
    ]);
}
2

Result

Result returned by BioPHP for the demonstration data.

5 variants read, 4 passing every filter
CHROM POS ID REF ALT QUAL FILTER INFO
20 14370 rs6054257 G A (SNV) 29 ✓ PASS NS=3
DP=14
AF=0.5
DB
H2
20 17330 . T A (SNV) 3 q10 NS=3
DP=11
AF=0.017
20 1110696 rs6040355 A G (SNV)
T (SNV)
67 ✓ PASS NS=2
DP=10
AF=0.333,0.667
AA=T
DB
20 1230237 . T none: reference call 47 ✓ PASS NS=3
DP=13
AA=T
20 1234567 microsat1 GTC G (deletion)
GTCT (insertion)
50 ✓ PASS NS=3
DP=9
AA=G
Malformed lines

Variants read: 1. The line whose position is not a number, and the one missing its INFO column, are reported and skipped:

Skipped line 3: non-numeric POS ("abc").

Skipped line 4: expected at least 8 tab-separated VCF columns, got 7.

The code above is the one actually executed by this page. Find the other examples in the left-hand column, or the tools in BioTools.