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