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;
9 import jalview.analysis.AlignmentUtils;
10 import jalview.api.AlignViewControllerGuiI;
11 import jalview.datamodel.AlignmentI;
12 import jalview.datamodel.DBRefEntry;
13 import jalview.datamodel.GeneLoci;
14 import jalview.datamodel.Mapping;
15 import jalview.datamodel.Sequence;
16 import jalview.datamodel.SequenceFeature;
17 import jalview.datamodel.SequenceI;
18 import jalview.ext.ensembl.EnsemblMap;
19 import jalview.ext.htsjdk.VCFReader;
20 import jalview.io.gff.SequenceOntologyI;
21 import jalview.util.MapList;
23 import java.io.IOException;
24 import java.util.HashMap;
25 import java.util.List;
27 import java.util.Map.Entry;
30 * A class to read VCF data (using the htsjdk) and add variants as sequence
31 * features on dna and any related protein product sequences
35 public class VCFLoader
37 private static final String EXCL = "!";
40 * the alignment we are associated VCF data with
42 private AlignmentI al;
45 * mappings between VCF and sequence reference assembly regions, as
46 * key = "species!chromosome!fromAssembly!toAssembly
47 * value = Map{fromRange, toRange}
49 private Map<String, Map<int[], int[]>> assemblyMappings;
52 * Constructor given an alignment context
56 public VCFLoader(AlignmentI alignment)
60 // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
61 assemblyMappings = new HashMap<String, Map<int[], int[]>>();
65 * Loads VCF on to an alignment - provided it can be related to one or more
66 * sequence's chromosomal coordinates.
68 * This method is not thread safe - concurrent threads should use separate
69 * instances of this class.
74 public void loadVCF(String filePath, AlignViewControllerGuiI status)
76 VCFReader reader = null;
80 // long start = System.currentTimeMillis();
81 reader = new VCFReader(filePath);
83 VCFHeader header = reader.getFileHeader();
84 VCFHeaderLine ref = header
85 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
86 // check if reference is wrt assembly19 (GRCh37)
87 // todo may need to allow user to specify reference assembly?
88 boolean isRefGrch37 = (ref != null && ref.getValue().contains(
95 * query for VCF overlapping each sequence in turn
97 for (SequenceI seq : al.getSequences())
99 int added = loadVCF(seq, reader, isRefGrch37);
104 computePeptideVariants(seq);
107 // long elapsed = System.currentTimeMillis() - start;
108 String msg = String.format("Added %d VCF variants to %d sequence(s)",
112 status.setStatus(msg);
114 } catch (Throwable e)
116 System.err.println("Error processing VCF: " + e.getMessage());
125 } catch (IOException e)
134 * (Re-)computes peptide variants from dna variants, for any protein sequence
135 * to which the dna sequence has a mapping. Note that although duplicate
136 * features may get computed, they will not be added, since duplicate sequence
137 * features are ignored in Sequence.addSequenceFeature.
141 protected void computePeptideVariants(SequenceI dnaSeq)
143 DBRefEntry[] dbrefs = dnaSeq.getDBRefs();
148 for (DBRefEntry dbref : dbrefs)
150 Mapping mapping = dbref.getMap();
151 if (mapping == null || mapping.getTo() == null
152 || mapping.getMap().getFromRatio() != 3)
156 AlignmentUtils.computeProteinFeatures(dnaSeq, mapping.getTo(),
162 * Tries to add overlapping variants read from a VCF file to the given
163 * sequence, and returns the number of overlapping variants found. Note that
164 * this requires the sequence to hold information as to its chromosomal
165 * positions and reference, in order to be able to map the VCF variants to the
170 * @param isVcfRefGrch37
173 protected int loadVCF(SequenceI seq, VCFReader reader,
174 boolean isVcfRefGrch37)
177 GeneLoci seqCoords = ((Sequence) seq).getGeneLoci();
178 if (seqCoords == null)
183 List<int[]> seqChromosomalContigs = seqCoords.mapping.getToRanges();
184 for (int[] range : seqChromosomalContigs)
186 count += addVcfVariants(seq, reader, range, isVcfRefGrch37);
193 * Queries the VCF reader for any variants that overlap the given chromosome
194 * region of the sequence, and adds as variant features. Returns the number of
195 * overlapping variants found.
200 * start-end range of a sequence region in its chromosomal
202 * @param isVcfRefGrch37
203 * true if the VCF is with reference to GRCh37
206 protected int addVcfVariants(SequenceI seq, VCFReader reader,
207 int[] range, boolean isVcfRefGrch37)
209 GeneLoci seqCoords = ((Sequence) seq).getGeneLoci();
211 String chromosome = seqCoords.chromosome;
212 String seqRef = seqCoords.assembly;
213 String species = seqCoords.species;
215 // TODO handle species properly
216 if ("".equals(species))
222 * map chromosomal coordinates from GRCh38 (sequence) to
223 * GRCh37 (VCF) if necessary
225 // TODO generalise for other assemblies and species
227 String fromRef = "GRCh38";
228 if (fromRef.equalsIgnoreCase(seqRef) && isVcfRefGrch37)
230 String toRef = "GRCh37";
231 int[] newRange = mapReferenceRange(range, chromosome, species,
233 if (newRange == null)
235 System.err.println(String.format(
236 "Failed to map %s:%s:%s:%d:%d to %s", species, chromosome,
237 fromRef, range[0], range[1], toRef));
240 offset = newRange[0] - range[0];
245 * query the VCF for overlaps
246 * (convert a reverse strand range to forwards)
249 MapList mapping = seqCoords.mapping;
251 int fromLocus = Math.min(range[0], range[1]);
252 int toLocus = Math.max(range[0], range[1]);
253 CloseableIterator<VariantContext> variants = reader.query(chromosome,
255 while (variants.hasNext())
258 * get variant location in sequence chromosomal coordinates
260 VariantContext variant = variants.next();
262 int start = variant.getStart() - offset;
263 int end = variant.getEnd() - offset;
266 * convert chromosomal location to sequence coordinates
267 * - null if a partially overlapping feature
269 int[] seqLocation = mapping.locateInFrom(start, end);
270 if (seqLocation != null)
272 addVariantFeatures(seq, variant, seqLocation[0], seqLocation[1]);
282 * Inspects the VCF variant record, and adds variant features to the sequence
286 * @param featureStart
289 protected void addVariantFeatures(SequenceI seq, VariantContext variant,
290 int featureStart, int featureEnd)
292 StringBuilder sb = new StringBuilder();
293 sb.append(variant.getReference().getBaseString());
296 for (Allele allele : variant.getAlleles())
298 if (!allele.isReference())
300 sb.append(",").append(allele.getBaseString());
304 String alleles = sb.toString(); // e.g. G,A,C
306 String type = SequenceOntologyI.SEQUENCE_VARIANT;
308 if (alleleCount == 1)
312 score = (float) variant.getAttributeAsDouble("AF", 0d);
313 } catch (NumberFormatException e)
318 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
319 featureEnd, score, "VCF");
322 * only add 'alleles' property if a SNP, as we can
323 * only handle SNPs when computing peptide variants
327 sf.setValue("alleles", alleles);
330 Map<String, Object> atts = variant.getAttributes();
331 for (Entry<String, Object> att : atts.entrySet())
333 sf.setValue(att.getKey(), att.getValue());
335 seq.addSequenceFeature(sf);
339 * Determines the location of the query range (chromosome positions) in a
340 * different reference assembly.
342 * If the range is just a subregion of one for which we already have a mapping
343 * (for example, an exon sub-region of a gene), then the mapping is just
344 * computed arithmetically.
346 * Otherwise, calls the Ensembl REST service that maps from one assembly
347 * reference's coordinates to another's
350 * start-end chromosomal range in 'fromRef' coordinates
354 * assembly reference for the query coordinates
356 * assembly reference we wish to translate to
357 * @return the start-end range in 'toRef' coordinates
359 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
360 String species, String fromRef, String toRef)
363 * first try shorcut of computing the mapping as a subregion of one
364 * we already have (e.g. for an exon, if we have the gene mapping)
366 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
367 species, fromRef, toRef);
368 if (mappedRange != null)
374 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
376 EnsemblMap mapper = new EnsemblMap();
377 int[] mapping = mapper.getMapping(species, chromosome, fromRef, toRef,
382 // mapping service failure
387 * save mapping for possible future re-use
389 String key = makeRangesKey(chromosome, species, fromRef, toRef);
390 if (!assemblyMappings.containsKey(key))
392 assemblyMappings.put(key, new HashMap<int[], int[]>());
395 assemblyMappings.get(key).put(queryRange, mapping);
401 * If we already have a 1:1 contiguous mapping which subsumes the given query
402 * range, this method just calculates and returns the subset of that mapping,
403 * else it returns null. In practical terms, if a gene has a contiguous
404 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
405 * subsidiary exons occupy unchanged relative positions, and just compute
406 * these as offsets, rather than do another lookup of the mapping.
408 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
409 * simply remove this method or let it always return null.
411 * Warning: many rapid calls to the /map service map result in a 429 overload
421 protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
422 String species, String fromRef, String toRef)
424 String key = makeRangesKey(chromosome, species, fromRef, toRef);
425 if (assemblyMappings.containsKey(key))
427 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
428 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
430 int[] fromRange = mappedRange.getKey();
431 int[] toRange = mappedRange.getValue();
432 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
435 * mapping is 1:1 in length, so we trust it to have no discontinuities
437 if (rangeContains(fromRange, queryRange))
440 * fromRange subsumes our query range
442 int offset = queryRange[0] - fromRange[0];
443 int mappedRangeFrom = toRange[0] + offset;
444 int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
445 return new int[] { mappedRangeFrom, mappedRangeTo };
454 * Answers true if range's start-end positions include those of queryRange,
455 * where either range might be in reverse direction, else false
461 protected static boolean rangeContains(int[] range, int[] queryRange)
463 int min = Math.min(range[0], range[1]);
464 int max = Math.max(range[0], range[1]);
466 return (min <= queryRange[0] && max >= queryRange[0]
467 && min <= queryRange[1] && max >= queryRange[1]);
471 * Formats a ranges map lookup key
479 protected static String makeRangesKey(String chromosome, String species,
480 String fromRef, String toRef)
482 return species + EXCL + chromosome + EXCL + fromRef + EXCL