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