Merge branch 'develop' into features/JAL-1793VCF
[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.AlignmentI;
8 import jalview.datamodel.DBRefEntry;
9 import jalview.datamodel.GeneLociI;
10 import jalview.datamodel.Mapping;
11 import jalview.datamodel.SequenceFeature;
12 import jalview.datamodel.SequenceI;
13 import jalview.datamodel.features.FeatureAttributeType;
14 import jalview.datamodel.features.FeatureSource;
15 import jalview.datamodel.features.FeatureSources;
16 import jalview.ext.ensembl.EnsemblMap;
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.IOException;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.SortedMap;
31 import java.util.TreeMap;
32 import java.util.regex.Pattern;
33 import java.util.regex.PatternSyntaxException;
34
35 import htsjdk.samtools.SAMSequenceRecord;
36 import htsjdk.samtools.util.CloseableIterator;
37 import htsjdk.variant.variantcontext.Allele;
38 import htsjdk.variant.variantcontext.VariantContext;
39 import htsjdk.variant.vcf.VCFContigHeaderLine;
40 import htsjdk.variant.vcf.VCFHeader;
41 import htsjdk.variant.vcf.VCFHeaderLine;
42 import htsjdk.variant.vcf.VCFHeaderLineCount;
43 import htsjdk.variant.vcf.VCFHeaderLineType;
44 import htsjdk.variant.vcf.VCFInfoHeaderLine;
45
46 /**
47  * A class to read VCF data (using the htsjdk) and add variants as sequence
48  * features on dna and any related protein product sequences
49  * 
50  * @author gmcarstairs
51  */
52 public class VCFLoader
53 {
54   /**
55    * A class to model the mapping from sequence to VCF coordinates. Cases include
56    * <ul>
57    * <li>a direct 1:1 mapping where the sequence is one of the VCF contigs</li>
58    * <li>a mapping of sequence to chromosomal coordinates, where sequence and VCF
59    * use the same reference assembly</li>
60    * <li>a modified mapping of sequence to chromosomal coordinates, where sequence
61    * and VCF use different reference assembles</li>
62    * </ul>
63    */
64   class VCFMap
65   {
66     final String chromosome;
67
68     final MapList map;
69
70     VCFMap(String chr, MapList m)
71     {
72       chromosome = chr;
73       map = m;
74     }
75   }
76
77   /*
78    * Lookup keys, and default values, for Preference entries that describe
79    * patterns for VCF and VEP fields to capture 
80    */
81   private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
82
83   private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
84
85   private static final String DEFAULT_VCF_FIELDS = ".*";
86
87   private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
88
89   /*
90    * keys to fields of VEP CSQ consequence data
91    * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
92    */
93   private static final String ALLELE_KEY = "Allele";
94
95   private static final String ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref), 1...
96   private static final String FEATURE_KEY = "Feature"; // Ensembl stable id
97
98   /*
99    * default VCF INFO key for VEP consequence data
100    * NB this can be overridden running VEP with --vcf_info_field
101    * - we don't handle this case (require identifier to be CSQ)
102    */
103   private static final String CSQ_FIELD = "CSQ";
104
105   /*
106    * separator for fields in consequence data is '|'
107    */
108   private static final String PIPE_REGEX = "\\|";
109
110   /*
111    * key for Allele Frequency output by VEP
112    * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
113    */
114   private static final String ALLELE_FREQUENCY_KEY = "AF";
115
116   /*
117    * delimiter that separates multiple consequence data blocks
118    */
119   private static final String COMMA = ",";
120
121   /*
122    * the feature group assigned to a VCF variant in Jalview
123    */
124   private static final String FEATURE_GROUP_VCF = "VCF";
125
126   /*
127    * internal delimiter used to build keys for assemblyMappings
128    * 
129    */
130   private static final String EXCL = "!";
131
132   /*
133    * the alignment we are associating VCF data with
134    */
135   private AlignmentI al;
136
137   /*
138    * mappings between VCF and sequence reference assembly regions, as 
139    * key = "species!chromosome!fromAssembly!toAssembly
140    * value = Map{fromRange, toRange}
141    */
142   private Map<String, Map<int[], int[]>> assemblyMappings;
143
144   /*
145    * holds details of the VCF header lines (metadata)
146    */
147   private VCFHeader header;
148
149   /*
150    * the position (0...) of field in each block of
151    * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
152    * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
153    */
154   private int csqAlleleFieldIndex = -1;
155   private int csqAlleleNumberFieldIndex = -1;
156   private int csqFeatureFieldIndex = -1;
157
158   /*
159    * a unique identifier under which to save metadata about feature
160    * attributes (selected INFO field data)
161    */
162   private String sourceId;
163
164   /*
165    * The INFO IDs of data that is both present in the VCF file, and
166    * also matched by any filters for data of interest
167    */
168   List<String> vcfFieldsOfInterest;
169
170   /*
171    * The field offsets and identifiers for VEP (CSQ) data that is both present
172    * in the VCF file, and also matched by any filters for data of interest
173    * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
174    */
175   Map<Integer, String> vepFieldsOfInterest;
176
177   /**
178    * Constructor given an alignment context
179    * 
180    * @param alignment
181    */
182   public VCFLoader(AlignmentI alignment)
183   {
184     al = alignment;
185
186     // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
187     assemblyMappings = new HashMap<>();
188   }
189
190   /**
191    * Starts a new thread to query and load VCF variant data on to the alignment
192    * <p>
193    * This method is not thread safe - concurrent threads should use separate
194    * instances of this class.
195    * 
196    * @param filePath
197    * @param gui
198    */
199   public void loadVCF(final String filePath,
200           final AlignViewControllerGuiI gui)
201   {
202     if (gui != null)
203     {
204       gui.setStatus(MessageManager.getString("label.searching_vcf"));
205     }
206
207     new Thread()
208     {
209
210       @Override
211       public void run()
212       {
213         VCFLoader.this.doLoad(filePath, gui);
214       }
215
216     }.start();
217   }
218
219   /**
220    * Loads VCF on to an alignment - provided it can be related to one or more
221    * sequence's chromosomal coordinates
222    * 
223    * @param filePath
224    * @param gui
225    *          optional callback handler for messages
226    */
227   protected void doLoad(String filePath, AlignViewControllerGuiI gui)
228   {
229     VCFReader reader = null;
230     try
231     {
232       // long start = System.currentTimeMillis();
233       reader = new VCFReader(filePath);
234
235       header = reader.getFileHeader();
236
237       sourceId = filePath;
238
239       saveMetadata(sourceId);
240
241       /*
242        * get offset of CSQ ALLELE_NUM and Feature if declared
243        */
244       parseCsqHeader();
245
246       VCFHeaderLine ref = header
247               .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
248       String vcfAssembly = ref.getValue();
249
250       int varCount = 0;
251       int seqCount = 0;
252
253       /*
254        * query for VCF overlapping each sequence in turn
255        */
256       for (SequenceI seq : al.getSequences())
257       {
258         int added = loadSequenceVCF(seq, reader, vcfAssembly);
259         if (added > 0)
260         {
261           seqCount++;
262           varCount += added;
263           transferAddedFeatures(seq);
264         }
265       }
266       if (gui != null)
267       {
268         // long elapsed = System.currentTimeMillis() - start;
269         String msg = MessageManager.formatMessage("label.added_vcf",
270                 varCount, seqCount);
271         gui.setStatus(msg);
272         if (gui.getFeatureSettingsUI() != null)
273         {
274           gui.getFeatureSettingsUI().discoverAllFeatureData();
275         }
276       }
277     } catch (Throwable e)
278     {
279       System.err.println("Error processing VCF: " + e.getMessage());
280       e.printStackTrace();
281       if (gui != null)
282       {
283         gui.setStatus("Error occurred - see console for details");
284       }
285     } finally
286     {
287       if (reader != null)
288       {
289         try
290         {
291           reader.close();
292         } catch (IOException e)
293         {
294           // ignore
295         }
296       }
297     }
298   }
299
300   /**
301    * Reads metadata (such as INFO field descriptions and datatypes) and saves
302    * them for future reference
303    * 
304    * @param theSourceId
305    */
306   void saveMetadata(String theSourceId)
307   {
308     List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
309             DEFAULT_VCF_FIELDS);
310     vcfFieldsOfInterest = new ArrayList<>();
311
312     FeatureSource metadata = new FeatureSource(theSourceId);
313
314     for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
315     {
316       String attributeId = info.getID();
317       String desc = info.getDescription();
318       VCFHeaderLineType type = info.getType();
319       FeatureAttributeType attType = null;
320       switch (type)
321       {
322       case Character:
323         attType = FeatureAttributeType.Character;
324         break;
325       case Flag:
326         attType = FeatureAttributeType.Flag;
327         break;
328       case Float:
329         attType = FeatureAttributeType.Float;
330         break;
331       case Integer:
332         attType = FeatureAttributeType.Integer;
333         break;
334       case String:
335         attType = FeatureAttributeType.String;
336         break;
337       }
338       metadata.setAttributeName(attributeId, desc);
339       metadata.setAttributeType(attributeId, attType);
340
341       if (isFieldWanted(attributeId, vcfFieldPatterns))
342       {
343         vcfFieldsOfInterest.add(attributeId);
344       }
345     }
346
347     FeatureSources.getInstance().addSource(theSourceId, metadata);
348   }
349
350   /**
351    * Answers true if the field id is matched by any of the filter patterns, else
352    * false. Matching is against regular expression patterns, and is not
353    * case-sensitive.
354    * 
355    * @param id
356    * @param filters
357    * @return
358    */
359   private boolean isFieldWanted(String id, List<Pattern> filters)
360   {
361     for (Pattern p : filters)
362     {
363       if (p.matcher(id.toUpperCase()).matches())
364       {
365         return true;
366       }
367     }
368     return false;
369   }
370
371   /**
372    * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
373    * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
374    * required for processing.
375    * <p>
376    * CSQ fields are declared in the CSQ INFO Description e.g.
377    * <p>
378    * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
379    */
380   protected void parseCsqHeader()
381   {
382     List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
383             DEFAULT_VEP_FIELDS);
384     vepFieldsOfInterest = new HashMap<>();
385
386     VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
387     if (csqInfo == null)
388     {
389       return;
390     }
391
392     /*
393      * parse out the pipe-separated list of CSQ fields; we assume here that
394      * these form the last part of the description, and contain no spaces
395      */
396     String desc = csqInfo.getDescription();
397     int spacePos = desc.lastIndexOf(" ");
398     desc = desc.substring(spacePos + 1);
399
400     if (desc != null)
401     {
402       String[] format = desc.split(PIPE_REGEX);
403       int index = 0;
404       for (String field : format)
405       {
406         if (ALLELE_NUM_KEY.equals(field))
407         {
408           csqAlleleNumberFieldIndex = index;
409         }
410         if (ALLELE_KEY.equals(field))
411         {
412           csqAlleleFieldIndex = index;
413         }
414         if (FEATURE_KEY.equals(field))
415         {
416           csqFeatureFieldIndex = index;
417         }
418
419         if (isFieldWanted(field, vepFieldFilters))
420         {
421           vepFieldsOfInterest.put(index, field);
422         }
423
424         index++;
425       }
426     }
427   }
428
429   /**
430    * Reads the Preference value for the given key, with default specified if no
431    * preference set. The value is interpreted as a comma-separated list of
432    * regular expressions, and converted into a list of compiled patterns ready
433    * for matching. Patterns are forced to upper-case for non-case-sensitive
434    * matching.
435    * <p>
436    * This supports user-defined filters for fields of interest to capture while
437    * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
438    * fields with an ID of AF, or starting with AC, would be matched.
439    * 
440    * @param key
441    * @param def
442    * @return
443    */
444   private List<Pattern> getFieldMatchers(String key, String def)
445   {
446     String pref = Cache.getDefault(key, def);
447     List<Pattern> patterns = new ArrayList<>();
448     String[] tokens = pref.split(",");
449     for (String token : tokens)
450     {
451       try
452       {
453       patterns.add(Pattern.compile(token.toUpperCase()));
454       } catch (PatternSyntaxException e)
455       {
456         System.err.println("Invalid pattern ignored: " + token);
457       }
458     }
459     return patterns;
460   }
461
462   /**
463    * Transfers VCF features to sequences to which this sequence has a mapping.
464    * If the mapping is 3:1, computes peptide variants from nucleotide variants.
465    * 
466    * @param seq
467    */
468   protected void transferAddedFeatures(SequenceI seq)
469   {
470     DBRefEntry[] dbrefs = seq.getDBRefs();
471     if (dbrefs == null)
472     {
473       return;
474     }
475     for (DBRefEntry dbref : dbrefs)
476     {
477       Mapping mapping = dbref.getMap();
478       if (mapping == null || mapping.getTo() == null)
479       {
480         continue;
481       }
482
483       SequenceI mapTo = mapping.getTo();
484       MapList map = mapping.getMap();
485       if (map.getFromRatio() == 3)
486       {
487         /*
488          * dna-to-peptide product mapping
489          */
490         AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
491       }
492       else
493       {
494         /*
495          * nucleotide-to-nucleotide mapping e.g. transcript to CDS
496          */
497         List<SequenceFeature> features = seq.getFeatures()
498                 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
499         for (SequenceFeature sf : features)
500         {
501           if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
502           {
503             transferFeature(sf, mapTo, map);
504           }
505         }
506       }
507     }
508   }
509
510   /**
511    * Tries to add overlapping variants read from a VCF file to the given
512    * sequence, and returns the number of variant features added. Note that this
513    * requires the sequence to hold information as to its species, chromosomal
514    * positions and reference assembly, in order to be able to map the VCF
515    * variants to the sequence (or not)
516    * 
517    * @param seq
518    * @param reader
519    * @param vcfAssembly
520    * @return
521    */
522   protected int loadSequenceVCF(SequenceI seq, VCFReader reader,
523           String vcfAssembly)
524   {
525     VCFMap vcfMap = getVcfMap(seq, vcfAssembly);
526     if (vcfMap == null)
527     {
528       return 0;
529     }
530
531     return addVcfVariants(seq, reader, vcfMap, vcfAssembly);
532   }
533
534   /**
535    * Answers a map from sequence coordinates to VCF chromosome ranges
536    * 
537    * @param seq
538    * @param vcfAssembly
539    * @return
540    */
541   private VCFMap getVcfMap(SequenceI seq, String vcfAssembly)
542   {
543     /*
544      * simplest case: sequence has id and length matching a VCF contig
545      */
546     GeneLociI seqCoords = seq.getGeneLoci();
547     if (seqCoords == null)
548     {
549       VCFMap map = getContigMap(seq);
550       if (map == null)
551       {
552         Cache.log.warn(String.format(
553                 "Can't query VCF for %s as chromosome coordinates not known",
554                 seq.getName()));
555       }
556       return map;
557     }
558
559     String species = seqCoords.getSpeciesId();
560     String chromosome = seqCoords.getChromosomeId();
561     String seqRef = seqCoords.getAssemblyId();
562     MapList map = seqCoords.getMap();
563
564     if (!vcfSpeciesMatchesSequence(vcfAssembly, species))
565     {
566       return null;
567     }
568
569     if (vcfAssemblyMatchesSequence(vcfAssembly, seqRef))
570     {
571       return new VCFMap(chromosome, map);
572     }
573
574     if (!"GRCh38".equalsIgnoreCase(seqRef) // Ensembl
575             || !vcfAssembly.contains("Homo_sapiens_assembly19")) // gnomAD
576     {
577       return null;
578     }
579
580     /*
581      * map chromosomal coordinates from sequence to VCF if the VCF
582      * data has a different reference assembly to the sequence
583      */
584     // TODO generalise for cases other than GRCh38 -> GRCh37 !
585     // - or get the user to choose in a dialog
586
587     List<int[]> toVcfRanges = new ArrayList<>();
588     List<int[]> fromSequenceRanges = new ArrayList<>();
589     String toRef = "GRCh37";
590
591     for (int[] range : map.getToRanges())
592     {
593       int[] fromRange = map.locateInFrom(range[0], range[1]);
594       if (fromRange == null)
595       {
596         // corrupted map?!?
597         continue;
598       }
599
600       int[] newRange = mapReferenceRange(range, chromosome, "human", seqRef,
601               toRef);
602       if (newRange == null)
603       {
604         Cache.log.error(
605                 String.format("Failed to map %s:%s:%s:%d:%d to %s", species,
606                         chromosome, seqRef, range[0], range[1], toRef));
607         continue;
608       }
609       else
610       {
611         toVcfRanges.add(newRange);
612         fromSequenceRanges.add(fromRange);
613       }
614     }
615
616     return new VCFMap(chromosome,
617             new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
618   }
619
620   /**
621    * If the sequence id matches a contig declared in the VCF file, and the
622    * sequence matches the contig length, then returns a 1:1 map of the sequence to
623    * the contig, else returns null
624    * 
625    * @param seq
626    * @return
627    */
628   private VCFMap getContigMap(SequenceI seq)
629   {
630     String id = seq.getName();
631     for (VCFContigHeaderLine contig : header.getContigLines())
632     {
633       if (contig.getID().equals(id))
634       {
635         /*
636          * have to construct a SAMSequenceRecord to
637          * read the contig 'length' field!
638          */
639         int len = seq.getLength();
640         SAMSequenceRecord ssr = contig.getSAMSequenceRecord();
641         if (len == ssr.getSequenceLength())
642         {
643           MapList map = new MapList(new int[] { 1, len },
644                   new int[]
645                   { 1, len }, 1, 1);
646           return new VCFMap(id, map);
647         }
648       }
649
650     }
651     return null;
652   }
653
654   /**
655    * Answers true if we determine that the VCF data uses the same reference
656    * assembly as the sequence, else false
657    * 
658    * @param vcfAssembly
659    * @param seqRef
660    * @return
661    */
662   private boolean vcfAssemblyMatchesSequence(String vcfAssembly,
663           String seqRef)
664   {
665     // TODO improve on this stub, which handles gnomAD and
666     // hopes for the best for other cases
667
668     if ("GRCh38".equalsIgnoreCase(seqRef) // Ensembl
669             && vcfAssembly.contains("Homo_sapiens_assembly19")) // gnomAD
670     {
671       return false;
672     }
673     return true;
674   }
675
676   /**
677    * Answers true if the species inferred from the VCF reference identifier
678    * matches that for the sequence
679    * 
680    * @param vcfAssembly
681    * @param speciesId
682    * @return
683    */
684   boolean vcfSpeciesMatchesSequence(String vcfAssembly, String speciesId)
685   {
686     // PROBLEM 1
687     // there are many aliases for species - how to equate one with another?
688     // PROBLEM 2
689     // VCF ##reference header is an unstructured URI - how to extract species?
690     // perhaps check if ref includes any (Ensembl) alias of speciesId??
691     // TODO ask the user to confirm this??
692
693     if (vcfAssembly.contains("Homo_sapiens") // gnomAD exome data example
694             && "HOMO_SAPIENS".equals(speciesId)) // Ensembl species id
695     {
696       return true;
697     }
698
699     if (vcfAssembly.contains("c_elegans") // VEP VCF response example
700             && "CAENORHABDITIS_ELEGANS".equals(speciesId)) // Ensembl
701     {
702       return true;
703     }
704
705     // this is not a sustainable solution...
706
707     return false;
708   }
709
710   /**
711    * Queries the VCF reader for any variants that overlap the mapped chromosome
712    * ranges of the sequence, and adds as variant features. Returns the number of
713    * overlapping variants found.
714    * 
715    * @param seq
716    * @param reader
717    * @param map
718    *          mapping from sequence to VCF coordinates
719    * @param vcfAssembly
720    *          the '##reference' identifier for the VCF reference assembly
721    * @return
722    */
723   protected int addVcfVariants(SequenceI seq, VCFReader reader,
724           VCFMap map, String vcfAssembly)
725   {
726     boolean forwardStrand = map.map.isToForwardStrand();
727
728     /*
729      * query the VCF for overlaps of each contiguous chromosomal region
730      */
731     int count = 0;
732
733     for (int[] range : map.map.getToRanges())
734     {
735       int vcfStart = Math.min(range[0], range[1]);
736       int vcfEnd = Math.max(range[0], range[1]);
737       CloseableIterator<VariantContext> variants = reader
738               .query(map.chromosome, vcfStart, vcfEnd);
739       while (variants.hasNext())
740       {
741         VariantContext variant = variants.next();
742
743         int[] featureRange = map.map.locateInFrom(variant.getStart(),
744                 variant.getEnd());
745
746         if (featureRange != null)
747         {
748           int featureStart = Math.min(featureRange[0], featureRange[1]);
749           int featureEnd = Math.max(featureRange[0], featureRange[1]);
750           count += addAlleleFeatures(seq, variant, featureStart, featureEnd,
751                   forwardStrand);
752         }
753       }
754       variants.close();
755     }
756
757     return count;
758   }
759
760   /**
761    * A convenience method to get the AF value for the given alternate allele
762    * index
763    * 
764    * @param variant
765    * @param alleleIndex
766    * @return
767    */
768   protected float getAlleleFrequency(VariantContext variant, int alleleIndex)
769   {
770     float score = 0f;
771     String attributeValue = getAttributeValue(variant,
772             ALLELE_FREQUENCY_KEY, alleleIndex);
773     if (attributeValue != null)
774     {
775       try
776       {
777         score = Float.parseFloat(attributeValue);
778       } catch (NumberFormatException e)
779       {
780         // leave as 0
781       }
782     }
783
784     return score;
785   }
786
787   /**
788    * A convenience method to get an attribute value for an alternate allele
789    * 
790    * @param variant
791    * @param attributeName
792    * @param alleleIndex
793    * @return
794    */
795   protected String getAttributeValue(VariantContext variant,
796           String attributeName, int alleleIndex)
797   {
798     Object att = variant.getAttribute(attributeName);
799
800     if (att instanceof String)
801     {
802       return (String) att;
803     }
804     else if (att instanceof ArrayList)
805     {
806       return ((List<String>) att).get(alleleIndex);
807     }
808
809     return null;
810   }
811
812   /**
813    * Adds one variant feature for each allele in the VCF variant record, and
814    * returns the number of features added.
815    * 
816    * @param seq
817    * @param variant
818    * @param featureStart
819    * @param featureEnd
820    * @param forwardStrand
821    * @return
822    */
823   protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
824           int featureStart, int featureEnd, boolean forwardStrand)
825   {
826     int added = 0;
827
828     /*
829      * Javadoc says getAlternateAlleles() imposes no order on the list returned
830      * so we proceed defensively to get them in strict order
831      */
832     int altAlleleCount = variant.getAlternateAlleles().size();
833     for (int i = 0; i < altAlleleCount; i++)
834     {
835       added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
836               forwardStrand);
837     }
838     return added;
839   }
840
841   /**
842    * Inspects one allele and attempts to add a variant feature for it to the
843    * sequence. We extract as much as possible of the additional data associated
844    * with this allele to store in the feature's key-value map. Answers the
845    * number of features added (0 or 1).
846    * 
847    * @param seq
848    * @param variant
849    * @param altAlleleIndex
850    *          (0, 1..)
851    * @param featureStart
852    * @param featureEnd
853    * @param forwardStrand
854    * @return
855    */
856   protected int addAlleleFeature(SequenceI seq, VariantContext variant,
857           int altAlleleIndex, int featureStart, int featureEnd,
858           boolean forwardStrand)
859   {
860     String reference = variant.getReference().getBaseString();
861     Allele alt = variant.getAlternateAllele(altAlleleIndex);
862     String allele = alt.getBaseString();
863
864     /*
865      * build the ref,alt allele description e.g. "G,A", using the base
866      * complement if the sequence is on the reverse strand
867      */
868     // TODO check how structural variants are shown on reverse strand
869     StringBuilder sb = new StringBuilder();
870     sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
871     sb.append(COMMA);
872     sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
873     String alleles = sb.toString(); // e.g. G,A
874
875     String type = SequenceOntologyI.SEQUENCE_VARIANT;
876     float score = getAlleleFrequency(variant, altAlleleIndex);
877
878     SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
879             featureEnd, score, FEATURE_GROUP_VCF);
880     sf.setSource(sourceId);
881
882     sf.setValue(Gff3Helper.ALLELES, alleles);
883
884     addAlleleProperties(variant, seq, sf, altAlleleIndex);
885
886     seq.addSequenceFeature(sf);
887
888     return 1;
889   }
890
891   /**
892    * Add any allele-specific VCF key-value data to the sequence feature
893    * 
894    * @param variant
895    * @param seq
896    * @param sf
897    * @param altAlelleIndex
898    *          (0, 1..)
899    */
900   protected void addAlleleProperties(VariantContext variant, SequenceI seq,
901           SequenceFeature sf, final int altAlelleIndex)
902   {
903     Map<String, Object> atts = variant.getAttributes();
904
905     for (Entry<String, Object> att : atts.entrySet())
906     {
907       String key = att.getKey();
908
909       /*
910        * extract Consequence data (if present) that we are able to
911        * associated with the allele for this variant feature
912        */
913       if (CSQ_FIELD.equals(key))
914       {
915         addConsequences(variant, seq, sf, altAlelleIndex);
916         continue;
917       }
918
919       /*
920        * filter out fields we don't want to capture
921        */
922       if (!vcfFieldsOfInterest.contains(key))
923       {
924         continue;
925       }
926
927       /*
928        * we extract values for other data which are allele-specific; 
929        * these may be per alternate allele (INFO[key].Number = 'A') 
930        * or per allele including reference (INFO[key].Number = 'R') 
931        */
932       VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
933       if (infoHeader == null)
934       {
935         /*
936          * can't be sure what data belongs to this allele, so
937          * play safe and don't take any
938          */
939         continue;
940       }
941
942       VCFHeaderLineCount number = infoHeader.getCountType();
943       int index = altAlelleIndex;
944       if (number == VCFHeaderLineCount.R)
945       {
946         /*
947          * one value per allele including reference, so bump index
948          * e.g. the 3rd value is for the  2nd alternate allele
949          */
950         index++;
951       }
952       else if (number != VCFHeaderLineCount.A)
953       {
954         /*
955          * don't save other values as not allele-related
956          */
957         continue;
958       }
959
960       /*
961        * take the index'th value
962        */
963       String value = getAttributeValue(variant, key, index);
964       if (value != null)
965       {
966         sf.setValue(key, value);
967       }
968     }
969   }
970
971   /**
972    * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
973    * feature for the current allele (and transcript if applicable)
974    * <p>
975    * Allele matching: if field ALLELE_NUM is present, it must match
976    * altAlleleIndex. If not present, then field Allele value must match the VCF
977    * Allele.
978    * <p>
979    * Transcript matching: if sequence name can be identified to at least one of
980    * the consequences' Feature values, then select only consequences that match
981    * the value (i.e. consequences for the current transcript sequence). If not,
982    * take all consequences (this is the case when adding features to the gene
983    * sequence).
984    * 
985    * @param variant
986    * @param seq
987    * @param sf
988    * @param altAlelleIndex
989    *          (0, 1..)
990    */
991   protected void addConsequences(VariantContext variant, SequenceI seq,
992           SequenceFeature sf, int altAlelleIndex)
993   {
994     Object value = variant.getAttribute(CSQ_FIELD);
995
996     if (value == null || !(value instanceof ArrayList<?>))
997     {
998       return;
999     }
1000
1001     List<String> consequences = (List<String>) value;
1002
1003     /*
1004      * if CSQ data includes 'Feature', and any value matches the sequence name,
1005      * then restrict consequence data to only the matching value (transcript)
1006      * i.e. just pick out consequences for the transcript the variant feature is on
1007      */
1008     String seqName = seq.getName()== null ? "" : seq.getName().toLowerCase();
1009     String matchFeature = null;
1010     if (csqFeatureFieldIndex > -1)
1011     {
1012       for (String consequence : consequences)
1013       {
1014         String[] csqFields = consequence.split(PIPE_REGEX);
1015         if (csqFields.length > csqFeatureFieldIndex)
1016         {
1017           String featureIdentifier = csqFields[csqFeatureFieldIndex];
1018           if (featureIdentifier.length() > 4
1019                   && seqName.indexOf(featureIdentifier.toLowerCase()) > -1)
1020           {
1021             matchFeature = featureIdentifier;
1022           }
1023         }
1024       }
1025     }
1026
1027     /*
1028      * inspect CSQ consequences; where possible restrict to the consequence
1029      * associated with the current transcript (Feature)
1030      */
1031     SortedMap<String, String> csqValues = new TreeMap<>(
1032             String.CASE_INSENSITIVE_ORDER);
1033
1034     for (String consequence : consequences)
1035     {
1036       String[] csqFields = consequence.split(PIPE_REGEX);
1037
1038       if (includeConsequence(csqFields, matchFeature, variant,
1039               altAlelleIndex))
1040       {
1041         /*
1042          * inspect individual fields of this consequence, copying non-null
1043          * values which are 'fields of interest'
1044          */
1045         int i = 0;
1046         for (String field : csqFields)
1047         {
1048           if (field != null && field.length() > 0)
1049           {
1050             String id = vepFieldsOfInterest.get(i);
1051             if (id != null)
1052             {
1053               csqValues.put(id, field);
1054             }
1055           }
1056           i++;
1057         }
1058       }
1059     }
1060
1061     if (!csqValues.isEmpty())
1062     {
1063       sf.setValue(CSQ_FIELD, csqValues);
1064     }
1065   }
1066
1067   /**
1068    * Answers true if we want to associate this block of consequence data with
1069    * the specified alternate allele of the VCF variant.
1070    * <p>
1071    * If consequence data includes the ALLELE_NUM field, then this has to match
1072    * altAlleleIndex. Otherwise the Allele field of the consequence data has to
1073    * match the allele value.
1074    * <p>
1075    * Optionally (if matchFeature is not null), restrict to only include
1076    * consequences whose Feature value matches. This allows us to attach
1077    * consequences to their respective transcripts.
1078    * 
1079    * @param csqFields
1080    * @param matchFeature
1081    * @param variant
1082    * @param altAlelleIndex
1083    *          (0, 1..)
1084    * @return
1085    */
1086   protected boolean includeConsequence(String[] csqFields,
1087           String matchFeature, VariantContext variant, int altAlelleIndex)
1088   {
1089     /*
1090      * check consequence is for the current transcript
1091      */
1092     if (matchFeature != null)
1093     {
1094       if (csqFields.length <= csqFeatureFieldIndex)
1095       {
1096         return false;
1097       }
1098       String featureIdentifier = csqFields[csqFeatureFieldIndex];
1099       if (!featureIdentifier.equals(matchFeature))
1100       {
1101         return false; // consequence is for a different transcript
1102       }
1103     }
1104
1105     /*
1106      * if ALLELE_NUM is present, it must match altAlleleIndex
1107      * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1108      */
1109     if (csqAlleleNumberFieldIndex > -1)
1110     {
1111       if (csqFields.length <= csqAlleleNumberFieldIndex)
1112       {
1113         return false;
1114       }
1115       String alleleNum = csqFields[csqAlleleNumberFieldIndex];
1116       return String.valueOf(altAlelleIndex + 1).equals(alleleNum);
1117     }
1118
1119     /*
1120      * else consequence allele must match variant allele
1121      */
1122     if (csqAlleleFieldIndex > -1 && csqFields.length > csqAlleleFieldIndex)
1123     {
1124       String csqAllele = csqFields[csqAlleleFieldIndex];
1125       String vcfAllele = variant.getAlternateAllele(altAlelleIndex)
1126               .getBaseString();
1127       return csqAllele.equals(vcfAllele);
1128     }
1129
1130     return false;
1131   }
1132
1133   /**
1134    * A convenience method to complement a dna base and return the string value
1135    * of its complement
1136    * 
1137    * @param reference
1138    * @return
1139    */
1140   protected String complement(byte[] reference)
1141   {
1142     return String.valueOf(Dna.getComplement((char) reference[0]));
1143   }
1144
1145   /**
1146    * Determines the location of the query range (chromosome positions) in a
1147    * different reference assembly.
1148    * <p>
1149    * If the range is just a subregion of one for which we already have a mapping
1150    * (for example, an exon sub-region of a gene), then the mapping is just
1151    * computed arithmetically.
1152    * <p>
1153    * Otherwise, calls the Ensembl REST service that maps from one assembly
1154    * reference's coordinates to another's
1155    * 
1156    * @param queryRange
1157    *          start-end chromosomal range in 'fromRef' coordinates
1158    * @param chromosome
1159    * @param species
1160    * @param fromRef
1161    *          assembly reference for the query coordinates
1162    * @param toRef
1163    *          assembly reference we wish to translate to
1164    * @return the start-end range in 'toRef' coordinates
1165    */
1166   protected int[] mapReferenceRange(int[] queryRange, String chromosome,
1167           String species, String fromRef, String toRef)
1168   {
1169     /*
1170      * first try shorcut of computing the mapping as a subregion of one
1171      * we already have (e.g. for an exon, if we have the gene mapping)
1172      */
1173     int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
1174             species, fromRef, toRef);
1175     if (mappedRange != null)
1176     {
1177       return mappedRange;
1178     }
1179
1180     /*
1181      * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
1182      */
1183     EnsemblMap mapper = new EnsemblMap();
1184     int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
1185             toRef, queryRange);
1186
1187     if (mapping == null)
1188     {
1189       // mapping service failure
1190       return null;
1191     }
1192
1193     /*
1194      * save mapping for possible future re-use
1195      */
1196     String key = makeRangesKey(chromosome, species, fromRef, toRef);
1197     if (!assemblyMappings.containsKey(key))
1198     {
1199       assemblyMappings.put(key, new HashMap<int[], int[]>());
1200     }
1201
1202     assemblyMappings.get(key).put(queryRange, mapping);
1203
1204     return mapping;
1205   }
1206
1207   /**
1208    * If we already have a 1:1 contiguous mapping which subsumes the given query
1209    * range, this method just calculates and returns the subset of that mapping,
1210    * else it returns null. In practical terms, if a gene has a contiguous
1211    * mapping between (for example) GRCh37 and GRCh38, then we assume that its
1212    * subsidiary exons occupy unchanged relative positions, and just compute
1213    * these as offsets, rather than do another lookup of the mapping.
1214    * <p>
1215    * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
1216    * simply remove this method or let it always return null.
1217    * <p>
1218    * Warning: many rapid calls to the /map service map result in a 429 overload
1219    * error response
1220    * 
1221    * @param queryRange
1222    * @param chromosome
1223    * @param species
1224    * @param fromRef
1225    * @param toRef
1226    * @return
1227    */
1228   protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
1229           String species, String fromRef, String toRef)
1230   {
1231     String key = makeRangesKey(chromosome, species, fromRef, toRef);
1232     if (assemblyMappings.containsKey(key))
1233     {
1234       Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
1235       for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
1236       {
1237         int[] fromRange = mappedRange.getKey();
1238         int[] toRange = mappedRange.getValue();
1239         if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
1240         {
1241           /*
1242            * mapping is 1:1 in length, so we trust it to have no discontinuities
1243            */
1244           if (MappingUtils.rangeContains(fromRange, queryRange))
1245           {
1246             /*
1247              * fromRange subsumes our query range
1248              */
1249             int offset = queryRange[0] - fromRange[0];
1250             int mappedRangeFrom = toRange[0] + offset;
1251             int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
1252             return new int[] { mappedRangeFrom, mappedRangeTo };
1253           }
1254         }
1255       }
1256     }
1257     return null;
1258   }
1259
1260   /**
1261    * Transfers the sequence feature to the target sequence, locating its start
1262    * and end range based on the mapping. Features which do not overlap the
1263    * target sequence are ignored.
1264    * 
1265    * @param sf
1266    * @param targetSequence
1267    * @param mapping
1268    *          mapping from the feature's coordinates to the target sequence
1269    */
1270   protected void transferFeature(SequenceFeature sf,
1271           SequenceI targetSequence, MapList mapping)
1272   {
1273     int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1274   
1275     if (mappedRange != null)
1276     {
1277       String group = sf.getFeatureGroup();
1278       int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1279       int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1280       SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1281               group, sf.getScore());
1282       targetSequence.addSequenceFeature(copy);
1283     }
1284   }
1285
1286   /**
1287    * Formats a ranges map lookup key
1288    * 
1289    * @param chromosome
1290    * @param species
1291    * @param fromRef
1292    * @param toRef
1293    * @return
1294    */
1295   protected static String makeRangesKey(String chromosome, String species,
1296           String fromRef, String toRef)
1297   {
1298     return species + EXCL + chromosome + EXCL + fromRef + EXCL
1299             + toRef;
1300   }
1301 }