JAL-2738 PoC of Load VCF file on to gene sequence
[jalview.git] / src / jalview / ext / htsjdk / VCFReader.java
1 package jalview.ext.htsjdk;
2
3 import htsjdk.samtools.util.CloseableIterator;
4 import htsjdk.variant.variantcontext.VariantContext;
5 import htsjdk.variant.vcf.VCFFileReader;
6 import htsjdk.variant.vcf.VCFHeader;
7
8 import java.io.Closeable;
9 import java.io.File;
10 import java.io.IOException;
11
12 /**
13  * A thin wrapper for htsjdk classes to read either plain, or compressed, or
14  * compressed and indexed VCF files
15  */
16 public class VCFReader implements Closeable, Iterable<VariantContext>
17 {
18   private static final String GZ = "gz";
19
20   private static final String TBI_EXTENSION = ".tbi";
21
22   private boolean indexed;
23
24   private VCFFileReader reader;
25
26   /**
27    * Constructor given a raw or compressed VCF file or a (tabix) index file
28    * <p>
29    * For now, file type is inferred from its suffix: .gz or .bgz for compressed
30    * data, .tbi for an index file, anything else is assumed to be plain text
31    * VCF.
32    * 
33    * @param f
34    * @throws IOException
35    */
36   public VCFReader(String filePath) throws IOException
37   {
38     if (filePath.endsWith(GZ))
39     {
40       if (new File(filePath + TBI_EXTENSION).exists())
41       {
42         indexed = true;
43       }
44     }
45     else if (filePath.endsWith(TBI_EXTENSION))
46     {
47       indexed = true;
48       filePath = filePath.substring(0, filePath.length() - 4);
49     }
50
51     reader = new VCFFileReader(new File(filePath), indexed);
52   }
53
54   @Override
55   public void close() throws IOException
56   {
57     if (reader != null)
58     {
59       reader.close();
60     }
61   }
62
63   /**
64    * Returns an iterator over VCF variants in the file. The client should call
65    * close() on the iterator when finished with it.
66    */
67   @Override
68   public CloseableIterator<VariantContext> iterator()
69   {
70     return reader == null ? null : reader.iterator();
71   }
72
73   /**
74    * Queries for records overlapping the region specified. Note that this method
75    * requires a VCF file with an associated index. If no index exists a
76    * TribbleException will be thrown. Client code should call close() on the
77    * iterator when finished with it.
78    * 
79    * @param chrom
80    *          the chromosome to query
81    * @param start
82    *          query interval start
83    * @param end
84    *          query interval end
85    * @return
86    */
87   public CloseableIterator<VariantContext> query(final String chrom,
88           final int start, final int end)
89   {
90     return reader == null ? null : reader.query(chrom, start, end);
91   }
92
93   /**
94    * Returns an object that models the VCF file headers
95    * 
96    * @return
97    */
98   public VCFHeader getFileHeader()
99   {
100     return reader == null ? null : reader.getFileHeader();
101   }
102 }