2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.io.vcf;
23 import java.util.Locale;
26 import java.io.IOException;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.Iterator;
31 import java.util.List;
33 import java.util.Map.Entry;
35 import java.util.regex.Pattern;
36 import java.util.regex.PatternSyntaxException;
38 import htsjdk.samtools.SAMException;
39 import htsjdk.samtools.SAMSequenceDictionary;
40 import htsjdk.samtools.SAMSequenceRecord;
41 import htsjdk.samtools.util.CloseableIterator;
42 import htsjdk.tribble.TribbleException;
43 import htsjdk.variant.variantcontext.Allele;
44 import htsjdk.variant.variantcontext.VariantContext;
45 import htsjdk.variant.vcf.VCFConstants;
46 import htsjdk.variant.vcf.VCFHeader;
47 import htsjdk.variant.vcf.VCFHeaderLine;
48 import htsjdk.variant.vcf.VCFHeaderLineCount;
49 import htsjdk.variant.vcf.VCFHeaderLineType;
50 import htsjdk.variant.vcf.VCFInfoHeaderLine;
51 import jalview.analysis.Dna;
52 import jalview.api.AlignViewControllerGuiI;
53 import jalview.bin.Cache;
54 import jalview.bin.Console;
55 import jalview.datamodel.DBRefEntry;
56 import jalview.datamodel.GeneLociI;
57 import jalview.datamodel.Mapping;
58 import jalview.datamodel.SequenceFeature;
59 import jalview.datamodel.SequenceI;
60 import jalview.datamodel.features.FeatureAttributeType;
61 import jalview.datamodel.features.FeatureSource;
62 import jalview.datamodel.features.FeatureSources;
63 import jalview.ext.ensembl.EnsemblMap;
64 import jalview.ext.htsjdk.HtsContigDb;
65 import jalview.ext.htsjdk.VCFReader;
66 import jalview.io.gff.Gff3Helper;
67 import jalview.io.gff.SequenceOntologyI;
68 import jalview.util.MapList;
69 import jalview.util.MappingUtils;
70 import jalview.util.MessageManager;
71 import jalview.util.StringUtils;
74 * A class to read VCF data (using the htsjdk) and add variants as sequence
75 * features on dna and any related protein product sequences
79 public class VCFLoader
81 private static final String VCF_ENCODABLE = ":;=%,";
84 * Jalview feature attributes for VCF fixed column data
86 private static final String VCF_POS = "POS";
88 private static final String VCF_ID = "ID";
90 private static final String VCF_QUAL = "QUAL";
92 private static final String VCF_FILTER = "FILTER";
94 private static final String NO_VALUE = VCFConstants.MISSING_VALUE_v4; // '.'
96 private static final String DEFAULT_SPECIES = "homo_sapiens";
99 * A class to model the mapping from sequence to VCF coordinates. Cases
102 * <li>a direct 1:1 mapping where the sequence is one of the VCF contigs</li>
103 * <li>a mapping of sequence to chromosomal coordinates, where sequence and
104 * VCF use the same reference assembly</li>
105 * <li>a modified mapping of sequence to chromosomal coordinates, where
106 * sequence and VCF use different reference assembles</li>
111 final String chromosome;
115 VCFMap(String chr, MapList m)
122 public String toString()
124 return chromosome + ":" + map.toString();
129 * Lookup keys, and default values, for Preference entries that describe
130 * patterns for VCF and VEP fields to capture
132 private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
134 private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
136 private static final String DEFAULT_VCF_FIELDS = ".*";
138 private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
141 * Lookup keys, and default values, for Preference entries that give
142 * mappings from tokens in the 'reference' header to species or assembly
144 private static final String VCF_ASSEMBLY = "VCF_ASSEMBLY";
146 private static final String DEFAULT_VCF_ASSEMBLY = "assembly19=GRCh37,hs37=GRCh37,grch37=GRCh37,grch38=GRCh38";
148 private static final String VCF_SPECIES = "VCF_SPECIES"; // default is human
150 private static final String DEFAULT_REFERENCE = "grch37"; // fallback default
154 * keys to fields of VEP CSQ consequence data
155 * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
157 private static final String CSQ_CONSEQUENCE_KEY = "Consequence";
159 private static final String CSQ_ALLELE_KEY = "Allele";
161 private static final String CSQ_ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref),
164 private static final String CSQ_FEATURE_KEY = "Feature"; // Ensembl stable id
167 * default VCF INFO key for VEP consequence data
168 * NB this can be overridden running VEP with --vcf_info_field
169 * - we don't handle this case (require identifier to be CSQ)
171 private static final String CSQ_FIELD = "CSQ";
174 * separator for fields in consequence data is '|'
176 private static final String PIPE_REGEX = "\\|";
179 * delimiter that separates multiple consequence data blocks
181 private static final String COMMA = ",";
184 * the feature group assigned to a VCF variant in Jalview
186 private static final String FEATURE_GROUP_VCF = "VCF";
189 * internal delimiter used to build keys for assemblyMappings
192 private static final String EXCL = "!";
195 * the VCF file we are processing
197 protected String vcfFilePath;
200 * mappings between VCF and sequence reference assembly regions, as
201 * key = "species!chromosome!fromAssembly!toAssembly
202 * value = Map{fromRange, toRange}
204 private Map<String, Map<int[], int[]>> assemblyMappings;
206 private VCFReader reader;
209 * holds details of the VCF header lines (metadata)
211 private VCFHeader header;
214 * species (as a valid Ensembl term) the VCF is for
216 private String vcfSpecies;
219 * genome assembly version (as a valid Ensembl identifier) the VCF is for
221 private String vcfAssembly;
224 * a Dictionary of contigs (if present) referenced in the VCF file
226 private SAMSequenceDictionary dictionary;
229 * the position (0...) of field in each block of
230 * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
231 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
233 private int csqConsequenceFieldIndex = -1;
235 private int csqAlleleFieldIndex = -1;
237 private int csqAlleleNumberFieldIndex = -1;
239 private int csqFeatureFieldIndex = -1;
241 // todo the same fields for SnpEff ANN data if wanted
242 // see http://snpeff.sourceforge.net/SnpEff_manual.html#input
245 * a unique identifier under which to save metadata about feature
246 * attributes (selected INFO field data)
248 private String sourceId;
251 * The INFO IDs of data that is both present in the VCF file, and
252 * also matched by any filters for data of interest
254 List<String> vcfFieldsOfInterest;
257 * The field offsets and identifiers for VEP (CSQ) data that is both present
258 * in the VCF file, and also matched by any filters for data of interest
259 * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
261 Map<Integer, String> vepFieldsOfInterest;
264 * key:value for which rejected data has been seen
265 * (the error is logged only once for each combination)
267 private Set<String> badData;
270 * Constructor given a VCF file
274 public VCFLoader(String vcfFile)
279 } catch (IOException e)
281 System.err.println("Error opening VCF file: " + e.getMessage());
284 // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
285 assemblyMappings = new HashMap<>();
289 * Starts a new thread to query and load VCF variant data on to the given
292 * This method is not thread safe - concurrent threads should use separate
293 * instances of this class.
298 public void loadVCF(SequenceI[] seqs, final AlignViewControllerGuiI gui)
302 gui.setStatus(MessageManager.getString("label.searching_vcf"));
310 VCFLoader.this.doLoad(seqs, gui);
316 * Reads the specified contig sequence and adds its VCF variants to it
319 * the id of a single sequence (contig) to load
322 public SequenceI loadVCFContig(String contig)
324 VCFHeaderLine headerLine = header
325 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
326 if (headerLine == null)
328 Console.error("VCF reference header not found");
331 String ref = headerLine.getValue();
332 if (ref.startsWith("file://"))
334 ref = ref.substring(7);
336 setSpeciesAndAssembly(ref);
338 SequenceI seq = null;
339 File dbFile = new File(ref);
343 HtsContigDb db = new HtsContigDb("", dbFile);
344 seq = db.getSequenceProxy(contig);
345 loadSequenceVCF(seq);
350 Console.error("VCF reference not found: " + ref);
357 * Loads VCF on to one or more sequences
361 * optional callback handler for messages
363 protected void doLoad(SequenceI[] seqs, AlignViewControllerGuiI gui)
367 VCFHeaderLine ref = header
368 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
369 String reference = ref == null ? null : ref.getValue();
371 setSpeciesAndAssembly(reference);
377 * query for VCF overlapping each sequence in turn
379 for (SequenceI seq : seqs)
381 int added = loadSequenceVCF(seq);
386 transferAddedFeatures(seq);
391 String msg = MessageManager.formatMessage("label.added_vcf",
394 if (gui.getFeatureSettingsUI() != null)
396 gui.getFeatureSettingsUI().discoverAllFeatureData();
399 } catch (Throwable e)
401 System.err.println("Error processing VCF: " + e.getMessage());
405 gui.setStatus("Error occurred - see console for details");
414 } catch (IOException e)
425 * Attempts to determine and save the species and genome assembly version to
426 * which the VCF data applies. This may be done by parsing the
427 * {@code reference} header line, configured in a property file, or
428 * (potentially) confirmed interactively by the user.
430 * The saved values should be identifiers valid for Ensembl's REST service
431 * {@code map} endpoint, so they can be used (if necessary) to retrieve the
432 * mapping between VCF coordinates and sequence coordinates.
435 * @see https://rest.ensembl.org/documentation/info/assembly_map
436 * @see https://rest.ensembl.org/info/assembly/human?content-type=text/xml
437 * @see https://rest.ensembl.org/info/species?content-type=text/xml
439 protected void setSpeciesAndAssembly(String reference)
441 if (reference == null)
443 Console.error("No VCF ##reference found, defaulting to "
444 + DEFAULT_REFERENCE + ":" + DEFAULT_SPECIES);
445 reference = DEFAULT_REFERENCE; // default to GRCh37 if not specified
447 reference = reference.toLowerCase(Locale.ROOT);
450 * for a non-human species, or other assembly identifier,
451 * specify as a Jalview property file entry e.g.
452 * VCF_ASSEMBLY = hs37=GRCh37,assembly19=GRCh37
453 * VCF_SPECIES = c_elegans=celegans
454 * to map a token in the reference header to a value
456 String prop = Cache.getDefault(VCF_ASSEMBLY, DEFAULT_VCF_ASSEMBLY);
457 for (String token : prop.split(","))
459 String[] tokens = token.split("=");
460 if (tokens.length == 2)
462 if (reference.contains(tokens[0].trim().toLowerCase(Locale.ROOT)))
464 vcfAssembly = tokens[1].trim();
470 vcfSpecies = DEFAULT_SPECIES;
471 prop = Cache.getProperty(VCF_SPECIES);
474 for (String token : prop.split(","))
476 String[] tokens = token.split("=");
477 if (tokens.length == 2)
479 if (reference.contains(tokens[0].trim().toLowerCase(Locale.ROOT)))
481 vcfSpecies = tokens[1].trim();
490 * Opens the VCF file and parses header data
493 * @throws IOException
495 private void initialise(String filePath) throws IOException
497 vcfFilePath = filePath;
499 reader = new VCFReader(filePath);
501 header = reader.getFileHeader();
505 dictionary = header.getSequenceDictionary();
506 } catch (SAMException e)
508 // ignore - thrown if any contig line lacks length info
513 saveMetadata(sourceId);
516 * get offset of CSQ ALLELE_NUM and Feature if declared
522 * Reads metadata (such as INFO field descriptions and datatypes) and saves
523 * them for future reference
527 void saveMetadata(String theSourceId)
529 List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
531 vcfFieldsOfInterest = new ArrayList<>();
533 FeatureSource metadata = new FeatureSource(theSourceId);
535 for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
537 String attributeId = info.getID();
538 String desc = info.getDescription();
539 VCFHeaderLineType type = info.getType();
540 FeatureAttributeType attType = null;
544 attType = FeatureAttributeType.Character;
547 attType = FeatureAttributeType.Flag;
550 attType = FeatureAttributeType.Float;
553 attType = FeatureAttributeType.Integer;
556 attType = FeatureAttributeType.String;
559 metadata.setAttributeName(attributeId, desc);
560 metadata.setAttributeType(attributeId, attType);
562 if (isFieldWanted(attributeId, vcfFieldPatterns))
564 vcfFieldsOfInterest.add(attributeId);
568 FeatureSources.getInstance().addSource(theSourceId, metadata);
572 * Answers true if the field id is matched by any of the filter patterns, else
573 * false. Matching is against regular expression patterns, and is not
580 private boolean isFieldWanted(String id, List<Pattern> filters)
582 for (Pattern p : filters)
584 if (p.matcher(id.toUpperCase(Locale.ROOT)).matches())
593 * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
594 * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
595 * required for processing.
597 * CSQ fields are declared in the CSQ INFO Description e.g.
599 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
601 protected void parseCsqHeader()
603 List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
605 vepFieldsOfInterest = new HashMap<>();
607 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
614 * parse out the pipe-separated list of CSQ fields; we assume here that
615 * these form the last part of the description, and contain no spaces
617 String desc = csqInfo.getDescription();
618 int spacePos = desc.lastIndexOf(" ");
619 desc = desc.substring(spacePos + 1);
623 String[] format = desc.split(PIPE_REGEX);
625 for (String field : format)
627 if (CSQ_CONSEQUENCE_KEY.equals(field))
629 csqConsequenceFieldIndex = index;
631 if (CSQ_ALLELE_NUM_KEY.equals(field))
633 csqAlleleNumberFieldIndex = index;
635 if (CSQ_ALLELE_KEY.equals(field))
637 csqAlleleFieldIndex = index;
639 if (CSQ_FEATURE_KEY.equals(field))
641 csqFeatureFieldIndex = index;
644 if (isFieldWanted(field, vepFieldFilters))
646 vepFieldsOfInterest.put(index, field);
655 * Reads the Preference value for the given key, with default specified if no
656 * preference set. The value is interpreted as a comma-separated list of
657 * regular expressions, and converted into a list of compiled patterns ready
658 * for matching. Patterns are forced to upper-case for non-case-sensitive
661 * This supports user-defined filters for fields of interest to capture while
662 * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
663 * fields with an ID of AF, or starting with AC, would be matched.
669 private List<Pattern> getFieldMatchers(String key, String def)
671 String pref = Cache.getDefault(key, def);
672 List<Pattern> patterns = new ArrayList<>();
673 String[] tokens = pref.split(",");
674 for (String token : tokens)
678 patterns.add(Pattern.compile(token.toUpperCase(Locale.ROOT)));
679 } catch (PatternSyntaxException e)
681 System.err.println("Invalid pattern ignored: " + token);
688 * Transfers VCF features to sequences to which this sequence has a mapping.
692 protected void transferAddedFeatures(SequenceI seq)
694 List<DBRefEntry> dbrefs = seq.getDBRefs();
699 for (DBRefEntry dbref : dbrefs)
701 Mapping mapping = dbref.getMap();
702 if (mapping == null || mapping.getTo() == null)
707 SequenceI mapTo = mapping.getTo();
708 MapList map = mapping.getMap();
709 if (map.getFromRatio() == 3)
712 * dna-to-peptide product mapping
714 // JAL-3187 render on the fly instead
715 // AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
720 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
722 List<SequenceFeature> features = seq.getFeatures()
723 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
724 for (SequenceFeature sf : features)
726 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
728 transferFeature(sf, mapTo, map);
736 * Tries to add overlapping variants read from a VCF file to the given
737 * sequence, and returns the number of variant features added
742 protected int loadSequenceVCF(SequenceI seq)
744 VCFMap vcfMap = getVcfMap(seq);
751 * work with the dataset sequence here
753 SequenceI dss = seq.getDatasetSequence();
758 return addVcfVariants(dss, vcfMap);
762 * Answers a map from sequence coordinates to VCF chromosome ranges
767 private VCFMap getVcfMap(SequenceI seq)
770 * simplest case: sequence has id and length matching a VCF contig
772 VCFMap vcfMap = null;
773 if (dictionary != null)
775 vcfMap = getContigMap(seq);
783 * otherwise, map to VCF from chromosomal coordinates
784 * of the sequence (if known)
786 GeneLociI seqCoords = seq.getGeneLoci();
787 if (seqCoords == null)
789 Console.warn(String.format(
790 "Can't query VCF for %s as chromosome coordinates not known",
795 String species = seqCoords.getSpeciesId();
796 String chromosome = seqCoords.getChromosomeId();
797 String seqRef = seqCoords.getAssemblyId();
798 MapList map = seqCoords.getMapping();
800 // note this requires the configured species to match that
801 // returned with the Ensembl sequence; todo: support aliases?
802 if (!vcfSpecies.equalsIgnoreCase(species))
804 Console.warn("No VCF loaded to " + seq.getName()
805 + " as species not matched");
809 if (seqRef.equalsIgnoreCase(vcfAssembly))
811 return new VCFMap(chromosome, map);
815 * VCF data has a different reference assembly to the sequence:
816 * query Ensembl to map chromosomal coordinates from sequence to VCF
818 List<int[]> toVcfRanges = new ArrayList<>();
819 List<int[]> fromSequenceRanges = new ArrayList<>();
821 for (int[] range : map.getToRanges())
823 int[] fromRange = map.locateInFrom(range[0], range[1]);
824 if (fromRange == null)
830 int[] newRange = mapReferenceRange(range, chromosome, "human", seqRef,
832 if (newRange == null)
834 Console.error(String.format("Failed to map %s:%s:%s:%d:%d to %s",
835 species, chromosome, seqRef, range[0], range[1],
841 toVcfRanges.add(newRange);
842 fromSequenceRanges.add(fromRange);
846 return new VCFMap(chromosome,
847 new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
851 * If the sequence id matches a contig declared in the VCF file, and the
852 * sequence length matches the contig length, then returns a 1:1 map of the
853 * sequence to the contig, else returns null
858 private VCFMap getContigMap(SequenceI seq)
860 String id = seq.getName();
861 SAMSequenceRecord contig = dictionary.getSequence(id);
864 int len = seq.getLength();
865 if (len == contig.getSequenceLength())
867 MapList map = new MapList(new int[] { 1, len },
870 return new VCFMap(id, map);
877 * Queries the VCF reader for any variants that overlap the mapped chromosome
878 * ranges of the sequence, and adds as variant features. Returns the number of
879 * overlapping variants found.
883 * mapping from sequence to VCF coordinates
886 protected int addVcfVariants(SequenceI seq, VCFMap map)
888 boolean forwardStrand = map.map.isToForwardStrand();
891 * query the VCF for overlaps of each contiguous chromosomal region
895 for (int[] range : map.map.getToRanges())
897 int vcfStart = Math.min(range[0], range[1]);
898 int vcfEnd = Math.max(range[0], range[1]);
901 CloseableIterator<VariantContext> variants = reader
902 .query(map.chromosome, vcfStart, vcfEnd);
903 while (variants.hasNext())
905 VariantContext variant = variants.next();
907 int[] featureRange = map.map.locateInFrom(variant.getStart(),
911 * only take features whose range is fully mappable to sequence positions
913 if (featureRange != null)
915 int featureStart = Math.min(featureRange[0], featureRange[1]);
916 int featureEnd = Math.max(featureRange[0], featureRange[1]);
917 if (featureEnd - featureStart == variant.getEnd()
918 - variant.getStart())
920 count += addAlleleFeatures(seq, variant, featureStart,
921 featureEnd, forwardStrand);
926 } catch (TribbleException e)
929 * RuntimeException throwable by htsjdk
931 String msg = String.format("Error reading VCF for %s:%d-%d: %s ",
932 map.chromosome, vcfStart, vcfEnd, e.getLocalizedMessage());
941 * A convenience method to get an attribute value for an alternate allele
944 * @param attributeName
948 protected String getAttributeValue(VariantContext variant,
949 String attributeName, int alleleIndex)
951 Object att = variant.getAttribute(attributeName);
953 if (att instanceof String)
957 else if (att instanceof ArrayList)
959 return ((List<String>) att).get(alleleIndex);
966 * Adds one variant feature for each allele in the VCF variant record, and
967 * returns the number of features added.
971 * @param featureStart
973 * @param forwardStrand
976 protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
977 int featureStart, int featureEnd, boolean forwardStrand)
982 * Javadoc says getAlternateAlleles() imposes no order on the list returned
983 * so we proceed defensively to get them in strict order
985 int altAlleleCount = variant.getAlternateAlleles().size();
986 for (int i = 0; i < altAlleleCount; i++)
988 added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
995 * Inspects one allele and attempts to add a variant feature for it to the
996 * sequence. The additional data associated with this allele is extracted to
997 * store in the feature's key-value map. Answers the number of features added
1002 * @param altAlleleIndex
1004 * @param featureStart
1006 * @param forwardStrand
1009 protected int addAlleleFeature(SequenceI seq, VariantContext variant,
1010 int altAlleleIndex, int featureStart, int featureEnd,
1011 boolean forwardStrand)
1013 String reference = variant.getReference().getBaseString();
1014 Allele alt = variant.getAlternateAllele(altAlleleIndex);
1015 String allele = alt.getBaseString();
1018 * insertion after a genomic base, if on reverse strand, has to be
1019 * converted to insertion of complement after the preceding position
1021 int referenceLength = reference.length();
1022 if (!forwardStrand && allele.length() > referenceLength
1023 && allele.startsWith(reference))
1025 featureStart -= referenceLength;
1026 featureEnd = featureStart;
1027 char insertAfter = seq.getCharAt(featureStart - seq.getStart());
1028 reference = Dna.reverseComplement(String.valueOf(insertAfter));
1029 allele = allele.substring(referenceLength) + reference;
1033 * build the ref,alt allele description e.g. "G,A", using the base
1034 * complement if the sequence is on the reverse strand
1036 StringBuilder sb = new StringBuilder();
1037 sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
1039 sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
1040 String alleles = sb.toString(); // e.g. G,A
1043 * pick out the consequence data (if any) that is for the current allele
1044 * and feature (transcript) that matches the current sequence
1046 String consequence = getConsequenceForAlleleAndFeature(variant,
1047 CSQ_FIELD, altAlleleIndex, csqAlleleFieldIndex,
1048 csqAlleleNumberFieldIndex,
1049 seq.getName().toLowerCase(Locale.ROOT), csqFeatureFieldIndex);
1052 * pick out the ontology term for the consequence type
1054 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1055 if (consequence != null)
1057 type = getOntologyTerm(consequence);
1060 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
1061 featureEnd, FEATURE_GROUP_VCF);
1062 sf.setSource(sourceId);
1065 * save the derived alleles as a named attribute; this will be
1066 * needed when Jalview computes derived peptide variants
1068 addFeatureAttribute(sf, Gff3Helper.ALLELES, alleles);
1071 * add selected VCF fixed column data as feature attributes
1073 addFeatureAttribute(sf, VCF_POS, String.valueOf(variant.getStart()));
1074 addFeatureAttribute(sf, VCF_ID, variant.getID());
1075 addFeatureAttribute(sf, VCF_QUAL,
1076 String.valueOf(variant.getPhredScaledQual()));
1077 addFeatureAttribute(sf, VCF_FILTER, getFilter(variant));
1079 addAlleleProperties(variant, sf, altAlleleIndex, consequence);
1081 seq.addSequenceFeature(sf);
1087 * Answers the VCF FILTER value for the variant - or an approximation to it.
1088 * This field is either PASS, or a semi-colon separated list of filters not
1089 * passed. htsjdk saves filters as a HashSet, so the order when reassembled
1090 * into a list may be different.
1095 String getFilter(VariantContext variant)
1097 Set<String> filters = variant.getFilters();
1098 if (filters.isEmpty())
1102 Iterator<String> iterator = filters.iterator();
1103 String first = iterator.next();
1104 if (filters.size() == 1)
1109 StringBuilder sb = new StringBuilder(first);
1110 while (iterator.hasNext())
1112 sb.append(";").append(iterator.next());
1115 return sb.toString();
1119 * Adds one feature attribute unless the value is null, empty or '.'
1125 void addFeatureAttribute(SequenceFeature sf, String key, String value)
1127 if (value != null && !value.isEmpty() && !NO_VALUE.equals(value))
1129 sf.setValue(key, value);
1134 * Determines the Sequence Ontology term to use for the variant feature type
1135 * in Jalview. The default is 'sequence_variant', but a more specific term is
1138 * <li>VEP (or SnpEff) Consequence annotation is included in the VCF</li>
1139 * <li>sequence id can be matched to VEP Feature (or SnpEff Feature_ID)</li>
1142 * @param consequence
1144 * @see http://www.sequenceontology.org/browser/current_svn/term/SO:0001060
1146 String getOntologyTerm(String consequence)
1148 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1151 * could we associate Consequence data with this allele and feature (transcript)?
1152 * if so, prefer the consequence term from that data
1154 if (csqAlleleFieldIndex == -1) // && snpEffAlleleFieldIndex == -1
1157 * no Consequence data so we can't refine the ontology term
1162 if (consequence != null)
1164 String[] csqFields = consequence.split(PIPE_REGEX);
1165 if (csqFields.length > csqConsequenceFieldIndex)
1167 type = csqFields[csqConsequenceFieldIndex];
1172 // todo the same for SnpEff consequence data matching if wanted
1176 * if of the form (e.g.) missense_variant&splice_region_variant,
1177 * just take the first ('most severe') consequence
1181 int pos = type.indexOf('&');
1184 type = type.substring(0, pos);
1191 * Returns matched consequence data if it can be found, else null.
1193 * <li>inspects the VCF data for key 'vcfInfoId'</li>
1194 * <li>splits this on comma (to distinct consequences)</li>
1195 * <li>returns the first consequence (if any) where</li>
1197 * <li>the allele matches the altAlleleIndex'th allele of variant</li>
1198 * <li>the feature matches the sequence name (e.g. transcript id)</li>
1201 * If matched, the consequence is returned (as pipe-delimited fields).
1205 * @param altAlleleIndex
1206 * @param alleleFieldIndex
1207 * @param alleleNumberFieldIndex
1209 * @param featureFieldIndex
1212 private String getConsequenceForAlleleAndFeature(VariantContext variant,
1213 String vcfInfoId, int altAlleleIndex, int alleleFieldIndex,
1214 int alleleNumberFieldIndex, String seqName, int featureFieldIndex)
1216 if (alleleFieldIndex == -1 || featureFieldIndex == -1)
1220 Object value = variant.getAttribute(vcfInfoId);
1222 if (value == null || !(value instanceof List<?>))
1228 * inspect each consequence in turn (comma-separated blocks
1229 * extracted by htsjdk)
1231 List<String> consequences = (List<String>) value;
1233 for (String consequence : consequences)
1235 String[] csqFields = consequence.split(PIPE_REGEX);
1236 if (csqFields.length > featureFieldIndex)
1238 String featureIdentifier = csqFields[featureFieldIndex];
1239 if (featureIdentifier.length() > 4 && seqName
1240 .indexOf(featureIdentifier.toLowerCase(Locale.ROOT)) > -1)
1243 * feature (transcript) matched - now check for allele match
1245 if (matchAllele(variant, altAlleleIndex, csqFields,
1246 alleleFieldIndex, alleleNumberFieldIndex))
1256 private boolean matchAllele(VariantContext variant, int altAlleleIndex,
1257 String[] csqFields, int alleleFieldIndex,
1258 int alleleNumberFieldIndex)
1261 * if ALLELE_NUM is present, it must match altAlleleIndex
1262 * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1264 if (alleleNumberFieldIndex > -1)
1266 if (csqFields.length <= alleleNumberFieldIndex)
1270 String alleleNum = csqFields[alleleNumberFieldIndex];
1271 return String.valueOf(altAlleleIndex + 1).equals(alleleNum);
1275 * else consequence allele must match variant allele
1277 if (alleleFieldIndex > -1 && csqFields.length > alleleFieldIndex)
1279 String csqAllele = csqFields[alleleFieldIndex];
1280 String vcfAllele = variant.getAlternateAllele(altAlleleIndex)
1282 return csqAllele.equals(vcfAllele);
1288 * Add any allele-specific VCF key-value data to the sequence feature
1292 * @param altAlelleIndex
1294 * @param consequence
1295 * if not null, the consequence specific to this sequence (transcript
1296 * feature) and allele
1298 protected void addAlleleProperties(VariantContext variant,
1299 SequenceFeature sf, final int altAlelleIndex, String consequence)
1301 Map<String, Object> atts = variant.getAttributes();
1303 for (Entry<String, Object> att : atts.entrySet())
1305 String key = att.getKey();
1308 * extract Consequence data (if present) that we are able to
1309 * associated with the allele for this variant feature
1311 if (CSQ_FIELD.equals(key))
1313 addConsequences(variant, sf, consequence);
1318 * filter out fields we don't want to capture
1320 if (!vcfFieldsOfInterest.contains(key))
1326 * we extract values for other data which are allele-specific;
1327 * these may be per alternate allele (INFO[key].Number = 'A')
1328 * or per allele including reference (INFO[key].Number = 'R')
1330 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
1331 if (infoHeader == null)
1334 * can't be sure what data belongs to this allele, so
1335 * play safe and don't take any
1340 VCFHeaderLineCount number = infoHeader.getCountType();
1341 int index = altAlelleIndex;
1342 if (number == VCFHeaderLineCount.R)
1345 * one value per allele including reference, so bump index
1346 * e.g. the 3rd value is for the 2nd alternate allele
1350 else if (number != VCFHeaderLineCount.A)
1353 * don't save other values as not allele-related
1359 * take the index'th value
1361 String value = getAttributeValue(variant, key, index);
1362 if (value != null && isValid(variant, key, value))
1365 * decode colon, semicolon, equals sign, percent sign, comma (only)
1366 * as required by the VCF specification (para 1.2)
1368 value = StringUtils.urlDecode(value, VCF_ENCODABLE);
1369 addFeatureAttribute(sf, key, value);
1375 * Answers true for '.', null, or an empty value, or if the INFO type is
1376 * String. If the INFO type is Integer or Float, answers false if the value is
1377 * not in valid format.
1384 protected boolean isValid(VariantContext variant, String infoId,
1387 if (value == null || value.isEmpty() || NO_VALUE.equals(value))
1391 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(infoId);
1392 if (infoHeader == null)
1394 Console.error("Field " + infoId + " has no INFO header");
1397 VCFHeaderLineType infoType = infoHeader.getType();
1400 if (infoType == VCFHeaderLineType.Integer)
1402 Integer.parseInt(value);
1404 else if (infoType == VCFHeaderLineType.Float)
1406 Float.parseFloat(value);
1408 } catch (NumberFormatException e)
1410 logInvalidValue(variant, infoId, value);
1417 * Logs an error message for malformed data; duplicate messages (same id and
1418 * value) are not logged
1424 private void logInvalidValue(VariantContext variant, String infoId,
1427 if (badData == null)
1429 badData = new HashSet<>();
1431 String token = infoId + ":" + value;
1432 if (!badData.contains(token))
1435 Console.error(String.format("Invalid VCF data at %s:%d %s=%s",
1436 variant.getContig(), variant.getStart(), infoId, value));
1441 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
1444 * If <code>myConsequence</code> is not null, then this is the specific
1445 * consequence data (pipe-delimited fields) that is for the current allele and
1446 * transcript (sequence) being processed)
1450 * @param myConsequence
1452 protected void addConsequences(VariantContext variant, SequenceFeature sf,
1453 String myConsequence)
1455 Object value = variant.getAttribute(CSQ_FIELD);
1457 if (value == null || !(value instanceof List<?>))
1462 List<String> consequences = (List<String>) value;
1465 * inspect CSQ consequences; restrict to the consequence
1466 * associated with the current transcript (Feature)
1468 Map<String, String> csqValues = new HashMap<>();
1470 for (String consequence : consequences)
1472 if (myConsequence == null || myConsequence.equals(consequence))
1474 String[] csqFields = consequence.split(PIPE_REGEX);
1477 * inspect individual fields of this consequence, copying non-null
1478 * values which are 'fields of interest'
1481 for (String field : csqFields)
1483 if (field != null && field.length() > 0)
1485 String id = vepFieldsOfInterest.get(i);
1489 * VCF spec requires encoding of special characters e.g. '='
1490 * so decode them here before storing
1492 field = StringUtils.urlDecode(field, VCF_ENCODABLE);
1493 csqValues.put(id, field);
1501 if (!csqValues.isEmpty())
1503 sf.setValue(CSQ_FIELD, csqValues);
1508 * A convenience method to complement a dna base and return the string value
1514 protected String complement(byte[] reference)
1516 return String.valueOf(Dna.getComplement((char) reference[0]));
1520 * Determines the location of the query range (chromosome positions) in a
1521 * different reference assembly.
1523 * If the range is just a subregion of one for which we already have a mapping
1524 * (for example, an exon sub-region of a gene), then the mapping is just
1525 * computed arithmetically.
1527 * Otherwise, calls the Ensembl REST service that maps from one assembly
1528 * reference's coordinates to another's
1531 * start-end chromosomal range in 'fromRef' coordinates
1535 * assembly reference for the query coordinates
1537 * assembly reference we wish to translate to
1538 * @return the start-end range in 'toRef' coordinates
1540 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
1541 String species, String fromRef, String toRef)
1544 * first try shorcut of computing the mapping as a subregion of one
1545 * we already have (e.g. for an exon, if we have the gene mapping)
1547 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
1548 species, fromRef, toRef);
1549 if (mappedRange != null)
1555 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
1557 EnsemblMap mapper = new EnsemblMap();
1558 int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
1561 if (mapping == null)
1563 // mapping service failure
1568 * save mapping for possible future re-use
1570 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1571 if (!assemblyMappings.containsKey(key))
1573 assemblyMappings.put(key, new HashMap<int[], int[]>());
1576 assemblyMappings.get(key).put(queryRange, mapping);
1582 * If we already have a 1:1 contiguous mapping which subsumes the given query
1583 * range, this method just calculates and returns the subset of that mapping,
1584 * else it returns null. In practical terms, if a gene has a contiguous
1585 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
1586 * subsidiary exons occupy unchanged relative positions, and just compute
1587 * these as offsets, rather than do another lookup of the mapping.
1589 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
1590 * simply remove this method or let it always return null.
1592 * Warning: many rapid calls to the /map service map result in a 429 overload
1602 protected int[] findSubsumedRangeMapping(int[] queryRange,
1603 String chromosome, String species, String fromRef, String toRef)
1605 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1606 if (assemblyMappings.containsKey(key))
1608 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
1609 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
1611 int[] fromRange = mappedRange.getKey();
1612 int[] toRange = mappedRange.getValue();
1613 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
1616 * mapping is 1:1 in length, so we trust it to have no discontinuities
1618 if (MappingUtils.rangeContains(fromRange, queryRange))
1621 * fromRange subsumes our query range
1623 int offset = queryRange[0] - fromRange[0];
1624 int mappedRangeFrom = toRange[0] + offset;
1625 int mappedRangeTo = mappedRangeFrom
1626 + (queryRange[1] - queryRange[0]);
1627 return new int[] { mappedRangeFrom, mappedRangeTo };
1636 * Transfers the sequence feature to the target sequence, locating its start
1637 * and end range based on the mapping. Features which do not overlap the
1638 * target sequence are ignored.
1641 * @param targetSequence
1643 * mapping from the feature's coordinates to the target sequence
1645 protected void transferFeature(SequenceFeature sf,
1646 SequenceI targetSequence, MapList mapping)
1648 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1650 if (mappedRange != null)
1652 String group = sf.getFeatureGroup();
1653 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1654 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1655 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1656 group, sf.getScore());
1657 targetSequence.addSequenceFeature(copy);
1662 * Formats a ranges map lookup key
1670 protected static String makeRangesKey(String chromosome, String species,
1671 String fromRef, String toRef)
1673 return species + EXCL + chromosome + EXCL + fromRef + EXCL + toRef;