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