JAL-3469 add "Number=." fields (all values) to all alleles in VCF record
[jalview.git] / src / jalview / io / vcf / VCFLoader.java
1 package jalview.io.vcf;
2
3 import jalview.analysis.Dna;
4 import jalview.api.AlignViewControllerGuiI;
5 import jalview.bin.Cache;
6 import jalview.datamodel.DBRefEntry;
7 import jalview.datamodel.GeneLociI;
8 import jalview.datamodel.Mapping;
9 import jalview.datamodel.SequenceFeature;
10 import jalview.datamodel.SequenceI;
11 import jalview.datamodel.features.FeatureAttributeType;
12 import jalview.datamodel.features.FeatureSource;
13 import jalview.datamodel.features.FeatureSources;
14 import jalview.ext.ensembl.EnsemblMap;
15 import jalview.ext.htsjdk.HtsContigDb;
16 import jalview.ext.htsjdk.VCFReader;
17 import jalview.io.gff.Gff3Helper;
18 import jalview.io.gff.SequenceOntologyI;
19 import jalview.util.MapList;
20 import jalview.util.MappingUtils;
21 import jalview.util.MessageManager;
22 import jalview.util.StringUtils;
23
24 import java.io.File;
25 import java.io.IOException;
26 import java.io.UnsupportedEncodingException;
27 import java.net.URLDecoder;
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.Iterator;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Map.Entry;
35 import java.util.Set;
36 import java.util.regex.Pattern;
37 import java.util.regex.PatternSyntaxException;
38
39 import htsjdk.samtools.SAMException;
40 import htsjdk.samtools.SAMSequenceDictionary;
41 import htsjdk.samtools.SAMSequenceRecord;
42 import htsjdk.samtools.util.CloseableIterator;
43 import htsjdk.tribble.TribbleException;
44 import htsjdk.variant.variantcontext.Allele;
45 import htsjdk.variant.variantcontext.VariantContext;
46 import htsjdk.variant.vcf.VCFConstants;
47 import htsjdk.variant.vcf.VCFHeader;
48 import htsjdk.variant.vcf.VCFHeaderLine;
49 import htsjdk.variant.vcf.VCFHeaderLineCount;
50 import htsjdk.variant.vcf.VCFHeaderLineType;
51 import htsjdk.variant.vcf.VCFInfoHeaderLine;
52
53 /**
54  * A class to read VCF data (using the htsjdk) and add variants as sequence
55  * features on dna and any related protein product sequences
56  * 
57  * @author gmcarstairs
58  */
59 public class VCFLoader
60 {
61   private static final String ENCODED_COMMA = "%2C";
62
63   private static final String ENCODED_PERCENT = "%25";
64
65   private static final String ENCODED_EQUALS = "%3D";
66
67   private static final String ENCODED_SEMICOLON = "%3B";
68
69   private static final String ENCODED_COLON = "%3A";
70
71   private static final String UTF_8 = "UTF-8";
72
73   /*
74    * Jalview feature attributes for VCF fixed column data
75    */
76   private static final String VCF_POS = "POS";
77
78   private static final String VCF_ID = "ID";
79
80   private static final String VCF_QUAL = "QUAL";
81
82   private static final String VCF_FILTER = "FILTER";
83
84   private static final String NO_VALUE = VCFConstants.MISSING_VALUE_v4; // '.'
85
86   private static final String DEFAULT_SPECIES = "homo_sapiens";
87
88   /**
89    * A class to model the mapping from sequence to VCF coordinates. Cases include
90    * <ul>
91    * <li>a direct 1:1 mapping where the sequence is one of the VCF contigs</li>
92    * <li>a mapping of sequence to chromosomal coordinates, where sequence and VCF
93    * use the same reference assembly</li>
94    * <li>a modified mapping of sequence to chromosomal coordinates, where sequence
95    * and VCF use different reference assembles</li>
96    * </ul>
97    */
98   class VCFMap
99   {
100     final String chromosome;
101
102     final MapList map;
103
104     VCFMap(String chr, MapList m)
105     {
106       chromosome = chr;
107       map = m;
108     }
109
110     @Override
111     public String toString()
112     {
113       return chromosome + ":" + map.toString();
114     }
115   }
116
117   /*
118    * Lookup keys, and default values, for Preference entries that describe
119    * patterns for VCF and VEP fields to capture
120    */
121   private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
122
123   private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
124
125   private static final String DEFAULT_VCF_FIELDS = ".*";
126
127   private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
128
129   /*
130    * Lookup keys, and default values, for Preference entries that give
131    * mappings from tokens in the 'reference' header to species or assembly
132    */
133   private static final String VCF_ASSEMBLY = "VCF_ASSEMBLY";
134
135   private static final String DEFAULT_VCF_ASSEMBLY = "assembly19=GRCh37,hs37=GRCh37,grch37=GRCh37,grch38=GRCh38";
136
137   private static final String VCF_SPECIES = "VCF_SPECIES"; // default is human
138
139   private static final String DEFAULT_REFERENCE = "grch37"; // fallback default is human GRCh37
140
141   /*
142    * keys to fields of VEP CSQ consequence data
143    * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
144    */
145   private static final String CSQ_CONSEQUENCE_KEY = "Consequence";
146   private static final String CSQ_ALLELE_KEY = "Allele";
147   private static final String CSQ_ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref), 1...
148   private static final String CSQ_FEATURE_KEY = "Feature"; // Ensembl stable id
149
150   /*
151    * default VCF INFO key for VEP consequence data
152    * NB this can be overridden running VEP with --vcf_info_field
153    * - we don't handle this case (require identifier to be CSQ)
154    */
155   private static final String CSQ_FIELD = "CSQ";
156
157   /*
158    * separator for fields in consequence data is '|'
159    */
160   private static final String PIPE_REGEX = "\\|";
161
162   /*
163    * delimiter that separates multiple consequence data blocks
164    */
165   private static final String COMMA = ",";
166
167   /*
168    * the feature group assigned to a VCF variant in Jalview
169    */
170   private static final String FEATURE_GROUP_VCF = "VCF";
171
172   /*
173    * internal delimiter used to build keys for assemblyMappings
174    * 
175    */
176   private static final String EXCL = "!";
177
178   /*
179    * the VCF file we are processing
180    */
181   protected String vcfFilePath;
182
183   /*
184    * mappings between VCF and sequence reference assembly regions, as 
185    * key = "species!chromosome!fromAssembly!toAssembly
186    * value = Map{fromRange, toRange}
187    */
188   private Map<String, Map<int[], int[]>> assemblyMappings;
189
190   private VCFReader reader;
191
192   /*
193    * holds details of the VCF header lines (metadata)
194    */
195   private VCFHeader header;
196
197   /*
198    * species (as a valid Ensembl term) the VCF is for 
199    */
200   private String vcfSpecies;
201
202   /*
203    * genome assembly version (as a valid Ensembl identifier) the VCF is for 
204    */
205   private String vcfAssembly;
206
207   /*
208    * a Dictionary of contigs (if present) referenced in the VCF file
209    */
210   private SAMSequenceDictionary dictionary;
211
212   /*
213    * the position (0...) of field in each block of
214    * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
215    * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
216    */
217   private int csqConsequenceFieldIndex = -1;
218   private int csqAlleleFieldIndex = -1;
219   private int csqAlleleNumberFieldIndex = -1;
220   private int csqFeatureFieldIndex = -1;
221
222   // todo the same fields for SnpEff ANN data if wanted
223   // see http://snpeff.sourceforge.net/SnpEff_manual.html#input
224
225   /*
226    * a unique identifier under which to save metadata about feature
227    * attributes (selected INFO field data)
228    */
229   private String sourceId;
230
231   /*
232    * The INFO IDs of data that is both present in the VCF file, and
233    * also matched by any filters for data of interest
234    */
235   List<String> vcfFieldsOfInterest;
236
237   /*
238    * The field offsets and identifiers for VEP (CSQ) data that is both present
239    * in the VCF file, and also matched by any filters for data of interest
240    * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
241    */
242   Map<Integer, String> vepFieldsOfInterest;
243
244   /*
245    * key:value for which rejected data has been seen
246    * (the error is logged only once for each combination)
247    */
248   private Set<String> badData;
249
250   /**
251    * Constructor given a path to a VCF file
252    * 
253    * @param vcfFile
254    */
255   public VCFLoader(String vcfFile)
256   {
257     try
258     {
259       initialise(vcfFile);
260     } catch (IOException e)
261     {
262       System.err.println("Error opening VCF file: " + e.getMessage());
263     }
264
265     // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
266     assemblyMappings = new HashMap<>();
267   }
268
269   /**
270    * Starts a new thread to query and load VCF variant data on to the given
271    * sequences
272    * <p>
273    * This method is not thread safe - concurrent threads should use separate
274    * instances of this class.
275    * 
276    * @param seqs
277    * @param gui
278    */
279   public void loadVCF(SequenceI[] seqs, final AlignViewControllerGuiI gui)
280   {
281     if (gui != null)
282     {
283       gui.setStatus(MessageManager.getString("label.searching_vcf"));
284     }
285
286     new Thread()
287     {
288       @Override
289       public void run()
290       {
291         VCFLoader.this.doLoad(seqs, gui);
292       }
293     }.start();
294   }
295
296   /**
297    * Reads the specified contig sequence and adds its VCF variants to it
298    * 
299    * @param contig
300    *          the id of a single sequence (contig) to load
301    * @return
302    */
303   public SequenceI loadVCFContig(String contig)
304   {
305     VCFHeaderLine headerLine = header.getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
306     if (headerLine == null)
307     {
308       Cache.log.error("VCF reference header not found");
309       return null;
310     }
311     String ref = headerLine.getValue();
312     if (ref.startsWith("file://"))
313     {
314       ref = ref.substring(7);
315     }
316     setSpeciesAndAssembly(ref);
317
318     SequenceI seq = null;
319     File dbFile = new File(ref);
320
321     if (dbFile.exists())
322     {
323       HtsContigDb db = new HtsContigDb("", dbFile);
324       seq = db.getSequenceProxy(contig);
325       loadSequenceVCF(seq);
326       db.close();
327     }
328     else
329     {
330       Cache.log.error("VCF reference not found: " + ref);
331     }
332
333     return seq;
334   }
335
336   /**
337    * Loads VCF on to one or more sequences
338    * 
339    * @param seqs
340    * @param gui
341    *          optional callback handler for messages
342    */
343   protected void doLoad(SequenceI[] seqs, AlignViewControllerGuiI gui)
344   {
345     try
346     {
347       VCFHeaderLine ref = header
348               .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
349       String reference = ref == null ? null : ref.getValue();
350
351       setSpeciesAndAssembly(reference);
352
353       int varCount = 0;
354       int seqCount = 0;
355
356       /*
357        * query for VCF overlapping each sequence in turn
358        */
359       for (SequenceI seq : seqs)
360       {
361         int added = loadSequenceVCF(seq);
362         if (added > 0)
363         {
364           seqCount++;
365           varCount += added;
366           transferAddedFeatures(seq);
367         }
368       }
369       if (gui != null)
370       {
371         String msg = MessageManager.formatMessage("label.added_vcf",
372                 varCount, seqCount);
373         gui.setStatus(msg);
374         if (gui.getFeatureSettingsUI() != null)
375         {
376           gui.getFeatureSettingsUI().discoverAllFeatureData();
377         }
378       }
379     } catch (Throwable e)
380     {
381       System.err.println("Error processing VCF: " + e.getMessage());
382       e.printStackTrace();
383       if (gui != null)
384       {
385         gui.setStatus("Error occurred - see console for details");
386       }
387     } finally
388     {
389       if (reader != null)
390       {
391         try
392         {
393           reader.close();
394         } catch (IOException e)
395         {
396           // ignore
397         }
398       }
399       header = null;
400       dictionary = null;
401     }
402   }
403
404   /**
405    * Attempts to determine and save the species and genome assembly version to
406    * which the VCF data applies. This may be done by parsing the {@code reference}
407    * header line, configured in a property file, or (potentially) confirmed
408    * interactively by the user.
409    * <p>
410    * The saved values should be identifiers valid for Ensembl's REST service
411    * {@code map} endpoint, so they can be used (if necessary) to retrieve the
412    * mapping between VCF coordinates and sequence coordinates.
413    * 
414    * @param reference
415    * @see https://rest.ensembl.org/documentation/info/assembly_map
416    * @see https://rest.ensembl.org/info/assembly/human?content-type=text/xml
417    * @see https://rest.ensembl.org/info/species?content-type=text/xml
418    */
419   protected void setSpeciesAndAssembly(String reference)
420   {
421     if (reference == null)
422     {
423       Cache.log.error("No VCF ##reference found, defaulting to "
424               + DEFAULT_REFERENCE + ":" + DEFAULT_SPECIES);
425       reference = DEFAULT_REFERENCE; // default to GRCh37 if not specified
426     }
427     reference = reference.toLowerCase();
428
429     /*
430      * for a non-human species, or other assembly identifier,
431      * specify as a Jalview property file entry e.g.
432      * VCF_ASSEMBLY = hs37=GRCh37,assembly19=GRCh37
433      * VCF_SPECIES = c_elegans=celegans
434      * to map a token in the reference header to a value
435      */
436     String prop = Cache.getDefault(VCF_ASSEMBLY, DEFAULT_VCF_ASSEMBLY);
437     for (String token : prop.split(","))
438     {
439       String[] tokens = token.split("=");
440       if (tokens.length == 2)
441       {
442         if (reference.contains(tokens[0].trim().toLowerCase()))
443         {
444           vcfAssembly = tokens[1].trim();
445           break;
446         }
447       }
448     }
449
450     vcfSpecies = DEFAULT_SPECIES;
451     prop = Cache.getProperty(VCF_SPECIES);
452     if (prop != null)
453     {
454       for (String token : prop.split(","))
455       {
456         String[] tokens = token.split("=");
457         if (tokens.length == 2)
458         {
459           if (reference.contains(tokens[0].trim().toLowerCase()))
460           {
461             vcfSpecies = tokens[1].trim();
462             break;
463           }
464         }
465       }
466     }
467   }
468
469   /**
470    * Opens the VCF file and parses header data
471    * 
472    * @param filePath
473    * @throws IOException
474    */
475   private void initialise(String filePath) throws IOException
476   {
477     vcfFilePath = filePath;
478
479     reader = new VCFReader(filePath);
480
481     header = reader.getFileHeader();
482
483     try
484     {
485       dictionary = header.getSequenceDictionary();
486     } catch (SAMException e)
487     {
488       // ignore - thrown if any contig line lacks length info
489     }
490
491     sourceId = filePath;
492
493     saveMetadata(sourceId);
494
495     /*
496      * get offset of CSQ ALLELE_NUM and Feature if declared
497      */
498     parseCsqHeader();
499   }
500
501   /**
502    * Reads metadata (such as INFO field descriptions and datatypes) and saves
503    * them for future reference
504    * 
505    * @param theSourceId
506    */
507   void saveMetadata(String theSourceId)
508   {
509     List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
510             DEFAULT_VCF_FIELDS);
511     vcfFieldsOfInterest = new ArrayList<>();
512
513     FeatureSource metadata = new FeatureSource(theSourceId);
514
515     for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
516     {
517       String attributeId = info.getID();
518       String desc = info.getDescription();
519       VCFHeaderLineType type = info.getType();
520       FeatureAttributeType attType = null;
521       switch (type)
522       {
523       case Character:
524         attType = FeatureAttributeType.Character;
525         break;
526       case Flag:
527         attType = FeatureAttributeType.Flag;
528         break;
529       case Float:
530         attType = FeatureAttributeType.Float;
531         break;
532       case Integer:
533         attType = FeatureAttributeType.Integer;
534         break;
535       case String:
536         attType = FeatureAttributeType.String;
537         break;
538       }
539       metadata.setAttributeName(attributeId, desc);
540       metadata.setAttributeType(attributeId, attType);
541
542       if (isFieldWanted(attributeId, vcfFieldPatterns))
543       {
544         vcfFieldsOfInterest.add(attributeId);
545       }
546     }
547
548     FeatureSources.getInstance().addSource(theSourceId, metadata);
549   }
550
551   /**
552    * Answers true if the field id is matched by any of the filter patterns, else
553    * false. Matching is against regular expression patterns, and is not
554    * case-sensitive.
555    * 
556    * @param id
557    * @param filters
558    * @return
559    */
560   private boolean isFieldWanted(String id, List<Pattern> filters)
561   {
562     for (Pattern p : filters)
563     {
564       if (p.matcher(id.toUpperCase()).matches())
565       {
566         return true;
567       }
568     }
569     return false;
570   }
571
572   /**
573    * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
574    * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
575    * required for processing.
576    * <p>
577    * CSQ fields are declared in the CSQ INFO Description e.g.
578    * <p>
579    * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
580    */
581   protected void parseCsqHeader()
582   {
583     List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
584             DEFAULT_VEP_FIELDS);
585     vepFieldsOfInterest = new HashMap<>();
586
587     VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
588     if (csqInfo == null)
589     {
590       return;
591     }
592
593     /*
594      * parse out the pipe-separated list of CSQ fields; we assume here that
595      * these form the last part of the description, and contain no spaces
596      */
597     String desc = csqInfo.getDescription();
598     int spacePos = desc.lastIndexOf(" ");
599     desc = desc.substring(spacePos + 1);
600
601     if (desc != null)
602     {
603       String[] format = desc.split(PIPE_REGEX);
604       int index = 0;
605       for (String field : format)
606       {
607         if (CSQ_CONSEQUENCE_KEY.equals(field))
608         {
609           csqConsequenceFieldIndex = index;
610         }
611         if (CSQ_ALLELE_NUM_KEY.equals(field))
612         {
613           csqAlleleNumberFieldIndex = index;
614         }
615         if (CSQ_ALLELE_KEY.equals(field))
616         {
617           csqAlleleFieldIndex = index;
618         }
619         if (CSQ_FEATURE_KEY.equals(field))
620         {
621           csqFeatureFieldIndex = index;
622         }
623
624         if (isFieldWanted(field, vepFieldFilters))
625         {
626           vepFieldsOfInterest.put(index, field);
627         }
628
629         index++;
630       }
631     }
632   }
633
634   /**
635    * Reads the Preference value for the given key, with default specified if no
636    * preference set. The value is interpreted as a comma-separated list of
637    * regular expressions, and converted into a list of compiled patterns ready
638    * for matching. Patterns are forced to upper-case for non-case-sensitive
639    * matching.
640    * <p>
641    * This supports user-defined filters for fields of interest to capture while
642    * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
643    * fields with an ID of AF, or starting with AC, would be matched.
644    * 
645    * @param key
646    * @param def
647    * @return
648    */
649   private List<Pattern> getFieldMatchers(String key, String def)
650   {
651     String pref = Cache.getDefault(key, def);
652     List<Pattern> patterns = new ArrayList<>();
653     String[] tokens = pref.split(",");
654     for (String token : tokens)
655     {
656       try
657       {
658       patterns.add(Pattern.compile(token.toUpperCase()));
659       } catch (PatternSyntaxException e)
660       {
661         System.err.println("Invalid pattern ignored: " + token);
662       }
663     }
664     return patterns;
665   }
666
667   /**
668    * Transfers VCF features to sequences to which this sequence has a mapping.
669    * If the mapping is 3:1, computes peptide variants from nucleotide variants.
670    * 
671    * @param seq
672    */
673   protected void transferAddedFeatures(SequenceI seq)
674   {
675     DBRefEntry[] dbrefs = seq.getDBRefs();
676     if (dbrefs == null)
677     {
678       return;
679     }
680     for (DBRefEntry dbref : dbrefs)
681     {
682       Mapping mapping = dbref.getMap();
683       if (mapping == null || mapping.getTo() == null)
684       {
685         continue;
686       }
687
688       SequenceI mapTo = mapping.getTo();
689       MapList map = mapping.getMap();
690       if (map.getFromRatio() == 3)
691       {
692         /*
693          * dna-to-peptide product mapping
694          */
695         // JAL-3187 render on the fly instead
696         // AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
697       }
698       else
699       {
700         /*
701          * nucleotide-to-nucleotide mapping e.g. transcript to CDS
702          */
703         List<SequenceFeature> features = seq.getFeatures()
704                 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
705         for (SequenceFeature sf : features)
706         {
707           if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
708           {
709             transferFeature(sf, mapTo, map);
710           }
711         }
712       }
713     }
714   }
715
716   /**
717    * Tries to add overlapping variants read from a VCF file to the given sequence,
718    * and returns the number of variant features added
719    * 
720    * @param seq
721    * @return
722    */
723   protected int loadSequenceVCF(SequenceI seq)
724   {
725     VCFMap vcfMap = getVcfMap(seq);
726     if (vcfMap == null)
727     {
728       return 0;
729     }
730
731     /*
732      * work with the dataset sequence here
733      */
734     SequenceI dss = seq.getDatasetSequence();
735     if (dss == null)
736     {
737       dss = seq;
738     }
739     return addVcfVariants(dss, vcfMap);
740   }
741
742   /**
743    * Answers a map from sequence coordinates to VCF chromosome ranges
744    * 
745    * @param seq
746    * @return
747    */
748   private VCFMap getVcfMap(SequenceI seq)
749   {
750     /*
751      * simplest case: sequence has id and length matching a VCF contig
752      */
753     VCFMap vcfMap = null;
754     if (dictionary != null)
755     {
756       vcfMap = getContigMap(seq);
757     }
758     if (vcfMap != null)
759     {
760       return vcfMap;
761     }
762
763     /*
764      * otherwise, map to VCF from chromosomal coordinates 
765      * of the sequence (if known)
766      */
767     GeneLociI seqCoords = seq.getGeneLoci();
768     if (seqCoords == null)
769     {
770       Cache.log.warn(String.format(
771               "Can't query VCF for %s as chromosome coordinates not known",
772               seq.getName()));
773       return null;
774     }
775
776     String species = seqCoords.getSpeciesId();
777     String chromosome = seqCoords.getChromosomeId();
778     String seqRef = seqCoords.getAssemblyId();
779     MapList map = seqCoords.getMapping();
780
781     // note this requires the configured species to match that
782     // returned with the Ensembl sequence; todo: support aliases?
783     if (!vcfSpecies.equalsIgnoreCase(species))
784     {
785       Cache.log.warn("No VCF loaded to " + seq.getName()
786               + " as species not matched");
787       return null;
788     }
789
790     if (seqRef.equalsIgnoreCase(vcfAssembly))
791     {
792       return new VCFMap(chromosome, map);
793     }
794
795     /*
796      * VCF data has a different reference assembly to the sequence:
797      * query Ensembl to map chromosomal coordinates from sequence to VCF
798      */
799     List<int[]> toVcfRanges = new ArrayList<>();
800     List<int[]> fromSequenceRanges = new ArrayList<>();
801
802     for (int[] range : map.getToRanges())
803     {
804       int[] fromRange = map.locateInFrom(range[0], range[1]);
805       if (fromRange == null)
806       {
807         // corrupted map?!?
808         continue;
809       }
810
811       int[] newRange = mapReferenceRange(range, chromosome, "human", seqRef,
812               vcfAssembly);
813       if (newRange == null)
814       {
815         Cache.log.error(
816                 String.format("Failed to map %s:%s:%s:%d:%d to %s", species,
817                         chromosome, seqRef, range[0], range[1],
818                         vcfAssembly));
819         continue;
820       }
821       else
822       {
823         toVcfRanges.add(newRange);
824         fromSequenceRanges.add(fromRange);
825       }
826     }
827
828     return new VCFMap(chromosome,
829             new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
830   }
831
832   /**
833    * If the sequence id matches a contig declared in the VCF file, and the
834    * sequence length matches the contig length, then returns a 1:1 map of the
835    * sequence to the contig, else returns null
836    * 
837    * @param seq
838    * @return
839    */
840   private VCFMap getContigMap(SequenceI seq)
841   {
842     String id = seq.getName();
843     SAMSequenceRecord contig = dictionary.getSequence(id);
844     if (contig != null)
845     {
846       int len = seq.getLength();
847       if (len == contig.getSequenceLength())
848       {
849         MapList map = new MapList(new int[] { 1, len },
850                 new int[]
851                 { 1, len }, 1, 1);
852         return new VCFMap(id, map);
853       }
854     }
855     return null;
856   }
857
858   /**
859    * Queries the VCF reader for any variants that overlap the mapped chromosome
860    * ranges of the sequence, and adds as variant features. Returns the number of
861    * overlapping variants found.
862    * 
863    * @param seq
864    * @param map
865    *          mapping from sequence to VCF coordinates
866    * @return
867    */
868   protected int addVcfVariants(SequenceI seq, VCFMap map)
869   {
870     boolean forwardStrand = map.map.isToForwardStrand();
871
872     /*
873      * query the VCF for overlaps of each contiguous chromosomal region
874      */
875     int count = 0;
876
877     for (int[] range : map.map.getToRanges())
878     {
879       int vcfStart = Math.min(range[0], range[1]);
880       int vcfEnd = Math.max(range[0], range[1]);
881       try
882       {
883         CloseableIterator<VariantContext> variants = reader
884                 .query(map.chromosome, vcfStart, vcfEnd);
885         while (variants.hasNext())
886         {
887           VariantContext variant = variants.next();
888
889           int[] featureRange = map.map.locateInFrom(variant.getStart(),
890                   variant.getEnd());
891
892           if (featureRange != null)
893           {
894             int featureStart = Math.min(featureRange[0], featureRange[1]);
895             int featureEnd = Math.max(featureRange[0], featureRange[1]);
896             count += addAlleleFeatures(seq, variant, featureStart,
897                     featureEnd, forwardStrand);
898           }
899         }
900         variants.close();
901       } catch (TribbleException e)
902       {
903         /*
904          * RuntimeException throwable by htsjdk
905          */
906         String msg = String.format("Error reading VCF for %s:%d-%d: %s ",
907                 map.chromosome, vcfStart, vcfEnd);
908         Cache.log.error(msg);
909       }
910     }
911
912     return count;
913   }
914
915   /**
916    * A convenience method to get an attribute value for an alternate allele.
917    * {@code alleleIndex} is the position in the list of values for the allele.
918    * If {@alleleIndex == -1} then all values are concatenated (comma-separated).
919    * This is the case for fields declared with "Number=." i.e. values are not
920    * related to specific alleles.
921    * 
922    * @param variant
923    * @param attributeName
924    * @param alleleIndex
925    * @return
926    */
927   protected String getAttributeValue(VariantContext variant,
928           String attributeName, int alleleIndex)
929   {
930     Object att = variant.getAttribute(attributeName);
931
932     String result = null;
933     if (att instanceof String)
934     {
935       result = (String) att;
936     }
937     else if (att instanceof List<?>)
938     {
939       List<String> theList = (List<String>) att;
940       if (alleleIndex == -1)
941       {
942         result = StringUtils.listToDelimitedString(theList, ",");
943       }
944       else
945       {
946         result = theList.get(alleleIndex);
947       }
948     }
949
950     return result;
951   }
952
953   /**
954    * Adds one variant feature for each allele in the VCF variant record, and
955    * returns the number of features added.
956    * 
957    * @param seq
958    * @param variant
959    * @param featureStart
960    * @param featureEnd
961    * @param forwardStrand
962    * @return
963    */
964   protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
965           int featureStart, int featureEnd, boolean forwardStrand)
966   {
967     int added = 0;
968
969     /*
970      * Javadoc says getAlternateAlleles() imposes no order on the list returned
971      * so we proceed defensively to get them in strict order
972      */
973     int altAlleleCount = variant.getAlternateAlleles().size();
974     for (int i = 0; i < altAlleleCount; i++)
975     {
976       added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
977               forwardStrand);
978     }
979     return added;
980   }
981
982   /**
983    * Inspects one allele and attempts to add a variant feature for it to the
984    * sequence. The additional data associated with this allele is extracted to
985    * store in the feature's key-value map. Answers the number of features added (0
986    * or 1).
987    * 
988    * @param seq
989    * @param variant
990    * @param altAlleleIndex
991    *          (0, 1..)
992    * @param featureStart
993    * @param featureEnd
994    * @param forwardStrand
995    * @return
996    */
997   protected int addAlleleFeature(SequenceI seq, VariantContext variant,
998           int altAlleleIndex, int featureStart, int featureEnd,
999           boolean forwardStrand)
1000   {
1001     String reference = variant.getReference().getBaseString();
1002     Allele alt = variant.getAlternateAllele(altAlleleIndex);
1003     String allele = alt.getBaseString();
1004
1005     /*
1006      * insertion after a genomic base, if on reverse strand, has to be 
1007      * converted to insertion of complement after the preceding position 
1008      */
1009     int referenceLength = reference.length();
1010     if (!forwardStrand && allele.length() > referenceLength
1011             && allele.startsWith(reference))
1012     {
1013       featureStart -= referenceLength;
1014       featureEnd = featureStart;
1015       char insertAfter = seq.getCharAt(featureStart - seq.getStart());
1016       reference = Dna.reverseComplement(String.valueOf(insertAfter));
1017       allele = allele.substring(referenceLength) + reference;
1018     }
1019
1020     /*
1021      * build the ref,alt allele description e.g. "G,A", using the base
1022      * complement if the sequence is on the reverse strand
1023      */
1024     StringBuilder sb = new StringBuilder();
1025     sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
1026     sb.append(COMMA);
1027     sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
1028     String alleles = sb.toString(); // e.g. G,A
1029
1030     /*
1031      * pick out the consequence data (if any) that is for the current allele
1032      * and feature (transcript) that matches the current sequence
1033      */
1034     String consequence = getConsequenceForAlleleAndFeature(variant, CSQ_FIELD,
1035             altAlleleIndex, csqAlleleFieldIndex,
1036             csqAlleleNumberFieldIndex, seq.getName().toLowerCase(),
1037             csqFeatureFieldIndex);
1038
1039     /*
1040      * pick out the ontology term for the consequence type
1041      */
1042     String type = SequenceOntologyI.SEQUENCE_VARIANT;
1043     if (consequence != null)
1044     {
1045       type = getOntologyTerm(consequence);
1046     }
1047
1048     SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
1049             featureEnd, FEATURE_GROUP_VCF);
1050     sf.setSource(sourceId);
1051
1052     /*
1053      * save the derived alleles as a named attribute; this will be
1054      * needed when Jalview computes derived peptide variants
1055      */
1056     addFeatureAttribute(sf, Gff3Helper.ALLELES, alleles);
1057
1058     /*
1059      * add selected VCF fixed column data as feature attributes
1060      */
1061     addFeatureAttribute(sf, VCF_POS, String.valueOf(variant.getStart()));
1062     addFeatureAttribute(sf, VCF_ID, variant.getID());
1063     addFeatureAttribute(sf, VCF_QUAL,
1064             String.valueOf(variant.getPhredScaledQual()));
1065     addFeatureAttribute(sf, VCF_FILTER, getFilter(variant));
1066
1067     addAlleleProperties(variant, sf, altAlleleIndex, consequence);
1068
1069     seq.addSequenceFeature(sf);
1070
1071     return 1;
1072   }
1073
1074   /**
1075    * Answers the VCF FILTER value for the variant - or an approximation to it.
1076    * This field is either PASS, or a semi-colon separated list of filters not
1077    * passed. htsjdk saves filters as a HashSet, so the order when reassembled into
1078    * a list may be different.
1079    * 
1080    * @param variant
1081    * @return
1082    */
1083   String getFilter(VariantContext variant)
1084   {
1085     Set<String> filters = variant.getFilters();
1086     if (filters.isEmpty())
1087     {
1088       return NO_VALUE;
1089     }
1090     Iterator<String> iterator = filters.iterator();
1091     String first = iterator.next();
1092     if (filters.size() == 1)
1093     {
1094       return first;
1095     }
1096
1097     StringBuilder sb = new StringBuilder(first);
1098     while (iterator.hasNext())
1099     {
1100       sb.append(";").append(iterator.next());
1101     }
1102
1103     return sb.toString();
1104   }
1105
1106   /**
1107    * Adds one feature attribute unless the value is null, empty or '.'
1108    * 
1109    * @param sf
1110    * @param key
1111    * @param value
1112    */
1113   void addFeatureAttribute(SequenceFeature sf, String key, String value)
1114   {
1115     if (value != null && !value.isEmpty() && !NO_VALUE.equals(value))
1116     {
1117       sf.setValue(key, value);
1118     }
1119   }
1120
1121   /**
1122    * Determines the Sequence Ontology term to use for the variant feature type in
1123    * Jalview. The default is 'sequence_variant', but a more specific term is used
1124    * if:
1125    * <ul>
1126    * <li>VEP (or SnpEff) Consequence annotation is included in the VCF</li>
1127    * <li>sequence id can be matched to VEP Feature (or SnpEff Feature_ID)</li>
1128    * </ul>
1129    * 
1130    * @param consequence
1131    * @return
1132    * @see http://www.sequenceontology.org/browser/current_svn/term/SO:0001060
1133    */
1134   String getOntologyTerm(String consequence)
1135   {
1136     String type = SequenceOntologyI.SEQUENCE_VARIANT;
1137
1138     /*
1139      * could we associate Consequence data with this allele and feature (transcript)?
1140      * if so, prefer the consequence term from that data
1141      */
1142     if (csqAlleleFieldIndex == -1) // && snpEffAlleleFieldIndex == -1
1143     {
1144       /*
1145        * no Consequence data so we can't refine the ontology term
1146        */
1147       return type;
1148     }
1149
1150     if (consequence != null)
1151     {
1152       String[] csqFields = consequence.split(PIPE_REGEX);
1153       if (csqFields.length > csqConsequenceFieldIndex)
1154       {
1155         type = csqFields[csqConsequenceFieldIndex];
1156       }
1157     }
1158     else
1159     {
1160       // todo the same for SnpEff consequence data matching if wanted
1161     }
1162
1163     /*
1164      * if of the form (e.g.) missense_variant&splice_region_variant,
1165      * just take the first ('most severe') consequence
1166      */
1167     if (type != null)
1168     {
1169       int pos = type.indexOf('&');
1170       if (pos > 0)
1171       {
1172         type = type.substring(0, pos);
1173       }
1174     }
1175     return type;
1176   }
1177
1178   /**
1179    * Returns matched consequence data if it can be found, else null.
1180    * <ul>
1181    * <li>inspects the VCF data for key 'vcfInfoId'</li>
1182    * <li>splits this on comma (to distinct consequences)</li>
1183    * <li>returns the first consequence (if any) where</li>
1184    * <ul>
1185    * <li>the allele matches the altAlleleIndex'th allele of variant</li>
1186    * <li>the feature matches the sequence name (e.g. transcript id)</li>
1187    * </ul>
1188    * </ul>
1189    * If matched, the consequence is returned (as pipe-delimited fields).
1190    * 
1191    * @param variant
1192    * @param vcfInfoId
1193    * @param altAlleleIndex
1194    * @param alleleFieldIndex
1195    * @param alleleNumberFieldIndex
1196    * @param seqName
1197    * @param featureFieldIndex
1198    * @return
1199    */
1200   private String getConsequenceForAlleleAndFeature(VariantContext variant,
1201           String vcfInfoId, int altAlleleIndex, int alleleFieldIndex,
1202           int alleleNumberFieldIndex,
1203           String seqName, int featureFieldIndex)
1204   {
1205     if (alleleFieldIndex == -1 || featureFieldIndex == -1)
1206     {
1207       return null;
1208     }
1209     Object value = variant.getAttribute(vcfInfoId);
1210
1211     if (value == null || !(value instanceof List<?>))
1212     {
1213       return null;
1214     }
1215
1216     /*
1217      * inspect each consequence in turn (comma-separated blocks
1218      * extracted by htsjdk)
1219      */
1220     List<String> consequences = (List<String>) value;
1221
1222     for (String consequence : consequences)
1223     {
1224       String[] csqFields = consequence.split(PIPE_REGEX);
1225       if (csqFields.length > featureFieldIndex)
1226       {
1227         String featureIdentifier = csqFields[featureFieldIndex];
1228         if (featureIdentifier.length() > 4
1229                 && seqName.indexOf(featureIdentifier.toLowerCase()) > -1)
1230         {
1231           /*
1232            * feature (transcript) matched - now check for allele match
1233            */
1234           if (matchAllele(variant, altAlleleIndex, csqFields,
1235                   alleleFieldIndex, alleleNumberFieldIndex))
1236           {
1237             return consequence;
1238           }
1239         }
1240       }
1241     }
1242     return null;
1243   }
1244
1245   private boolean matchAllele(VariantContext variant, int altAlleleIndex,
1246           String[] csqFields, int alleleFieldIndex,
1247           int alleleNumberFieldIndex)
1248   {
1249     /*
1250      * if ALLELE_NUM is present, it must match altAlleleIndex
1251      * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1252      */
1253     if (alleleNumberFieldIndex > -1)
1254     {
1255       if (csqFields.length <= alleleNumberFieldIndex)
1256       {
1257         return false;
1258       }
1259       String alleleNum = csqFields[alleleNumberFieldIndex];
1260       return String.valueOf(altAlleleIndex + 1).equals(alleleNum);
1261     }
1262
1263     /*
1264      * else consequence allele must match variant allele
1265      */
1266     if (alleleFieldIndex > -1 && csqFields.length > alleleFieldIndex)
1267     {
1268       String csqAllele = csqFields[alleleFieldIndex];
1269       String vcfAllele = variant.getAlternateAllele(altAlleleIndex)
1270               .getBaseString();
1271       return csqAllele.equals(vcfAllele);
1272     }
1273     return false;
1274   }
1275
1276   /**
1277    * Add any allele-specific VCF key-value data to the sequence feature
1278    * 
1279    * @param variant
1280    * @param sf
1281    * @param altAlelleIndex
1282    *          (0, 1..)
1283    * @param consequence
1284    *          if not null, the consequence specific to this sequence (transcript
1285    *          feature) and allele
1286    */
1287   protected void addAlleleProperties(VariantContext variant,
1288           SequenceFeature sf, final int altAlelleIndex, String consequence)
1289   {
1290     Map<String, Object> atts = variant.getAttributes();
1291
1292     for (Entry<String, Object> att : atts.entrySet())
1293     {
1294       String key = att.getKey();
1295
1296       /*
1297        * extract Consequence data (if present) that we are able to
1298        * associated with the allele for this variant feature
1299        */
1300       if (CSQ_FIELD.equals(key))
1301       {
1302         addConsequences(variant, sf, consequence);
1303         continue;
1304       }
1305
1306       /*
1307        * filter out fields we don't want to capture
1308        */
1309       if (!vcfFieldsOfInterest.contains(key))
1310       {
1311         continue;
1312       }
1313
1314       /*
1315        * we extract values for other data which are allele-specific; 
1316        * these may be per alternate allele (INFO[key].Number = 'A') 
1317        * or per allele including reference (INFO[key].Number = 'R') 
1318        */
1319       VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
1320       if (infoHeader == null)
1321       {
1322         /*
1323          * can't be sure what data belongs to this allele, so
1324          * play safe and don't take any
1325          */
1326         continue;
1327       }
1328
1329       VCFHeaderLineCount number = infoHeader.getCountType();
1330       int index = altAlelleIndex;
1331       if (number == VCFHeaderLineCount.R)
1332       {
1333         /*
1334          * one value per allele including reference, so bump index
1335          * e.g. the 3rd value is for the  2nd alternate allele
1336          */
1337         index++;
1338       }
1339       else if (number == VCFHeaderLineCount.UNBOUNDED) // .
1340       {
1341         index = -1;
1342       }
1343       else if (number != VCFHeaderLineCount.A)
1344       {
1345         /*
1346          * don't save other values as not allele-related
1347          */
1348         continue;
1349       }
1350
1351       /*
1352        * take the index'th value
1353        */
1354       String value = getAttributeValue(variant, key, index);
1355       if (value != null && isValid(variant, key, value))
1356       {
1357         value = decodeSpecialCharacters(value);
1358         addFeatureAttribute(sf, key, value);
1359       }
1360     }
1361   }
1362
1363   /**
1364    * Decodes colon, semicolon, equals sign, percent sign, comma to their decoded
1365    * form. The VCF specification (para 1.2) requires these to be encoded where not
1366    * used with their special meaning in the VCF syntax. Note that general URL
1367    * decoding should not be applied, since this would incorrectly decode (for
1368    * example) a '+' sign.
1369    * 
1370    * @param value
1371    * @return
1372    */
1373   protected static String decodeSpecialCharacters(String value)
1374   {
1375     /*
1376      * avoid regex compilation if it is not needed!
1377      */
1378     if (!value.contains(ENCODED_COLON) && !value.contains(ENCODED_SEMICOLON)
1379             && !value.contains(ENCODED_EQUALS)
1380             && !value.contains(ENCODED_PERCENT)
1381             && !value.contains(ENCODED_COMMA))
1382     {
1383       return value;
1384     }
1385
1386     value = value.replace(ENCODED_COLON, ":")
1387             .replace(ENCODED_SEMICOLON, ";").replace(ENCODED_EQUALS, "=")
1388             .replace(ENCODED_PERCENT, "%").replace(ENCODED_COMMA, ",");
1389     return value;
1390   }
1391
1392   /**
1393    * Answers true for '.', null, or an empty value, or if the INFO type is String.
1394    * If the INFO type is Integer or Float, answers false if the value is not in
1395    * valid format.
1396    * 
1397    * @param variant
1398    * @param infoId
1399    * @param value
1400    * @return
1401    */
1402   protected boolean isValid(VariantContext variant, String infoId,
1403           String value)
1404   {
1405     if (value == null || value.isEmpty() || NO_VALUE.equals(value))
1406     {
1407       return true;
1408     }
1409     VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(infoId);
1410     if (infoHeader == null)
1411     {
1412       Cache.log.error("Field " + infoId + " has no INFO header");
1413       return false;
1414     }
1415     VCFHeaderLineType infoType = infoHeader.getType();
1416     try
1417     {
1418       if (infoType == VCFHeaderLineType.Integer)
1419       {
1420         Integer.parseInt(value);
1421       }
1422       else if (infoType == VCFHeaderLineType.Float)
1423       {
1424         Float.parseFloat(value);
1425       }
1426     } catch (NumberFormatException e)
1427     {
1428       logInvalidValue(variant, infoId, value);
1429       return false;
1430     }
1431     return true;
1432   }
1433
1434   /**
1435    * Logs an error message for malformed data; duplicate messages (same id and
1436    * value) are not logged
1437    * 
1438    * @param variant
1439    * @param infoId
1440    * @param value
1441    */
1442   private void logInvalidValue(VariantContext variant, String infoId,
1443           String value)
1444   {
1445     if (badData == null)
1446     {
1447       badData = new HashSet<>();
1448     }
1449     String token = infoId + ":" + value;
1450     if (!badData.contains(token))
1451     {
1452       badData.add(token);
1453       Cache.log.error(String.format("Invalid VCF data at %s:%d %s=%s",
1454               variant.getContig(), variant.getStart(), infoId, value));
1455     }
1456   }
1457
1458   /**
1459    * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
1460    * feature.
1461    * <p>
1462    * If <code>myConsequence</code> is not null, then this is the specific
1463    * consequence data (pipe-delimited fields) that is for the current allele and
1464    * transcript (sequence) being processed)
1465    * 
1466    * @param variant
1467    * @param sf
1468    * @param myConsequence
1469    */
1470   protected void addConsequences(VariantContext variant, SequenceFeature sf,
1471           String myConsequence)
1472   {
1473     Object value = variant.getAttribute(CSQ_FIELD);
1474
1475     if (value == null || !(value instanceof List<?>))
1476     {
1477       return;
1478     }
1479
1480     List<String> consequences = (List<String>) value;
1481
1482     /*
1483      * inspect CSQ consequences; restrict to the consequence
1484      * associated with the current transcript (Feature)
1485      */
1486     Map<String, String> csqValues = new HashMap<>();
1487
1488     for (String consequence : consequences)
1489     {
1490       if (myConsequence == null || myConsequence.equals(consequence))
1491       {
1492         String[] csqFields = consequence.split(PIPE_REGEX);
1493
1494         /*
1495          * inspect individual fields of this consequence, copying non-null
1496          * values which are 'fields of interest'
1497          */
1498         int i = 0;
1499         for (String field : csqFields)
1500         {
1501           if (field != null && field.length() > 0)
1502           {
1503             String id = vepFieldsOfInterest.get(i);
1504             if (id != null)
1505             {
1506               /*
1507                * VCF spec requires encoding of special characters e.g. '='
1508                * so decode them here before storing
1509                */
1510               try
1511               {
1512                 field = URLDecoder.decode(field, UTF_8);
1513               } catch (UnsupportedEncodingException e)
1514               {
1515               }
1516               csqValues.put(id, field);
1517             }
1518           }
1519           i++;
1520         }
1521       }
1522     }
1523
1524     if (!csqValues.isEmpty())
1525     {
1526       sf.setValue(CSQ_FIELD, csqValues);
1527     }
1528   }
1529
1530   /**
1531    * A convenience method to complement a dna base and return the string value
1532    * of its complement
1533    * 
1534    * @param reference
1535    * @return
1536    */
1537   protected String complement(byte[] reference)
1538   {
1539     return String.valueOf(Dna.getComplement((char) reference[0]));
1540   }
1541
1542   /**
1543    * Determines the location of the query range (chromosome positions) in a
1544    * different reference assembly.
1545    * <p>
1546    * If the range is just a subregion of one for which we already have a mapping
1547    * (for example, an exon sub-region of a gene), then the mapping is just
1548    * computed arithmetically.
1549    * <p>
1550    * Otherwise, calls the Ensembl REST service that maps from one assembly
1551    * reference's coordinates to another's
1552    * 
1553    * @param queryRange
1554    *          start-end chromosomal range in 'fromRef' coordinates
1555    * @param chromosome
1556    * @param species
1557    * @param fromRef
1558    *          assembly reference for the query coordinates
1559    * @param toRef
1560    *          assembly reference we wish to translate to
1561    * @return the start-end range in 'toRef' coordinates
1562    */
1563   protected int[] mapReferenceRange(int[] queryRange, String chromosome,
1564           String species, String fromRef, String toRef)
1565   {
1566     /*
1567      * first try shorcut of computing the mapping as a subregion of one
1568      * we already have (e.g. for an exon, if we have the gene mapping)
1569      */
1570     int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
1571             species, fromRef, toRef);
1572     if (mappedRange != null)
1573     {
1574       return mappedRange;
1575     }
1576
1577     /*
1578      * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
1579      */
1580     EnsemblMap mapper = new EnsemblMap();
1581     int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
1582             toRef, queryRange);
1583
1584     if (mapping == null)
1585     {
1586       // mapping service failure
1587       return null;
1588     }
1589
1590     /*
1591      * save mapping for possible future re-use
1592      */
1593     String key = makeRangesKey(chromosome, species, fromRef, toRef);
1594     if (!assemblyMappings.containsKey(key))
1595     {
1596       assemblyMappings.put(key, new HashMap<int[], int[]>());
1597     }
1598
1599     assemblyMappings.get(key).put(queryRange, mapping);
1600
1601     return mapping;
1602   }
1603
1604   /**
1605    * If we already have a 1:1 contiguous mapping which subsumes the given query
1606    * range, this method just calculates and returns the subset of that mapping,
1607    * else it returns null. In practical terms, if a gene has a contiguous
1608    * mapping between (for example) GRCh37 and GRCh38, then we assume that its
1609    * subsidiary exons occupy unchanged relative positions, and just compute
1610    * these as offsets, rather than do another lookup of the mapping.
1611    * <p>
1612    * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
1613    * simply remove this method or let it always return null.
1614    * <p>
1615    * Warning: many rapid calls to the /map service map result in a 429 overload
1616    * error response
1617    * 
1618    * @param queryRange
1619    * @param chromosome
1620    * @param species
1621    * @param fromRef
1622    * @param toRef
1623    * @return
1624    */
1625   protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
1626           String species, String fromRef, String toRef)
1627   {
1628     String key = makeRangesKey(chromosome, species, fromRef, toRef);
1629     if (assemblyMappings.containsKey(key))
1630     {
1631       Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
1632       for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
1633       {
1634         int[] fromRange = mappedRange.getKey();
1635         int[] toRange = mappedRange.getValue();
1636         if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
1637         {
1638           /*
1639            * mapping is 1:1 in length, so we trust it to have no discontinuities
1640            */
1641           if (MappingUtils.rangeContains(fromRange, queryRange))
1642           {
1643             /*
1644              * fromRange subsumes our query range
1645              */
1646             int offset = queryRange[0] - fromRange[0];
1647             int mappedRangeFrom = toRange[0] + offset;
1648             int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
1649             return new int[] { mappedRangeFrom, mappedRangeTo };
1650           }
1651         }
1652       }
1653     }
1654     return null;
1655   }
1656
1657   /**
1658    * Transfers the sequence feature to the target sequence, locating its start
1659    * and end range based on the mapping. Features which do not overlap the
1660    * target sequence are ignored.
1661    * 
1662    * @param sf
1663    * @param targetSequence
1664    * @param mapping
1665    *          mapping from the feature's coordinates to the target sequence
1666    */
1667   protected void transferFeature(SequenceFeature sf,
1668           SequenceI targetSequence, MapList mapping)
1669   {
1670     int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1671   
1672     if (mappedRange != null)
1673     {
1674       String group = sf.getFeatureGroup();
1675       int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1676       int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1677       SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1678               group, sf.getScore());
1679       targetSequence.addSequenceFeature(copy);
1680     }
1681   }
1682
1683   /**
1684    * Formats a ranges map lookup key
1685    * 
1686    * @param chromosome
1687    * @param species
1688    * @param fromRef
1689    * @param toRef
1690    * @return
1691    */
1692   protected static String makeRangesKey(String chromosome, String species,
1693           String fromRef, String toRef)
1694   {
1695     return species + EXCL + chromosome + EXCL + fromRef + EXCL
1696             + toRef;
1697   }
1698 }