1 package jalview.io.vcf;
3 import htsjdk.samtools.util.CloseableIterator;
4 import htsjdk.variant.variantcontext.Allele;
5 import htsjdk.variant.variantcontext.VariantContext;
6 import htsjdk.variant.vcf.VCFHeader;
7 import htsjdk.variant.vcf.VCFHeaderLine;
8 import htsjdk.variant.vcf.VCFHeaderLineCount;
9 import htsjdk.variant.vcf.VCFInfoHeaderLine;
11 import jalview.analysis.AlignmentUtils;
12 import jalview.analysis.Dna;
13 import jalview.api.AlignViewControllerGuiI;
14 import jalview.datamodel.AlignmentI;
15 import jalview.datamodel.DBRefEntry;
16 import jalview.datamodel.GeneLociI;
17 import jalview.datamodel.Mapping;
18 import jalview.datamodel.SequenceFeature;
19 import jalview.datamodel.SequenceI;
20 import jalview.ext.ensembl.EnsemblMap;
21 import jalview.ext.htsjdk.VCFReader;
22 import jalview.io.gff.Gff3Helper;
23 import jalview.io.gff.SequenceOntologyI;
24 import jalview.util.MapList;
25 import jalview.util.MappingUtils;
26 import jalview.util.MessageManager;
28 import java.io.IOException;
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.List;
33 import java.util.Map.Entry;
36 * A class to read VCF data (using the htsjdk) and add variants as sequence
37 * features on dna and any related protein product sequences
41 public class VCFLoader
44 * keys to fields of VEP CSQ consequence data
45 * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
47 private static final String ALLELE_KEY = "Allele";
49 private static final String ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref), 1...
50 private static final String FEATURE_KEY = "Feature"; // Ensembl stable id
53 * what comes before column headings in CSQ Description field
55 private static final String FORMAT = "Format: ";
58 * default VCF INFO key for VEP consequence data
59 * NB this can be overridden running VEP with --vcf_info_field
60 * - we don't handle this case (require CSQ identifier)
62 private static final String CSQ = "CSQ";
65 * separator for fields in consequence data
67 private static final String PIPE = "|";
69 private static final String PIPE_REGEX = "\\" + PIPE;
72 * key for Allele Frequency output by VEP
73 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
75 private static final String ALLELE_FREQUENCY_KEY = "AF";
78 * delimiter that separates multiple consequence data blocks
80 private static final String COMMA = ",";
83 * the feature group assigned to a VCF variant in Jalview
85 private static final String FEATURE_GROUP_VCF = "VCF";
88 * internal delimiter used to build keys for assemblyMappings
91 private static final String EXCL = "!";
94 * the alignment we are associating VCF data with
96 private AlignmentI al;
99 * mappings between VCF and sequence reference assembly regions, as
100 * key = "species!chromosome!fromAssembly!toAssembly
101 * value = Map{fromRange, toRange}
103 private Map<String, Map<int[], int[]>> assemblyMappings;
106 * holds details of the VCF header lines (metadata)
108 private VCFHeader header;
111 * the position (0...) of field in each block of
112 * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
113 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
115 private int csqAlleleFieldIndex = -1;
116 private int csqAlleleNumberFieldIndex = -1;
117 private int csqFeatureFieldIndex = -1;
120 * Constructor given an alignment context
124 public VCFLoader(AlignmentI alignment)
128 // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
129 assemblyMappings = new HashMap<String, Map<int[], int[]>>();
133 * Starts a new thread to query and load VCF variant data on to the alignment
135 * This method is not thread safe - concurrent threads should use separate
136 * instances of this class.
141 public void loadVCF(final String filePath,
142 final AlignViewControllerGuiI gui)
146 gui.setStatus(MessageManager.getString("label.searching_vcf"));
155 VCFLoader.this.doLoad(filePath, gui);
162 * Loads VCF on to an alignment - provided it can be related to one or more
163 * sequence's chromosomal coordinates
167 * optional callback handler for messages
169 protected void doLoad(String filePath, AlignViewControllerGuiI gui)
171 VCFReader reader = null;
174 // long start = System.currentTimeMillis();
175 reader = new VCFReader(filePath);
177 header = reader.getFileHeader();
178 VCFHeaderLine ref = header
179 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
182 * get offset of CSQ ALLELE_NUM and Feature if declared
186 String vcfAssembly = ref.getValue();
192 * query for VCF overlapping each sequence in turn
194 for (SequenceI seq : al.getSequences())
196 int added = loadSequenceVCF(seq, reader, vcfAssembly);
201 transferAddedFeatures(seq);
206 // long elapsed = System.currentTimeMillis() - start;
207 String msg = MessageManager.formatMessage("label.added_vcf",
210 if (gui.getFeatureSettingsUI() != null)
212 gui.getFeatureSettingsUI().discoverAllFeatureData();
215 } catch (Throwable e)
217 System.err.println("Error processing VCF: " + e.getMessage());
221 gui.setStatus("Error occurred - see console for details");
230 } catch (IOException e)
239 * Records the position of selected fields defined in the CSQ INFO header (if
240 * there is one). CSQ fields are declared in the CSQ INFO Description e.g.
242 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
244 protected void locateCsqFields()
246 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ);
252 String desc = csqInfo.getDescription();
253 int formatPos = desc.indexOf(FORMAT);
256 System.err.println("Parse error, failed to find " + FORMAT
260 desc = desc.substring(formatPos + FORMAT.length());
264 String[] format = desc.split(PIPE_REGEX);
266 for (String field : format)
268 if (ALLELE_NUM_KEY.equals(field))
270 csqAlleleNumberFieldIndex = index;
272 if (ALLELE_KEY.equals(field))
274 csqAlleleFieldIndex = index;
276 if (FEATURE_KEY.equals(field))
278 csqFeatureFieldIndex = index;
286 * Transfers VCF features to sequences to which this sequence has a mapping.
287 * If the mapping is 3:1, computes peptide variants from nucleotide variants.
291 protected void transferAddedFeatures(SequenceI seq)
293 DBRefEntry[] dbrefs = seq.getDBRefs();
298 for (DBRefEntry dbref : dbrefs)
300 Mapping mapping = dbref.getMap();
301 if (mapping == null || mapping.getTo() == null)
306 SequenceI mapTo = mapping.getTo();
307 MapList map = mapping.getMap();
308 if (map.getFromRatio() == 3)
311 * dna-to-peptide product mapping
313 AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
318 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
320 List<SequenceFeature> features = seq.getFeatures()
321 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
322 for (SequenceFeature sf : features)
324 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
326 transferFeature(sf, mapTo, map);
334 * Tries to add overlapping variants read from a VCF file to the given
335 * sequence, and returns the number of variant features added. Note that this
336 * requires the sequence to hold information as to its species, chromosomal
337 * positions and reference assembly, in order to be able to map the VCF
338 * variants to the sequence (or not)
345 protected int loadSequenceVCF(SequenceI seq, VCFReader reader,
349 GeneLociI seqCoords = seq.getGeneLoci();
350 if (seqCoords == null)
352 System.out.println(String.format(
353 "Can't query VCF for %s as chromosome coordinates not known",
358 if (!vcfSpeciesMatchesSequence(vcfAssembly, seqCoords.getSpeciesId()))
363 List<int[]> seqChromosomalContigs = seqCoords.getMap().getToRanges();
364 for (int[] range : seqChromosomalContigs)
366 count += addVcfVariants(seq, reader, range, vcfAssembly);
373 * Answers true if the species inferred from the VCF reference identifier
374 * matches that for the sequence
380 boolean vcfSpeciesMatchesSequence(String vcfAssembly, String speciesId)
383 // there are many aliases for species - how to equate one with another?
385 // VCF ##reference header is an unstructured URI - how to extract species?
386 // perhaps check if ref includes any (Ensembl) alias of speciesId??
387 // TODO ask the user to confirm this??
389 if (vcfAssembly.contains("Homo_sapiens") // gnomAD exome data example
390 && "HOMO_SAPIENS".equals(speciesId)) // Ensembl species id
395 if (vcfAssembly.contains("c_elegans") // VEP VCF response example
396 && "CAENORHABDITIS_ELEGANS".equals(speciesId)) // Ensembl
401 // this is not a sustainable solution...
407 * Queries the VCF reader for any variants that overlap the given chromosome
408 * region of the sequence, and adds as variant features. Returns the number of
409 * overlapping variants found.
414 * start-end range of a sequence region in its chromosomal
417 * the '##reference' identifier for the VCF reference assembly
420 protected int addVcfVariants(SequenceI seq, VCFReader reader,
421 int[] range, String vcfAssembly)
423 GeneLociI seqCoords = seq.getGeneLoci();
425 String chromosome = seqCoords.getChromosomeId();
426 String seqRef = seqCoords.getAssemblyId();
427 String species = seqCoords.getSpeciesId();
430 * map chromosomal coordinates from sequence to VCF if the VCF
431 * data has a different reference assembly to the sequence
433 // TODO generalise for non-human species
434 // - or get the user to choose in a dialog
437 if ("GRCh38".equalsIgnoreCase(seqRef) // Ensembl
438 && vcfAssembly.contains("Homo_sapiens_assembly19")) // gnomAD
440 String toRef = "GRCh37";
441 int[] newRange = mapReferenceRange(range, chromosome, "human",
443 if (newRange == null)
445 System.err.println(String.format(
446 "Failed to map %s:%s:%s:%d:%d to %s", species, chromosome,
447 seqRef, range[0], range[1], toRef));
450 offset = newRange[0] - range[0];
454 boolean forwardStrand = range[0] <= range[1];
457 * query the VCF for overlaps
458 * (convert a reverse strand range to forwards)
461 MapList mapping = seqCoords.getMap();
463 int fromLocus = Math.min(range[0], range[1]);
464 int toLocus = Math.max(range[0], range[1]);
465 CloseableIterator<VariantContext> variants = reader.query(chromosome,
467 while (variants.hasNext())
470 * get variant location in sequence chromosomal coordinates
472 VariantContext variant = variants.next();
474 int start = variant.getStart() - offset;
475 int end = variant.getEnd() - offset;
478 * convert chromosomal location to sequence coordinates
479 * - may be reverse strand (convert to forward for sequence feature)
480 * - null if a partially overlapping feature
482 int[] seqLocation = mapping.locateInFrom(start, end);
483 if (seqLocation != null)
485 int featureStart = Math.min(seqLocation[0], seqLocation[1]);
486 int featureEnd = Math.max(seqLocation[0], seqLocation[1]);
487 count += addAlleleFeatures(seq, variant, featureStart, featureEnd,
498 * A convenience method to get the AF value for the given alternate allele
505 protected float getAlleleFrequency(VariantContext variant, int alleleIndex)
508 String attributeValue = getAttributeValue(variant,
509 ALLELE_FREQUENCY_KEY, alleleIndex);
510 if (attributeValue != null)
514 score = Float.parseFloat(attributeValue);
515 } catch (NumberFormatException e)
525 * A convenience method to get an attribute value for an alternate allele
528 * @param attributeName
532 protected String getAttributeValue(VariantContext variant,
533 String attributeName, int alleleIndex)
535 Object att = variant.getAttribute(attributeName);
537 if (att instanceof String)
541 else if (att instanceof ArrayList)
543 return ((List<String>) att).get(alleleIndex);
550 * Adds one variant feature for each allele in the VCF variant record, and
551 * returns the number of features added.
555 * @param featureStart
557 * @param forwardStrand
560 protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
561 int featureStart, int featureEnd, boolean forwardStrand)
566 * Javadoc says getAlternateAlleles() imposes no order on the list returned
567 * so we proceed defensively to get them in strict order
569 int altAlleleCount = variant.getAlternateAlleles().size();
570 for (int i = 0; i < altAlleleCount; i++)
572 added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
579 * Inspects one allele and attempts to add a variant feature for it to the
580 * sequence. We extract as much as possible of the additional data associated
581 * with this allele to store in the feature's key-value map. Answers the
582 * number of features added (0 or 1).
586 * @param altAlleleIndex
588 * @param featureStart
590 * @param forwardStrand
593 protected int addAlleleFeature(SequenceI seq, VariantContext variant,
594 int altAlleleIndex, int featureStart, int featureEnd,
595 boolean forwardStrand)
597 String reference = variant.getReference().getBaseString();
598 Allele alt = variant.getAlternateAllele(altAlleleIndex);
599 String allele = alt.getBaseString();
602 * build the ref,alt allele description e.g. "G,A", using the base
603 * complement if the sequence is on the reverse strand
605 // TODO check how structural variants are shown on reverse strand
606 StringBuilder sb = new StringBuilder();
607 sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
609 sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
610 String alleles = sb.toString(); // e.g. G,A
612 String type = SequenceOntologyI.SEQUENCE_VARIANT;
613 float score = getAlleleFrequency(variant, altAlleleIndex);
615 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
616 featureEnd, score, FEATURE_GROUP_VCF);
618 sf.setValue(Gff3Helper.ALLELES, alleles);
620 addAlleleProperties(variant, seq, sf, altAlleleIndex);
622 seq.addSequenceFeature(sf);
628 * Add any allele-specific VCF key-value data to the sequence feature
633 * @param altAlelleIndex
636 protected void addAlleleProperties(VariantContext variant, SequenceI seq,
637 SequenceFeature sf, final int altAlelleIndex)
639 Map<String, Object> atts = variant.getAttributes();
641 for (Entry<String, Object> att : atts.entrySet())
643 String key = att.getKey();
646 * extract Consequence data (if present) that we are able to
647 * associated with the allele for this variant feature
651 addConsequences(variant, seq, sf, altAlelleIndex);
656 * we extract values for other data which are allele-specific;
657 * these may be per alternate allele (INFO[key].Number = 'A')
658 * or per allele including reference (INFO[key].Number = 'R')
660 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
661 if (infoHeader == null)
664 * can't be sure what data belongs to this allele, so
665 * play safe and don't take any
670 VCFHeaderLineCount number = infoHeader.getCountType();
671 int index = altAlelleIndex;
672 if (number == VCFHeaderLineCount.R)
675 * one value per allele including reference, so bump index
676 * e.g. the 3rd value is for the 2nd alternate allele
680 else if (number != VCFHeaderLineCount.A)
683 * don't save other values as not allele-related
689 * take the index'th value
691 String value = getAttributeValue(variant, key, index);
694 sf.setValue(key, value);
700 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
701 * feature for the current allele (and transcript if applicable)
703 * Allele matching: if field ALLELE_NUM is present, it must match
704 * altAlleleIndex. If not present, then field Allele value must match the VCF
707 * Transcript matching: if sequence name can be identified to at least one of
708 * the consequences' Feature values, then select only consequences that match
709 * the value (i.e. consequences for the current transcript sequence). If not,
710 * take all consequences (this is the case when adding features to the gene
716 * @param altAlelleIndex
719 protected void addConsequences(VariantContext variant, SequenceI seq,
720 SequenceFeature sf, int altAlelleIndex)
722 Object value = variant.getAttribute(CSQ);
724 if (value == null || !(value instanceof ArrayList<?>))
729 List<String> consequences = (List<String>) value;
732 * if CSQ data includes 'Feature', and any value matches the sequence name,
733 * then restrict consequence data to only the matching value (transcript)
734 * i.e. just pick out consequences for the transcript the variant feature is on
736 String seqName = seq.getName()== null ? "" : seq.getName().toLowerCase();
737 String matchFeature = null;
738 if (csqFeatureFieldIndex > -1)
740 for (String consequence : consequences)
742 String[] csqFields = consequence.split(PIPE_REGEX);
743 if (csqFields.length > csqFeatureFieldIndex)
745 String featureIdentifier = csqFields[csqFeatureFieldIndex];
746 if (featureIdentifier.length() > 4
747 && seqName.indexOf(featureIdentifier.toLowerCase()) > -1)
749 matchFeature = featureIdentifier;
755 StringBuilder sb = new StringBuilder(128);
756 boolean found = false;
758 for (String consequence : consequences)
760 String[] csqFields = consequence.split(PIPE_REGEX);
762 if (includeConsequence(csqFields, matchFeature, variant,
770 sb.append(consequence);
776 sf.setValue(CSQ, sb.toString());
781 * Answers true if we want to associate this block of consequence data with
782 * the specified alternate allele of the VCF variant.
784 * If consequence data includes the ALLELE_NUM field, then this has to match
785 * altAlleleIndex. Otherwise the Allele field of the consequence data has to
786 * match the allele value.
788 * Optionally (if matchFeature is not null), restrict to only include
789 * consequences whose Feature value matches. This allows us to attach
790 * consequences to their respective transcripts.
793 * @param matchFeature
795 * @param altAlelleIndex
799 protected boolean includeConsequence(String[] csqFields,
800 String matchFeature, VariantContext variant, int altAlelleIndex)
803 * check consequence is for the current transcript
805 if (matchFeature != null)
807 if (csqFields.length <= csqFeatureFieldIndex)
811 String featureIdentifier = csqFields[csqFeatureFieldIndex];
812 if (!featureIdentifier.equals(matchFeature))
814 return false; // consequence is for a different transcript
819 * if ALLELE_NUM is present, it must match altAlleleIndex
820 * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
822 if (csqAlleleNumberFieldIndex > -1)
824 if (csqFields.length <= csqAlleleNumberFieldIndex)
828 String alleleNum = csqFields[csqAlleleNumberFieldIndex];
829 return String.valueOf(altAlelleIndex + 1).equals(alleleNum);
833 * else consequence allele must match variant allele
835 if (csqAlleleFieldIndex > -1 && csqFields.length > csqAlleleFieldIndex)
837 String csqAllele = csqFields[csqAlleleFieldIndex];
838 String vcfAllele = variant.getAlternateAllele(altAlelleIndex)
840 return csqAllele.equals(vcfAllele);
847 * A convenience method to complement a dna base and return the string value
853 protected String complement(byte[] reference)
855 return String.valueOf(Dna.getComplement((char) reference[0]));
859 * Determines the location of the query range (chromosome positions) in a
860 * different reference assembly.
862 * If the range is just a subregion of one for which we already have a mapping
863 * (for example, an exon sub-region of a gene), then the mapping is just
864 * computed arithmetically.
866 * Otherwise, calls the Ensembl REST service that maps from one assembly
867 * reference's coordinates to another's
870 * start-end chromosomal range in 'fromRef' coordinates
874 * assembly reference for the query coordinates
876 * assembly reference we wish to translate to
877 * @return the start-end range in 'toRef' coordinates
879 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
880 String species, String fromRef, String toRef)
883 * first try shorcut of computing the mapping as a subregion of one
884 * we already have (e.g. for an exon, if we have the gene mapping)
886 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
887 species, fromRef, toRef);
888 if (mappedRange != null)
894 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
896 EnsemblMap mapper = new EnsemblMap();
897 int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
903 // mapping service failure
908 * save mapping for possible future re-use
910 String key = makeRangesKey(chromosome, species, fromRef, toRef);
911 if (!assemblyMappings.containsKey(key))
913 assemblyMappings.put(key, new HashMap<int[], int[]>());
916 assemblyMappings.get(key).put(queryRange, mapping);
922 * If we already have a 1:1 contiguous mapping which subsumes the given query
923 * range, this method just calculates and returns the subset of that mapping,
924 * else it returns null. In practical terms, if a gene has a contiguous
925 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
926 * subsidiary exons occupy unchanged relative positions, and just compute
927 * these as offsets, rather than do another lookup of the mapping.
929 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
930 * simply remove this method or let it always return null.
932 * Warning: many rapid calls to the /map service map result in a 429 overload
942 protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
943 String species, String fromRef, String toRef)
945 String key = makeRangesKey(chromosome, species, fromRef, toRef);
946 if (assemblyMappings.containsKey(key))
948 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
949 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
951 int[] fromRange = mappedRange.getKey();
952 int[] toRange = mappedRange.getValue();
953 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
956 * mapping is 1:1 in length, so we trust it to have no discontinuities
958 if (MappingUtils.rangeContains(fromRange, queryRange))
961 * fromRange subsumes our query range
963 int offset = queryRange[0] - fromRange[0];
964 int mappedRangeFrom = toRange[0] + offset;
965 int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
966 return new int[] { mappedRangeFrom, mappedRangeTo };
975 * Transfers the sequence feature to the target sequence, locating its start
976 * and end range based on the mapping. Features which do not overlap the
977 * target sequence are ignored.
980 * @param targetSequence
982 * mapping from the feature's coordinates to the target sequence
984 protected void transferFeature(SequenceFeature sf,
985 SequenceI targetSequence, MapList mapping)
987 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
989 if (mappedRange != null)
991 String group = sf.getFeatureGroup();
992 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
993 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
994 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
995 group, sf.getScore());
996 targetSequence.addSequenceFeature(copy);
1001 * Formats a ranges map lookup key
1009 protected static String makeRangesKey(String chromosome, String species,
1010 String fromRef, String toRef)
1012 return species + EXCL + chromosome + EXCL + fromRef + EXCL