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       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     /*
800      * VCF data has a different reference assembly to the sequence:
801      * query Ensembl to map chromosomal coordinates from sequence to VCF
802      */
803     List<int[]> toVcfRanges = new ArrayList<>();
804     List<int[]> fromSequenceRanges = new ArrayList<>();
805
806     for (int[] range : map.getToRanges())
807     {
808       int[] fromRange = map.locateInFrom(range[0], range[1]);
809       if (fromRange == null)
810       {
811         // corrupted map?!?
812         continue;
813       }
814
815       int[] newRange = GenomicAssemblies.mapReferenceRange(range, chromosome, "human", seqRef,
816               vcfAssembly);
817       if (newRange == null)
818       {
819         Console.error(String.format("Failed to map %s:%s:%s:%d:%d to %s",
820                 species, chromosome, seqRef, range[0], range[1],
821                 vcfAssembly));
822         continue;
823       }
824       else
825       {
826         toVcfRanges.add(newRange);
827         fromSequenceRanges.add(fromRange);
828       }
829     }
830
831     return new VCFMap(chromosome,
832             new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
833   }
834
835   /**
836    * If the sequence id matches a contig declared in the VCF file, and the
837    * sequence length matches the contig length, then returns a 1:1 map of the
838    * sequence to the contig, else returns null
839    * 
840    * @param seq
841    * @return
842    */
843   private VCFMap getContigMap(SequenceI seq)
844   {
845     String id = seq.getName();
846     SAMSequenceRecord contig = dictionary.getSequence(id);
847     if (contig != null)
848     {
849       int len = seq.getLength();
850       if (len == contig.getSequenceLength())
851       {
852         MapList map = new MapList(new int[] { 1, len },
853                 new int[]
854                 { 1, len }, 1, 1);
855         return new VCFMap(id, map);
856       }
857     }
858     return null;
859   }
860
861   /**
862    * Queries the VCF reader for any variants that overlap the mapped chromosome
863    * ranges of the sequence, and adds as variant features. Returns the number of
864    * overlapping variants found.
865    * 
866    * @param seq
867    * @param map
868    *          mapping from sequence to VCF coordinates
869    * @return
870    */
871   protected int addVcfVariants(SequenceI seq, VCFMap map)
872   {
873     boolean forwardStrand = map.map.isToForwardStrand();
874
875     /*
876      * query the VCF for overlaps of each contiguous chromosomal region
877      */
878     int count = 0;
879
880     for (int[] range : map.map.getToRanges())
881     {
882       int vcfStart = Math.min(range[0], range[1]);
883       int vcfEnd = Math.max(range[0], range[1]);
884       try
885       {
886         CloseableIterator<VariantContext> variants = reader
887                 .query(map.chromosome, vcfStart, vcfEnd);
888         while (variants.hasNext())
889         {
890           VariantContext variant = variants.next();
891
892           int[] featureRange = map.map.locateInFrom(variant.getStart(),
893                   variant.getEnd());
894
895           /*
896            * only take features whose range is fully mappable to sequence positions
897            */
898           if (featureRange != null)
899           {
900             int featureStart = Math.min(featureRange[0], featureRange[1]);
901             int featureEnd = Math.max(featureRange[0], featureRange[1]);
902             if (featureEnd - featureStart == variant.getEnd()
903                     - variant.getStart())
904             {
905               count += addAlleleFeatures(seq, variant, featureStart,
906                       featureEnd, forwardStrand);
907             }
908           }
909         }
910         variants.close();
911       } catch (TribbleException e)
912       {
913         /*
914          * RuntimeException throwable by htsjdk
915          */
916         String msg = String.format("Error reading VCF for %s:%d-%d: %s ",
917                 map.chromosome, vcfStart, vcfEnd, e.getLocalizedMessage());
918         Console.error(msg);
919       }
920     }
921
922     return count;
923   }
924
925   /**
926    * A convenience method to get an attribute value for an alternate allele
927    * 
928    * @param variant
929    * @param attributeName
930    * @param alleleIndex
931    * @return
932    */
933   protected String getAttributeValue(VariantContext variant,
934           String attributeName, int alleleIndex)
935   {
936     Object att = variant.getAttribute(attributeName);
937
938     if (att instanceof String)
939     {
940       return (String) att;
941     }
942     else if (att instanceof ArrayList)
943     {
944       return ((List<String>) att).get(alleleIndex);
945     }
946
947     return null;
948   }
949
950   /**
951    * Adds one variant feature for each allele in the VCF variant record, and
952    * returns the number of features added.
953    * 
954    * @param seq
955    * @param variant
956    * @param featureStart
957    * @param featureEnd
958    * @param forwardStrand
959    * @return
960    */
961   protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
962           int featureStart, int featureEnd, boolean forwardStrand)
963   {
964     int added = 0;
965
966     /*
967      * Javadoc says getAlternateAlleles() imposes no order on the list returned
968      * so we proceed defensively to get them in strict order
969      */
970     int altAlleleCount = variant.getAlternateAlleles().size();
971     for (int i = 0; i < altAlleleCount; i++)
972     {
973       added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
974               forwardStrand);
975     }
976     return added;
977   }
978
979   /**
980    * Inspects one allele and attempts to add a variant feature for it to the
981    * sequence. The additional data associated with this allele is extracted to
982    * store in the feature's key-value map. Answers the number of features added
983    * (0 or 1).
984    * 
985    * @param seq
986    * @param variant
987    * @param altAlleleIndex
988    *          (0, 1..)
989    * @param featureStart
990    * @param featureEnd
991    * @param forwardStrand
992    * @return
993    */
994   protected int addAlleleFeature(SequenceI seq, VariantContext variant,
995           int altAlleleIndex, int featureStart, int featureEnd,
996           boolean forwardStrand)
997   {
998     String reference = variant.getReference().getBaseString();
999     Allele alt = variant.getAlternateAllele(altAlleleIndex);
1000     String allele = alt.getBaseString();
1001
1002     /*
1003      * insertion after a genomic base, if on reverse strand, has to be 
1004      * converted to insertion of complement after the preceding position 
1005      */
1006     int referenceLength = reference.length();
1007     if (!forwardStrand && allele.length() > referenceLength
1008             && allele.startsWith(reference))
1009     {
1010       featureStart -= referenceLength;
1011       featureEnd = featureStart;
1012       char insertAfter = seq.getCharAt(featureStart - seq.getStart());
1013       reference = Dna.reverseComplement(String.valueOf(insertAfter));
1014       allele = allele.substring(referenceLength) + reference;
1015     }
1016
1017     /*
1018      * build the ref,alt allele description e.g. "G,A", using the base
1019      * complement if the sequence is on the reverse strand
1020      */
1021     StringBuilder sb = new StringBuilder();
1022     sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
1023     sb.append(COMMA);
1024     sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
1025     String alleles = sb.toString(); // e.g. G,A
1026
1027     /*
1028      * pick out the consequence data (if any) that is for the current allele
1029      * and feature (transcript) that matches the current sequence
1030      */
1031     String consequence = getConsequenceForAlleleAndFeature(variant,
1032             CSQ_FIELD, altAlleleIndex, csqAlleleFieldIndex,
1033             csqAlleleNumberFieldIndex,
1034             seq.getName().toLowerCase(Locale.ROOT), csqFeatureFieldIndex);
1035
1036     /*
1037      * pick out the ontology term for the consequence type
1038      */
1039     String type = SequenceOntologyI.SEQUENCE_VARIANT;
1040     if (consequence != null)
1041     {
1042       type = getOntologyTerm(consequence);
1043     }
1044
1045     SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
1046             featureEnd, FEATURE_GROUP_VCF);
1047     sf.setSource(sourceId);
1048
1049     /*
1050      * save the derived alleles as a named attribute; this will be
1051      * needed when Jalview computes derived peptide variants
1052      */
1053     addFeatureAttribute(sf, Gff3Helper.ALLELES, alleles);
1054
1055     /*
1056      * add selected VCF fixed column data as feature attributes
1057      */
1058     addFeatureAttribute(sf, VCF_POS, String.valueOf(variant.getStart()));
1059     addFeatureAttribute(sf, VCF_ID, variant.getID());
1060     addFeatureAttribute(sf, VCF_QUAL,
1061             String.valueOf(variant.getPhredScaledQual()));
1062     addFeatureAttribute(sf, VCF_FILTER, getFilter(variant));
1063
1064     addAlleleProperties(variant, sf, altAlleleIndex, consequence);
1065
1066     seq.addSequenceFeature(sf);
1067
1068     return 1;
1069   }
1070
1071   /**
1072    * Answers the VCF FILTER value for the variant - or an approximation to it.
1073    * This field is either PASS, or a semi-colon separated list of filters not
1074    * passed. htsjdk saves filters as a HashSet, so the order when reassembled
1075    * into a list may be different.
1076    * 
1077    * @param variant
1078    * @return
1079    */
1080   String getFilter(VariantContext variant)
1081   {
1082     Set<String> filters = variant.getFilters();
1083     if (filters.isEmpty())
1084     {
1085       return NO_VALUE;
1086     }
1087     Iterator<String> iterator = filters.iterator();
1088     String first = iterator.next();
1089     if (filters.size() == 1)
1090     {
1091       return first;
1092     }
1093
1094     StringBuilder sb = new StringBuilder(first);
1095     while (iterator.hasNext())
1096     {
1097       sb.append(";").append(iterator.next());
1098     }
1099
1100     return sb.toString();
1101   }
1102
1103   /**
1104    * Adds one feature attribute unless the value is null, empty or '.'
1105    * 
1106    * @param sf
1107    * @param key
1108    * @param value
1109    */
1110   void addFeatureAttribute(SequenceFeature sf, String key, String value)
1111   {
1112     if (value != null && !value.isEmpty() && !NO_VALUE.equals(value))
1113     {
1114       sf.setValue(key, value);
1115     }
1116   }
1117
1118   /**
1119    * Determines the Sequence Ontology term to use for the variant feature type
1120    * in Jalview. The default is 'sequence_variant', but a more specific term is
1121    * used if:
1122    * <ul>
1123    * <li>VEP (or SnpEff) Consequence annotation is included in the VCF</li>
1124    * <li>sequence id can be matched to VEP Feature (or SnpEff Feature_ID)</li>
1125    * </ul>
1126    * 
1127    * @param consequence
1128    * @return
1129    * @see http://www.sequenceontology.org/browser/current_svn/term/SO:0001060
1130    */
1131   String getOntologyTerm(String consequence)
1132   {
1133     String type = SequenceOntologyI.SEQUENCE_VARIANT;
1134
1135     /*
1136      * could we associate Consequence data with this allele and feature (transcript)?
1137      * if so, prefer the consequence term from that data
1138      */
1139     if (csqAlleleFieldIndex == -1) // && snpEffAlleleFieldIndex == -1
1140     {
1141       /*
1142        * no Consequence data so we can't refine the ontology term
1143        */
1144       return type;
1145     }
1146
1147     if (consequence != null)
1148     {
1149       String[] csqFields = consequence.split(PIPE_REGEX);
1150       if (csqFields.length > csqConsequenceFieldIndex)
1151       {
1152         type = csqFields[csqConsequenceFieldIndex];
1153       }
1154     }
1155     else
1156     {
1157       // todo the same for SnpEff consequence data matching if wanted
1158     }
1159
1160     /*
1161      * if of the form (e.g.) missense_variant&splice_region_variant,
1162      * just take the first ('most severe') consequence
1163      */
1164     if (type != null)
1165     {
1166       int pos = type.indexOf('&');
1167       if (pos > 0)
1168       {
1169         type = type.substring(0, pos);
1170       }
1171     }
1172     return type;
1173   }
1174
1175   /**
1176    * Returns matched consequence data if it can be found, else null.
1177    * <ul>
1178    * <li>inspects the VCF data for key 'vcfInfoId'</li>
1179    * <li>splits this on comma (to distinct consequences)</li>
1180    * <li>returns the first consequence (if any) where</li>
1181    * <ul>
1182    * <li>the allele matches the altAlleleIndex'th allele of variant</li>
1183    * <li>the feature matches the sequence name (e.g. transcript id)</li>
1184    * </ul>
1185    * </ul>
1186    * If matched, the consequence is returned (as pipe-delimited fields).
1187    * 
1188    * @param variant
1189    * @param vcfInfoId
1190    * @param altAlleleIndex
1191    * @param alleleFieldIndex
1192    * @param alleleNumberFieldIndex
1193    * @param seqName
1194    * @param featureFieldIndex
1195    * @return
1196    */
1197   private String getConsequenceForAlleleAndFeature(VariantContext variant,
1198           String vcfInfoId, int altAlleleIndex, int alleleFieldIndex,
1199           int alleleNumberFieldIndex, String seqName, int featureFieldIndex)
1200   {
1201     if (alleleFieldIndex == -1 || featureFieldIndex == -1)
1202     {
1203       return null;
1204     }
1205     Object value = variant.getAttribute(vcfInfoId);
1206
1207     if (value == null || !(value instanceof List<?>))
1208     {
1209       return null;
1210     }
1211
1212     /*
1213      * inspect each consequence in turn (comma-separated blocks
1214      * extracted by htsjdk)
1215      */
1216     List<String> consequences = (List<String>) value;
1217
1218     for (String consequence : consequences)
1219     {
1220       String[] csqFields = consequence.split(PIPE_REGEX);
1221       if (csqFields.length > featureFieldIndex)
1222       {
1223         String featureIdentifier = csqFields[featureFieldIndex];
1224         if (featureIdentifier.length() > 4 && seqName
1225                 .indexOf(featureIdentifier.toLowerCase(Locale.ROOT)) > -1)
1226         {
1227           /*
1228            * feature (transcript) matched - now check for allele match
1229            */
1230           if (matchAllele(variant, altAlleleIndex, csqFields,
1231                   alleleFieldIndex, alleleNumberFieldIndex))
1232           {
1233             return consequence;
1234           }
1235         }
1236       }
1237     }
1238     return null;
1239   }
1240
1241   private boolean matchAllele(VariantContext variant, int altAlleleIndex,
1242           String[] csqFields, int alleleFieldIndex,
1243           int alleleNumberFieldIndex)
1244   {
1245     /*
1246      * if ALLELE_NUM is present, it must match altAlleleIndex
1247      * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1248      */
1249     if (alleleNumberFieldIndex > -1)
1250     {
1251       if (csqFields.length <= alleleNumberFieldIndex)
1252       {
1253         return false;
1254       }
1255       String alleleNum = csqFields[alleleNumberFieldIndex];
1256       return String.valueOf(altAlleleIndex + 1).equals(alleleNum);
1257     }
1258
1259     /*
1260      * else consequence allele must match variant allele
1261      */
1262     if (alleleFieldIndex > -1 && csqFields.length > alleleFieldIndex)
1263     {
1264       String csqAllele = csqFields[alleleFieldIndex];
1265       String vcfAllele = variant.getAlternateAllele(altAlleleIndex)
1266               .getBaseString();
1267       return csqAllele.equals(vcfAllele);
1268     }
1269     return false;
1270   }
1271
1272   /**
1273    * Add any allele-specific VCF key-value data to the sequence feature
1274    * 
1275    * @param variant
1276    * @param sf
1277    * @param altAlelleIndex
1278    *          (0, 1..)
1279    * @param consequence
1280    *          if not null, the consequence specific to this sequence (transcript
1281    *          feature) and allele
1282    */
1283   protected void addAlleleProperties(VariantContext variant,
1284           SequenceFeature sf, final int altAlelleIndex, String consequence)
1285   {
1286     Map<String, Object> atts = variant.getAttributes();
1287
1288     for (Entry<String, Object> att : atts.entrySet())
1289     {
1290       String key = att.getKey();
1291
1292       /*
1293        * extract Consequence data (if present) that we are able to
1294        * associated with the allele for this variant feature
1295        */
1296       if (CSQ_FIELD.equals(key))
1297       {
1298         addConsequences(variant, sf, consequence);
1299         continue;
1300       }
1301
1302       /*
1303        * filter out fields we don't want to capture
1304        */
1305       if (!vcfFieldsOfInterest.contains(key))
1306       {
1307         continue;
1308       }
1309
1310       /*
1311        * we extract values for other data which are allele-specific; 
1312        * these may be per alternate allele (INFO[key].Number = 'A') 
1313        * or per allele including reference (INFO[key].Number = 'R') 
1314        */
1315       VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
1316       if (infoHeader == null)
1317       {
1318         /*
1319          * can't be sure what data belongs to this allele, so
1320          * play safe and don't take any
1321          */
1322         continue;
1323       }
1324
1325       VCFHeaderLineCount number = infoHeader.getCountType();
1326       int index = altAlelleIndex;
1327       if (number == VCFHeaderLineCount.R)
1328       {
1329         /*
1330          * one value per allele including reference, so bump index
1331          * e.g. the 3rd value is for the  2nd alternate allele
1332          */
1333         index++;
1334       }
1335       else if (number != VCFHeaderLineCount.A)
1336       {
1337         /*
1338          * don't save other values as not allele-related
1339          */
1340         continue;
1341       }
1342
1343       /*
1344        * take the index'th value
1345        */
1346       String value = getAttributeValue(variant, key, index);
1347       if (value != null && isValid(variant, key, value))
1348       {
1349         /*
1350          * decode colon, semicolon, equals sign, percent sign, comma (only)
1351          * as required by the VCF specification (para 1.2)
1352          */
1353         value = StringUtils.urlDecode(value, VCF_ENCODABLE);
1354         addFeatureAttribute(sf, key, value);
1355       }
1356     }
1357   }
1358
1359   /**
1360    * Answers true for '.', null, or an empty value, or if the INFO type is
1361    * String. If the INFO type is Integer or Float, answers false if the value is
1362    * not in valid format.
1363    * 
1364    * @param variant
1365    * @param infoId
1366    * @param value
1367    * @return
1368    */
1369   protected boolean isValid(VariantContext variant, String infoId,
1370           String value)
1371   {
1372     if (value == null || value.isEmpty() || NO_VALUE.equals(value))
1373     {
1374       return true;
1375     }
1376     VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(infoId);
1377     if (infoHeader == null)
1378     {
1379       Console.error("Field " + infoId + " has no INFO header");
1380       return false;
1381     }
1382     VCFHeaderLineType infoType = infoHeader.getType();
1383     try
1384     {
1385       if (infoType == VCFHeaderLineType.Integer)
1386       {
1387         Integer.parseInt(value);
1388       }
1389       else if (infoType == VCFHeaderLineType.Float)
1390       {
1391         Float.parseFloat(value);
1392       }
1393     } catch (NumberFormatException e)
1394     {
1395       logInvalidValue(variant, infoId, value);
1396       return false;
1397     }
1398     return true;
1399   }
1400
1401   /**
1402    * Logs an error message for malformed data; duplicate messages (same id and
1403    * value) are not logged
1404    * 
1405    * @param variant
1406    * @param infoId
1407    * @param value
1408    */
1409   private void logInvalidValue(VariantContext variant, String infoId,
1410           String value)
1411   {
1412     if (badData == null)
1413     {
1414       badData = new HashSet<>();
1415     }
1416     String token = infoId + ":" + value;
1417     if (!badData.contains(token))
1418     {
1419       badData.add(token);
1420       Console.error(String.format("Invalid VCF data at %s:%d %s=%s",
1421               variant.getContig(), variant.getStart(), infoId, value));
1422     }
1423   }
1424
1425   /**
1426    * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
1427    * feature.
1428    * <p>
1429    * If <code>myConsequence</code> is not null, then this is the specific
1430    * consequence data (pipe-delimited fields) that is for the current allele and
1431    * transcript (sequence) being processed)
1432    * 
1433    * @param variant
1434    * @param sf
1435    * @param myConsequence
1436    */
1437   protected void addConsequences(VariantContext variant, SequenceFeature sf,
1438           String myConsequence)
1439   {
1440     Object value = variant.getAttribute(CSQ_FIELD);
1441
1442     if (value == null || !(value instanceof List<?>))
1443     {
1444       return;
1445     }
1446
1447     List<String> consequences = (List<String>) value;
1448
1449     /*
1450      * inspect CSQ consequences; restrict to the consequence
1451      * associated with the current transcript (Feature)
1452      */
1453     Map<String, String> csqValues = new HashMap<>();
1454
1455     for (String consequence : consequences)
1456     {
1457       if (myConsequence == null || myConsequence.equals(consequence))
1458       {
1459         String[] csqFields = consequence.split(PIPE_REGEX);
1460
1461         /*
1462          * inspect individual fields of this consequence, copying non-null
1463          * values which are 'fields of interest'
1464          */
1465         int i = 0;
1466         for (String field : csqFields)
1467         {
1468           if (field != null && field.length() > 0)
1469           {
1470             String id = vepFieldsOfInterest.get(i);
1471             if (id != null)
1472             {
1473               /*
1474                * VCF spec requires encoding of special characters e.g. '='
1475                * so decode them here before storing
1476                */
1477               field = StringUtils.urlDecode(field, VCF_ENCODABLE);
1478               csqValues.put(id, field);
1479             }
1480           }
1481           i++;
1482         }
1483       }
1484     }
1485
1486     if (!csqValues.isEmpty())
1487     {
1488       sf.setValue(CSQ_FIELD, csqValues);
1489     }
1490   }
1491
1492   /**
1493    * A convenience method to complement a dna base and return the string value
1494    * of its complement
1495    * 
1496    * @param reference
1497    * @return
1498    */
1499   protected String complement(byte[] reference)
1500   {
1501     return String.valueOf(Dna.getComplement((char) reference[0]));
1502   }
1503
1504   /**
1505    * Transfers the sequence feature to the target sequence, locating its start
1506    * and end range based on the mapping. Features which do not overlap the
1507    * target sequence are ignored.
1508    * 
1509    * @param sf
1510    * @param targetSequence
1511    * @param mapping
1512    *          mapping from the feature's coordinates to the target sequence
1513    */
1514   protected void transferFeature(SequenceFeature sf,
1515           SequenceI targetSequence, MapList mapping)
1516   {
1517     int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1518
1519     if (mappedRange != null)
1520     {
1521       String group = sf.getFeatureGroup();
1522       int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1523       int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1524       SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1525               group, sf.getScore());
1526       targetSequence.addSequenceFeature(copy);
1527     }
1528   }
1529 }