JAL-3982 JAL-3860 encapsulate genomic coordinates mapping/liftover logic
[jalview.git] / src / jalview / io / vcf / VCFLoader.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.io.vcf;
22
23 import java.util.Locale;
24
25 import java.io.File;
26 import java.io.IOException;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.Iterator;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Map.Entry;
34 import java.util.Set;
35 import java.util.regex.Pattern;
36 import java.util.regex.PatternSyntaxException;
37
38 import htsjdk.samtools.SAMException;
39 import htsjdk.samtools.SAMSequenceDictionary;
40 import htsjdk.samtools.SAMSequenceRecord;
41 import htsjdk.samtools.util.CloseableIterator;
42 import htsjdk.tribble.TribbleException;
43 import htsjdk.variant.variantcontext.Allele;
44 import htsjdk.variant.variantcontext.VariantContext;
45 import htsjdk.variant.vcf.VCFConstants;
46 import htsjdk.variant.vcf.VCFHeader;
47 import htsjdk.variant.vcf.VCFHeaderLine;
48 import htsjdk.variant.vcf.VCFHeaderLineCount;
49 import htsjdk.variant.vcf.VCFHeaderLineType;
50 import htsjdk.variant.vcf.VCFInfoHeaderLine;
51 import jalview.analysis.Dna;
52 import jalview.api.AlignViewControllerGuiI;
53 import jalview.bin.Cache;
54 import jalview.bin.Console;
55 import jalview.datamodel.DBRefEntry;
56 import jalview.datamodel.GeneLociI;
57 import jalview.datamodel.GenomicAssemblies;
58 import jalview.datamodel.Mapping;
59 import jalview.datamodel.SequenceFeature;
60 import jalview.datamodel.SequenceI;
61 import jalview.datamodel.features.FeatureAttributeType;
62 import jalview.datamodel.features.FeatureSource;
63 import jalview.datamodel.features.FeatureSources;
64 import jalview.ext.ensembl.EnsemblMap;
65 import jalview.ext.htsjdk.HtsContigDb;
66 import jalview.ext.htsjdk.VCFReader;
67 import jalview.io.gff.Gff3Helper;
68 import jalview.io.gff.SequenceOntologyI;
69 import jalview.util.MapList;
70 import jalview.util.MappingUtils;
71 import jalview.util.MessageManager;
72 import jalview.util.StringUtils;
73
74 /**
75  * A class to read VCF data (using the htsjdk) and add variants as sequence
76  * features on dna and any related protein product sequences
77  * 
78  * @author gmcarstairs
79  */
80 public class VCFLoader
81 {
82   private static final String VCF_ENCODABLE = ":;=%,";
83
84   /*
85    * Jalview feature attributes for VCF fixed column data
86    */
87   private static final String VCF_POS = "POS";
88
89   private static final String VCF_ID = "ID";
90
91   private static final String VCF_QUAL = "QUAL";
92
93   private static final String VCF_FILTER = "FILTER";
94
95   private static final String NO_VALUE = VCFConstants.MISSING_VALUE_v4; // '.'
96
97   private static final String DEFAULT_SPECIES = "homo_sapiens";
98
99   /**
100    * A class to model the mapping from sequence to VCF coordinates. Cases
101    * include
102    * <ul>
103    * <li>a direct 1:1 mapping where the sequence is one of the VCF contigs</li>
104    * <li>a mapping of sequence to chromosomal coordinates, where sequence and
105    * VCF use the same reference assembly</li>
106    * <li>a modified mapping of sequence to chromosomal coordinates, where
107    * sequence and VCF use different reference assembles</li>
108    * </ul>
109    */
110   class VCFMap
111   {
112     final String chromosome;
113
114     final MapList map;
115
116     VCFMap(String chr, MapList m)
117     {
118       chromosome = chr;
119       map = m;
120     }
121
122     @Override
123     public String toString()
124     {
125       return chromosome + ":" + map.toString();
126     }
127   }
128
129   /*
130    * Lookup keys, and default values, for Preference entries that describe
131    * patterns for VCF and VEP fields to capture
132    */
133   private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
134
135   private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
136
137   private static final String DEFAULT_VCF_FIELDS = ".*";
138
139   private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
140
141   /*
142    * Lookup keys, and default values, for Preference entries that give
143    * mappings from tokens in the 'reference' header to species or assembly
144    */
145   private static final String VCF_ASSEMBLY = "VCF_ASSEMBLY";
146
147   private static final String DEFAULT_VCF_ASSEMBLY = "assembly19=GRCh37,hs37=GRCh37,grch37=GRCh37,grch38=GRCh38";
148
149   private static final String VCF_SPECIES = "VCF_SPECIES"; // default is human
150
151   private static final String DEFAULT_REFERENCE = "grch37"; // fallback default
152                                                             // is human GRCh37
153
154   /*
155    * keys to fields of VEP CSQ consequence data
156    * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
157    */
158   private static final String CSQ_CONSEQUENCE_KEY = "Consequence";
159
160   private static final String CSQ_ALLELE_KEY = "Allele";
161
162   private static final String CSQ_ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref),
163                                                                  // 1...
164
165   private static final String CSQ_FEATURE_KEY = "Feature"; // Ensembl stable id
166
167   /*
168    * default VCF INFO key for VEP consequence data
169    * NB this can be overridden running VEP with --vcf_info_field
170    * - we don't handle this case (require identifier to be CSQ)
171    */
172   private static final String CSQ_FIELD = "CSQ";
173
174   /*
175    * separator for fields in consequence data is '|'
176    */
177   private static final String PIPE_REGEX = "\\|";
178
179   /*
180    * delimiter that separates multiple consequence data blocks
181    */
182   private static final String COMMA = ",";
183
184   /*
185    * the feature group assigned to a VCF variant in Jalview
186    */
187   private static final String FEATURE_GROUP_VCF = "VCF";
188
189   /*
190    * the VCF file we are processing
191    */
192   protected String vcfFilePath;
193
194   private VCFReader reader;
195
196   /*
197    * holds details of the VCF header lines (metadata)
198    */
199   private VCFHeader header;
200
201   /*
202    * species (as a valid Ensembl term) the VCF is for 
203    */
204   private String vcfSpecies;
205
206   /*
207    * genome assembly version (as a valid Ensembl identifier) the VCF is for 
208    */
209   private String vcfAssembly;
210
211   /*
212    * a Dictionary of contigs (if present) referenced in the VCF file
213    */
214   private SAMSequenceDictionary dictionary;
215
216   /*
217    * the position (0...) of field in each block of
218    * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
219    * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
220    */
221   private int csqConsequenceFieldIndex = -1;
222
223   private int csqAlleleFieldIndex = -1;
224
225   private int csqAlleleNumberFieldIndex = -1;
226
227   private int csqFeatureFieldIndex = -1;
228
229   // todo the same fields for SnpEff ANN data if wanted
230   // see http://snpeff.sourceforge.net/SnpEff_manual.html#input
231
232   /*
233    * a unique identifier under which to save metadata about feature
234    * attributes (selected INFO field data)
235    */
236   private String sourceId;
237
238   /*
239    * The INFO IDs of data that is both present in the VCF file, and
240    * also matched by any filters for data of interest
241    */
242   List<String> vcfFieldsOfInterest;
243
244   /*
245    * The field offsets and identifiers for VEP (CSQ) data that is both present
246    * in the VCF file, and also matched by any filters for data of interest
247    * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
248    */
249   Map<Integer, String> vepFieldsOfInterest;
250
251   /*
252    * key:value for which rejected data has been seen
253    * (the error is logged only once for each combination)
254    */
255   private Set<String> badData;
256
257   /**
258    * Constructor given a VCF file
259    * 
260    * @param alignment
261    */
262   public VCFLoader(String vcfFile)
263   {
264     try
265     {
266       initialise(vcfFile);
267     } catch (IOException e)
268     {
269       System.err.println("Error opening VCF file: " + e.getMessage());
270     }
271   }
272
273   /**
274    * Starts a new thread to query and load VCF variant data on to the given
275    * sequences
276    * <p>
277    * This method is not thread safe - concurrent threads should use separate
278    * instances of this class.
279    * 
280    * @param seqs
281    * @param gui
282    */
283   public void loadVCF(SequenceI[] seqs, final AlignViewControllerGuiI gui)
284   {
285     if (gui != null)
286     {
287       gui.setStatus(MessageManager.getString("label.searching_vcf"));
288     }
289
290     new Thread()
291     {
292       @Override
293       public void run()
294       {
295         VCFLoader.this.doLoad(seqs, gui);
296       }
297     }.start();
298   }
299
300   /**
301    * Reads the specified contig sequence and adds its VCF variants to it
302    * 
303    * @param contig
304    *          the id of a single sequence (contig) to load
305    * @return
306    */
307   public SequenceI loadVCFContig(String contig)
308   {
309     VCFHeaderLine headerLine = header
310             .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
311     if (headerLine == null)
312     {
313       Console.error("VCF reference header not found");
314       return null;
315     }
316     String ref = headerLine.getValue();
317     if (ref.startsWith("file://"))
318     {
319       ref = ref.substring(7);
320     }
321     setSpeciesAndAssembly(ref);
322
323     SequenceI seq = null;
324     File dbFile = new File(ref);
325
326     if (dbFile.exists())
327     {
328       HtsContigDb db = new HtsContigDb("", dbFile);
329       seq = db.getSequenceProxy(contig);
330       loadSequenceVCF(seq);
331       db.close();
332     }
333     else
334     {
335       Console.error("VCF reference not found: " + ref);
336     }
337
338     return seq;
339   }
340
341   /**
342    * Loads VCF on to one or more sequences
343    * 
344    * @param seqs
345    * @param gui
346    *          optional callback handler for messages
347    */
348   protected void doLoad(SequenceI[] seqs, AlignViewControllerGuiI gui)
349   {
350     try
351     {
352       VCFHeaderLine ref = header
353               .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
354       String reference = ref == null ? null : ref.getValue();
355
356       setSpeciesAndAssembly(reference);
357
358       int varCount = 0;
359       int seqCount = 0;
360
361       /*
362        * query for VCF overlapping each sequence in turn
363        */
364       for (SequenceI seq : seqs)
365       {
366         int added = loadSequenceVCF(seq);
367         if (added > 0)
368         {
369           seqCount++;
370           varCount += added;
371           transferAddedFeatures(seq);
372         }
373       }
374       if (gui != null)
375       {
376         String msg = MessageManager.formatMessage("label.added_vcf",
377                 varCount, seqCount);
378         gui.setStatus(msg);
379         if (gui.getFeatureSettingsUI() != null)
380         {
381           gui.getFeatureSettingsUI().discoverAllFeatureData();
382         }
383       }
384     } catch (Throwable e)
385     {
386       System.err.println("Error processing VCF: " + e.getMessage());
387       e.printStackTrace();
388       if (gui != null)
389       {
390         gui.setStatus("Error occurred - see console for details");
391       }
392     } finally
393     {
394       if (reader != null)
395       {
396         try
397         {
398           reader.close();
399         } catch (IOException e)
400         {
401           // ignore
402         }
403       }
404       header = null;
405       dictionary = null;
406     }
407   }
408
409   /**
410    * Attempts to determine and save the species and genome assembly version to
411    * which the VCF data applies. This may be done by parsing the
412    * {@code reference} header line, configured in a property file, or
413    * (potentially) confirmed interactively by the user.
414    * <p>
415    * The saved values should be identifiers valid for Ensembl's REST service
416    * {@code map} endpoint, so they can be used (if necessary) to retrieve the
417    * mapping between VCF coordinates and sequence coordinates.
418    * 
419    * @param reference
420    * @see https://rest.ensembl.org/documentation/info/assembly_map
421    * @see https://rest.ensembl.org/info/assembly/human?content-type=text/xml
422    * @see https://rest.ensembl.org/info/species?content-type=text/xml
423    */
424   protected void setSpeciesAndAssembly(String reference)
425   {
426     if (reference == null)
427     {
428       Console.error("No VCF ##reference found, defaulting to "
429               + DEFAULT_REFERENCE + ":" + DEFAULT_SPECIES);
430       reference = DEFAULT_REFERENCE; // default to GRCh37 if not specified
431     }
432     reference = reference.toLowerCase(Locale.ROOT);
433
434     /*
435      * for a non-human species, or other assembly identifier,
436      * specify as a Jalview property file entry e.g.
437      * VCF_ASSEMBLY = hs37=GRCh37,assembly19=GRCh37
438      * VCF_SPECIES = c_elegans=celegans
439      * to map a token in the reference header to a value
440      */
441     String prop = Cache.getDefault(VCF_ASSEMBLY, DEFAULT_VCF_ASSEMBLY);
442     for (String token : prop.split(","))
443     {
444       String[] tokens = token.split("=");
445       if (tokens.length == 2)
446       {
447         if (reference.contains(tokens[0].trim().toLowerCase(Locale.ROOT)))
448         {
449           vcfAssembly = tokens[1].trim();
450           break;
451         }
452       }
453     }
454
455     vcfSpecies = DEFAULT_SPECIES;
456     prop = Cache.getProperty(VCF_SPECIES);
457     if (prop != null)
458     {
459       for (String token : prop.split(","))
460       {
461         String[] tokens = token.split("=");
462         if (tokens.length == 2)
463         {
464           if (reference.contains(tokens[0].trim().toLowerCase(Locale.ROOT)))
465           {
466             vcfSpecies = tokens[1].trim();
467             break;
468           }
469         }
470       }
471     }
472   }
473
474   /**
475    * Opens the VCF file and parses header data
476    * 
477    * @param filePath
478    * @throws IOException
479    */
480   private void initialise(String filePath) throws IOException
481   {
482     vcfFilePath = filePath;
483
484     reader = new VCFReader(filePath);
485
486     header = reader.getFileHeader();
487
488     try
489     {
490       dictionary = header.getSequenceDictionary();
491     } catch (SAMException e)
492     {
493       // ignore - thrown if any contig line lacks length info
494     }
495
496     sourceId = filePath;
497
498     saveMetadata(sourceId);
499
500     /*
501      * get offset of CSQ ALLELE_NUM and Feature if declared
502      */
503     parseCsqHeader();
504   }
505
506   /**
507    * Reads metadata (such as INFO field descriptions and datatypes) and saves
508    * them for future reference
509    * 
510    * @param theSourceId
511    */
512   void saveMetadata(String theSourceId)
513   {
514     List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
515             DEFAULT_VCF_FIELDS);
516     vcfFieldsOfInterest = new ArrayList<>();
517
518     FeatureSource metadata = new FeatureSource(theSourceId);
519
520     for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
521     {
522       String attributeId = info.getID();
523       String desc = info.getDescription();
524       VCFHeaderLineType type = info.getType();
525       FeatureAttributeType attType = null;
526       switch (type)
527       {
528       case Character:
529         attType = FeatureAttributeType.Character;
530         break;
531       case Flag:
532         attType = FeatureAttributeType.Flag;
533         break;
534       case Float:
535         attType = FeatureAttributeType.Float;
536         break;
537       case Integer:
538         attType = FeatureAttributeType.Integer;
539         break;
540       case String:
541         attType = FeatureAttributeType.String;
542         break;
543       }
544       metadata.setAttributeName(attributeId, desc);
545       metadata.setAttributeType(attributeId, attType);
546
547       if (isFieldWanted(attributeId, vcfFieldPatterns))
548       {
549         vcfFieldsOfInterest.add(attributeId);
550       }
551     }
552
553     FeatureSources.getInstance().addSource(theSourceId, metadata);
554   }
555
556   /**
557    * Answers true if the field id is matched by any of the filter patterns, else
558    * false. Matching is against regular expression patterns, and is not
559    * case-sensitive.
560    * 
561    * @param id
562    * @param filters
563    * @return
564    */
565   private boolean isFieldWanted(String id, List<Pattern> filters)
566   {
567     for (Pattern p : filters)
568     {
569       if (p.matcher(id.toUpperCase(Locale.ROOT)).matches())
570       {
571         return true;
572       }
573     }
574     return false;
575   }
576
577   /**
578    * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
579    * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
580    * required for processing.
581    * <p>
582    * CSQ fields are declared in the CSQ INFO Description e.g.
583    * <p>
584    * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
585    */
586   protected void parseCsqHeader()
587   {
588     List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
589             DEFAULT_VEP_FIELDS);
590     vepFieldsOfInterest = new HashMap<>();
591
592     VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
593     if (csqInfo == null)
594     {
595       return;
596     }
597
598     /*
599      * parse out the pipe-separated list of CSQ fields; we assume here that
600      * these form the last part of the description, and contain no spaces
601      */
602     String desc = csqInfo.getDescription();
603     int spacePos = desc.lastIndexOf(" ");
604     desc = desc.substring(spacePos + 1);
605
606     if (desc != null)
607     {
608       String[] format = desc.split(PIPE_REGEX);
609       int index = 0;
610       for (String field : format)
611       {
612         if (CSQ_CONSEQUENCE_KEY.equals(field))
613         {
614           csqConsequenceFieldIndex = index;
615         }
616         if (CSQ_ALLELE_NUM_KEY.equals(field))
617         {
618           csqAlleleNumberFieldIndex = index;
619         }
620         if (CSQ_ALLELE_KEY.equals(field))
621         {
622           csqAlleleFieldIndex = index;
623         }
624         if (CSQ_FEATURE_KEY.equals(field))
625         {
626           csqFeatureFieldIndex = index;
627         }
628
629         if (isFieldWanted(field, vepFieldFilters))
630         {
631           vepFieldsOfInterest.put(index, field);
632         }
633
634         index++;
635       }
636     }
637   }
638
639   /**
640    * Reads the Preference value for the given key, with default specified if no
641    * preference set. The value is interpreted as a comma-separated list of
642    * regular expressions, and converted into a list of compiled patterns ready
643    * for matching. Patterns are forced to upper-case for non-case-sensitive
644    * matching.
645    * <p>
646    * This supports user-defined filters for fields of interest to capture while
647    * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
648    * fields with an ID of AF, or starting with AC, would be matched.
649    * 
650    * @param key
651    * @param def
652    * @return
653    */
654   private List<Pattern> getFieldMatchers(String key, String def)
655   {
656     String pref = Cache.getDefault(key, def);
657     List<Pattern> patterns = new ArrayList<>();
658     String[] tokens = pref.split(",");
659     for (String token : tokens)
660     {
661       try
662       {
663         patterns.add(Pattern.compile(token.toUpperCase(Locale.ROOT)));
664       } catch (PatternSyntaxException e)
665       {
666         System.err.println("Invalid pattern ignored: " + token);
667       }
668     }
669     return patterns;
670   }
671
672   /**
673    * Transfers VCF features to sequences to which this sequence has a mapping.
674    * 
675    * @param seq
676    */
677   protected void transferAddedFeatures(SequenceI seq)
678   {
679     List<DBRefEntry> dbrefs = seq.getDBRefs();
680     if (dbrefs == null)
681     {
682       return;
683     }
684     for (DBRefEntry dbref : dbrefs)
685     {
686       Mapping mapping = dbref.getMap();
687       if (mapping == null || mapping.getTo() == null)
688       {
689         continue;
690       }
691
692       SequenceI mapTo = mapping.getTo();
693       MapList map = mapping.getMap();
694       if (map.getFromRatio() == 3)
695       {
696         /*
697          * dna-to-peptide product mapping
698          */
699         // JAL-3187 render on the fly instead
700         // AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
701       }
702       else
703       {
704         /*
705          * nucleotide-to-nucleotide mapping e.g. transcript to CDS
706          */
707         List<SequenceFeature> features = seq.getFeatures()
708                 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
709         for (SequenceFeature sf : features)
710         {
711           if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
712           {
713             transferFeature(sf, mapTo, map);
714           }
715         }
716       }
717     }
718   }
719
720   /**
721    * Tries to add overlapping variants read from a VCF file to the given
722    * sequence, and returns the number of variant features added
723    * 
724    * @param seq
725    * @return
726    */
727   protected int loadSequenceVCF(SequenceI seq)
728   {
729     VCFMap vcfMap = getVcfMap(seq);
730     if (vcfMap == null)
731     {
732       return 0;
733     }
734
735     /*
736      * work with the dataset sequence here
737      */
738     SequenceI dss = seq.getDatasetSequence();
739     if (dss == null)
740     {
741       dss = seq;
742     }
743     return addVcfVariants(dss, vcfMap);
744   }
745
746   /**
747    * Answers a map from sequence coordinates to VCF chromosome ranges
748    * 
749    * @param seq
750    * @return
751    */
752   private VCFMap getVcfMap(SequenceI seq)
753   {
754     /*
755      * simplest case: sequence has id and length matching a VCF contig
756      */
757     VCFMap vcfMap = null;
758     if (dictionary != null)
759     {
760       vcfMap = getContigMap(seq);
761     }
762     if (vcfMap != null)
763     {
764       return vcfMap;
765     }
766
767     /*
768      * otherwise, map to VCF from chromosomal coordinates 
769      * of the sequence (if known)
770      */
771     GeneLociI seqCoords = seq.getGeneLoci();
772     if (seqCoords == null)
773     {
774       Console.warn(String.format(
775               "Can't query VCF for %s as chromosome coordinates not known",
776               seq.getName()));
777       return null;
778     }
779
780     String species = seqCoords.getSpeciesId();
781     String chromosome = seqCoords.getChromosomeId();
782     String seqRef = seqCoords.getAssemblyId();
783     MapList map = seqCoords.getMapping();
784
785     // note this requires the configured species to match that
786     // returned with the Ensembl sequence; todo: support aliases?
787     if (!vcfSpecies.equalsIgnoreCase(species))
788     {
789       Console.warn("No VCF loaded to " + seq.getName()
790               + " as species not matched");
791       return null;
792     }
793
794     if (seqRef.equalsIgnoreCase(vcfAssembly))
795     {
796       return new VCFMap(chromosome, map);
797     }
798
799     return new VCFMap(chromosome,GenomicAssemblies.mapAssemblyFor(seqRef,"human",map,chromosome,vcfAssembly));
800   }
801   /**
802    * If the sequence id matches a contig declared in the VCF file, and the
803    * sequence length matches the contig length, then returns a 1:1 map of the
804    * sequence to the contig, else returns null
805    * 
806    * @param seq
807    * @return
808    */
809   private VCFMap getContigMap(SequenceI seq)
810   {
811     String id = seq.getName();
812     SAMSequenceRecord contig = dictionary.getSequence(id);
813     if (contig != null)
814     {
815       int len = seq.getLength();
816       if (len == contig.getSequenceLength())
817       {
818         MapList map = new MapList(new int[] { 1, len },
819                 new int[]
820                 { 1, len }, 1, 1);
821         return new VCFMap(id, map);
822       }
823     }
824     return null;
825   }
826
827   /**
828    * Queries the VCF reader for any variants that overlap the mapped chromosome
829    * ranges of the sequence, and adds as variant features. Returns the number of
830    * overlapping variants found.
831    * 
832    * @param seq
833    * @param map
834    *          mapping from sequence to VCF coordinates
835    * @return
836    */
837   protected int addVcfVariants(SequenceI seq, VCFMap map)
838   {
839     boolean forwardStrand = map.map.isToForwardStrand();
840
841     /*
842      * query the VCF for overlaps of each contiguous chromosomal region
843      */
844     int count = 0;
845
846     for (int[] range : map.map.getToRanges())
847     {
848       int vcfStart = Math.min(range[0], range[1]);
849       int vcfEnd = Math.max(range[0], range[1]);
850       try
851       {
852         CloseableIterator<VariantContext> variants = reader
853                 .query(map.chromosome, vcfStart, vcfEnd);
854         while (variants.hasNext())
855         {
856           VariantContext variant = variants.next();
857
858           int[] featureRange = map.map.locateInFrom(variant.getStart(),
859                   variant.getEnd());
860
861           /*
862            * only take features whose range is fully mappable to sequence positions
863            */
864           if (featureRange != null)
865           {
866             int featureStart = Math.min(featureRange[0], featureRange[1]);
867             int featureEnd = Math.max(featureRange[0], featureRange[1]);
868             if (featureEnd - featureStart == variant.getEnd()
869                     - variant.getStart())
870             {
871               count += addAlleleFeatures(seq, variant, featureStart,
872                       featureEnd, forwardStrand);
873             }
874           }
875         }
876         variants.close();
877       } catch (TribbleException e)
878       {
879         /*
880          * RuntimeException throwable by htsjdk
881          */
882         String msg = String.format("Error reading VCF for %s:%d-%d: %s ",
883                 map.chromosome, vcfStart, vcfEnd, e.getLocalizedMessage());
884         Console.error(msg);
885       }
886     }
887
888     return count;
889   }
890
891   /**
892    * A convenience method to get an attribute value for an alternate allele
893    * 
894    * @param variant
895    * @param attributeName
896    * @param alleleIndex
897    * @return
898    */
899   protected String getAttributeValue(VariantContext variant,
900           String attributeName, int alleleIndex)
901   {
902     Object att = variant.getAttribute(attributeName);
903
904     if (att instanceof String)
905     {
906       return (String) att;
907     }
908     else if (att instanceof ArrayList)
909     {
910       return ((List<String>) att).get(alleleIndex);
911     }
912
913     return null;
914   }
915
916   /**
917    * Adds one variant feature for each allele in the VCF variant record, and
918    * returns the number of features added.
919    * 
920    * @param seq
921    * @param variant
922    * @param featureStart
923    * @param featureEnd
924    * @param forwardStrand
925    * @return
926    */
927   protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
928           int featureStart, int featureEnd, boolean forwardStrand)
929   {
930     int added = 0;
931
932     /*
933      * Javadoc says getAlternateAlleles() imposes no order on the list returned
934      * so we proceed defensively to get them in strict order
935      */
936     int altAlleleCount = variant.getAlternateAlleles().size();
937     for (int i = 0; i < altAlleleCount; i++)
938     {
939       added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
940               forwardStrand);
941     }
942     return added;
943   }
944
945   /**
946    * Inspects one allele and attempts to add a variant feature for it to the
947    * sequence. The additional data associated with this allele is extracted to
948    * store in the feature's key-value map. Answers the number of features added
949    * (0 or 1).
950    * 
951    * @param seq
952    * @param variant
953    * @param altAlleleIndex
954    *          (0, 1..)
955    * @param featureStart
956    * @param featureEnd
957    * @param forwardStrand
958    * @return
959    */
960   protected int addAlleleFeature(SequenceI seq, VariantContext variant,
961           int altAlleleIndex, int featureStart, int featureEnd,
962           boolean forwardStrand)
963   {
964     String reference = variant.getReference().getBaseString();
965     Allele alt = variant.getAlternateAllele(altAlleleIndex);
966     String allele = alt.getBaseString();
967
968     /*
969      * insertion after a genomic base, if on reverse strand, has to be 
970      * converted to insertion of complement after the preceding position 
971      */
972     int referenceLength = reference.length();
973     if (!forwardStrand && allele.length() > referenceLength
974             && allele.startsWith(reference))
975     {
976       featureStart -= referenceLength;
977       featureEnd = featureStart;
978       char insertAfter = seq.getCharAt(featureStart - seq.getStart());
979       reference = Dna.reverseComplement(String.valueOf(insertAfter));
980       allele = allele.substring(referenceLength) + reference;
981     }
982
983     /*
984      * build the ref,alt allele description e.g. "G,A", using the base
985      * complement if the sequence is on the reverse strand
986      */
987     StringBuilder sb = new StringBuilder();
988     sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
989     sb.append(COMMA);
990     sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
991     String alleles = sb.toString(); // e.g. G,A
992
993     /*
994      * pick out the consequence data (if any) that is for the current allele
995      * and feature (transcript) that matches the current sequence
996      */
997     String consequence = getConsequenceForAlleleAndFeature(variant,
998             CSQ_FIELD, altAlleleIndex, csqAlleleFieldIndex,
999             csqAlleleNumberFieldIndex,
1000             seq.getName().toLowerCase(Locale.ROOT), csqFeatureFieldIndex);
1001
1002     /*
1003      * pick out the ontology term for the consequence type
1004      */
1005     String type = SequenceOntologyI.SEQUENCE_VARIANT;
1006     if (consequence != null)
1007     {
1008       type = getOntologyTerm(consequence);
1009     }
1010
1011     SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
1012             featureEnd, FEATURE_GROUP_VCF);
1013     sf.setSource(sourceId);
1014
1015     /*
1016      * save the derived alleles as a named attribute; this will be
1017      * needed when Jalview computes derived peptide variants
1018      */
1019     addFeatureAttribute(sf, Gff3Helper.ALLELES, alleles);
1020
1021     /*
1022      * add selected VCF fixed column data as feature attributes
1023      */
1024     addFeatureAttribute(sf, VCF_POS, String.valueOf(variant.getStart()));
1025     addFeatureAttribute(sf, VCF_ID, variant.getID());
1026     addFeatureAttribute(sf, VCF_QUAL,
1027             String.valueOf(variant.getPhredScaledQual()));
1028     addFeatureAttribute(sf, VCF_FILTER, getFilter(variant));
1029
1030     addAlleleProperties(variant, sf, altAlleleIndex, consequence);
1031
1032     seq.addSequenceFeature(sf);
1033
1034     return 1;
1035   }
1036
1037   /**
1038    * Answers the VCF FILTER value for the variant - or an approximation to it.
1039    * This field is either PASS, or a semi-colon separated list of filters not
1040    * passed. htsjdk saves filters as a HashSet, so the order when reassembled
1041    * into a list may be different.
1042    * 
1043    * @param variant
1044    * @return
1045    */
1046   String getFilter(VariantContext variant)
1047   {
1048     Set<String> filters = variant.getFilters();
1049     if (filters.isEmpty())
1050     {
1051       return NO_VALUE;
1052     }
1053     Iterator<String> iterator = filters.iterator();
1054     String first = iterator.next();
1055     if (filters.size() == 1)
1056     {
1057       return first;
1058     }
1059
1060     StringBuilder sb = new StringBuilder(first);
1061     while (iterator.hasNext())
1062     {
1063       sb.append(";").append(iterator.next());
1064     }
1065
1066     return sb.toString();
1067   }
1068
1069   /**
1070    * Adds one feature attribute unless the value is null, empty or '.'
1071    * 
1072    * @param sf
1073    * @param key
1074    * @param value
1075    */
1076   void addFeatureAttribute(SequenceFeature sf, String key, String value)
1077   {
1078     if (value != null && !value.isEmpty() && !NO_VALUE.equals(value))
1079     {
1080       sf.setValue(key, value);
1081     }
1082   }
1083
1084   /**
1085    * Determines the Sequence Ontology term to use for the variant feature type
1086    * in Jalview. The default is 'sequence_variant', but a more specific term is
1087    * used if:
1088    * <ul>
1089    * <li>VEP (or SnpEff) Consequence annotation is included in the VCF</li>
1090    * <li>sequence id can be matched to VEP Feature (or SnpEff Feature_ID)</li>
1091    * </ul>
1092    * 
1093    * @param consequence
1094    * @return
1095    * @see http://www.sequenceontology.org/browser/current_svn/term/SO:0001060
1096    */
1097   String getOntologyTerm(String consequence)
1098   {
1099     String type = SequenceOntologyI.SEQUENCE_VARIANT;
1100
1101     /*
1102      * could we associate Consequence data with this allele and feature (transcript)?
1103      * if so, prefer the consequence term from that data
1104      */
1105     if (csqAlleleFieldIndex == -1) // && snpEffAlleleFieldIndex == -1
1106     {
1107       /*
1108        * no Consequence data so we can't refine the ontology term
1109        */
1110       return type;
1111     }
1112
1113     if (consequence != null)
1114     {
1115       String[] csqFields = consequence.split(PIPE_REGEX);
1116       if (csqFields.length > csqConsequenceFieldIndex)
1117       {
1118         type = csqFields[csqConsequenceFieldIndex];
1119       }
1120     }
1121     else
1122     {
1123       // todo the same for SnpEff consequence data matching if wanted
1124     }
1125
1126     /*
1127      * if of the form (e.g.) missense_variant&splice_region_variant,
1128      * just take the first ('most severe') consequence
1129      */
1130     if (type != null)
1131     {
1132       int pos = type.indexOf('&');
1133       if (pos > 0)
1134       {
1135         type = type.substring(0, pos);
1136       }
1137     }
1138     return type;
1139   }
1140
1141   /**
1142    * Returns matched consequence data if it can be found, else null.
1143    * <ul>
1144    * <li>inspects the VCF data for key 'vcfInfoId'</li>
1145    * <li>splits this on comma (to distinct consequences)</li>
1146    * <li>returns the first consequence (if any) where</li>
1147    * <ul>
1148    * <li>the allele matches the altAlleleIndex'th allele of variant</li>
1149    * <li>the feature matches the sequence name (e.g. transcript id)</li>
1150    * </ul>
1151    * </ul>
1152    * If matched, the consequence is returned (as pipe-delimited fields).
1153    * 
1154    * @param variant
1155    * @param vcfInfoId
1156    * @param altAlleleIndex
1157    * @param alleleFieldIndex
1158    * @param alleleNumberFieldIndex
1159    * @param seqName
1160    * @param featureFieldIndex
1161    * @return
1162    */
1163   private String getConsequenceForAlleleAndFeature(VariantContext variant,
1164           String vcfInfoId, int altAlleleIndex, int alleleFieldIndex,
1165           int alleleNumberFieldIndex, String seqName, int featureFieldIndex)
1166   {
1167     if (alleleFieldIndex == -1 || featureFieldIndex == -1)
1168     {
1169       return null;
1170     }
1171     Object value = variant.getAttribute(vcfInfoId);
1172
1173     if (value == null || !(value instanceof List<?>))
1174     {
1175       return null;
1176     }
1177
1178     /*
1179      * inspect each consequence in turn (comma-separated blocks
1180      * extracted by htsjdk)
1181      */
1182     List<String> consequences = (List<String>) value;
1183
1184     for (String consequence : consequences)
1185     {
1186       String[] csqFields = consequence.split(PIPE_REGEX);
1187       if (csqFields.length > featureFieldIndex)
1188       {
1189         String featureIdentifier = csqFields[featureFieldIndex];
1190         if (featureIdentifier.length() > 4 && seqName
1191                 .indexOf(featureIdentifier.toLowerCase(Locale.ROOT)) > -1)
1192         {
1193           /*
1194            * feature (transcript) matched - now check for allele match
1195            */
1196           if (matchAllele(variant, altAlleleIndex, csqFields,
1197                   alleleFieldIndex, alleleNumberFieldIndex))
1198           {
1199             return consequence;
1200           }
1201         }
1202       }
1203     }
1204     return null;
1205   }
1206
1207   private boolean matchAllele(VariantContext variant, int altAlleleIndex,
1208           String[] csqFields, int alleleFieldIndex,
1209           int alleleNumberFieldIndex)
1210   {
1211     /*
1212      * if ALLELE_NUM is present, it must match altAlleleIndex
1213      * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1214      */
1215     if (alleleNumberFieldIndex > -1)
1216     {
1217       if (csqFields.length <= alleleNumberFieldIndex)
1218       {
1219         return false;
1220       }
1221       String alleleNum = csqFields[alleleNumberFieldIndex];
1222       return String.valueOf(altAlleleIndex + 1).equals(alleleNum);
1223     }
1224
1225     /*
1226      * else consequence allele must match variant allele
1227      */
1228     if (alleleFieldIndex > -1 && csqFields.length > alleleFieldIndex)
1229     {
1230       String csqAllele = csqFields[alleleFieldIndex];
1231       String vcfAllele = variant.getAlternateAllele(altAlleleIndex)
1232               .getBaseString();
1233       return csqAllele.equals(vcfAllele);
1234     }
1235     return false;
1236   }
1237
1238   /**
1239    * Add any allele-specific VCF key-value data to the sequence feature
1240    * 
1241    * @param variant
1242    * @param sf
1243    * @param altAlelleIndex
1244    *          (0, 1..)
1245    * @param consequence
1246    *          if not null, the consequence specific to this sequence (transcript
1247    *          feature) and allele
1248    */
1249   protected void addAlleleProperties(VariantContext variant,
1250           SequenceFeature sf, final int altAlelleIndex, String consequence)
1251   {
1252     Map<String, Object> atts = variant.getAttributes();
1253
1254     for (Entry<String, Object> att : atts.entrySet())
1255     {
1256       String key = att.getKey();
1257
1258       /*
1259        * extract Consequence data (if present) that we are able to
1260        * associated with the allele for this variant feature
1261        */
1262       if (CSQ_FIELD.equals(key))
1263       {
1264         addConsequences(variant, sf, consequence);
1265         continue;
1266       }
1267
1268       /*
1269        * filter out fields we don't want to capture
1270        */
1271       if (!vcfFieldsOfInterest.contains(key))
1272       {
1273         continue;
1274       }
1275
1276       /*
1277        * we extract values for other data which are allele-specific; 
1278        * these may be per alternate allele (INFO[key].Number = 'A') 
1279        * or per allele including reference (INFO[key].Number = 'R') 
1280        */
1281       VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
1282       if (infoHeader == null)
1283       {
1284         /*
1285          * can't be sure what data belongs to this allele, so
1286          * play safe and don't take any
1287          */
1288         continue;
1289       }
1290
1291       VCFHeaderLineCount number = infoHeader.getCountType();
1292       int index = altAlelleIndex;
1293       if (number == VCFHeaderLineCount.R)
1294       {
1295         /*
1296          * one value per allele including reference, so bump index
1297          * e.g. the 3rd value is for the  2nd alternate allele
1298          */
1299         index++;
1300       }
1301       else if (number != VCFHeaderLineCount.A)
1302       {
1303         /*
1304          * don't save other values as not allele-related
1305          */
1306         continue;
1307       }
1308
1309       /*
1310        * take the index'th value
1311        */
1312       String value = getAttributeValue(variant, key, index);
1313       if (value != null && isValid(variant, key, value))
1314       {
1315         /*
1316          * decode colon, semicolon, equals sign, percent sign, comma (only)
1317          * as required by the VCF specification (para 1.2)
1318          */
1319         value = StringUtils.urlDecode(value, VCF_ENCODABLE);
1320         addFeatureAttribute(sf, key, value);
1321       }
1322     }
1323   }
1324
1325   /**
1326    * Answers true for '.', null, or an empty value, or if the INFO type is
1327    * String. If the INFO type is Integer or Float, answers false if the value is
1328    * not in valid format.
1329    * 
1330    * @param variant
1331    * @param infoId
1332    * @param value
1333    * @return
1334    */
1335   protected boolean isValid(VariantContext variant, String infoId,
1336           String value)
1337   {
1338     if (value == null || value.isEmpty() || NO_VALUE.equals(value))
1339     {
1340       return true;
1341     }
1342     VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(infoId);
1343     if (infoHeader == null)
1344     {
1345       Console.error("Field " + infoId + " has no INFO header");
1346       return false;
1347     }
1348     VCFHeaderLineType infoType = infoHeader.getType();
1349     try
1350     {
1351       if (infoType == VCFHeaderLineType.Integer)
1352       {
1353         Integer.parseInt(value);
1354       }
1355       else if (infoType == VCFHeaderLineType.Float)
1356       {
1357         Float.parseFloat(value);
1358       }
1359     } catch (NumberFormatException e)
1360     {
1361       logInvalidValue(variant, infoId, value);
1362       return false;
1363     }
1364     return true;
1365   }
1366
1367   /**
1368    * Logs an error message for malformed data; duplicate messages (same id and
1369    * value) are not logged
1370    * 
1371    * @param variant
1372    * @param infoId
1373    * @param value
1374    */
1375   private void logInvalidValue(VariantContext variant, String infoId,
1376           String value)
1377   {
1378     if (badData == null)
1379     {
1380       badData = new HashSet<>();
1381     }
1382     String token = infoId + ":" + value;
1383     if (!badData.contains(token))
1384     {
1385       badData.add(token);
1386       Console.error(String.format("Invalid VCF data at %s:%d %s=%s",
1387               variant.getContig(), variant.getStart(), infoId, value));
1388     }
1389   }
1390
1391   /**
1392    * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
1393    * feature.
1394    * <p>
1395    * If <code>myConsequence</code> is not null, then this is the specific
1396    * consequence data (pipe-delimited fields) that is for the current allele and
1397    * transcript (sequence) being processed)
1398    * 
1399    * @param variant
1400    * @param sf
1401    * @param myConsequence
1402    */
1403   protected void addConsequences(VariantContext variant, SequenceFeature sf,
1404           String myConsequence)
1405   {
1406     Object value = variant.getAttribute(CSQ_FIELD);
1407
1408     if (value == null || !(value instanceof List<?>))
1409     {
1410       return;
1411     }
1412
1413     List<String> consequences = (List<String>) value;
1414
1415     /*
1416      * inspect CSQ consequences; restrict to the consequence
1417      * associated with the current transcript (Feature)
1418      */
1419     Map<String, String> csqValues = new HashMap<>();
1420
1421     for (String consequence : consequences)
1422     {
1423       if (myConsequence == null || myConsequence.equals(consequence))
1424       {
1425         String[] csqFields = consequence.split(PIPE_REGEX);
1426
1427         /*
1428          * inspect individual fields of this consequence, copying non-null
1429          * values which are 'fields of interest'
1430          */
1431         int i = 0;
1432         for (String field : csqFields)
1433         {
1434           if (field != null && field.length() > 0)
1435           {
1436             String id = vepFieldsOfInterest.get(i);
1437             if (id != null)
1438             {
1439               /*
1440                * VCF spec requires encoding of special characters e.g. '='
1441                * so decode them here before storing
1442                */
1443               field = StringUtils.urlDecode(field, VCF_ENCODABLE);
1444               csqValues.put(id, field);
1445             }
1446           }
1447           i++;
1448         }
1449       }
1450     }
1451
1452     if (!csqValues.isEmpty())
1453     {
1454       sf.setValue(CSQ_FIELD, csqValues);
1455     }
1456   }
1457
1458   /**
1459    * A convenience method to complement a dna base and return the string value
1460    * of its complement
1461    * 
1462    * @param reference
1463    * @return
1464    */
1465   protected String complement(byte[] reference)
1466   {
1467     return String.valueOf(Dna.getComplement((char) reference[0]));
1468   }
1469
1470   /**
1471    * Transfers the sequence feature to the target sequence, locating its start
1472    * and end range based on the mapping. Features which do not overlap the
1473    * target sequence are ignored.
1474    * 
1475    * @param sf
1476    * @param targetSequence
1477    * @param mapping
1478    *          mapping from the feature's coordinates to the target sequence
1479    */
1480   protected void transferFeature(SequenceFeature sf,
1481           SequenceI targetSequence, MapList mapping)
1482   {
1483     int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1484
1485     if (mappedRange != null)
1486     {
1487       String group = sf.getFeatureGroup();
1488       int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1489       int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1490       SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1491               group, sf.getScore());
1492       targetSequence.addSequenceFeature(copy);
1493     }
1494   }
1495 }