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 // check if reference is wrt assembly19 (GRCh37)
187 // todo may need to allow user to specify reference assembly?
188 boolean isRefGrch37 = (ref != null && ref.getValue().contains(
195 * query for VCF overlapping each sequence in turn
197 for (SequenceI seq : al.getSequences())
199 int added = loadSequenceVCF(seq, reader, isRefGrch37);
204 transferAddedFeatures(seq);
209 // long elapsed = System.currentTimeMillis() - start;
210 String msg = MessageManager.formatMessage("label.added_vcf",
213 if (gui.getFeatureSettingsUI() != null)
215 gui.getFeatureSettingsUI().discoverAllFeatureData();
218 } catch (Throwable e)
220 System.err.println("Error processing VCF: " + e.getMessage());
224 gui.setStatus("Error occurred - see console for details");
233 } catch (IOException e)
242 * Records the position of selected fields defined in the CSQ INFO header (if
243 * there is one). CSQ fields are declared in the CSQ INFO Description e.g.
245 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
247 protected void locateCsqFields()
249 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ);
255 String desc = csqInfo.getDescription();
256 int formatPos = desc.indexOf(FORMAT);
259 System.err.println("Parse error, failed to find " + FORMAT
263 desc = desc.substring(formatPos + FORMAT.length());
267 String[] format = desc.split(PIPE_REGEX);
269 for (String field : format)
271 if (ALLELE_NUM_KEY.equals(field))
273 csqAlleleNumberFieldIndex = index;
275 if (ALLELE_KEY.equals(field))
277 csqAlleleFieldIndex = index;
279 if (FEATURE_KEY.equals(field))
281 csqFeatureFieldIndex = index;
289 * Transfers VCF features to sequences to which this sequence has a mapping.
290 * If the mapping is 1:3, computes peptide variants from nucleotide variants.
294 protected void transferAddedFeatures(SequenceI seq)
296 DBRefEntry[] dbrefs = seq.getDBRefs();
301 for (DBRefEntry dbref : dbrefs)
303 Mapping mapping = dbref.getMap();
304 if (mapping == null || mapping.getTo() == null)
309 SequenceI mapTo = mapping.getTo();
310 MapList map = mapping.getMap();
311 if (map.getFromRatio() == 3)
314 * dna-to-peptide product mapping
316 AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
321 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
323 List<SequenceFeature> features = seq.getFeatures()
324 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
325 for (SequenceFeature sf : features)
327 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
329 transferFeature(sf, mapTo, map);
337 * Tries to add overlapping variants read from a VCF file to the given
338 * sequence, and returns the number of variant features added. Note that this
339 * requires the sequence to hold information as to its chromosomal positions
340 * and reference, in order to be able to map the VCF variants to the sequence.
344 * @param isVcfRefGrch37
347 protected int loadSequenceVCF(SequenceI seq, VCFReader reader,
348 boolean isVcfRefGrch37)
351 GeneLociI seqCoords = seq.getGeneLoci();
352 if (seqCoords == null)
354 System.out.println(String.format(
355 "Can't query VCF for %s as chromosome coordinates not known",
360 List<int[]> seqChromosomalContigs = seqCoords.getMap().getToRanges();
361 for (int[] range : seqChromosomalContigs)
363 count += addVcfVariants(seq, reader, range, isVcfRefGrch37);
370 * Queries the VCF reader for any variants that overlap the given chromosome
371 * region of the sequence, and adds as variant features. Returns the number of
372 * overlapping variants found.
377 * start-end range of a sequence region in its chromosomal
379 * @param isVcfRefGrch37
380 * true if the VCF is with reference to GRCh37
383 protected int addVcfVariants(SequenceI seq, VCFReader reader,
384 int[] range, boolean isVcfRefGrch37)
386 GeneLociI seqCoords = seq.getGeneLoci();
388 String chromosome = seqCoords.getChromosomeId();
389 String seqRef = seqCoords.getAssemblyId();
390 String species = seqCoords.getSpeciesId();
393 * map chromosomal coordinates from GRCh38 (sequence) to
394 * GRCh37 (VCF) if necessary
396 // TODO generalise for other assemblies and species
398 String fromRef = "GRCh38";
399 if (fromRef.equalsIgnoreCase(seqRef) && isVcfRefGrch37)
401 String toRef = "GRCh37";
402 int[] newRange = mapReferenceRange(range, chromosome, "human",
404 if (newRange == null)
406 System.err.println(String.format(
407 "Failed to map %s:%s:%s:%d:%d to %s", species, chromosome,
408 fromRef, range[0], range[1], toRef));
411 offset = newRange[0] - range[0];
415 boolean forwardStrand = range[0] <= range[1];
418 * query the VCF for overlaps
419 * (convert a reverse strand range to forwards)
422 MapList mapping = seqCoords.getMap();
424 int fromLocus = Math.min(range[0], range[1]);
425 int toLocus = Math.max(range[0], range[1]);
426 CloseableIterator<VariantContext> variants = reader.query(chromosome,
428 while (variants.hasNext())
431 * get variant location in sequence chromosomal coordinates
433 VariantContext variant = variants.next();
436 * we can only process SNP variants (which can be reported
437 * as part of a MIXED variant record
439 if (!variant.isSNP() && !variant.isMixed())
444 int start = variant.getStart() - offset;
445 int end = variant.getEnd() - offset;
448 * convert chromosomal location to sequence coordinates
449 * - null if a partially overlapping feature
451 int[] seqLocation = mapping.locateInFrom(start, end);
452 if (seqLocation != null)
454 count += addAlleleFeatures(seq, variant, seqLocation[0],
455 seqLocation[1], forwardStrand);
465 * A convenience method to get the AF value for the given alternate allele
472 protected float getAlleleFrequency(VariantContext variant, int alleleIndex)
475 String attributeValue = getAttributeValue(variant,
476 ALLELE_FREQUENCY_KEY, alleleIndex);
477 if (attributeValue != null)
481 score = Float.parseFloat(attributeValue);
482 } catch (NumberFormatException e)
492 * A convenience method to get an attribute value for an alternate allele
495 * @param attributeName
499 protected String getAttributeValue(VariantContext variant,
500 String attributeName, int alleleIndex)
502 Object att = variant.getAttribute(attributeName);
504 if (att instanceof String)
508 else if (att instanceof ArrayList)
510 return ((List<String>) att).get(alleleIndex);
517 * Adds one variant feature for each allele in the VCF variant record, and
518 * returns the number of features added.
522 * @param featureStart
524 * @param forwardStrand
527 protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
528 int featureStart, int featureEnd, boolean forwardStrand)
533 * Javadoc says getAlternateAlleles() imposes no order on the list returned
534 * so we proceed defensively to get them in strict order
536 int altAlleleCount = variant.getAlternateAlleles().size();
537 for (int i = 0; i < altAlleleCount; i++)
539 added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
546 * Inspects one allele and attempts to add a variant feature for it to the
547 * sequence. We extract as much as possible of the additional data associated
548 * with this allele to store in the feature's key-value map. Answers the
549 * number of features added (0 or 1).
553 * @param altAlleleIndex
555 * @param featureStart
557 * @param forwardStrand
560 protected int addAlleleFeature(SequenceI seq, VariantContext variant,
561 int altAlleleIndex, int featureStart, int featureEnd,
562 boolean forwardStrand)
564 String reference = variant.getReference().getBaseString();
565 Allele alt = variant.getAlternateAllele(altAlleleIndex);
566 String allele = alt.getBaseString();
567 if (allele.length() != 1)
576 * build the ref,alt allele description e.g. "G,A", using the base
577 * complement if the sequence is on the reverse strand
579 // TODO check how structural variants are shown on reverse strand
580 StringBuilder sb = new StringBuilder();
581 sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
583 sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
584 String alleles = sb.toString(); // e.g. G,A
586 String type = SequenceOntologyI.SEQUENCE_VARIANT;
587 float score = getAlleleFrequency(variant, altAlleleIndex);
589 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
590 featureEnd, score, FEATURE_GROUP_VCF);
592 sf.setValue(Gff3Helper.ALLELES, alleles);
594 addAlleleProperties(variant, seq, sf, altAlleleIndex);
596 seq.addSequenceFeature(sf);
602 * Add any allele-specific VCF key-value data to the sequence feature
607 * @param altAlelleIndex
610 protected void addAlleleProperties(VariantContext variant, SequenceI seq,
611 SequenceFeature sf, final int altAlelleIndex)
613 Map<String, Object> atts = variant.getAttributes();
615 for (Entry<String, Object> att : atts.entrySet())
617 String key = att.getKey();
620 * extract Consequence data (if present) that we are able to
621 * associated with the allele for this variant feature
625 addConsequences(variant, seq, sf, altAlelleIndex);
630 * we extract values for other data which are allele-specific;
631 * these may be per alternate allele (INFO[key].Number = 'A')
632 * or per allele including reference (INFO[key].Number = 'R')
634 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
635 if (infoHeader == null)
638 * can't be sure what data belongs to this allele, so
639 * play safe and don't take any
644 VCFHeaderLineCount number = infoHeader.getCountType();
645 int index = altAlelleIndex;
646 if (number == VCFHeaderLineCount.R)
649 * one value per allele including reference, so bump index
650 * e.g. the 3rd value is for the 2nd alternate allele
654 else if (number != VCFHeaderLineCount.A)
657 * don't save other values as not allele-related
663 * take the index'th value
665 String value = getAttributeValue(variant, key, index);
668 sf.setValue(key, value);
674 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
675 * feature for the current allele (and transcript if applicable)
677 * Allele matching: if field ALLELE_NUM is present, it must match
678 * altAlleleIndex. If not present, then field Allele value must match the VCF
681 * Transcript matching: if sequence name can be identified to at least one of
682 * the consequences' Feature values, then select only consequences that match
683 * the value (i.e. consequences for the current transcript sequence). If not,
684 * take all consequences (this is the case when adding features to the gene
690 * @param altAlelleIndex
693 protected void addConsequences(VariantContext variant, SequenceI seq,
694 SequenceFeature sf, int altAlelleIndex)
696 Object value = variant.getAttribute(CSQ);
698 if (value == null || !(value instanceof ArrayList<?>))
703 List<String> consequences = (List<String>) value;
706 * if CSQ data includes 'Feature', and any value matches the sequence name,
707 * then restrict consequence data to only the matching value (transcript)
708 * i.e. just pick out consequences for the transcript the variant feature is on
710 String seqName = seq.getName()== null ? "" : seq.getName().toLowerCase();
711 String matchFeature = null;
712 if (csqFeatureFieldIndex > -1)
714 for (String consequence : consequences)
716 String[] csqFields = consequence.split(PIPE_REGEX);
717 if (csqFields.length > csqFeatureFieldIndex)
719 String featureIdentifier = csqFields[csqFeatureFieldIndex];
720 if (featureIdentifier.length() > 4
721 && seqName.indexOf(featureIdentifier.toLowerCase()) > -1)
723 matchFeature = featureIdentifier;
729 StringBuilder sb = new StringBuilder(128);
730 boolean found = false;
732 for (String consequence : consequences)
734 String[] csqFields = consequence.split(PIPE_REGEX);
736 if (includeConsequence(csqFields, matchFeature, variant,
744 sb.append(consequence);
750 sf.setValue(CSQ, sb.toString());
755 * Answers true if we want to associate this block of consequence data with
756 * the specified alternate allele of the VCF variant.
758 * If consequence data includes the ALLELE_NUM field, then this has to match
759 * altAlleleIndex. Otherwise the Allele field of the consequence data has to
760 * match the allele value.
762 * Optionally (if matchFeature is not null), restrict to only include
763 * consequences whose Feature value matches. This allows us to attach
764 * consequences to their respective transcripts.
767 * @param matchFeature
769 * @param altAlelleIndex
773 protected boolean includeConsequence(String[] csqFields,
774 String matchFeature, VariantContext variant, int altAlelleIndex)
777 * check consequence is for the current transcript
779 if (matchFeature != null)
781 if (csqFields.length <= csqFeatureFieldIndex)
785 String featureIdentifier = csqFields[csqFeatureFieldIndex];
786 if (!featureIdentifier.equals(matchFeature))
788 return false; // consequence is for a different transcript
793 * if ALLELE_NUM is present, it must match altAlleleIndex
794 * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
796 if (csqAlleleNumberFieldIndex > -1)
798 if (csqFields.length <= csqAlleleNumberFieldIndex)
802 String alleleNum = csqFields[csqAlleleNumberFieldIndex];
803 return String.valueOf(altAlelleIndex + 1).equals(alleleNum);
807 * else consequence allele must match variant allele
809 if (csqAlleleFieldIndex > -1 && csqFields.length > csqAlleleFieldIndex)
811 String csqAllele = csqFields[csqAlleleFieldIndex];
812 String vcfAllele = variant.getAlternateAllele(altAlelleIndex)
814 return csqAllele.equals(vcfAllele);
821 * A convenience method to complement a dna base and return the string value
827 protected String complement(byte[] reference)
829 return String.valueOf(Dna.getComplement((char) reference[0]));
833 * Determines the location of the query range (chromosome positions) in a
834 * different reference assembly.
836 * If the range is just a subregion of one for which we already have a mapping
837 * (for example, an exon sub-region of a gene), then the mapping is just
838 * computed arithmetically.
840 * Otherwise, calls the Ensembl REST service that maps from one assembly
841 * reference's coordinates to another's
844 * start-end chromosomal range in 'fromRef' coordinates
848 * assembly reference for the query coordinates
850 * assembly reference we wish to translate to
851 * @return the start-end range in 'toRef' coordinates
853 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
854 String species, String fromRef, String toRef)
857 * first try shorcut of computing the mapping as a subregion of one
858 * we already have (e.g. for an exon, if we have the gene mapping)
860 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
861 species, fromRef, toRef);
862 if (mappedRange != null)
868 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
870 EnsemblMap mapper = new EnsemblMap();
871 int[] mapping = mapper.getMapping(species, chromosome, fromRef, toRef,
876 // mapping service failure
881 * save mapping for possible future re-use
883 String key = makeRangesKey(chromosome, species, fromRef, toRef);
884 if (!assemblyMappings.containsKey(key))
886 assemblyMappings.put(key, new HashMap<int[], int[]>());
889 assemblyMappings.get(key).put(queryRange, mapping);
895 * If we already have a 1:1 contiguous mapping which subsumes the given query
896 * range, this method just calculates and returns the subset of that mapping,
897 * else it returns null. In practical terms, if a gene has a contiguous
898 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
899 * subsidiary exons occupy unchanged relative positions, and just compute
900 * these as offsets, rather than do another lookup of the mapping.
902 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
903 * simply remove this method or let it always return null.
905 * Warning: many rapid calls to the /map service map result in a 429 overload
915 protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
916 String species, String fromRef, String toRef)
918 String key = makeRangesKey(chromosome, species, fromRef, toRef);
919 if (assemblyMappings.containsKey(key))
921 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
922 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
924 int[] fromRange = mappedRange.getKey();
925 int[] toRange = mappedRange.getValue();
926 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
929 * mapping is 1:1 in length, so we trust it to have no discontinuities
931 if (MappingUtils.rangeContains(fromRange, queryRange))
934 * fromRange subsumes our query range
936 int offset = queryRange[0] - fromRange[0];
937 int mappedRangeFrom = toRange[0] + offset;
938 int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
939 return new int[] { mappedRangeFrom, mappedRangeTo };
948 * Transfers the sequence feature to the target sequence, locating its start
949 * and end range based on the mapping. Features which do not overlap the
950 * target sequence are ignored.
953 * @param targetSequence
955 * mapping from the feature's coordinates to the target sequence
957 protected void transferFeature(SequenceFeature sf,
958 SequenceI targetSequence, MapList mapping)
960 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
962 if (mappedRange != null)
964 String group = sf.getFeatureGroup();
965 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
966 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
967 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
968 group, sf.getScore());
969 targetSequence.addSequenceFeature(copy);
974 * Formats a ranges map lookup key
982 protected static String makeRangesKey(String chromosome, String species,
983 String fromRef, String toRef)
985 return species + EXCL + chromosome + EXCL + fromRef + EXCL