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;
22 import jalview.util.MappingUtils;
24 import java.io.IOException;
25 import java.util.HashMap;
26 import java.util.List;
28 import java.util.Map.Entry;
31 * A class to read VCF data (using the htsjdk) and add variants as sequence
32 * features on dna and any related protein product sequences
36 public class VCFLoader
38 private static final String EXCL = "!";
41 * the alignment we are associated VCF data with
43 private AlignmentI al;
46 * mappings between VCF and sequence reference assembly regions, as
47 * key = "species!chromosome!fromAssembly!toAssembly
48 * value = Map{fromRange, toRange}
50 private Map<String, Map<int[], int[]>> assemblyMappings;
53 * Constructor given an alignment context
57 public VCFLoader(AlignmentI alignment)
61 // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
62 assemblyMappings = new HashMap<String, Map<int[], int[]>>();
66 * Loads VCF on to an alignment - provided it can be related to one or more
67 * sequence's chromosomal coordinates.
69 * This method is not thread safe - concurrent threads should use separate
70 * instances of this class.
75 public void loadVCF(String filePath, AlignViewControllerGuiI status)
77 VCFReader reader = null;
81 // long start = System.currentTimeMillis();
82 reader = new VCFReader(filePath);
84 VCFHeader header = reader.getFileHeader();
85 VCFHeaderLine ref = header
86 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
87 // check if reference is wrt assembly19 (GRCh37)
88 // todo may need to allow user to specify reference assembly?
89 boolean isRefGrch37 = (ref != null && ref.getValue().contains(
96 * query for VCF overlapping each sequence in turn
98 for (SequenceI seq : al.getSequences())
100 int added = loadVCF(seq, reader, isRefGrch37);
105 computePeptideVariants(seq);
108 // long elapsed = System.currentTimeMillis() - start;
109 String msg = String.format("Added %d VCF variants to %d sequence(s)",
113 status.setStatus(msg);
115 } catch (Throwable e)
117 System.err.println("Error processing VCF: " + e.getMessage());
126 } catch (IOException e)
135 * (Re-)computes peptide variants from dna variants, for any protein sequence
136 * to which the dna sequence has a mapping. Note that although duplicate
137 * features may get computed, they will not be added, since duplicate sequence
138 * features are ignored in Sequence.addSequenceFeature.
142 protected void computePeptideVariants(SequenceI dnaSeq)
144 DBRefEntry[] dbrefs = dnaSeq.getDBRefs();
149 for (DBRefEntry dbref : dbrefs)
151 Mapping mapping = dbref.getMap();
152 if (mapping == null || mapping.getTo() == null
153 || mapping.getMap().getFromRatio() != 3)
157 AlignmentUtils.computeProteinFeatures(dnaSeq, mapping.getTo(),
163 * Tries to add overlapping variants read from a VCF file to the given
164 * sequence, and returns the number of overlapping variants found. Note that
165 * this requires the sequence to hold information as to its chromosomal
166 * positions and reference, in order to be able to map the VCF variants to the
171 * @param isVcfRefGrch37
174 protected int loadVCF(SequenceI seq, VCFReader reader,
175 boolean isVcfRefGrch37)
178 GeneLoci seqCoords = ((Sequence) seq).getGeneLoci();
179 if (seqCoords == null)
184 List<int[]> seqChromosomalContigs = seqCoords.mapping.getToRanges();
185 for (int[] range : seqChromosomalContigs)
187 count += addVcfVariants(seq, reader, range, isVcfRefGrch37);
194 * Queries the VCF reader for any variants that overlap the given chromosome
195 * region of the sequence, and adds as variant features. Returns the number of
196 * overlapping variants found.
201 * start-end range of a sequence region in its chromosomal
203 * @param isVcfRefGrch37
204 * true if the VCF is with reference to GRCh37
207 protected int addVcfVariants(SequenceI seq, VCFReader reader,
208 int[] range, boolean isVcfRefGrch37)
210 GeneLoci seqCoords = ((Sequence) seq).getGeneLoci();
212 String chromosome = seqCoords.chromosome;
213 String seqRef = seqCoords.assembly;
214 String species = seqCoords.species;
216 // TODO handle species properly
217 if ("".equals(species))
223 * map chromosomal coordinates from GRCh38 (sequence) to
224 * GRCh37 (VCF) if necessary
226 // TODO generalise for other assemblies and species
228 String fromRef = "GRCh38";
229 if (fromRef.equalsIgnoreCase(seqRef) && isVcfRefGrch37)
231 String toRef = "GRCh37";
232 int[] newRange = mapReferenceRange(range, chromosome, species,
234 if (newRange == null)
236 System.err.println(String.format(
237 "Failed to map %s:%s:%s:%d:%d to %s", species, chromosome,
238 fromRef, range[0], range[1], toRef));
241 offset = newRange[0] - range[0];
246 * query the VCF for overlaps
247 * (convert a reverse strand range to forwards)
250 MapList mapping = seqCoords.mapping;
252 int fromLocus = Math.min(range[0], range[1]);
253 int toLocus = Math.max(range[0], range[1]);
254 CloseableIterator<VariantContext> variants = reader.query(chromosome,
256 while (variants.hasNext())
259 * get variant location in sequence chromosomal coordinates
261 VariantContext variant = variants.next();
264 * we can only process SNP variants (which can be reported
265 * as part of a MIXED variant record
267 if (!variant.isSNP() && !variant.isMixed())
273 int start = variant.getStart() - offset;
274 int end = variant.getEnd() - offset;
277 * convert chromosomal location to sequence coordinates
278 * - null if a partially overlapping feature
280 int[] seqLocation = mapping.locateInFrom(start, end);
281 if (seqLocation != null)
283 addVariantFeatures(seq, variant, seqLocation[0], seqLocation[1]);
293 * Inspects the VCF variant record, and adds variant features to the sequence.
294 * Only SNP variants are added, not INDELs.
298 * @param featureStart
301 protected void addVariantFeatures(SequenceI seq, VariantContext variant,
302 int featureStart, int featureEnd)
304 String reference = variant.getReference().getBaseString();
305 if (reference.length() != 1)
308 * sorry, we don't handle INDEL variants
314 * for now we extract allele frequency as feature score; note
315 * this attribute is String for a simple SNP, but List<String> if
316 * multiple alleles at the locus; we extract for the simple case only,
317 * since not sure how to match allele order with AF values
319 Object af = variant.getAttribute("AF");
321 if (af instanceof String)
325 score = Float.parseFloat((String) af);
326 } catch (NumberFormatException e)
332 StringBuilder sb = new StringBuilder();
333 sb.append(reference);
336 * inspect alleles and record SNP variants (as the variant
337 * record could be MIXED and include INDEL and SNP alleles)
342 * inspect alleles; warning: getAlleles gives no guarantee
343 * as to the order in which they are returned
345 for (Allele allele : variant.getAlleles())
347 if (!allele.isReference())
349 String alleleBase = allele.getBaseString();
350 if (alleleBase.length() == 1)
352 sb.append(",").append(alleleBase);
357 String alleles = sb.toString(); // e.g. G,A,C
359 String type = SequenceOntologyI.SEQUENCE_VARIANT;
361 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
362 featureEnd, score, "VCF");
364 sf.setValue("alleles", alleles);
366 Map<String, Object> atts = variant.getAttributes();
367 for (Entry<String, Object> att : atts.entrySet())
369 sf.setValue(att.getKey(), att.getValue());
371 seq.addSequenceFeature(sf);
375 * Determines the location of the query range (chromosome positions) in a
376 * different reference assembly.
378 * If the range is just a subregion of one for which we already have a mapping
379 * (for example, an exon sub-region of a gene), then the mapping is just
380 * computed arithmetically.
382 * Otherwise, calls the Ensembl REST service that maps from one assembly
383 * reference's coordinates to another's
386 * start-end chromosomal range in 'fromRef' coordinates
390 * assembly reference for the query coordinates
392 * assembly reference we wish to translate to
393 * @return the start-end range in 'toRef' coordinates
395 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
396 String species, String fromRef, String toRef)
399 * first try shorcut of computing the mapping as a subregion of one
400 * we already have (e.g. for an exon, if we have the gene mapping)
402 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
403 species, fromRef, toRef);
404 if (mappedRange != null)
410 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
412 EnsemblMap mapper = new EnsemblMap();
413 int[] mapping = mapper.getMapping(species, chromosome, fromRef, toRef,
418 // mapping service failure
423 * save mapping for possible future re-use
425 String key = makeRangesKey(chromosome, species, fromRef, toRef);
426 if (!assemblyMappings.containsKey(key))
428 assemblyMappings.put(key, new HashMap<int[], int[]>());
431 assemblyMappings.get(key).put(queryRange, mapping);
437 * If we already have a 1:1 contiguous mapping which subsumes the given query
438 * range, this method just calculates and returns the subset of that mapping,
439 * else it returns null. In practical terms, if a gene has a contiguous
440 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
441 * subsidiary exons occupy unchanged relative positions, and just compute
442 * these as offsets, rather than do another lookup of the mapping.
444 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
445 * simply remove this method or let it always return null.
447 * Warning: many rapid calls to the /map service map result in a 429 overload
457 protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
458 String species, String fromRef, String toRef)
460 String key = makeRangesKey(chromosome, species, fromRef, toRef);
461 if (assemblyMappings.containsKey(key))
463 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
464 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
466 int[] fromRange = mappedRange.getKey();
467 int[] toRange = mappedRange.getValue();
468 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
471 * mapping is 1:1 in length, so we trust it to have no discontinuities
473 if (MappingUtils.rangeContains(fromRange, queryRange))
476 * fromRange subsumes our query range
478 int offset = queryRange[0] - fromRange[0];
479 int mappedRangeFrom = toRange[0] + offset;
480 int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
481 return new int[] { mappedRangeFrom, mappedRangeTo };
490 * Formats a ranges map lookup key
498 protected static String makeRangesKey(String chromosome, String species,
499 String fromRef, String toRef)
501 return species + EXCL + chromosome + EXCL + fromRef + EXCL