JAL-2850 improved use of htsjdk api to read contig info
[jalview.git] / src / jalview / io / vcf / VCFLoader.java
1 package jalview.io.vcf;
2
3 import jalview.analysis.AlignmentUtils;
4 import jalview.analysis.Dna;
5 import jalview.api.AlignViewControllerGuiI;
6 import jalview.bin.Cache;
7 import jalview.datamodel.AlignmentI;
8 import jalview.datamodel.DBRefEntry;
9 import jalview.datamodel.GeneLociI;
10 import jalview.datamodel.Mapping;
11 import jalview.datamodel.SequenceFeature;
12 import jalview.datamodel.SequenceI;
13 import jalview.datamodel.features.FeatureAttributeType;
14 import jalview.datamodel.features.FeatureSource;
15 import jalview.datamodel.features.FeatureSources;
16 import jalview.ext.ensembl.EnsemblMap;
17 import jalview.ext.htsjdk.VCFReader;
18 import jalview.io.gff.Gff3Helper;
19 import jalview.io.gff.SequenceOntologyI;
20 import jalview.util.MapList;
21 import jalview.util.MappingUtils;
22 import jalview.util.MessageManager;
23
24 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.SortedMap;
31 import java.util.TreeMap;
32 import java.util.regex.Pattern;
33 import java.util.regex.PatternSyntaxException;
34
35 import htsjdk.samtools.SAMException;
36 import htsjdk.samtools.SAMSequenceDictionary;
37 import htsjdk.samtools.SAMSequenceRecord;
38 import htsjdk.samtools.util.CloseableIterator;
39 import htsjdk.variant.variantcontext.Allele;
40 import htsjdk.variant.variantcontext.VariantContext;
41 import htsjdk.variant.vcf.VCFHeader;
42 import htsjdk.variant.vcf.VCFHeaderLine;
43 import htsjdk.variant.vcf.VCFHeaderLineCount;
44 import htsjdk.variant.vcf.VCFHeaderLineType;
45 import htsjdk.variant.vcf.VCFInfoHeaderLine;
46
47 /**
48  * A class to read VCF data (using the htsjdk) and add variants as sequence
49  * features on dna and any related protein product sequences
50  * 
51  * @author gmcarstairs
52  */
53 public class VCFLoader
54 {
55   /**
56    * A class to model the mapping from sequence to VCF coordinates. Cases include
57    * <ul>
58    * <li>a direct 1:1 mapping where the sequence is one of the VCF contigs</li>
59    * <li>a mapping of sequence to chromosomal coordinates, where sequence and VCF
60    * use the same reference assembly</li>
61    * <li>a modified mapping of sequence to chromosomal coordinates, where sequence
62    * and VCF use different reference assembles</li>
63    * </ul>
64    */
65   class VCFMap
66   {
67     final String chromosome;
68
69     final MapList map;
70
71     VCFMap(String chr, MapList m)
72     {
73       chromosome = chr;
74       map = m;
75     }
76   }
77
78   /*
79    * Lookup keys, and default values, for Preference entries that describe
80    * patterns for VCF and VEP fields to capture 
81    */
82   private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
83
84   private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
85
86   private static final String DEFAULT_VCF_FIELDS = ".*";
87
88   private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
89
90   /*
91    * keys to fields of VEP CSQ consequence data
92    * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
93    */
94   private static final String ALLELE_KEY = "Allele";
95
96   private static final String ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref), 1...
97   private static final String FEATURE_KEY = "Feature"; // Ensembl stable id
98
99   /*
100    * default VCF INFO key for VEP consequence data
101    * NB this can be overridden running VEP with --vcf_info_field
102    * - we don't handle this case (require identifier to be CSQ)
103    */
104   private static final String CSQ_FIELD = "CSQ";
105
106   /*
107    * separator for fields in consequence data is '|'
108    */
109   private static final String PIPE_REGEX = "\\|";
110
111   /*
112    * key for Allele Frequency output by VEP
113    * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
114    */
115   private static final String ALLELE_FREQUENCY_KEY = "AF";
116
117   /*
118    * delimiter that separates multiple consequence data blocks
119    */
120   private static final String COMMA = ",";
121
122   /*
123    * the feature group assigned to a VCF variant in Jalview
124    */
125   private static final String FEATURE_GROUP_VCF = "VCF";
126
127   /*
128    * internal delimiter used to build keys for assemblyMappings
129    * 
130    */
131   private static final String EXCL = "!";
132
133   /*
134    * the alignment we are associating VCF data with
135    */
136   private AlignmentI al;
137
138   /*
139    * mappings between VCF and sequence reference assembly regions, as 
140    * key = "species!chromosome!fromAssembly!toAssembly
141    * value = Map{fromRange, toRange}
142    */
143   private Map<String, Map<int[], int[]>> assemblyMappings;
144
145   /*
146    * holds details of the VCF header lines (metadata)
147    */
148   private VCFHeader header;
149
150   /*
151    * a Dictionary of contigs (if present) referenced in the VCF file
152    */
153   private SAMSequenceDictionary dictionary;
154
155   /*
156    * the position (0...) of field in each block of
157    * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
158    * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
159    */
160   private int csqAlleleFieldIndex = -1;
161   private int csqAlleleNumberFieldIndex = -1;
162   private int csqFeatureFieldIndex = -1;
163
164   /*
165    * a unique identifier under which to save metadata about feature
166    * attributes (selected INFO field data)
167    */
168   private String sourceId;
169
170   /*
171    * The INFO IDs of data that is both present in the VCF file, and
172    * also matched by any filters for data of interest
173    */
174   List<String> vcfFieldsOfInterest;
175
176   /*
177    * The field offsets and identifiers for VEP (CSQ) data that is both present
178    * in the VCF file, and also matched by any filters for data of interest
179    * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
180    */
181   Map<Integer, String> vepFieldsOfInterest;
182
183   /**
184    * Constructor given an alignment context
185    * 
186    * @param alignment
187    */
188   public VCFLoader(AlignmentI alignment)
189   {
190     al = alignment;
191
192     // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
193     assemblyMappings = new HashMap<>();
194   }
195
196   /**
197    * Starts a new thread to query and load VCF variant data on to the alignment
198    * <p>
199    * This method is not thread safe - concurrent threads should use separate
200    * instances of this class.
201    * 
202    * @param filePath
203    * @param gui
204    */
205   public void loadVCF(final String filePath,
206           final AlignViewControllerGuiI gui)
207   {
208     if (gui != null)
209     {
210       gui.setStatus(MessageManager.getString("label.searching_vcf"));
211     }
212
213     new Thread()
214     {
215
216       @Override
217       public void run()
218       {
219         VCFLoader.this.doLoad(filePath, gui);
220       }
221
222     }.start();
223   }
224
225   /**
226    * Loads VCF on to an alignment - provided it can be related to one or more
227    * sequence's chromosomal coordinates
228    * 
229    * @param filePath
230    * @param gui
231    *          optional callback handler for messages
232    */
233   protected void doLoad(String filePath, AlignViewControllerGuiI gui)
234   {
235     VCFReader reader = null;
236     try
237     {
238       // long start = System.currentTimeMillis();
239       reader = new VCFReader(filePath);
240
241       header = reader.getFileHeader();
242
243       try
244       {
245         dictionary = header.getSequenceDictionary();
246       } catch (SAMException e)
247       {
248         // ignore - thrown if any contig line lacks length info
249       }
250
251       sourceId = filePath;
252
253       saveMetadata(sourceId);
254
255       /*
256        * get offset of CSQ ALLELE_NUM and Feature if declared
257        */
258       parseCsqHeader();
259
260       VCFHeaderLine ref = header
261               .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
262       String vcfAssembly = ref.getValue();
263
264       int varCount = 0;
265       int seqCount = 0;
266
267       /*
268        * query for VCF overlapping each sequence in turn
269        */
270       for (SequenceI seq : al.getSequences())
271       {
272         int added = loadSequenceVCF(seq, reader, vcfAssembly);
273         if (added > 0)
274         {
275           seqCount++;
276           varCount += added;
277           transferAddedFeatures(seq);
278         }
279       }
280       if (gui != null)
281       {
282         // long elapsed = System.currentTimeMillis() - start;
283         String msg = MessageManager.formatMessage("label.added_vcf",
284                 varCount, seqCount);
285         gui.setStatus(msg);
286         if (gui.getFeatureSettingsUI() != null)
287         {
288           gui.getFeatureSettingsUI().discoverAllFeatureData();
289         }
290       }
291     } catch (Throwable e)
292     {
293       System.err.println("Error processing VCF: " + e.getMessage());
294       e.printStackTrace();
295       if (gui != null)
296       {
297         gui.setStatus("Error occurred - see console for details");
298       }
299     } finally
300     {
301       if (reader != null)
302       {
303         try
304         {
305           reader.close();
306         } catch (IOException e)
307         {
308           // ignore
309         }
310       }
311       header = null;
312       dictionary = null;
313     }
314   }
315
316   /**
317    * Reads metadata (such as INFO field descriptions and datatypes) and saves
318    * them for future reference
319    * 
320    * @param theSourceId
321    */
322   void saveMetadata(String theSourceId)
323   {
324     List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
325             DEFAULT_VCF_FIELDS);
326     vcfFieldsOfInterest = new ArrayList<>();
327
328     FeatureSource metadata = new FeatureSource(theSourceId);
329
330     for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
331     {
332       String attributeId = info.getID();
333       String desc = info.getDescription();
334       VCFHeaderLineType type = info.getType();
335       FeatureAttributeType attType = null;
336       switch (type)
337       {
338       case Character:
339         attType = FeatureAttributeType.Character;
340         break;
341       case Flag:
342         attType = FeatureAttributeType.Flag;
343         break;
344       case Float:
345         attType = FeatureAttributeType.Float;
346         break;
347       case Integer:
348         attType = FeatureAttributeType.Integer;
349         break;
350       case String:
351         attType = FeatureAttributeType.String;
352         break;
353       }
354       metadata.setAttributeName(attributeId, desc);
355       metadata.setAttributeType(attributeId, attType);
356
357       if (isFieldWanted(attributeId, vcfFieldPatterns))
358       {
359         vcfFieldsOfInterest.add(attributeId);
360       }
361     }
362
363     FeatureSources.getInstance().addSource(theSourceId, metadata);
364   }
365
366   /**
367    * Answers true if the field id is matched by any of the filter patterns, else
368    * false. Matching is against regular expression patterns, and is not
369    * case-sensitive.
370    * 
371    * @param id
372    * @param filters
373    * @return
374    */
375   private boolean isFieldWanted(String id, List<Pattern> filters)
376   {
377     for (Pattern p : filters)
378     {
379       if (p.matcher(id.toUpperCase()).matches())
380       {
381         return true;
382       }
383     }
384     return false;
385   }
386
387   /**
388    * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
389    * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
390    * required for processing.
391    * <p>
392    * CSQ fields are declared in the CSQ INFO Description e.g.
393    * <p>
394    * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
395    */
396   protected void parseCsqHeader()
397   {
398     List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
399             DEFAULT_VEP_FIELDS);
400     vepFieldsOfInterest = new HashMap<>();
401
402     VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
403     if (csqInfo == null)
404     {
405       return;
406     }
407
408     /*
409      * parse out the pipe-separated list of CSQ fields; we assume here that
410      * these form the last part of the description, and contain no spaces
411      */
412     String desc = csqInfo.getDescription();
413     int spacePos = desc.lastIndexOf(" ");
414     desc = desc.substring(spacePos + 1);
415
416     if (desc != null)
417     {
418       String[] format = desc.split(PIPE_REGEX);
419       int index = 0;
420       for (String field : format)
421       {
422         if (ALLELE_NUM_KEY.equals(field))
423         {
424           csqAlleleNumberFieldIndex = index;
425         }
426         if (ALLELE_KEY.equals(field))
427         {
428           csqAlleleFieldIndex = index;
429         }
430         if (FEATURE_KEY.equals(field))
431         {
432           csqFeatureFieldIndex = index;
433         }
434
435         if (isFieldWanted(field, vepFieldFilters))
436         {
437           vepFieldsOfInterest.put(index, field);
438         }
439
440         index++;
441       }
442     }
443   }
444
445   /**
446    * Reads the Preference value for the given key, with default specified if no
447    * preference set. The value is interpreted as a comma-separated list of
448    * regular expressions, and converted into a list of compiled patterns ready
449    * for matching. Patterns are forced to upper-case for non-case-sensitive
450    * matching.
451    * <p>
452    * This supports user-defined filters for fields of interest to capture while
453    * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
454    * fields with an ID of AF, or starting with AC, would be matched.
455    * 
456    * @param key
457    * @param def
458    * @return
459    */
460   private List<Pattern> getFieldMatchers(String key, String def)
461   {
462     String pref = Cache.getDefault(key, def);
463     List<Pattern> patterns = new ArrayList<>();
464     String[] tokens = pref.split(",");
465     for (String token : tokens)
466     {
467       try
468       {
469       patterns.add(Pattern.compile(token.toUpperCase()));
470       } catch (PatternSyntaxException e)
471       {
472         System.err.println("Invalid pattern ignored: " + token);
473       }
474     }
475     return patterns;
476   }
477
478   /**
479    * Transfers VCF features to sequences to which this sequence has a mapping.
480    * If the mapping is 3:1, computes peptide variants from nucleotide variants.
481    * 
482    * @param seq
483    */
484   protected void transferAddedFeatures(SequenceI seq)
485   {
486     DBRefEntry[] dbrefs = seq.getDBRefs();
487     if (dbrefs == null)
488     {
489       return;
490     }
491     for (DBRefEntry dbref : dbrefs)
492     {
493       Mapping mapping = dbref.getMap();
494       if (mapping == null || mapping.getTo() == null)
495       {
496         continue;
497       }
498
499       SequenceI mapTo = mapping.getTo();
500       MapList map = mapping.getMap();
501       if (map.getFromRatio() == 3)
502       {
503         /*
504          * dna-to-peptide product mapping
505          */
506         AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
507       }
508       else
509       {
510         /*
511          * nucleotide-to-nucleotide mapping e.g. transcript to CDS
512          */
513         List<SequenceFeature> features = seq.getFeatures()
514                 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
515         for (SequenceFeature sf : features)
516         {
517           if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
518           {
519             transferFeature(sf, mapTo, map);
520           }
521         }
522       }
523     }
524   }
525
526   /**
527    * Tries to add overlapping variants read from a VCF file to the given
528    * sequence, and returns the number of variant features added. Note that this
529    * requires the sequence to hold information as to its species, chromosomal
530    * positions and reference assembly, in order to be able to map the VCF
531    * variants to the sequence (or not)
532    * 
533    * @param seq
534    * @param reader
535    * @param vcfAssembly
536    * @return
537    */
538   protected int loadSequenceVCF(SequenceI seq, VCFReader reader,
539           String vcfAssembly)
540   {
541     VCFMap vcfMap = getVcfMap(seq, vcfAssembly);
542     if (vcfMap == null)
543     {
544       return 0;
545     }
546
547     return addVcfVariants(seq, reader, vcfMap, vcfAssembly);
548   }
549
550   /**
551    * Answers a map from sequence coordinates to VCF chromosome ranges
552    * 
553    * @param seq
554    * @param vcfAssembly
555    * @return
556    */
557   private VCFMap getVcfMap(SequenceI seq, String vcfAssembly)
558   {
559     /*
560      * simplest case: sequence has id and length matching a VCF contig
561      */
562     VCFMap vcfMap = null;
563     if (dictionary != null)
564     {
565       vcfMap = getContigMap(seq);
566     }
567     if (vcfMap != null)
568     {
569       return vcfMap;
570     }
571
572     /*
573      * otherwise, map to VCF from chromosomal coordinates 
574      * of the sequence (if known)
575      */
576     GeneLociI seqCoords = seq.getGeneLoci();
577     if (seqCoords == null)
578     {
579       Cache.log.warn(String.format(
580               "Can't query VCF for %s as chromosome coordinates not known",
581               seq.getName()));
582       return null;
583     }
584
585     String species = seqCoords.getSpeciesId();
586     String chromosome = seqCoords.getChromosomeId();
587     String seqRef = seqCoords.getAssemblyId();
588     MapList map = seqCoords.getMap();
589
590     if (!vcfSpeciesMatchesSequence(vcfAssembly, species))
591     {
592       return null;
593     }
594
595     if (vcfAssemblyMatchesSequence(vcfAssembly, seqRef))
596     {
597       return new VCFMap(chromosome, map);
598     }
599
600     if (!"GRCh38".equalsIgnoreCase(seqRef) // Ensembl
601             || !vcfAssembly.contains("Homo_sapiens_assembly19")) // gnomAD
602     {
603       return null;
604     }
605
606     /*
607      * map chromosomal coordinates from sequence to VCF if the VCF
608      * data has a different reference assembly to the sequence
609      */
610     // TODO generalise for cases other than GRCh38 -> GRCh37 !
611     // - or get the user to choose in a dialog
612
613     List<int[]> toVcfRanges = new ArrayList<>();
614     List<int[]> fromSequenceRanges = new ArrayList<>();
615     String toRef = "GRCh37";
616
617     for (int[] range : map.getToRanges())
618     {
619       int[] fromRange = map.locateInFrom(range[0], range[1]);
620       if (fromRange == null)
621       {
622         // corrupted map?!?
623         continue;
624       }
625
626       int[] newRange = mapReferenceRange(range, chromosome, "human", seqRef,
627               toRef);
628       if (newRange == null)
629       {
630         Cache.log.error(
631                 String.format("Failed to map %s:%s:%s:%d:%d to %s", species,
632                         chromosome, seqRef, range[0], range[1], toRef));
633         continue;
634       }
635       else
636       {
637         toVcfRanges.add(newRange);
638         fromSequenceRanges.add(fromRange);
639       }
640     }
641
642     return new VCFMap(chromosome,
643             new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
644   }
645
646   /**
647    * If the sequence id matches a contig declared in the VCF file, and the
648    * sequence length matches the contig length, then returns a 1:1 map of the
649    * sequence to the contig, else returns null
650    * 
651    * @param seq
652    * @return
653    */
654   private VCFMap getContigMap(SequenceI seq)
655   {
656     String id = seq.getName();
657     SAMSequenceRecord contig = dictionary.getSequence(id);
658     if (contig != null)
659     {
660       int len = seq.getLength();
661       if (len == contig.getSequenceLength())
662       {
663         MapList map = new MapList(new int[] { 1, len },
664                 new int[]
665                 { 1, len }, 1, 1);
666         return new VCFMap(id, map);
667       }
668     }
669     return null;
670   }
671
672   /**
673    * Answers true if we determine that the VCF data uses the same reference
674    * assembly as the sequence, else false
675    * 
676    * @param vcfAssembly
677    * @param seqRef
678    * @return
679    */
680   private boolean vcfAssemblyMatchesSequence(String vcfAssembly,
681           String seqRef)
682   {
683     // TODO improve on this stub, which handles gnomAD and
684     // hopes for the best for other cases
685
686     if ("GRCh38".equalsIgnoreCase(seqRef) // Ensembl
687             && vcfAssembly.contains("Homo_sapiens_assembly19")) // gnomAD
688     {
689       return false;
690     }
691     return true;
692   }
693
694   /**
695    * Answers true if the species inferred from the VCF reference identifier
696    * matches that for the sequence
697    * 
698    * @param vcfAssembly
699    * @param speciesId
700    * @return
701    */
702   boolean vcfSpeciesMatchesSequence(String vcfAssembly, String speciesId)
703   {
704     // PROBLEM 1
705     // there are many aliases for species - how to equate one with another?
706     // PROBLEM 2
707     // VCF ##reference header is an unstructured URI - how to extract species?
708     // perhaps check if ref includes any (Ensembl) alias of speciesId??
709     // TODO ask the user to confirm this??
710
711     if (vcfAssembly.contains("Homo_sapiens") // gnomAD exome data example
712             && "HOMO_SAPIENS".equals(speciesId)) // Ensembl species id
713     {
714       return true;
715     }
716
717     if (vcfAssembly.contains("c_elegans") // VEP VCF response example
718             && "CAENORHABDITIS_ELEGANS".equals(speciesId)) // Ensembl
719     {
720       return true;
721     }
722
723     // this is not a sustainable solution...
724
725     return false;
726   }
727
728   /**
729    * Queries the VCF reader for any variants that overlap the mapped chromosome
730    * ranges of the sequence, and adds as variant features. Returns the number of
731    * overlapping variants found.
732    * 
733    * @param seq
734    * @param reader
735    * @param map
736    *          mapping from sequence to VCF coordinates
737    * @param vcfAssembly
738    *          the '##reference' identifier for the VCF reference assembly
739    * @return
740    */
741   protected int addVcfVariants(SequenceI seq, VCFReader reader,
742           VCFMap map, String vcfAssembly)
743   {
744     boolean forwardStrand = map.map.isToForwardStrand();
745
746     /*
747      * query the VCF for overlaps of each contiguous chromosomal region
748      */
749     int count = 0;
750
751     for (int[] range : map.map.getToRanges())
752     {
753       int vcfStart = Math.min(range[0], range[1]);
754       int vcfEnd = Math.max(range[0], range[1]);
755       CloseableIterator<VariantContext> variants = reader
756               .query(map.chromosome, vcfStart, vcfEnd);
757       while (variants.hasNext())
758       {
759         VariantContext variant = variants.next();
760
761         int[] featureRange = map.map.locateInFrom(variant.getStart(),
762                 variant.getEnd());
763
764         if (featureRange != null)
765         {
766           int featureStart = Math.min(featureRange[0], featureRange[1]);
767           int featureEnd = Math.max(featureRange[0], featureRange[1]);
768           count += addAlleleFeatures(seq, variant, featureStart, featureEnd,
769                   forwardStrand);
770         }
771       }
772       variants.close();
773     }
774
775     return count;
776   }
777
778   /**
779    * A convenience method to get the AF value for the given alternate allele
780    * index
781    * 
782    * @param variant
783    * @param alleleIndex
784    * @return
785    */
786   protected float getAlleleFrequency(VariantContext variant, int alleleIndex)
787   {
788     float score = 0f;
789     String attributeValue = getAttributeValue(variant,
790             ALLELE_FREQUENCY_KEY, alleleIndex);
791     if (attributeValue != null)
792     {
793       try
794       {
795         score = Float.parseFloat(attributeValue);
796       } catch (NumberFormatException e)
797       {
798         // leave as 0
799       }
800     }
801
802     return score;
803   }
804
805   /**
806    * A convenience method to get an attribute value for an alternate allele
807    * 
808    * @param variant
809    * @param attributeName
810    * @param alleleIndex
811    * @return
812    */
813   protected String getAttributeValue(VariantContext variant,
814           String attributeName, int alleleIndex)
815   {
816     Object att = variant.getAttribute(attributeName);
817
818     if (att instanceof String)
819     {
820       return (String) att;
821     }
822     else if (att instanceof ArrayList)
823     {
824       return ((List<String>) att).get(alleleIndex);
825     }
826
827     return null;
828   }
829
830   /**
831    * Adds one variant feature for each allele in the VCF variant record, and
832    * returns the number of features added.
833    * 
834    * @param seq
835    * @param variant
836    * @param featureStart
837    * @param featureEnd
838    * @param forwardStrand
839    * @return
840    */
841   protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
842           int featureStart, int featureEnd, boolean forwardStrand)
843   {
844     int added = 0;
845
846     /*
847      * Javadoc says getAlternateAlleles() imposes no order on the list returned
848      * so we proceed defensively to get them in strict order
849      */
850     int altAlleleCount = variant.getAlternateAlleles().size();
851     for (int i = 0; i < altAlleleCount; i++)
852     {
853       added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
854               forwardStrand);
855     }
856     return added;
857   }
858
859   /**
860    * Inspects one allele and attempts to add a variant feature for it to the
861    * sequence. We extract as much as possible of the additional data associated
862    * with this allele to store in the feature's key-value map. Answers the
863    * number of features added (0 or 1).
864    * 
865    * @param seq
866    * @param variant
867    * @param altAlleleIndex
868    *          (0, 1..)
869    * @param featureStart
870    * @param featureEnd
871    * @param forwardStrand
872    * @return
873    */
874   protected int addAlleleFeature(SequenceI seq, VariantContext variant,
875           int altAlleleIndex, int featureStart, int featureEnd,
876           boolean forwardStrand)
877   {
878     String reference = variant.getReference().getBaseString();
879     Allele alt = variant.getAlternateAllele(altAlleleIndex);
880     String allele = alt.getBaseString();
881
882     /*
883      * build the ref,alt allele description e.g. "G,A", using the base
884      * complement if the sequence is on the reverse strand
885      */
886     // TODO check how structural variants are shown on reverse strand
887     StringBuilder sb = new StringBuilder();
888     sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
889     sb.append(COMMA);
890     sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
891     String alleles = sb.toString(); // e.g. G,A
892
893     String type = SequenceOntologyI.SEQUENCE_VARIANT;
894     float score = getAlleleFrequency(variant, altAlleleIndex);
895
896     SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
897             featureEnd, score, FEATURE_GROUP_VCF);
898     sf.setSource(sourceId);
899
900     sf.setValue(Gff3Helper.ALLELES, alleles);
901
902     addAlleleProperties(variant, seq, sf, altAlleleIndex);
903
904     seq.addSequenceFeature(sf);
905
906     return 1;
907   }
908
909   /**
910    * Add any allele-specific VCF key-value data to the sequence feature
911    * 
912    * @param variant
913    * @param seq
914    * @param sf
915    * @param altAlelleIndex
916    *          (0, 1..)
917    */
918   protected void addAlleleProperties(VariantContext variant, SequenceI seq,
919           SequenceFeature sf, final int altAlelleIndex)
920   {
921     Map<String, Object> atts = variant.getAttributes();
922
923     for (Entry<String, Object> att : atts.entrySet())
924     {
925       String key = att.getKey();
926
927       /*
928        * extract Consequence data (if present) that we are able to
929        * associated with the allele for this variant feature
930        */
931       if (CSQ_FIELD.equals(key))
932       {
933         addConsequences(variant, seq, sf, altAlelleIndex);
934         continue;
935       }
936
937       /*
938        * filter out fields we don't want to capture
939        */
940       if (!vcfFieldsOfInterest.contains(key))
941       {
942         continue;
943       }
944
945       /*
946        * we extract values for other data which are allele-specific; 
947        * these may be per alternate allele (INFO[key].Number = 'A') 
948        * or per allele including reference (INFO[key].Number = 'R') 
949        */
950       VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
951       if (infoHeader == null)
952       {
953         /*
954          * can't be sure what data belongs to this allele, so
955          * play safe and don't take any
956          */
957         continue;
958       }
959
960       VCFHeaderLineCount number = infoHeader.getCountType();
961       int index = altAlelleIndex;
962       if (number == VCFHeaderLineCount.R)
963       {
964         /*
965          * one value per allele including reference, so bump index
966          * e.g. the 3rd value is for the  2nd alternate allele
967          */
968         index++;
969       }
970       else if (number != VCFHeaderLineCount.A)
971       {
972         /*
973          * don't save other values as not allele-related
974          */
975         continue;
976       }
977
978       /*
979        * take the index'th value
980        */
981       String value = getAttributeValue(variant, key, index);
982       if (value != null)
983       {
984         sf.setValue(key, value);
985       }
986     }
987   }
988
989   /**
990    * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
991    * feature for the current allele (and transcript if applicable)
992    * <p>
993    * Allele matching: if field ALLELE_NUM is present, it must match
994    * altAlleleIndex. If not present, then field Allele value must match the VCF
995    * Allele.
996    * <p>
997    * Transcript matching: if sequence name can be identified to at least one of
998    * the consequences' Feature values, then select only consequences that match
999    * the value (i.e. consequences for the current transcript sequence). If not,
1000    * take all consequences (this is the case when adding features to the gene
1001    * sequence).
1002    * 
1003    * @param variant
1004    * @param seq
1005    * @param sf
1006    * @param altAlelleIndex
1007    *          (0, 1..)
1008    */
1009   protected void addConsequences(VariantContext variant, SequenceI seq,
1010           SequenceFeature sf, int altAlelleIndex)
1011   {
1012     Object value = variant.getAttribute(CSQ_FIELD);
1013
1014     if (value == null || !(value instanceof ArrayList<?>))
1015     {
1016       return;
1017     }
1018
1019     List<String> consequences = (List<String>) value;
1020
1021     /*
1022      * if CSQ data includes 'Feature', and any value matches the sequence name,
1023      * then restrict consequence data to only the matching value (transcript)
1024      * i.e. just pick out consequences for the transcript the variant feature is on
1025      */
1026     String seqName = seq.getName()== null ? "" : seq.getName().toLowerCase();
1027     String matchFeature = null;
1028     if (csqFeatureFieldIndex > -1)
1029     {
1030       for (String consequence : consequences)
1031       {
1032         String[] csqFields = consequence.split(PIPE_REGEX);
1033         if (csqFields.length > csqFeatureFieldIndex)
1034         {
1035           String featureIdentifier = csqFields[csqFeatureFieldIndex];
1036           if (featureIdentifier.length() > 4
1037                   && seqName.indexOf(featureIdentifier.toLowerCase()) > -1)
1038           {
1039             matchFeature = featureIdentifier;
1040           }
1041         }
1042       }
1043     }
1044
1045     /*
1046      * inspect CSQ consequences; where possible restrict to the consequence
1047      * associated with the current transcript (Feature)
1048      */
1049     SortedMap<String, String> csqValues = new TreeMap<>(
1050             String.CASE_INSENSITIVE_ORDER);
1051
1052     for (String consequence : consequences)
1053     {
1054       String[] csqFields = consequence.split(PIPE_REGEX);
1055
1056       if (includeConsequence(csqFields, matchFeature, variant,
1057               altAlelleIndex))
1058       {
1059         /*
1060          * inspect individual fields of this consequence, copying non-null
1061          * values which are 'fields of interest'
1062          */
1063         int i = 0;
1064         for (String field : csqFields)
1065         {
1066           if (field != null && field.length() > 0)
1067           {
1068             String id = vepFieldsOfInterest.get(i);
1069             if (id != null)
1070             {
1071               csqValues.put(id, field);
1072             }
1073           }
1074           i++;
1075         }
1076       }
1077     }
1078
1079     if (!csqValues.isEmpty())
1080     {
1081       sf.setValue(CSQ_FIELD, csqValues);
1082     }
1083   }
1084
1085   /**
1086    * Answers true if we want to associate this block of consequence data with
1087    * the specified alternate allele of the VCF variant.
1088    * <p>
1089    * If consequence data includes the ALLELE_NUM field, then this has to match
1090    * altAlleleIndex. Otherwise the Allele field of the consequence data has to
1091    * match the allele value.
1092    * <p>
1093    * Optionally (if matchFeature is not null), restrict to only include
1094    * consequences whose Feature value matches. This allows us to attach
1095    * consequences to their respective transcripts.
1096    * 
1097    * @param csqFields
1098    * @param matchFeature
1099    * @param variant
1100    * @param altAlelleIndex
1101    *          (0, 1..)
1102    * @return
1103    */
1104   protected boolean includeConsequence(String[] csqFields,
1105           String matchFeature, VariantContext variant, int altAlelleIndex)
1106   {
1107     /*
1108      * check consequence is for the current transcript
1109      */
1110     if (matchFeature != null)
1111     {
1112       if (csqFields.length <= csqFeatureFieldIndex)
1113       {
1114         return false;
1115       }
1116       String featureIdentifier = csqFields[csqFeatureFieldIndex];
1117       if (!featureIdentifier.equals(matchFeature))
1118       {
1119         return false; // consequence is for a different transcript
1120       }
1121     }
1122
1123     /*
1124      * if ALLELE_NUM is present, it must match altAlleleIndex
1125      * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1126      */
1127     if (csqAlleleNumberFieldIndex > -1)
1128     {
1129       if (csqFields.length <= csqAlleleNumberFieldIndex)
1130       {
1131         return false;
1132       }
1133       String alleleNum = csqFields[csqAlleleNumberFieldIndex];
1134       return String.valueOf(altAlelleIndex + 1).equals(alleleNum);
1135     }
1136
1137     /*
1138      * else consequence allele must match variant allele
1139      */
1140     if (csqAlleleFieldIndex > -1 && csqFields.length > csqAlleleFieldIndex)
1141     {
1142       String csqAllele = csqFields[csqAlleleFieldIndex];
1143       String vcfAllele = variant.getAlternateAllele(altAlelleIndex)
1144               .getBaseString();
1145       return csqAllele.equals(vcfAllele);
1146     }
1147
1148     return false;
1149   }
1150
1151   /**
1152    * A convenience method to complement a dna base and return the string value
1153    * of its complement
1154    * 
1155    * @param reference
1156    * @return
1157    */
1158   protected String complement(byte[] reference)
1159   {
1160     return String.valueOf(Dna.getComplement((char) reference[0]));
1161   }
1162
1163   /**
1164    * Determines the location of the query range (chromosome positions) in a
1165    * different reference assembly.
1166    * <p>
1167    * If the range is just a subregion of one for which we already have a mapping
1168    * (for example, an exon sub-region of a gene), then the mapping is just
1169    * computed arithmetically.
1170    * <p>
1171    * Otherwise, calls the Ensembl REST service that maps from one assembly
1172    * reference's coordinates to another's
1173    * 
1174    * @param queryRange
1175    *          start-end chromosomal range in 'fromRef' coordinates
1176    * @param chromosome
1177    * @param species
1178    * @param fromRef
1179    *          assembly reference for the query coordinates
1180    * @param toRef
1181    *          assembly reference we wish to translate to
1182    * @return the start-end range in 'toRef' coordinates
1183    */
1184   protected int[] mapReferenceRange(int[] queryRange, String chromosome,
1185           String species, String fromRef, String toRef)
1186   {
1187     /*
1188      * first try shorcut of computing the mapping as a subregion of one
1189      * we already have (e.g. for an exon, if we have the gene mapping)
1190      */
1191     int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
1192             species, fromRef, toRef);
1193     if (mappedRange != null)
1194     {
1195       return mappedRange;
1196     }
1197
1198     /*
1199      * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
1200      */
1201     EnsemblMap mapper = new EnsemblMap();
1202     int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
1203             toRef, queryRange);
1204
1205     if (mapping == null)
1206     {
1207       // mapping service failure
1208       return null;
1209     }
1210
1211     /*
1212      * save mapping for possible future re-use
1213      */
1214     String key = makeRangesKey(chromosome, species, fromRef, toRef);
1215     if (!assemblyMappings.containsKey(key))
1216     {
1217       assemblyMappings.put(key, new HashMap<int[], int[]>());
1218     }
1219
1220     assemblyMappings.get(key).put(queryRange, mapping);
1221
1222     return mapping;
1223   }
1224
1225   /**
1226    * If we already have a 1:1 contiguous mapping which subsumes the given query
1227    * range, this method just calculates and returns the subset of that mapping,
1228    * else it returns null. In practical terms, if a gene has a contiguous
1229    * mapping between (for example) GRCh37 and GRCh38, then we assume that its
1230    * subsidiary exons occupy unchanged relative positions, and just compute
1231    * these as offsets, rather than do another lookup of the mapping.
1232    * <p>
1233    * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
1234    * simply remove this method or let it always return null.
1235    * <p>
1236    * Warning: many rapid calls to the /map service map result in a 429 overload
1237    * error response
1238    * 
1239    * @param queryRange
1240    * @param chromosome
1241    * @param species
1242    * @param fromRef
1243    * @param toRef
1244    * @return
1245    */
1246   protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
1247           String species, String fromRef, String toRef)
1248   {
1249     String key = makeRangesKey(chromosome, species, fromRef, toRef);
1250     if (assemblyMappings.containsKey(key))
1251     {
1252       Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
1253       for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
1254       {
1255         int[] fromRange = mappedRange.getKey();
1256         int[] toRange = mappedRange.getValue();
1257         if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
1258         {
1259           /*
1260            * mapping is 1:1 in length, so we trust it to have no discontinuities
1261            */
1262           if (MappingUtils.rangeContains(fromRange, queryRange))
1263           {
1264             /*
1265              * fromRange subsumes our query range
1266              */
1267             int offset = queryRange[0] - fromRange[0];
1268             int mappedRangeFrom = toRange[0] + offset;
1269             int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
1270             return new int[] { mappedRangeFrom, mappedRangeTo };
1271           }
1272         }
1273       }
1274     }
1275     return null;
1276   }
1277
1278   /**
1279    * Transfers the sequence feature to the target sequence, locating its start
1280    * and end range based on the mapping. Features which do not overlap the
1281    * target sequence are ignored.
1282    * 
1283    * @param sf
1284    * @param targetSequence
1285    * @param mapping
1286    *          mapping from the feature's coordinates to the target sequence
1287    */
1288   protected void transferFeature(SequenceFeature sf,
1289           SequenceI targetSequence, MapList mapping)
1290   {
1291     int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1292   
1293     if (mappedRange != null)
1294     {
1295       String group = sf.getFeatureGroup();
1296       int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1297       int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1298       SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1299               group, sf.getScore());
1300       targetSequence.addSequenceFeature(copy);
1301     }
1302   }
1303
1304   /**
1305    * Formats a ranges map lookup key
1306    * 
1307    * @param chromosome
1308    * @param species
1309    * @param fromRef
1310    * @param toRef
1311    * @return
1312    */
1313   protected static String makeRangesKey(String chromosome, String species,
1314           String fromRef, String toRef)
1315   {
1316     return species + EXCL + chromosome + EXCL + fromRef + EXCL
1317             + toRef;
1318   }
1319 }