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