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