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 jalview.analysis.Dna;
24 import jalview.api.AlignViewControllerGuiI;
25 import jalview.bin.Cache;
26 import jalview.datamodel.DBRefEntry;
27 import jalview.datamodel.GeneLociI;
28 import jalview.datamodel.Mapping;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceI;
31 import jalview.datamodel.features.FeatureAttributeType;
32 import jalview.datamodel.features.FeatureSource;
33 import jalview.datamodel.features.FeatureSources;
34 import jalview.ext.ensembl.EnsemblMap;
35 import jalview.ext.htsjdk.HtsContigDb;
36 import jalview.ext.htsjdk.VCFReader;
37 import jalview.io.gff.Gff3Helper;
38 import jalview.io.gff.SequenceOntologyI;
39 import jalview.util.MapList;
40 import jalview.util.MappingUtils;
41 import jalview.util.MessageManager;
42 import jalview.util.StringUtils;
45 import java.io.IOException;
46 import java.util.ArrayList;
47 import java.util.HashMap;
48 import java.util.HashSet;
49 import java.util.Iterator;
50 import java.util.List;
51 import java.util.Locale;
53 import java.util.Map.Entry;
55 import java.util.regex.Pattern;
56 import java.util.regex.PatternSyntaxException;
58 import htsjdk.samtools.SAMException;
59 import htsjdk.samtools.SAMSequenceDictionary;
60 import htsjdk.samtools.SAMSequenceRecord;
61 import htsjdk.samtools.util.CloseableIterator;
62 import htsjdk.tribble.TribbleException;
63 import htsjdk.variant.variantcontext.Allele;
64 import htsjdk.variant.variantcontext.VariantContext;
65 import htsjdk.variant.vcf.VCFConstants;
66 import htsjdk.variant.vcf.VCFHeader;
67 import htsjdk.variant.vcf.VCFHeaderLine;
68 import htsjdk.variant.vcf.VCFHeaderLineCount;
69 import htsjdk.variant.vcf.VCFHeaderLineType;
70 import htsjdk.variant.vcf.VCFInfoHeaderLine;
73 * A class to read VCF data (using the htsjdk) and add variants as sequence
74 * features on dna and any related protein product sequences
78 public class VCFLoader
80 private static final String VCF_ENCODABLE = ":;=%,";
83 * Jalview feature attributes for VCF fixed column data
85 private static final String VCF_POS = "POS";
87 private static final String VCF_ID = "ID";
89 private static final String VCF_QUAL = "QUAL";
91 private static final String VCF_FILTER = "FILTER";
93 private static final String NO_VALUE = VCFConstants.MISSING_VALUE_v4; // '.'
95 private static final String DEFAULT_SPECIES = "homo_sapiens";
98 * A class to model the mapping from sequence to VCF coordinates. Cases include
100 * <li>a direct 1:1 mapping where the sequence is one of the VCF contigs</li>
101 * <li>a mapping of sequence to chromosomal coordinates, where sequence and VCF
102 * use the same reference assembly</li>
103 * <li>a modified mapping of sequence to chromosomal coordinates, where sequence
104 * and VCF use different reference assembles</li>
109 final String chromosome;
113 VCFMap(String chr, MapList m)
120 public String toString()
122 return chromosome + ":" + map.toString();
127 * Lookup keys, and default values, for Preference entries that describe
128 * patterns for VCF and VEP fields to capture
130 private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
132 private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
134 private static final String DEFAULT_VCF_FIELDS = ".*";
136 private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
139 * Lookup keys, and default values, for Preference entries that give
140 * mappings from tokens in the 'reference' header to species or assembly
142 private static final String VCF_ASSEMBLY = "VCF_ASSEMBLY";
144 private static final String DEFAULT_VCF_ASSEMBLY = "assembly19=GRCh37,hs37=GRCh37,grch37=GRCh37,grch38=GRCh38";
146 private static final String VCF_SPECIES = "VCF_SPECIES"; // default is human
148 private static final String DEFAULT_REFERENCE = "grch37"; // fallback default is human GRCh37
151 * keys to fields of VEP CSQ consequence data
152 * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
154 private static final String CSQ_CONSEQUENCE_KEY = "Consequence";
155 private static final String CSQ_ALLELE_KEY = "Allele";
156 private static final String CSQ_ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref), 1...
157 private static final String CSQ_FEATURE_KEY = "Feature"; // Ensembl stable id
160 * default VCF INFO key for VEP consequence data
161 * NB this can be overridden running VEP with --vcf_info_field
162 * - we don't handle this case (require identifier to be CSQ)
164 private static final String CSQ_FIELD = "CSQ";
167 * separator for fields in consequence data is '|'
169 private static final String PIPE_REGEX = "\\|";
172 * delimiter that separates multiple consequence data blocks
174 private static final String COMMA = ",";
177 * the feature group assigned to a VCF variant in Jalview
179 private static final String FEATURE_GROUP_VCF = "VCF";
182 * internal delimiter used to build keys for assemblyMappings
185 private static final String EXCL = "!";
188 * the VCF file we are processing
190 protected String vcfFilePath;
193 * mappings between VCF and sequence reference assembly regions, as
194 * key = "species!chromosome!fromAssembly!toAssembly
195 * value = Map{fromRange, toRange}
197 private Map<String, Map<int[], int[]>> assemblyMappings;
199 private VCFReader reader;
202 * holds details of the VCF header lines (metadata)
204 private VCFHeader header;
207 * species (as a valid Ensembl term) the VCF is for
209 private String vcfSpecies;
212 * genome assembly version (as a valid Ensembl identifier) the VCF is for
214 private String vcfAssembly;
217 * a Dictionary of contigs (if present) referenced in the VCF file
219 private SAMSequenceDictionary dictionary;
222 * the position (0...) of field in each block of
223 * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
224 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
226 private int csqConsequenceFieldIndex = -1;
227 private int csqAlleleFieldIndex = -1;
228 private int csqAlleleNumberFieldIndex = -1;
229 private int csqFeatureFieldIndex = -1;
231 // todo the same fields for SnpEff ANN data if wanted
232 // see http://snpeff.sourceforge.net/SnpEff_manual.html#input
235 * a unique identifier under which to save metadata about feature
236 * attributes (selected INFO field data)
238 private String sourceId;
241 * The INFO IDs of data that is both present in the VCF file, and
242 * also matched by any filters for data of interest
244 List<String> vcfFieldsOfInterest;
247 * The field offsets and identifiers for VEP (CSQ) data that is both present
248 * in the VCF file, and also matched by any filters for data of interest
249 * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
251 Map<Integer, String> vepFieldsOfInterest;
254 * key:value for which rejected data has been seen
255 * (the error is logged only once for each combination)
257 private Set<String> badData;
260 * Constructor given a VCF file
264 public VCFLoader(String vcfFile)
269 } catch (IOException e)
271 System.err.println("Error opening VCF file: " + e.getMessage());
274 // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
275 assemblyMappings = new HashMap<>();
279 * Starts a new thread to query and load VCF variant data on to the given
282 * This method is not thread safe - concurrent threads should use separate
283 * instances of this class.
288 public void loadVCF(SequenceI[] seqs, final AlignViewControllerGuiI gui)
292 gui.setStatus(MessageManager.getString("label.searching_vcf"));
300 VCFLoader.this.doLoad(seqs, gui);
306 * Reads the specified contig sequence and adds its VCF variants to it
309 * the id of a single sequence (contig) to load
312 public SequenceI loadVCFContig(String contig)
314 VCFHeaderLine headerLine = header.getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
315 if (headerLine == null)
317 Cache.log.error("VCF reference header not found");
320 String ref = headerLine.getValue();
321 if (ref.startsWith("file://"))
323 ref = ref.substring(7);
325 setSpeciesAndAssembly(ref);
327 SequenceI seq = null;
328 File dbFile = new File(ref);
332 HtsContigDb db = new HtsContigDb("", dbFile);
333 seq = db.getSequenceProxy(contig);
334 loadSequenceVCF(seq);
339 Cache.log.error("VCF reference not found: " + ref);
346 * Loads VCF on to one or more sequences
350 * optional callback handler for messages
352 protected void doLoad(SequenceI[] seqs, AlignViewControllerGuiI gui)
356 VCFHeaderLine ref = header
357 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
358 String reference = ref == null ? null : ref.getValue();
360 setSpeciesAndAssembly(reference);
366 * query for VCF overlapping each sequence in turn
368 for (SequenceI seq : seqs)
370 int added = loadSequenceVCF(seq);
375 transferAddedFeatures(seq);
380 String msg = MessageManager.formatMessage("label.added_vcf",
383 if (gui.getFeatureSettingsUI() != null)
385 gui.getFeatureSettingsUI().discoverAllFeatureData();
388 } catch (Throwable e)
390 System.err.println("Error processing VCF: " + e.getMessage());
394 gui.setStatus("Error occurred - see console for details");
403 } catch (IOException e)
414 * Attempts to determine and save the species and genome assembly version to
415 * which the VCF data applies. This may be done by parsing the {@code reference}
416 * header line, configured in a property file, or (potentially) confirmed
417 * interactively by the user.
419 * The saved values should be identifiers valid for Ensembl's REST service
420 * {@code map} endpoint, so they can be used (if necessary) to retrieve the
421 * mapping between VCF coordinates and sequence coordinates.
424 * @see https://rest.ensembl.org/documentation/info/assembly_map
425 * @see https://rest.ensembl.org/info/assembly/human?content-type=text/xml
426 * @see https://rest.ensembl.org/info/species?content-type=text/xml
428 protected void setSpeciesAndAssembly(String reference)
430 if (reference == null)
432 Cache.log.error("No VCF ##reference found, defaulting to "
433 + DEFAULT_REFERENCE + ":" + DEFAULT_SPECIES);
434 reference = DEFAULT_REFERENCE; // default to GRCh37 if not specified
436 reference = reference.toLowerCase();
439 * for a non-human species, or other assembly identifier,
440 * specify as a Jalview property file entry e.g.
441 * VCF_ASSEMBLY = hs37=GRCh37,assembly19=GRCh37
442 * VCF_SPECIES = c_elegans=celegans
443 * to map a token in the reference header to a value
445 String prop = Cache.getDefault(VCF_ASSEMBLY, DEFAULT_VCF_ASSEMBLY);
446 for (String token : prop.split(","))
448 String[] tokens = token.split("=");
449 if (tokens.length == 2)
451 if (reference.contains(tokens[0].trim().toLowerCase()))
453 vcfAssembly = tokens[1].trim();
459 vcfSpecies = DEFAULT_SPECIES;
460 prop = Cache.getProperty(VCF_SPECIES);
463 for (String token : prop.split(","))
465 String[] tokens = token.split("=");
466 if (tokens.length == 2)
468 if (reference.contains(tokens[0].trim().toLowerCase()))
470 vcfSpecies = tokens[1].trim();
479 * Opens the VCF file and parses header data
482 * @throws IOException
484 private void initialise(String filePath) throws IOException
486 vcfFilePath = filePath;
488 reader = new VCFReader(filePath);
490 header = reader.getFileHeader();
494 dictionary = header.getSequenceDictionary();
495 } catch (SAMException e)
497 // ignore - thrown if any contig line lacks length info
502 saveMetadata(sourceId);
505 * get offset of CSQ ALLELE_NUM and Feature if declared
511 * Reads metadata (such as INFO field descriptions and datatypes) and saves
512 * them for future reference
516 void saveMetadata(String theSourceId)
518 List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
520 vcfFieldsOfInterest = new ArrayList<>();
522 FeatureSource metadata = new FeatureSource(theSourceId);
524 for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
526 String attributeId = info.getID();
527 String desc = info.getDescription();
528 VCFHeaderLineType type = info.getType();
529 FeatureAttributeType attType = null;
533 attType = FeatureAttributeType.Character;
536 attType = FeatureAttributeType.Flag;
539 attType = FeatureAttributeType.Float;
542 attType = FeatureAttributeType.Integer;
545 attType = FeatureAttributeType.String;
548 metadata.setAttributeName(attributeId, desc);
549 metadata.setAttributeType(attributeId, attType);
551 if (isFieldWanted(attributeId, vcfFieldPatterns))
553 vcfFieldsOfInterest.add(attributeId);
557 FeatureSources.getInstance().addSource(theSourceId, metadata);
561 * Answers true if the field id is matched by any of the filter patterns, else
562 * false. Matching is against regular expression patterns, and is not
569 private boolean isFieldWanted(String id, List<Pattern> filters)
571 for (Pattern p : filters)
573 if (p.matcher(id.toUpperCase(Locale.ROOT)).matches())
582 * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
583 * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
584 * required for processing.
586 * CSQ fields are declared in the CSQ INFO Description e.g.
588 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
590 protected void parseCsqHeader()
592 List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
594 vepFieldsOfInterest = new HashMap<>();
596 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
603 * parse out the pipe-separated list of CSQ fields; we assume here that
604 * these form the last part of the description, and contain no spaces
606 String desc = csqInfo.getDescription();
607 int spacePos = desc.lastIndexOf(" ");
608 desc = desc.substring(spacePos + 1);
612 String[] format = desc.split(PIPE_REGEX);
614 for (String field : format)
616 if (CSQ_CONSEQUENCE_KEY.equals(field))
618 csqConsequenceFieldIndex = index;
620 if (CSQ_ALLELE_NUM_KEY.equals(field))
622 csqAlleleNumberFieldIndex = index;
624 if (CSQ_ALLELE_KEY.equals(field))
626 csqAlleleFieldIndex = index;
628 if (CSQ_FEATURE_KEY.equals(field))
630 csqFeatureFieldIndex = index;
633 if (isFieldWanted(field, vepFieldFilters))
635 vepFieldsOfInterest.put(index, field);
644 * Reads the Preference value for the given key, with default specified if no
645 * preference set. The value is interpreted as a comma-separated list of
646 * regular expressions, and converted into a list of compiled patterns ready
647 * for matching. Patterns are forced to upper-case for non-case-sensitive
650 * This supports user-defined filters for fields of interest to capture while
651 * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
652 * fields with an ID of AF, or starting with AC, would be matched.
658 private List<Pattern> getFieldMatchers(String key, String def)
660 String pref = Cache.getDefault(key, def);
661 List<Pattern> patterns = new ArrayList<>();
662 String[] tokens = pref.split(",");
663 for (String token : tokens)
667 patterns.add(Pattern.compile(token.toUpperCase(Locale.ROOT)));
668 } catch (PatternSyntaxException e)
670 System.err.println("Invalid pattern ignored: " + token);
677 * Transfers VCF features to sequences to which this sequence has a mapping.
678 * If the mapping is 3:1, computes peptide variants from nucleotide variants.
682 protected void transferAddedFeatures(SequenceI seq)
684 DBRefEntry[] dbrefs = seq.getDBRefs();
689 for (DBRefEntry dbref : dbrefs)
691 Mapping mapping = dbref.getMap();
692 if (mapping == null || mapping.getTo() == null)
697 SequenceI mapTo = mapping.getTo();
698 MapList map = mapping.getMap();
699 if (map.getFromRatio() == 3)
702 * dna-to-peptide product mapping
704 // JAL-3187 render on the fly instead
705 // AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
710 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
712 List<SequenceFeature> features = seq.getFeatures()
713 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
714 for (SequenceFeature sf : features)
716 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
718 transferFeature(sf, mapTo, map);
726 * Tries to add overlapping variants read from a VCF file to the given sequence,
727 * and returns the number of variant features added
732 protected int loadSequenceVCF(SequenceI seq)
734 VCFMap vcfMap = getVcfMap(seq);
741 * work with the dataset sequence here
743 SequenceI dss = seq.getDatasetSequence();
748 return addVcfVariants(dss, vcfMap);
752 * Answers a map from sequence coordinates to VCF chromosome ranges
757 private VCFMap getVcfMap(SequenceI seq)
760 * simplest case: sequence has id and length matching a VCF contig
762 VCFMap vcfMap = null;
763 if (dictionary != null)
765 vcfMap = getContigMap(seq);
773 * otherwise, map to VCF from chromosomal coordinates
774 * of the sequence (if known)
776 GeneLociI seqCoords = seq.getGeneLoci();
777 if (seqCoords == null)
779 Cache.log.warn(String.format(
780 "Can't query VCF for %s as chromosome coordinates not known",
785 String species = seqCoords.getSpeciesId();
786 String chromosome = seqCoords.getChromosomeId();
787 String seqRef = seqCoords.getAssemblyId();
788 MapList map = seqCoords.getMapping();
790 // note this requires the configured species to match that
791 // returned with the Ensembl sequence; todo: support aliases?
792 if (!vcfSpecies.equalsIgnoreCase(species))
794 Cache.log.warn("No VCF loaded to " + seq.getName()
795 + " as species not matched");
799 if (seqRef.equalsIgnoreCase(vcfAssembly))
801 return new VCFMap(chromosome, map);
805 * VCF data has a different reference assembly to the sequence:
806 * query Ensembl to map chromosomal coordinates from sequence to VCF
808 List<int[]> toVcfRanges = new ArrayList<>();
809 List<int[]> fromSequenceRanges = new ArrayList<>();
811 for (int[] range : map.getToRanges())
813 int[] fromRange = map.locateInFrom(range[0], range[1]);
814 if (fromRange == null)
820 int[] newRange = mapReferenceRange(range, chromosome, "human", seqRef,
822 if (newRange == null)
825 String.format("Failed to map %s:%s:%s:%d:%d to %s", species,
826 chromosome, seqRef, range[0], range[1],
832 toVcfRanges.add(newRange);
833 fromSequenceRanges.add(fromRange);
837 return new VCFMap(chromosome,
838 new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
842 * If the sequence id matches a contig declared in the VCF file, and the
843 * sequence length matches the contig length, then returns a 1:1 map of the
844 * sequence to the contig, else returns null
849 private VCFMap getContigMap(SequenceI seq)
851 String id = seq.getName();
852 SAMSequenceRecord contig = dictionary.getSequence(id);
855 int len = seq.getLength();
856 if (len == contig.getSequenceLength())
858 MapList map = new MapList(new int[] { 1, len },
861 return new VCFMap(id, map);
868 * Queries the VCF reader for any variants that overlap the mapped chromosome
869 * ranges of the sequence, and adds as variant features. Returns the number of
870 * overlapping variants found.
874 * mapping from sequence to VCF coordinates
877 protected int addVcfVariants(SequenceI seq, VCFMap map)
879 boolean forwardStrand = map.map.isToForwardStrand();
882 * query the VCF for overlaps of each contiguous chromosomal region
886 for (int[] range : map.map.getToRanges())
888 int vcfStart = Math.min(range[0], range[1]);
889 int vcfEnd = Math.max(range[0], range[1]);
892 CloseableIterator<VariantContext> variants = reader
893 .query(map.chromosome, vcfStart, vcfEnd);
894 while (variants.hasNext())
896 VariantContext variant = variants.next();
898 int[] featureRange = map.map.locateInFrom(variant.getStart(),
901 if (featureRange != null)
903 int featureStart = Math.min(featureRange[0], featureRange[1]);
904 int featureEnd = Math.max(featureRange[0], featureRange[1]);
905 count += addAlleleFeatures(seq, variant, featureStart,
906 featureEnd, forwardStrand);
910 } catch (TribbleException e)
913 * RuntimeException throwable by htsjdk
915 String msg = String.format("Error reading VCF for %s:%d-%d: %s ",
916 map.chromosome, vcfStart, vcfEnd,e.getLocalizedMessage());
917 Cache.log.error(msg);
925 * A convenience method to get an attribute value for an alternate allele
928 * @param attributeName
932 protected String getAttributeValue(VariantContext variant,
933 String attributeName, int alleleIndex)
935 Object att = variant.getAttribute(attributeName);
937 if (att instanceof String)
941 else if (att instanceof ArrayList)
943 return ((List<String>) att).get(alleleIndex);
950 * Adds one variant feature for each allele in the VCF variant record, and
951 * returns the number of features added.
955 * @param featureStart
957 * @param forwardStrand
960 protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
961 int featureStart, int featureEnd, boolean forwardStrand)
966 * Javadoc says getAlternateAlleles() imposes no order on the list returned
967 * so we proceed defensively to get them in strict order
969 int altAlleleCount = variant.getAlternateAlleles().size();
970 for (int i = 0; i < altAlleleCount; i++)
972 added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
979 * Inspects one allele and attempts to add a variant feature for it to the
980 * sequence. The additional data associated with this allele is extracted to
981 * store in the feature's key-value map. Answers the number of features added (0
986 * @param altAlleleIndex
988 * @param featureStart
990 * @param forwardStrand
993 protected int addAlleleFeature(SequenceI seq, VariantContext variant,
994 int altAlleleIndex, int featureStart, int featureEnd,
995 boolean forwardStrand)
997 String reference = variant.getReference().getBaseString();
998 Allele alt = variant.getAlternateAllele(altAlleleIndex);
999 String allele = alt.getBaseString();
1002 * insertion after a genomic base, if on reverse strand, has to be
1003 * converted to insertion of complement after the preceding position
1005 int referenceLength = reference.length();
1006 if (!forwardStrand && allele.length() > referenceLength
1007 && allele.startsWith(reference))
1009 featureStart -= referenceLength;
1010 featureEnd = featureStart;
1011 char insertAfter = seq.getCharAt(featureStart - seq.getStart());
1012 reference = Dna.reverseComplement(String.valueOf(insertAfter));
1013 allele = allele.substring(referenceLength) + reference;
1017 * build the ref,alt allele description e.g. "G,A", using the base
1018 * complement if the sequence is on the reverse strand
1020 StringBuilder sb = new StringBuilder();
1021 sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
1023 sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
1024 String alleles = sb.toString(); // e.g. G,A
1027 * pick out the consequence data (if any) that is for the current allele
1028 * and feature (transcript) that matches the current sequence
1030 String consequence = getConsequenceForAlleleAndFeature(variant, CSQ_FIELD,
1031 altAlleleIndex, csqAlleleFieldIndex,
1032 csqAlleleNumberFieldIndex, seq.getName().toLowerCase(),
1033 csqFeatureFieldIndex);
1036 * pick out the ontology term for the consequence type
1038 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1039 if (consequence != null)
1041 type = getOntologyTerm(consequence);
1044 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
1045 featureEnd, FEATURE_GROUP_VCF);
1046 sf.setSource(sourceId);
1049 * save the derived alleles as a named attribute; this will be
1050 * needed when Jalview computes derived peptide variants
1052 addFeatureAttribute(sf, Gff3Helper.ALLELES, alleles);
1055 * add selected VCF fixed column data as feature attributes
1057 addFeatureAttribute(sf, VCF_POS, String.valueOf(variant.getStart()));
1058 addFeatureAttribute(sf, VCF_ID, variant.getID());
1059 addFeatureAttribute(sf, VCF_QUAL,
1060 String.valueOf(variant.getPhredScaledQual()));
1061 addFeatureAttribute(sf, VCF_FILTER, getFilter(variant));
1063 addAlleleProperties(variant, sf, altAlleleIndex, consequence);
1065 seq.addSequenceFeature(sf);
1071 * Answers the VCF FILTER value for the variant - or an approximation to it.
1072 * This field is either PASS, or a semi-colon separated list of filters not
1073 * passed. htsjdk saves filters as a HashSet, so the order when reassembled into
1074 * a list may be different.
1079 String getFilter(VariantContext variant)
1081 Set<String> filters = variant.getFilters();
1082 if (filters.isEmpty())
1086 Iterator<String> iterator = filters.iterator();
1087 String first = iterator.next();
1088 if (filters.size() == 1)
1093 StringBuilder sb = new StringBuilder(first);
1094 while (iterator.hasNext())
1096 sb.append(";").append(iterator.next());
1099 return sb.toString();
1103 * Adds one feature attribute unless the value is null, empty or '.'
1109 void addFeatureAttribute(SequenceFeature sf, String key, String value)
1111 if (value != null && !value.isEmpty() && !NO_VALUE.equals(value))
1113 sf.setValue(key, value);
1118 * Determines the Sequence Ontology term to use for the variant feature type in
1119 * Jalview. The default is 'sequence_variant', but a more specific term is used
1122 * <li>VEP (or SnpEff) Consequence annotation is included in the VCF</li>
1123 * <li>sequence id can be matched to VEP Feature (or SnpEff Feature_ID)</li>
1126 * @param consequence
1128 * @see http://www.sequenceontology.org/browser/current_svn/term/SO:0001060
1130 String getOntologyTerm(String consequence)
1132 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1135 * could we associate Consequence data with this allele and feature (transcript)?
1136 * if so, prefer the consequence term from that data
1138 if (csqAlleleFieldIndex == -1) // && snpEffAlleleFieldIndex == -1
1141 * no Consequence data so we can't refine the ontology term
1146 if (consequence != null)
1148 String[] csqFields = consequence.split(PIPE_REGEX);
1149 if (csqFields.length > csqConsequenceFieldIndex)
1151 type = csqFields[csqConsequenceFieldIndex];
1156 // todo the same for SnpEff consequence data matching if wanted
1160 * if of the form (e.g.) missense_variant&splice_region_variant,
1161 * just take the first ('most severe') consequence
1165 int pos = type.indexOf('&');
1168 type = type.substring(0, pos);
1175 * Returns matched consequence data if it can be found, else null.
1177 * <li>inspects the VCF data for key 'vcfInfoId'</li>
1178 * <li>splits this on comma (to distinct consequences)</li>
1179 * <li>returns the first consequence (if any) where</li>
1181 * <li>the allele matches the altAlleleIndex'th allele of variant</li>
1182 * <li>the feature matches the sequence name (e.g. transcript id)</li>
1185 * If matched, the consequence is returned (as pipe-delimited fields).
1189 * @param altAlleleIndex
1190 * @param alleleFieldIndex
1191 * @param alleleNumberFieldIndex
1193 * @param featureFieldIndex
1196 private String getConsequenceForAlleleAndFeature(VariantContext variant,
1197 String vcfInfoId, int altAlleleIndex, int alleleFieldIndex,
1198 int alleleNumberFieldIndex,
1199 String seqName, int featureFieldIndex)
1201 if (alleleFieldIndex == -1 || featureFieldIndex == -1)
1205 Object value = variant.getAttribute(vcfInfoId);
1207 if (value == null || !(value instanceof List<?>))
1213 * inspect each consequence in turn (comma-separated blocks
1214 * extracted by htsjdk)
1216 List<String> consequences = (List<String>) value;
1218 for (String consequence : consequences)
1220 String[] csqFields = consequence.split(PIPE_REGEX);
1221 if (csqFields.length > featureFieldIndex)
1223 String featureIdentifier = csqFields[featureFieldIndex];
1224 if (featureIdentifier.length() > 4
1225 && seqName.indexOf(featureIdentifier.toLowerCase()) > -1)
1228 * feature (transcript) matched - now check for allele match
1230 if (matchAllele(variant, altAlleleIndex, csqFields,
1231 alleleFieldIndex, alleleNumberFieldIndex))
1241 private boolean matchAllele(VariantContext variant, int altAlleleIndex,
1242 String[] csqFields, int alleleFieldIndex,
1243 int alleleNumberFieldIndex)
1246 * if ALLELE_NUM is present, it must match altAlleleIndex
1247 * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1249 if (alleleNumberFieldIndex > -1)
1251 if (csqFields.length <= alleleNumberFieldIndex)
1255 String alleleNum = csqFields[alleleNumberFieldIndex];
1256 return String.valueOf(altAlleleIndex + 1).equals(alleleNum);
1260 * else consequence allele must match variant allele
1262 if (alleleFieldIndex > -1 && csqFields.length > alleleFieldIndex)
1264 String csqAllele = csqFields[alleleFieldIndex];
1265 String vcfAllele = variant.getAlternateAllele(altAlleleIndex)
1267 return csqAllele.equals(vcfAllele);
1273 * Add any allele-specific VCF key-value data to the sequence feature
1277 * @param altAlelleIndex
1279 * @param consequence
1280 * if not null, the consequence specific to this sequence (transcript
1281 * feature) and allele
1283 protected void addAlleleProperties(VariantContext variant,
1284 SequenceFeature sf, final int altAlelleIndex, String consequence)
1286 Map<String, Object> atts = variant.getAttributes();
1288 for (Entry<String, Object> att : atts.entrySet())
1290 String key = att.getKey();
1293 * extract Consequence data (if present) that we are able to
1294 * associated with the allele for this variant feature
1296 if (CSQ_FIELD.equals(key))
1298 addConsequences(variant, sf, consequence);
1303 * filter out fields we don't want to capture
1305 if (!vcfFieldsOfInterest.contains(key))
1311 * we extract values for other data which are allele-specific;
1312 * these may be per alternate allele (INFO[key].Number = 'A')
1313 * or per allele including reference (INFO[key].Number = 'R')
1315 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
1316 if (infoHeader == null)
1319 * can't be sure what data belongs to this allele, so
1320 * play safe and don't take any
1325 VCFHeaderLineCount number = infoHeader.getCountType();
1326 int index = altAlelleIndex;
1327 if (number == VCFHeaderLineCount.R)
1330 * one value per allele including reference, so bump index
1331 * e.g. the 3rd value is for the 2nd alternate allele
1335 else if (number != VCFHeaderLineCount.A)
1338 * don't save other values as not allele-related
1344 * take the index'th value
1346 String value = getAttributeValue(variant, key, index);
1347 if (value != null && isValid(variant, key, value))
1350 * decode colon, semicolon, equals sign, percent sign, comma (only)
1351 * as required by the VCF specification (para 1.2)
1353 value = StringUtils.urlDecode(value, VCF_ENCODABLE);
1354 addFeatureAttribute(sf, key, value);
1360 * Answers true for '.', null, or an empty value, or if the INFO type is String.
1361 * If the INFO type is Integer or Float, answers false if the value is not in
1369 protected boolean isValid(VariantContext variant, String infoId,
1372 if (value == null || value.isEmpty() || NO_VALUE.equals(value))
1376 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(infoId);
1377 if (infoHeader == null)
1379 Cache.log.error("Field " + infoId + " has no INFO header");
1382 VCFHeaderLineType infoType = infoHeader.getType();
1385 if (infoType == VCFHeaderLineType.Integer)
1387 Integer.parseInt(value);
1389 else if (infoType == VCFHeaderLineType.Float)
1391 Float.parseFloat(value);
1393 } catch (NumberFormatException e)
1395 logInvalidValue(variant, infoId, value);
1402 * Logs an error message for malformed data; duplicate messages (same id and
1403 * value) are not logged
1409 private void logInvalidValue(VariantContext variant, String infoId,
1412 if (badData == null)
1414 badData = new HashSet<>();
1416 String token = infoId + ":" + value;
1417 if (!badData.contains(token))
1420 Cache.log.error(String.format("Invalid VCF data at %s:%d %s=%s",
1421 variant.getContig(), variant.getStart(), infoId, value));
1426 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
1429 * If <code>myConsequence</code> is not null, then this is the specific
1430 * consequence data (pipe-delimited fields) that is for the current allele and
1431 * transcript (sequence) being processed)
1435 * @param myConsequence
1437 protected void addConsequences(VariantContext variant, SequenceFeature sf,
1438 String myConsequence)
1440 Object value = variant.getAttribute(CSQ_FIELD);
1442 if (value == null || !(value instanceof List<?>))
1447 List<String> consequences = (List<String>) value;
1450 * inspect CSQ consequences; restrict to the consequence
1451 * associated with the current transcript (Feature)
1453 Map<String, String> csqValues = new HashMap<>();
1455 for (String consequence : consequences)
1457 if (myConsequence == null || myConsequence.equals(consequence))
1459 String[] csqFields = consequence.split(PIPE_REGEX);
1462 * inspect individual fields of this consequence, copying non-null
1463 * values which are 'fields of interest'
1466 for (String field : csqFields)
1468 if (field != null && field.length() > 0)
1470 String id = vepFieldsOfInterest.get(i);
1474 * VCF spec requires encoding of special characters e.g. '='
1475 * so decode them here before storing
1477 field = StringUtils.urlDecode(field, VCF_ENCODABLE);
1478 csqValues.put(id, field);
1486 if (!csqValues.isEmpty())
1488 sf.setValue(CSQ_FIELD, csqValues);
1493 * A convenience method to complement a dna base and return the string value
1499 protected String complement(byte[] reference)
1501 return String.valueOf(Dna.getComplement((char) reference[0]));
1505 * Determines the location of the query range (chromosome positions) in a
1506 * different reference assembly.
1508 * If the range is just a subregion of one for which we already have a mapping
1509 * (for example, an exon sub-region of a gene), then the mapping is just
1510 * computed arithmetically.
1512 * Otherwise, calls the Ensembl REST service that maps from one assembly
1513 * reference's coordinates to another's
1516 * start-end chromosomal range in 'fromRef' coordinates
1520 * assembly reference for the query coordinates
1522 * assembly reference we wish to translate to
1523 * @return the start-end range in 'toRef' coordinates
1525 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
1526 String species, String fromRef, String toRef)
1529 * first try shorcut of computing the mapping as a subregion of one
1530 * we already have (e.g. for an exon, if we have the gene mapping)
1532 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
1533 species, fromRef, toRef);
1534 if (mappedRange != null)
1540 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
1542 EnsemblMap mapper = new EnsemblMap();
1543 int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
1546 if (mapping == null)
1548 // mapping service failure
1553 * save mapping for possible future re-use
1555 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1556 if (!assemblyMappings.containsKey(key))
1558 assemblyMappings.put(key, new HashMap<int[], int[]>());
1561 assemblyMappings.get(key).put(queryRange, mapping);
1567 * If we already have a 1:1 contiguous mapping which subsumes the given query
1568 * range, this method just calculates and returns the subset of that mapping,
1569 * else it returns null. In practical terms, if a gene has a contiguous
1570 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
1571 * subsidiary exons occupy unchanged relative positions, and just compute
1572 * these as offsets, rather than do another lookup of the mapping.
1574 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
1575 * simply remove this method or let it always return null.
1577 * Warning: many rapid calls to the /map service map result in a 429 overload
1587 protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
1588 String species, String fromRef, String toRef)
1590 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1591 if (assemblyMappings.containsKey(key))
1593 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
1594 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
1596 int[] fromRange = mappedRange.getKey();
1597 int[] toRange = mappedRange.getValue();
1598 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
1601 * mapping is 1:1 in length, so we trust it to have no discontinuities
1603 if (MappingUtils.rangeContains(fromRange, queryRange))
1606 * fromRange subsumes our query range
1608 int offset = queryRange[0] - fromRange[0];
1609 int mappedRangeFrom = toRange[0] + offset;
1610 int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
1611 return new int[] { mappedRangeFrom, mappedRangeTo };
1620 * Transfers the sequence feature to the target sequence, locating its start
1621 * and end range based on the mapping. Features which do not overlap the
1622 * target sequence are ignored.
1625 * @param targetSequence
1627 * mapping from the feature's coordinates to the target sequence
1629 protected void transferFeature(SequenceFeature sf,
1630 SequenceI targetSequence, MapList mapping)
1632 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1634 if (mappedRange != null)
1636 String group = sf.getFeatureGroup();
1637 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1638 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1639 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1640 group, sf.getScore());
1641 targetSequence.addSequenceFeature(copy);
1646 * Formats a ranges map lookup key
1654 protected static String makeRangesKey(String chromosome, String species,
1655 String fromRef, String toRef)
1657 return species + EXCL + chromosome + EXCL + fromRef + EXCL