711b82abb3ebe5c7391d765f4f39080d1ed30898
[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       // check if reference is wrt assembly19 (GRCh37)
187       // todo may need to allow user to specify reference assembly?
188       boolean isRefGrch37 = (ref != null && ref.getValue().contains(
189               "assembly19"));
190
191       int varCount = 0;
192       int seqCount = 0;
193
194       /*
195        * query for VCF overlapping each sequence in turn
196        */
197       for (SequenceI seq : al.getSequences())
198       {
199         int added = loadSequenceVCF(seq, reader, isRefGrch37);
200         if (added > 0)
201         {
202           seqCount++;
203           varCount += added;
204           transferAddedFeatures(seq);
205         }
206       }
207       if (gui != null)
208       {
209         // long elapsed = System.currentTimeMillis() - start;
210         String msg = MessageManager.formatMessage("label.added_vcf",
211                 varCount, seqCount);
212         gui.setStatus(msg);
213         if (gui.getFeatureSettingsUI() != null)
214         {
215           gui.getFeatureSettingsUI().discoverAllFeatureData();
216         }
217       }
218     } catch (Throwable e)
219     {
220       System.err.println("Error processing VCF: " + e.getMessage());
221       e.printStackTrace();
222       if (gui != null)
223       {
224         gui.setStatus("Error occurred - see console for details");
225       }
226     } finally
227     {
228       if (reader != null)
229       {
230         try
231         {
232           reader.close();
233         } catch (IOException e)
234         {
235           // ignore
236         }
237       }
238     }
239   }
240
241   /**
242    * Records the position of selected fields defined in the CSQ INFO header (if
243    * there is one). CSQ fields are declared in the CSQ INFO Description e.g.
244    * <p>
245    * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
246    */
247   protected void locateCsqFields()
248   {
249     VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ);
250     if (csqInfo == null)
251     {
252       return;
253     }
254
255     String desc = csqInfo.getDescription();
256     int formatPos = desc.indexOf(FORMAT);
257     if (formatPos == -1)
258     {
259       System.err.println("Parse error, failed to find " + FORMAT
260               + " in " + desc);
261       return;
262     }
263     desc = desc.substring(formatPos + FORMAT.length());
264
265     if (desc != null)
266     {
267       String[] format = desc.split(PIPE_REGEX);
268       int index = 0;
269       for (String field : format)
270       {
271         if (ALLELE_NUM_KEY.equals(field))
272         {
273           csqAlleleNumberFieldIndex = index;
274         }
275         if (ALLELE_KEY.equals(field))
276         {
277           csqAlleleFieldIndex = index;
278         }
279         if (FEATURE_KEY.equals(field))
280         {
281           csqFeatureFieldIndex = index;
282         }
283         index++;
284       }
285     }
286   }
287
288   /**
289    * Transfers VCF features to sequences to which this sequence has a mapping.
290    * If the mapping is 1:3, computes peptide variants from nucleotide variants.
291    * 
292    * @param seq
293    */
294   protected void transferAddedFeatures(SequenceI seq)
295   {
296     DBRefEntry[] dbrefs = seq.getDBRefs();
297     if (dbrefs == null)
298     {
299       return;
300     }
301     for (DBRefEntry dbref : dbrefs)
302     {
303       Mapping mapping = dbref.getMap();
304       if (mapping == null || mapping.getTo() == null)
305       {
306         continue;
307       }
308
309       SequenceI mapTo = mapping.getTo();
310       MapList map = mapping.getMap();
311       if (map.getFromRatio() == 3)
312       {
313         /*
314          * dna-to-peptide product mapping
315          */
316         AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
317       }
318       else
319       {
320         /*
321          * nucleotide-to-nucleotide mapping e.g. transcript to CDS
322          */
323         List<SequenceFeature> features = seq.getFeatures()
324                 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
325         for (SequenceFeature sf : features)
326         {
327           if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
328           {
329             transferFeature(sf, mapTo, map);
330           }
331         }
332       }
333     }
334   }
335
336   /**
337    * Tries to add overlapping variants read from a VCF file to the given
338    * sequence, and returns the number of variant features added. Note that this
339    * requires the sequence to hold information as to its chromosomal positions
340    * and reference, in order to be able to map the VCF variants to the sequence.
341    * 
342    * @param seq
343    * @param reader
344    * @param isVcfRefGrch37
345    * @return
346    */
347   protected int loadSequenceVCF(SequenceI seq, VCFReader reader,
348           boolean isVcfRefGrch37)
349   {
350     int count = 0;
351     GeneLociI seqCoords = seq.getGeneLoci();
352     if (seqCoords == null)
353     {
354       System.out.println(String.format(
355               "Can't query VCF for %s as chromosome coordinates not known",
356               seq.getName()));
357       return 0;
358     }
359
360     List<int[]> seqChromosomalContigs = seqCoords.getMap().getToRanges();
361     for (int[] range : seqChromosomalContigs)
362     {
363       count += addVcfVariants(seq, reader, range, isVcfRefGrch37);
364     }
365
366     return count;
367   }
368
369   /**
370    * Queries the VCF reader for any variants that overlap the given chromosome
371    * region of the sequence, and adds as variant features. Returns the number of
372    * overlapping variants found.
373    * 
374    * @param seq
375    * @param reader
376    * @param range
377    *          start-end range of a sequence region in its chromosomal
378    *          coordinates
379    * @param isVcfRefGrch37
380    *          true if the VCF is with reference to GRCh37
381    * @return
382    */
383   protected int addVcfVariants(SequenceI seq, VCFReader reader,
384           int[] range, boolean isVcfRefGrch37)
385   {
386     GeneLociI seqCoords = seq.getGeneLoci();
387
388     String chromosome = seqCoords.getChromosomeId();
389     String seqRef = seqCoords.getAssemblyId();
390     String species = seqCoords.getSpeciesId();
391
392     /*
393      * map chromosomal coordinates from GRCh38 (sequence) to
394      * GRCh37 (VCF) if necessary
395      */
396     // TODO generalise for other assemblies and species
397     int offset = 0;
398     String fromRef = "GRCh38";
399     if (fromRef.equalsIgnoreCase(seqRef) && isVcfRefGrch37)
400     {
401       String toRef = "GRCh37";
402       int[] newRange = mapReferenceRange(range, chromosome, "human",
403               fromRef, toRef);
404       if (newRange == null)
405       {
406         System.err.println(String.format(
407                 "Failed to map %s:%s:%s:%d:%d to %s", species, chromosome,
408                 fromRef, range[0], range[1], toRef));
409         return 0;
410       }
411       offset = newRange[0] - range[0];
412       range = newRange;
413     }
414
415     boolean forwardStrand = range[0] <= range[1];
416
417     /*
418      * query the VCF for overlaps
419      * (convert a reverse strand range to forwards)
420      */
421     int count = 0;
422     MapList mapping = seqCoords.getMap();
423
424     int fromLocus = Math.min(range[0], range[1]);
425     int toLocus = Math.max(range[0], range[1]);
426     CloseableIterator<VariantContext> variants = reader.query(chromosome,
427             fromLocus, toLocus);
428     while (variants.hasNext())
429     {
430       /*
431        * get variant location in sequence chromosomal coordinates
432        */
433       VariantContext variant = variants.next();
434
435       int start = variant.getStart() - offset;
436       int end = variant.getEnd() - offset;
437
438       /*
439        * convert chromosomal location to sequence coordinates
440        * - null if a partially overlapping feature
441        */
442       int[] seqLocation = mapping.locateInFrom(start, end);
443       if (seqLocation != null)
444       {
445         count += addAlleleFeatures(seq, variant, seqLocation[0],
446                 seqLocation[1], forwardStrand);
447       }
448     }
449
450     variants.close();
451
452     return count;
453   }
454
455   /**
456    * A convenience method to get the AF value for the given alternate allele
457    * index
458    * 
459    * @param variant
460    * @param alleleIndex
461    * @return
462    */
463   protected float getAlleleFrequency(VariantContext variant, int alleleIndex)
464   {
465     float score = 0f;
466     String attributeValue = getAttributeValue(variant,
467             ALLELE_FREQUENCY_KEY, alleleIndex);
468     if (attributeValue != null)
469     {
470       try
471       {
472         score = Float.parseFloat(attributeValue);
473       } catch (NumberFormatException e)
474       {
475         // leave as 0
476       }
477     }
478
479     return score;
480   }
481
482   /**
483    * A convenience method to get an attribute value for an alternate allele
484    * 
485    * @param variant
486    * @param attributeName
487    * @param alleleIndex
488    * @return
489    */
490   protected String getAttributeValue(VariantContext variant,
491           String attributeName, int alleleIndex)
492   {
493     Object att = variant.getAttribute(attributeName);
494
495     if (att instanceof String)
496     {
497       return (String) att;
498     }
499     else if (att instanceof ArrayList)
500     {
501       return ((List<String>) att).get(alleleIndex);
502     }
503
504     return null;
505   }
506
507   /**
508    * Adds one variant feature for each allele in the VCF variant record, and
509    * returns the number of features added.
510    * 
511    * @param seq
512    * @param variant
513    * @param featureStart
514    * @param featureEnd
515    * @param forwardStrand
516    * @return
517    */
518   protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
519           int featureStart, int featureEnd, boolean forwardStrand)
520   {
521     int added = 0;
522
523     /*
524      * Javadoc says getAlternateAlleles() imposes no order on the list returned
525      * so we proceed defensively to get them in strict order
526      */
527     int altAlleleCount = variant.getAlternateAlleles().size();
528     for (int i = 0; i < altAlleleCount; i++)
529     {
530       added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
531               forwardStrand);
532     }
533     return added;
534   }
535
536   /**
537    * Inspects one allele and attempts to add a variant feature for it to the
538    * sequence. We extract as much as possible of the additional data associated
539    * with this allele to store in the feature's key-value map. Answers the
540    * number of features added (0 or 1).
541    * 
542    * @param seq
543    * @param variant
544    * @param altAlleleIndex
545    *          (0, 1..)
546    * @param featureStart
547    * @param featureEnd
548    * @param forwardStrand
549    * @return
550    */
551   protected int addAlleleFeature(SequenceI seq, VariantContext variant,
552           int altAlleleIndex, int featureStart, int featureEnd,
553           boolean forwardStrand)
554   {
555     String reference = variant.getReference().getBaseString();
556     Allele alt = variant.getAlternateAllele(altAlleleIndex);
557     String allele = alt.getBaseString();
558
559     /*
560      * build the ref,alt allele description e.g. "G,A", using the base
561      * complement if the sequence is on the reverse strand
562      */
563     // TODO check how structural variants are shown on reverse strand
564     StringBuilder sb = new StringBuilder();
565     sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
566     sb.append(COMMA);
567     sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
568     String alleles = sb.toString(); // e.g. G,A
569
570     String type = SequenceOntologyI.SEQUENCE_VARIANT;
571     float score = getAlleleFrequency(variant, altAlleleIndex);
572
573     SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
574             featureEnd, score, FEATURE_GROUP_VCF);
575
576     sf.setValue(Gff3Helper.ALLELES, alleles);
577
578     addAlleleProperties(variant, seq, sf, altAlleleIndex);
579
580     seq.addSequenceFeature(sf);
581
582     return 1;
583   }
584
585   /**
586    * Add any allele-specific VCF key-value data to the sequence feature
587    * 
588    * @param variant
589    * @param seq
590    * @param sf
591    * @param altAlelleIndex
592    *          (0, 1..)
593    */
594   protected void addAlleleProperties(VariantContext variant, SequenceI seq,
595           SequenceFeature sf, final int altAlelleIndex)
596   {
597     Map<String, Object> atts = variant.getAttributes();
598
599     for (Entry<String, Object> att : atts.entrySet())
600     {
601       String key = att.getKey();
602
603       /*
604        * extract Consequence data (if present) that we are able to
605        * associated with the allele for this variant feature
606        */
607       if (CSQ.equals(key))
608       {
609         addConsequences(variant, seq, sf, altAlelleIndex);
610         continue;
611       }
612
613       /*
614        * we extract values for other data which are allele-specific; 
615        * these may be per alternate allele (INFO[key].Number = 'A') 
616        * or per allele including reference (INFO[key].Number = 'R') 
617        */
618       VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
619       if (infoHeader == null)
620       {
621         /*
622          * can't be sure what data belongs to this allele, so
623          * play safe and don't take any
624          */
625         continue;
626       }
627
628       VCFHeaderLineCount number = infoHeader.getCountType();
629       int index = altAlelleIndex;
630       if (number == VCFHeaderLineCount.R)
631       {
632         /*
633          * one value per allele including reference, so bump index
634          * e.g. the 3rd value is for the  2nd alternate allele
635          */
636         index++;
637       }
638       else if (number != VCFHeaderLineCount.A)
639       {
640         /*
641          * don't save other values as not allele-related
642          */
643         continue;
644       }
645
646       /*
647        * take the index'th value
648        */
649       String value = getAttributeValue(variant, key, index);
650       if (value != null)
651       {
652         sf.setValue(key, value);
653       }
654     }
655   }
656
657   /**
658    * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
659    * feature for the current allele (and transcript if applicable)
660    * <p>
661    * Allele matching: if field ALLELE_NUM is present, it must match
662    * altAlleleIndex. If not present, then field Allele value must match the VCF
663    * Allele.
664    * <p>
665    * Transcript matching: if sequence name can be identified to at least one of
666    * the consequences' Feature values, then select only consequences that match
667    * the value (i.e. consequences for the current transcript sequence). If not,
668    * take all consequences (this is the case when adding features to the gene
669    * sequence).
670    * 
671    * @param variant
672    * @param seq
673    * @param sf
674    * @param altAlelleIndex
675    *          (0, 1..)
676    */
677   protected void addConsequences(VariantContext variant, SequenceI seq,
678           SequenceFeature sf, int altAlelleIndex)
679   {
680     Object value = variant.getAttribute(CSQ);
681
682     if (value == null || !(value instanceof ArrayList<?>))
683     {
684       return;
685     }
686
687     List<String> consequences = (List<String>) value;
688
689     /*
690      * if CSQ data includes 'Feature', and any value matches the sequence name,
691      * then restrict consequence data to only the matching value (transcript)
692      * i.e. just pick out consequences for the transcript the variant feature is on
693      */
694     String seqName = seq.getName()== null ? "" : seq.getName().toLowerCase();
695     String matchFeature = null;
696     if (csqFeatureFieldIndex > -1)
697     {
698       for (String consequence : consequences)
699       {
700         String[] csqFields = consequence.split(PIPE_REGEX);
701         if (csqFields.length > csqFeatureFieldIndex)
702         {
703           String featureIdentifier = csqFields[csqFeatureFieldIndex];
704           if (featureIdentifier.length() > 4
705                   && seqName.indexOf(featureIdentifier.toLowerCase()) > -1)
706           {
707             matchFeature = featureIdentifier;
708           }
709         }
710       }
711     }
712
713     StringBuilder sb = new StringBuilder(128);
714     boolean found = false;
715
716     for (String consequence : consequences)
717     {
718       String[] csqFields = consequence.split(PIPE_REGEX);
719
720       if (includeConsequence(csqFields, matchFeature, variant,
721               altAlelleIndex))
722       {
723         if (found)
724         {
725           sb.append(COMMA);
726         }
727         found = true;
728         sb.append(consequence);
729       }
730     }
731
732     if (found)
733     {
734       sf.setValue(CSQ, sb.toString());
735     }
736   }
737
738   /**
739    * Answers true if we want to associate this block of consequence data with
740    * the specified alternate allele of the VCF variant.
741    * <p>
742    * If consequence data includes the ALLELE_NUM field, then this has to match
743    * altAlleleIndex. Otherwise the Allele field of the consequence data has to
744    * match the allele value.
745    * <p>
746    * Optionally (if matchFeature is not null), restrict to only include
747    * consequences whose Feature value matches. This allows us to attach
748    * consequences to their respective transcripts.
749    * 
750    * @param csqFields
751    * @param matchFeature
752    * @param variant
753    * @param altAlelleIndex
754    *          (0, 1..)
755    * @return
756    */
757   protected boolean includeConsequence(String[] csqFields,
758           String matchFeature, VariantContext variant, int altAlelleIndex)
759   {
760     /*
761      * check consequence is for the current transcript
762      */
763     if (matchFeature != null)
764     {
765       if (csqFields.length <= csqFeatureFieldIndex)
766       {
767         return false;
768       }
769       String featureIdentifier = csqFields[csqFeatureFieldIndex];
770       if (!featureIdentifier.equals(matchFeature))
771       {
772         return false; // consequence is for a different transcript
773       }
774     }
775
776     /*
777      * if ALLELE_NUM is present, it must match altAlleleIndex
778      * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
779      */
780     if (csqAlleleNumberFieldIndex > -1)
781     {
782       if (csqFields.length <= csqAlleleNumberFieldIndex)
783       {
784         return false;
785       }
786       String alleleNum = csqFields[csqAlleleNumberFieldIndex];
787       return String.valueOf(altAlelleIndex + 1).equals(alleleNum);
788     }
789
790     /*
791      * else consequence allele must match variant allele
792      */
793     if (csqAlleleFieldIndex > -1 && csqFields.length > csqAlleleFieldIndex)
794     {
795       String csqAllele = csqFields[csqAlleleFieldIndex];
796       String vcfAllele = variant.getAlternateAllele(altAlelleIndex)
797               .getBaseString();
798       return csqAllele.equals(vcfAllele);
799     }
800
801     return false;
802   }
803
804   /**
805    * A convenience method to complement a dna base and return the string value
806    * of its complement
807    * 
808    * @param reference
809    * @return
810    */
811   protected String complement(byte[] reference)
812   {
813     return String.valueOf(Dna.getComplement((char) reference[0]));
814   }
815
816   /**
817    * Determines the location of the query range (chromosome positions) in a
818    * different reference assembly.
819    * <p>
820    * If the range is just a subregion of one for which we already have a mapping
821    * (for example, an exon sub-region of a gene), then the mapping is just
822    * computed arithmetically.
823    * <p>
824    * Otherwise, calls the Ensembl REST service that maps from one assembly
825    * reference's coordinates to another's
826    * 
827    * @param queryRange
828    *          start-end chromosomal range in 'fromRef' coordinates
829    * @param chromosome
830    * @param species
831    * @param fromRef
832    *          assembly reference for the query coordinates
833    * @param toRef
834    *          assembly reference we wish to translate to
835    * @return the start-end range in 'toRef' coordinates
836    */
837   protected int[] mapReferenceRange(int[] queryRange, String chromosome,
838           String species, String fromRef, String toRef)
839   {
840     /*
841      * first try shorcut of computing the mapping as a subregion of one
842      * we already have (e.g. for an exon, if we have the gene mapping)
843      */
844     int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
845             species, fromRef, toRef);
846     if (mappedRange != null)
847     {
848       return mappedRange;
849     }
850
851     /*
852      * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
853      */
854     EnsemblMap mapper = new EnsemblMap();
855     int[] mapping = mapper.getMapping(species, chromosome, fromRef, toRef,
856             queryRange);
857
858     if (mapping == null)
859     {
860       // mapping service failure
861       return null;
862     }
863
864     /*
865      * save mapping for possible future re-use
866      */
867     String key = makeRangesKey(chromosome, species, fromRef, toRef);
868     if (!assemblyMappings.containsKey(key))
869     {
870       assemblyMappings.put(key, new HashMap<int[], int[]>());
871     }
872
873     assemblyMappings.get(key).put(queryRange, mapping);
874
875     return mapping;
876   }
877
878   /**
879    * If we already have a 1:1 contiguous mapping which subsumes the given query
880    * range, this method just calculates and returns the subset of that mapping,
881    * else it returns null. In practical terms, if a gene has a contiguous
882    * mapping between (for example) GRCh37 and GRCh38, then we assume that its
883    * subsidiary exons occupy unchanged relative positions, and just compute
884    * these as offsets, rather than do another lookup of the mapping.
885    * <p>
886    * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
887    * simply remove this method or let it always return null.
888    * <p>
889    * Warning: many rapid calls to the /map service map result in a 429 overload
890    * error response
891    * 
892    * @param queryRange
893    * @param chromosome
894    * @param species
895    * @param fromRef
896    * @param toRef
897    * @return
898    */
899   protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
900           String species, String fromRef, String toRef)
901   {
902     String key = makeRangesKey(chromosome, species, fromRef, toRef);
903     if (assemblyMappings.containsKey(key))
904     {
905       Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
906       for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
907       {
908         int[] fromRange = mappedRange.getKey();
909         int[] toRange = mappedRange.getValue();
910         if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
911         {
912           /*
913            * mapping is 1:1 in length, so we trust it to have no discontinuities
914            */
915           if (MappingUtils.rangeContains(fromRange, queryRange))
916           {
917             /*
918              * fromRange subsumes our query range
919              */
920             int offset = queryRange[0] - fromRange[0];
921             int mappedRangeFrom = toRange[0] + offset;
922             int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
923             return new int[] { mappedRangeFrom, mappedRangeTo };
924           }
925         }
926       }
927     }
928     return null;
929   }
930
931   /**
932    * Transfers the sequence feature to the target sequence, locating its start
933    * and end range based on the mapping. Features which do not overlap the
934    * target sequence are ignored.
935    * 
936    * @param sf
937    * @param targetSequence
938    * @param mapping
939    *          mapping from the feature's coordinates to the target sequence
940    */
941   protected void transferFeature(SequenceFeature sf,
942           SequenceI targetSequence, MapList mapping)
943   {
944     int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
945   
946     if (mappedRange != null)
947     {
948       String group = sf.getFeatureGroup();
949       int newBegin = Math.min(mappedRange[0], mappedRange[1]);
950       int newEnd = Math.max(mappedRange[0], mappedRange[1]);
951       SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
952               group, sf.getScore());
953       targetSequence.addSequenceFeature(copy);
954     }
955   }
956
957   /**
958    * Formats a ranges map lookup key
959    * 
960    * @param chromosome
961    * @param species
962    * @param fromRef
963    * @param toRef
964    * @return
965    */
966   protected static String makeRangesKey(String chromosome, String species,
967           String fromRef, String toRef)
968   {
969     return species + EXCL + chromosome + EXCL + fromRef + EXCL
970             + toRef;
971   }
972 }