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