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