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();
263 int start = variant.getStart() - offset;
264 int end = variant.getEnd() - offset;
267 * convert chromosomal location to sequence coordinates
268 * - null if a partially overlapping feature
270 int[] seqLocation = mapping.locateInFrom(start, end);
271 if (seqLocation != null)
273 addVariantFeatures(seq, variant, seqLocation[0], seqLocation[1]);
283 * Inspects the VCF variant record, and adds variant features to the sequence
287 * @param featureStart
290 protected void addVariantFeatures(SequenceI seq, VariantContext variant,
291 int featureStart, int featureEnd)
293 StringBuilder sb = new StringBuilder();
294 sb.append(variant.getReference().getBaseString());
297 for (Allele allele : variant.getAlleles())
299 if (!allele.isReference())
301 sb.append(",").append(allele.getBaseString());
305 String alleles = sb.toString(); // e.g. G,A,C
307 String type = SequenceOntologyI.SEQUENCE_VARIANT;
310 * extract allele frequency as feature score, but only if
311 * a simple SNP (not for >1 co-located SNPs as each has a score)
314 if (alleleCount == 1)
318 score = (float) variant.getAttributeAsDouble("AF", 0d);
319 } catch (NumberFormatException e)
324 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
325 featureEnd, score, "VCF");
328 * only add 'alleles' property if a SNP, as we can
329 * only handle SNPs when computing peptide variants
333 sf.setValue("alleles", alleles);
336 Map<String, Object> atts = variant.getAttributes();
337 for (Entry<String, Object> att : atts.entrySet())
339 sf.setValue(att.getKey(), att.getValue());
341 seq.addSequenceFeature(sf);
345 * Determines the location of the query range (chromosome positions) in a
346 * different reference assembly.
348 * If the range is just a subregion of one for which we already have a mapping
349 * (for example, an exon sub-region of a gene), then the mapping is just
350 * computed arithmetically.
352 * Otherwise, calls the Ensembl REST service that maps from one assembly
353 * reference's coordinates to another's
356 * start-end chromosomal range in 'fromRef' coordinates
360 * assembly reference for the query coordinates
362 * assembly reference we wish to translate to
363 * @return the start-end range in 'toRef' coordinates
365 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
366 String species, String fromRef, String toRef)
369 * first try shorcut of computing the mapping as a subregion of one
370 * we already have (e.g. for an exon, if we have the gene mapping)
372 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
373 species, fromRef, toRef);
374 if (mappedRange != null)
380 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
382 EnsemblMap mapper = new EnsemblMap();
383 int[] mapping = mapper.getMapping(species, chromosome, fromRef, toRef,
388 // mapping service failure
393 * save mapping for possible future re-use
395 String key = makeRangesKey(chromosome, species, fromRef, toRef);
396 if (!assemblyMappings.containsKey(key))
398 assemblyMappings.put(key, new HashMap<int[], int[]>());
401 assemblyMappings.get(key).put(queryRange, mapping);
407 * If we already have a 1:1 contiguous mapping which subsumes the given query
408 * range, this method just calculates and returns the subset of that mapping,
409 * else it returns null. In practical terms, if a gene has a contiguous
410 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
411 * subsidiary exons occupy unchanged relative positions, and just compute
412 * these as offsets, rather than do another lookup of the mapping.
414 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
415 * simply remove this method or let it always return null.
417 * Warning: many rapid calls to the /map service map result in a 429 overload
427 protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
428 String species, String fromRef, String toRef)
430 String key = makeRangesKey(chromosome, species, fromRef, toRef);
431 if (assemblyMappings.containsKey(key))
433 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
434 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
436 int[] fromRange = mappedRange.getKey();
437 int[] toRange = mappedRange.getValue();
438 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
441 * mapping is 1:1 in length, so we trust it to have no discontinuities
443 if (MappingUtils.rangeContains(fromRange, queryRange))
446 * fromRange subsumes our query range
448 int offset = queryRange[0] - fromRange[0];
449 int mappedRangeFrom = toRange[0] + offset;
450 int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
451 return new int[] { mappedRangeFrom, mappedRangeTo };
460 * Formats a ranges map lookup key
468 protected static String makeRangesKey(String chromosome, String species,
469 String fromRef, String toRef)
471 return species + EXCL + chromosome + EXCL + fromRef + EXCL