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;
52 import java.util.Map.Entry;
54 import java.util.regex.Pattern;
55 import java.util.regex.PatternSyntaxException;
57 import htsjdk.samtools.SAMException;
58 import htsjdk.samtools.SAMSequenceDictionary;
59 import htsjdk.samtools.SAMSequenceRecord;
60 import htsjdk.samtools.util.CloseableIterator;
61 import htsjdk.tribble.TribbleException;
62 import htsjdk.variant.variantcontext.Allele;
63 import htsjdk.variant.variantcontext.VariantContext;
64 import htsjdk.variant.vcf.VCFConstants;
65 import htsjdk.variant.vcf.VCFHeader;
66 import htsjdk.variant.vcf.VCFHeaderLine;
67 import htsjdk.variant.vcf.VCFHeaderLineCount;
68 import htsjdk.variant.vcf.VCFHeaderLineType;
69 import htsjdk.variant.vcf.VCFInfoHeaderLine;
72 * A class to read VCF data (using the htsjdk) and add variants as sequence
73 * features on dna and any related protein product sequences
77 public class VCFLoader
79 private static final String VCF_ENCODABLE = ":;=%,";
82 * Jalview feature attributes for VCF fixed column data
84 private static final String VCF_POS = "POS";
86 private static final String VCF_ID = "ID";
88 private static final String VCF_QUAL = "QUAL";
90 private static final String VCF_FILTER = "FILTER";
92 private static final String NO_VALUE = VCFConstants.MISSING_VALUE_v4; // '.'
94 private static final String DEFAULT_SPECIES = "homo_sapiens";
97 * A class to model the mapping from sequence to VCF coordinates. Cases include
99 * <li>a direct 1:1 mapping where the sequence is one of the VCF contigs</li>
100 * <li>a mapping of sequence to chromosomal coordinates, where sequence and VCF
101 * use the same reference assembly</li>
102 * <li>a modified mapping of sequence to chromosomal coordinates, where sequence
103 * and VCF use different reference assembles</li>
108 final String chromosome;
112 VCFMap(String chr, MapList m)
119 public String toString()
121 return chromosome + ":" + map.toString();
126 * Lookup keys, and default values, for Preference entries that describe
127 * patterns for VCF and VEP fields to capture
129 private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
131 private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
133 private static final String DEFAULT_VCF_FIELDS = ".*";
135 private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
138 * Lookup keys, and default values, for Preference entries that give
139 * mappings from tokens in the 'reference' header to species or assembly
141 private static final String VCF_ASSEMBLY = "VCF_ASSEMBLY";
143 private static final String DEFAULT_VCF_ASSEMBLY = "assembly19=GRCh37,hs37=GRCh37,grch37=GRCh37,grch38=GRCh38";
145 private static final String VCF_SPECIES = "VCF_SPECIES"; // default is human
147 private static final String DEFAULT_REFERENCE = "grch37"; // fallback default is human GRCh37
150 * keys to fields of VEP CSQ consequence data
151 * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
153 private static final String CSQ_CONSEQUENCE_KEY = "Consequence";
154 private static final String CSQ_ALLELE_KEY = "Allele";
155 private static final String CSQ_ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref), 1...
156 private static final String CSQ_FEATURE_KEY = "Feature"; // Ensembl stable id
159 * default VCF INFO key for VEP consequence data
160 * NB this can be overridden running VEP with --vcf_info_field
161 * - we don't handle this case (require identifier to be CSQ)
163 private static final String CSQ_FIELD = "CSQ";
166 * separator for fields in consequence data is '|'
168 private static final String PIPE_REGEX = "\\|";
171 * delimiter that separates multiple consequence data blocks
173 private static final String COMMA = ",";
176 * the feature group assigned to a VCF variant in Jalview
178 private static final String FEATURE_GROUP_VCF = "VCF";
181 * internal delimiter used to build keys for assemblyMappings
184 private static final String EXCL = "!";
187 * the VCF file we are processing
189 protected String vcfFilePath;
192 * mappings between VCF and sequence reference assembly regions, as
193 * key = "species!chromosome!fromAssembly!toAssembly
194 * value = Map{fromRange, toRange}
196 private Map<String, Map<int[], int[]>> assemblyMappings;
198 private VCFReader reader;
201 * holds details of the VCF header lines (metadata)
203 private VCFHeader header;
206 * species (as a valid Ensembl term) the VCF is for
208 private String vcfSpecies;
211 * genome assembly version (as a valid Ensembl identifier) the VCF is for
213 private String vcfAssembly;
216 * a Dictionary of contigs (if present) referenced in the VCF file
218 private SAMSequenceDictionary dictionary;
221 * the position (0...) of field in each block of
222 * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
223 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
225 private int csqConsequenceFieldIndex = -1;
226 private int csqAlleleFieldIndex = -1;
227 private int csqAlleleNumberFieldIndex = -1;
228 private int csqFeatureFieldIndex = -1;
230 // todo the same fields for SnpEff ANN data if wanted
231 // see http://snpeff.sourceforge.net/SnpEff_manual.html#input
234 * a unique identifier under which to save metadata about feature
235 * attributes (selected INFO field data)
237 private String sourceId;
240 * The INFO IDs of data that is both present in the VCF file, and
241 * also matched by any filters for data of interest
243 List<String> vcfFieldsOfInterest;
246 * The field offsets and identifiers for VEP (CSQ) data that is both present
247 * in the VCF file, and also matched by any filters for data of interest
248 * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
250 Map<Integer, String> vepFieldsOfInterest;
253 * key:value for which rejected data has been seen
254 * (the error is logged only once for each combination)
256 private Set<String> badData;
259 * Constructor given a VCF file
263 public VCFLoader(String vcfFile)
268 } catch (IOException e)
270 System.err.println("Error opening VCF file: " + e.getMessage());
273 // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
274 assemblyMappings = new HashMap<>();
278 * Starts a new thread to query and load VCF variant data on to the given
281 * This method is not thread safe - concurrent threads should use separate
282 * instances of this class.
287 public void loadVCF(SequenceI[] seqs, final AlignViewControllerGuiI gui)
291 gui.setStatus(MessageManager.getString("label.searching_vcf"));
299 VCFLoader.this.doLoad(seqs, gui);
305 * Reads the specified contig sequence and adds its VCF variants to it
308 * the id of a single sequence (contig) to load
311 public SequenceI loadVCFContig(String contig)
313 VCFHeaderLine headerLine = header.getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
314 if (headerLine == null)
316 Cache.log.error("VCF reference header not found");
319 String ref = headerLine.getValue();
320 if (ref.startsWith("file://"))
322 ref = ref.substring(7);
324 setSpeciesAndAssembly(ref);
326 SequenceI seq = null;
327 File dbFile = new File(ref);
331 HtsContigDb db = new HtsContigDb("", dbFile);
332 seq = db.getSequenceProxy(contig);
333 loadSequenceVCF(seq);
338 Cache.log.error("VCF reference not found: " + ref);
345 * Loads VCF on to one or more sequences
349 * optional callback handler for messages
351 protected void doLoad(SequenceI[] seqs, AlignViewControllerGuiI gui)
355 VCFHeaderLine ref = header
356 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
357 String reference = ref == null ? null : ref.getValue();
359 setSpeciesAndAssembly(reference);
365 * query for VCF overlapping each sequence in turn
367 for (SequenceI seq : seqs)
369 int added = loadSequenceVCF(seq);
374 transferAddedFeatures(seq);
379 String msg = MessageManager.formatMessage("label.added_vcf",
382 if (gui.getFeatureSettingsUI() != null)
384 gui.getFeatureSettingsUI().discoverAllFeatureData();
387 } catch (Throwable e)
389 System.err.println("Error processing VCF: " + e.getMessage());
393 gui.setStatus("Error occurred - see console for details");
402 } catch (IOException e)
413 * Attempts to determine and save the species and genome assembly version to
414 * which the VCF data applies. This may be done by parsing the {@code reference}
415 * header line, configured in a property file, or (potentially) confirmed
416 * interactively by the user.
418 * The saved values should be identifiers valid for Ensembl's REST service
419 * {@code map} endpoint, so they can be used (if necessary) to retrieve the
420 * mapping between VCF coordinates and sequence coordinates.
423 * @see https://rest.ensembl.org/documentation/info/assembly_map
424 * @see https://rest.ensembl.org/info/assembly/human?content-type=text/xml
425 * @see https://rest.ensembl.org/info/species?content-type=text/xml
427 protected void setSpeciesAndAssembly(String reference)
429 if (reference == null)
431 Cache.log.error("No VCF ##reference found, defaulting to "
432 + DEFAULT_REFERENCE + ":" + DEFAULT_SPECIES);
433 reference = DEFAULT_REFERENCE; // default to GRCh37 if not specified
435 reference = reference.toLowerCase();
438 * for a non-human species, or other assembly identifier,
439 * specify as a Jalview property file entry e.g.
440 * VCF_ASSEMBLY = hs37=GRCh37,assembly19=GRCh37
441 * VCF_SPECIES = c_elegans=celegans
442 * to map a token in the reference header to a value
444 String prop = Cache.getDefault(VCF_ASSEMBLY, DEFAULT_VCF_ASSEMBLY);
445 for (String token : prop.split(","))
447 String[] tokens = token.split("=");
448 if (tokens.length == 2)
450 if (reference.contains(tokens[0].trim().toLowerCase()))
452 vcfAssembly = tokens[1].trim();
458 vcfSpecies = DEFAULT_SPECIES;
459 prop = Cache.getProperty(VCF_SPECIES);
462 for (String token : prop.split(","))
464 String[] tokens = token.split("=");
465 if (tokens.length == 2)
467 if (reference.contains(tokens[0].trim().toLowerCase()))
469 vcfSpecies = tokens[1].trim();
478 * Opens the VCF file and parses header data
481 * @throws IOException
483 private void initialise(String filePath) throws IOException
485 vcfFilePath = filePath;
487 reader = new VCFReader(filePath);
489 header = reader.getFileHeader();
493 dictionary = header.getSequenceDictionary();
494 } catch (SAMException e)
496 // ignore - thrown if any contig line lacks length info
501 saveMetadata(sourceId);
504 * get offset of CSQ ALLELE_NUM and Feature if declared
510 * Reads metadata (such as INFO field descriptions and datatypes) and saves
511 * them for future reference
515 void saveMetadata(String theSourceId)
517 List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
519 vcfFieldsOfInterest = new ArrayList<>();
521 FeatureSource metadata = new FeatureSource(theSourceId);
523 for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
525 String attributeId = info.getID();
526 String desc = info.getDescription();
527 VCFHeaderLineType type = info.getType();
528 FeatureAttributeType attType = null;
532 attType = FeatureAttributeType.Character;
535 attType = FeatureAttributeType.Flag;
538 attType = FeatureAttributeType.Float;
541 attType = FeatureAttributeType.Integer;
544 attType = FeatureAttributeType.String;
547 metadata.setAttributeName(attributeId, desc);
548 metadata.setAttributeType(attributeId, attType);
550 if (isFieldWanted(attributeId, vcfFieldPatterns))
552 vcfFieldsOfInterest.add(attributeId);
556 FeatureSources.getInstance().addSource(theSourceId, metadata);
560 * Answers true if the field id is matched by any of the filter patterns, else
561 * false. Matching is against regular expression patterns, and is not
568 private boolean isFieldWanted(String id, List<Pattern> filters)
570 for (Pattern p : filters)
572 if (p.matcher(id.toUpperCase()).matches())
581 * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
582 * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
583 * required for processing.
585 * CSQ fields are declared in the CSQ INFO Description e.g.
587 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
589 protected void parseCsqHeader()
591 List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
593 vepFieldsOfInterest = new HashMap<>();
595 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
602 * parse out the pipe-separated list of CSQ fields; we assume here that
603 * these form the last part of the description, and contain no spaces
605 String desc = csqInfo.getDescription();
606 int spacePos = desc.lastIndexOf(" ");
607 desc = desc.substring(spacePos + 1);
611 String[] format = desc.split(PIPE_REGEX);
613 for (String field : format)
615 if (CSQ_CONSEQUENCE_KEY.equals(field))
617 csqConsequenceFieldIndex = index;
619 if (CSQ_ALLELE_NUM_KEY.equals(field))
621 csqAlleleNumberFieldIndex = index;
623 if (CSQ_ALLELE_KEY.equals(field))
625 csqAlleleFieldIndex = index;
627 if (CSQ_FEATURE_KEY.equals(field))
629 csqFeatureFieldIndex = index;
632 if (isFieldWanted(field, vepFieldFilters))
634 vepFieldsOfInterest.put(index, field);
643 * Reads the Preference value for the given key, with default specified if no
644 * preference set. The value is interpreted as a comma-separated list of
645 * regular expressions, and converted into a list of compiled patterns ready
646 * for matching. Patterns are forced to upper-case for non-case-sensitive
649 * This supports user-defined filters for fields of interest to capture while
650 * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
651 * fields with an ID of AF, or starting with AC, would be matched.
657 private List<Pattern> getFieldMatchers(String key, String def)
659 String pref = Cache.getDefault(key, def);
660 List<Pattern> patterns = new ArrayList<>();
661 String[] tokens = pref.split(",");
662 for (String token : tokens)
666 patterns.add(Pattern.compile(token.toUpperCase()));
667 } catch (PatternSyntaxException e)
669 System.err.println("Invalid pattern ignored: " + token);
676 * Transfers VCF features to sequences to which this sequence has a mapping.
677 * If the mapping is 3:1, computes peptide variants from nucleotide variants.
681 protected void transferAddedFeatures(SequenceI seq)
683 List<DBRefEntry> dbrefs = seq.getDBRefs();
688 for (DBRefEntry dbref : dbrefs)
690 Mapping mapping = dbref.getMap();
691 if (mapping == null || mapping.getTo() == null)
696 SequenceI mapTo = mapping.getTo();
697 MapList map = mapping.getMap();
698 if (map.getFromRatio() == 3)
701 * dna-to-peptide product mapping
703 // JAL-3187 render on the fly instead
704 // AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
709 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
711 List<SequenceFeature> features = seq.getFeatures()
712 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
713 for (SequenceFeature sf : features)
715 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
717 transferFeature(sf, mapTo, map);
725 * Tries to add overlapping variants read from a VCF file to the given sequence,
726 * and returns the number of variant features added
731 protected int loadSequenceVCF(SequenceI seq)
733 VCFMap vcfMap = getVcfMap(seq);
740 * work with the dataset sequence here
742 SequenceI dss = seq.getDatasetSequence();
747 return addVcfVariants(dss, vcfMap);
751 * Answers a map from sequence coordinates to VCF chromosome ranges
756 private VCFMap getVcfMap(SequenceI seq)
759 * simplest case: sequence has id and length matching a VCF contig
761 VCFMap vcfMap = null;
762 if (dictionary != null)
764 vcfMap = getContigMap(seq);
772 * otherwise, map to VCF from chromosomal coordinates
773 * of the sequence (if known)
775 GeneLociI seqCoords = seq.getGeneLoci();
776 if (seqCoords == null)
778 Cache.log.warn(String.format(
779 "Can't query VCF for %s as chromosome coordinates not known",
784 String species = seqCoords.getSpeciesId();
785 String chromosome = seqCoords.getChromosomeId();
786 String seqRef = seqCoords.getAssemblyId();
787 MapList map = seqCoords.getMapping();
789 // note this requires the configured species to match that
790 // returned with the Ensembl sequence; todo: support aliases?
791 if (!vcfSpecies.equalsIgnoreCase(species))
793 Cache.log.warn("No VCF loaded to " + seq.getName()
794 + " as species not matched");
798 if (seqRef.equalsIgnoreCase(vcfAssembly))
800 return new VCFMap(chromosome, map);
804 * VCF data has a different reference assembly to the sequence:
805 * query Ensembl to map chromosomal coordinates from sequence to VCF
807 List<int[]> toVcfRanges = new ArrayList<>();
808 List<int[]> fromSequenceRanges = new ArrayList<>();
810 for (int[] range : map.getToRanges())
812 int[] fromRange = map.locateInFrom(range[0], range[1]);
813 if (fromRange == null)
819 int[] newRange = mapReferenceRange(range, chromosome, "human", seqRef,
821 if (newRange == null)
824 String.format("Failed to map %s:%s:%s:%d:%d to %s", species,
825 chromosome, seqRef, range[0], range[1],
831 toVcfRanges.add(newRange);
832 fromSequenceRanges.add(fromRange);
836 return new VCFMap(chromosome,
837 new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
841 * If the sequence id matches a contig declared in the VCF file, and the
842 * sequence length matches the contig length, then returns a 1:1 map of the
843 * sequence to the contig, else returns null
848 private VCFMap getContigMap(SequenceI seq)
850 String id = seq.getName();
851 SAMSequenceRecord contig = dictionary.getSequence(id);
854 int len = seq.getLength();
855 if (len == contig.getSequenceLength())
857 MapList map = new MapList(new int[] { 1, len },
860 return new VCFMap(id, map);
867 * Queries the VCF reader for any variants that overlap the mapped chromosome
868 * ranges of the sequence, and adds as variant features. Returns the number of
869 * overlapping variants found.
873 * mapping from sequence to VCF coordinates
876 protected int addVcfVariants(SequenceI seq, VCFMap map)
878 boolean forwardStrand = map.map.isToForwardStrand();
881 * query the VCF for overlaps of each contiguous chromosomal region
885 for (int[] range : map.map.getToRanges())
887 int vcfStart = Math.min(range[0], range[1]);
888 int vcfEnd = Math.max(range[0], range[1]);
891 CloseableIterator<VariantContext> variants = reader
892 .query(map.chromosome, vcfStart, vcfEnd);
893 while (variants.hasNext())
895 VariantContext variant = variants.next();
897 int[] featureRange = map.map.locateInFrom(variant.getStart(),
900 if (featureRange != null)
902 int featureStart = Math.min(featureRange[0], featureRange[1]);
903 int featureEnd = Math.max(featureRange[0], featureRange[1]);
904 count += addAlleleFeatures(seq, variant, featureStart,
905 featureEnd, forwardStrand);
909 } catch (TribbleException e)
912 * RuntimeException throwable by htsjdk
914 String msg = String.format("Error reading VCF for %s:%d-%d: %s ",
915 map.chromosome, vcfStart, vcfEnd);
916 Cache.log.error(msg);
924 * A convenience method to get an attribute value for an alternate allele
927 * @param attributeName
931 protected String getAttributeValue(VariantContext variant,
932 String attributeName, int alleleIndex)
934 Object att = variant.getAttribute(attributeName);
936 if (att instanceof String)
940 else if (att instanceof ArrayList)
942 return ((List<String>) att).get(alleleIndex);
949 * Adds one variant feature for each allele in the VCF variant record, and
950 * returns the number of features added.
954 * @param featureStart
956 * @param forwardStrand
959 protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
960 int featureStart, int featureEnd, boolean forwardStrand)
965 * Javadoc says getAlternateAlleles() imposes no order on the list returned
966 * so we proceed defensively to get them in strict order
968 int altAlleleCount = variant.getAlternateAlleles().size();
969 for (int i = 0; i < altAlleleCount; i++)
971 added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
978 * Inspects one allele and attempts to add a variant feature for it to the
979 * sequence. The additional data associated with this allele is extracted to
980 * store in the feature's key-value map. Answers the number of features added (0
985 * @param altAlleleIndex
987 * @param featureStart
989 * @param forwardStrand
992 protected int addAlleleFeature(SequenceI seq, VariantContext variant,
993 int altAlleleIndex, int featureStart, int featureEnd,
994 boolean forwardStrand)
996 String reference = variant.getReference().getBaseString();
997 Allele alt = variant.getAlternateAllele(altAlleleIndex);
998 String allele = alt.getBaseString();
1001 * insertion after a genomic base, if on reverse strand, has to be
1002 * converted to insertion of complement after the preceding position
1004 int referenceLength = reference.length();
1005 if (!forwardStrand && allele.length() > referenceLength
1006 && allele.startsWith(reference))
1008 featureStart -= referenceLength;
1009 featureEnd = featureStart;
1010 char insertAfter = seq.getCharAt(featureStart - seq.getStart());
1011 reference = Dna.reverseComplement(String.valueOf(insertAfter));
1012 allele = allele.substring(referenceLength) + reference;
1016 * build the ref,alt allele description e.g. "G,A", using the base
1017 * complement if the sequence is on the reverse strand
1019 StringBuilder sb = new StringBuilder();
1020 sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
1022 sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
1023 String alleles = sb.toString(); // e.g. G,A
1026 * pick out the consequence data (if any) that is for the current allele
1027 * and feature (transcript) that matches the current sequence
1029 String consequence = getConsequenceForAlleleAndFeature(variant, CSQ_FIELD,
1030 altAlleleIndex, csqAlleleFieldIndex,
1031 csqAlleleNumberFieldIndex, seq.getName().toLowerCase(),
1032 csqFeatureFieldIndex);
1035 * pick out the ontology term for the consequence type
1037 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1038 if (consequence != null)
1040 type = getOntologyTerm(consequence);
1043 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
1044 featureEnd, FEATURE_GROUP_VCF);
1045 sf.setSource(sourceId);
1048 * save the derived alleles as a named attribute; this will be
1049 * needed when Jalview computes derived peptide variants
1051 addFeatureAttribute(sf, Gff3Helper.ALLELES, alleles);
1054 * add selected VCF fixed column data as feature attributes
1056 addFeatureAttribute(sf, VCF_POS, String.valueOf(variant.getStart()));
1057 addFeatureAttribute(sf, VCF_ID, variant.getID());
1058 addFeatureAttribute(sf, VCF_QUAL,
1059 String.valueOf(variant.getPhredScaledQual()));
1060 addFeatureAttribute(sf, VCF_FILTER, getFilter(variant));
1062 addAlleleProperties(variant, sf, altAlleleIndex, consequence);
1064 seq.addSequenceFeature(sf);
1070 * Answers the VCF FILTER value for the variant - or an approximation to it.
1071 * This field is either PASS, or a semi-colon separated list of filters not
1072 * passed. htsjdk saves filters as a HashSet, so the order when reassembled into
1073 * a list may be different.
1078 String getFilter(VariantContext variant)
1080 Set<String> filters = variant.getFilters();
1081 if (filters.isEmpty())
1085 Iterator<String> iterator = filters.iterator();
1086 String first = iterator.next();
1087 if (filters.size() == 1)
1092 StringBuilder sb = new StringBuilder(first);
1093 while (iterator.hasNext())
1095 sb.append(";").append(iterator.next());
1098 return sb.toString();
1102 * Adds one feature attribute unless the value is null, empty or '.'
1108 void addFeatureAttribute(SequenceFeature sf, String key, String value)
1110 if (value != null && !value.isEmpty() && !NO_VALUE.equals(value))
1112 sf.setValue(key, value);
1117 * Determines the Sequence Ontology term to use for the variant feature type in
1118 * Jalview. The default is 'sequence_variant', but a more specific term is used
1121 * <li>VEP (or SnpEff) Consequence annotation is included in the VCF</li>
1122 * <li>sequence id can be matched to VEP Feature (or SnpEff Feature_ID)</li>
1125 * @param consequence
1127 * @see http://www.sequenceontology.org/browser/current_svn/term/SO:0001060
1129 String getOntologyTerm(String consequence)
1131 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1134 * could we associate Consequence data with this allele and feature (transcript)?
1135 * if so, prefer the consequence term from that data
1137 if (csqAlleleFieldIndex == -1) // && snpEffAlleleFieldIndex == -1
1140 * no Consequence data so we can't refine the ontology term
1145 if (consequence != null)
1147 String[] csqFields = consequence.split(PIPE_REGEX);
1148 if (csqFields.length > csqConsequenceFieldIndex)
1150 type = csqFields[csqConsequenceFieldIndex];
1155 // todo the same for SnpEff consequence data matching if wanted
1159 * if of the form (e.g.) missense_variant&splice_region_variant,
1160 * just take the first ('most severe') consequence
1164 int pos = type.indexOf('&');
1167 type = type.substring(0, pos);
1174 * Returns matched consequence data if it can be found, else null.
1176 * <li>inspects the VCF data for key 'vcfInfoId'</li>
1177 * <li>splits this on comma (to distinct consequences)</li>
1178 * <li>returns the first consequence (if any) where</li>
1180 * <li>the allele matches the altAlleleIndex'th allele of variant</li>
1181 * <li>the feature matches the sequence name (e.g. transcript id)</li>
1184 * If matched, the consequence is returned (as pipe-delimited fields).
1188 * @param altAlleleIndex
1189 * @param alleleFieldIndex
1190 * @param alleleNumberFieldIndex
1192 * @param featureFieldIndex
1195 private String getConsequenceForAlleleAndFeature(VariantContext variant,
1196 String vcfInfoId, int altAlleleIndex, int alleleFieldIndex,
1197 int alleleNumberFieldIndex,
1198 String seqName, int featureFieldIndex)
1200 if (alleleFieldIndex == -1 || featureFieldIndex == -1)
1204 Object value = variant.getAttribute(vcfInfoId);
1206 if (value == null || !(value instanceof List<?>))
1212 * inspect each consequence in turn (comma-separated blocks
1213 * extracted by htsjdk)
1215 List<String> consequences = (List<String>) value;
1217 for (String consequence : consequences)
1219 String[] csqFields = consequence.split(PIPE_REGEX);
1220 if (csqFields.length > featureFieldIndex)
1222 String featureIdentifier = csqFields[featureFieldIndex];
1223 if (featureIdentifier.length() > 4
1224 && seqName.indexOf(featureIdentifier.toLowerCase()) > -1)
1227 * feature (transcript) matched - now check for allele match
1229 if (matchAllele(variant, altAlleleIndex, csqFields,
1230 alleleFieldIndex, alleleNumberFieldIndex))
1240 private boolean matchAllele(VariantContext variant, int altAlleleIndex,
1241 String[] csqFields, int alleleFieldIndex,
1242 int alleleNumberFieldIndex)
1245 * if ALLELE_NUM is present, it must match altAlleleIndex
1246 * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1248 if (alleleNumberFieldIndex > -1)
1250 if (csqFields.length <= alleleNumberFieldIndex)
1254 String alleleNum = csqFields[alleleNumberFieldIndex];
1255 return String.valueOf(altAlleleIndex + 1).equals(alleleNum);
1259 * else consequence allele must match variant allele
1261 if (alleleFieldIndex > -1 && csqFields.length > alleleFieldIndex)
1263 String csqAllele = csqFields[alleleFieldIndex];
1264 String vcfAllele = variant.getAlternateAllele(altAlleleIndex)
1266 return csqAllele.equals(vcfAllele);
1272 * Add any allele-specific VCF key-value data to the sequence feature
1276 * @param altAlelleIndex
1278 * @param consequence
1279 * if not null, the consequence specific to this sequence (transcript
1280 * feature) and allele
1282 protected void addAlleleProperties(VariantContext variant,
1283 SequenceFeature sf, final int altAlelleIndex, String consequence)
1285 Map<String, Object> atts = variant.getAttributes();
1287 for (Entry<String, Object> att : atts.entrySet())
1289 String key = att.getKey();
1292 * extract Consequence data (if present) that we are able to
1293 * associated with the allele for this variant feature
1295 if (CSQ_FIELD.equals(key))
1297 addConsequences(variant, sf, consequence);
1302 * filter out fields we don't want to capture
1304 if (!vcfFieldsOfInterest.contains(key))
1310 * we extract values for other data which are allele-specific;
1311 * these may be per alternate allele (INFO[key].Number = 'A')
1312 * or per allele including reference (INFO[key].Number = 'R')
1314 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
1315 if (infoHeader == null)
1318 * can't be sure what data belongs to this allele, so
1319 * play safe and don't take any
1324 VCFHeaderLineCount number = infoHeader.getCountType();
1325 int index = altAlelleIndex;
1326 if (number == VCFHeaderLineCount.R)
1329 * one value per allele including reference, so bump index
1330 * e.g. the 3rd value is for the 2nd alternate allele
1334 else if (number != VCFHeaderLineCount.A)
1337 * don't save other values as not allele-related
1343 * take the index'th value
1345 String value = getAttributeValue(variant, key, index);
1346 if (value != null && isValid(variant, key, value))
1349 * decode colon, semicolon, equals sign, percent sign, comma (only)
1350 * as required by the VCF specification (para 1.2)
1352 value = StringUtils.urlDecode(value, VCF_ENCODABLE);
1353 addFeatureAttribute(sf, key, value);
1359 * Answers true for '.', null, or an empty value, or if the INFO type is String.
1360 * If the INFO type is Integer or Float, answers false if the value is not in
1368 protected boolean isValid(VariantContext variant, String infoId,
1371 if (value == null || value.isEmpty() || NO_VALUE.equals(value))
1375 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(infoId);
1376 if (infoHeader == null)
1378 Cache.log.error("Field " + infoId + " has no INFO header");
1381 VCFHeaderLineType infoType = infoHeader.getType();
1384 if (infoType == VCFHeaderLineType.Integer)
1386 Integer.parseInt(value);
1388 else if (infoType == VCFHeaderLineType.Float)
1390 Float.parseFloat(value);
1392 } catch (NumberFormatException e)
1394 logInvalidValue(variant, infoId, value);
1401 * Logs an error message for malformed data; duplicate messages (same id and
1402 * value) are not logged
1408 private void logInvalidValue(VariantContext variant, String infoId,
1411 if (badData == null)
1413 badData = new HashSet<>();
1415 String token = infoId + ":" + value;
1416 if (!badData.contains(token))
1419 Cache.log.error(String.format("Invalid VCF data at %s:%d %s=%s",
1420 variant.getContig(), variant.getStart(), infoId, value));
1425 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
1428 * If <code>myConsequence</code> is not null, then this is the specific
1429 * consequence data (pipe-delimited fields) that is for the current allele and
1430 * transcript (sequence) being processed)
1434 * @param myConsequence
1436 protected void addConsequences(VariantContext variant, SequenceFeature sf,
1437 String myConsequence)
1439 Object value = variant.getAttribute(CSQ_FIELD);
1441 if (value == null || !(value instanceof List<?>))
1446 List<String> consequences = (List<String>) value;
1449 * inspect CSQ consequences; restrict to the consequence
1450 * associated with the current transcript (Feature)
1452 Map<String, String> csqValues = new HashMap<>();
1454 for (String consequence : consequences)
1456 if (myConsequence == null || myConsequence.equals(consequence))
1458 String[] csqFields = consequence.split(PIPE_REGEX);
1461 * inspect individual fields of this consequence, copying non-null
1462 * values which are 'fields of interest'
1465 for (String field : csqFields)
1467 if (field != null && field.length() > 0)
1469 String id = vepFieldsOfInterest.get(i);
1473 * VCF spec requires encoding of special characters e.g. '='
1474 * so decode them here before storing
1476 field = StringUtils.urlDecode(field, VCF_ENCODABLE);
1477 csqValues.put(id, field);
1485 if (!csqValues.isEmpty())
1487 sf.setValue(CSQ_FIELD, csqValues);
1492 * A convenience method to complement a dna base and return the string value
1498 protected String complement(byte[] reference)
1500 return String.valueOf(Dna.getComplement((char) reference[0]));
1504 * Determines the location of the query range (chromosome positions) in a
1505 * different reference assembly.
1507 * If the range is just a subregion of one for which we already have a mapping
1508 * (for example, an exon sub-region of a gene), then the mapping is just
1509 * computed arithmetically.
1511 * Otherwise, calls the Ensembl REST service that maps from one assembly
1512 * reference's coordinates to another's
1515 * start-end chromosomal range in 'fromRef' coordinates
1519 * assembly reference for the query coordinates
1521 * assembly reference we wish to translate to
1522 * @return the start-end range in 'toRef' coordinates
1524 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
1525 String species, String fromRef, String toRef)
1528 * first try shorcut of computing the mapping as a subregion of one
1529 * we already have (e.g. for an exon, if we have the gene mapping)
1531 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
1532 species, fromRef, toRef);
1533 if (mappedRange != null)
1539 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
1541 EnsemblMap mapper = new EnsemblMap();
1542 int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
1545 if (mapping == null)
1547 // mapping service failure
1552 * save mapping for possible future re-use
1554 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1555 if (!assemblyMappings.containsKey(key))
1557 assemblyMappings.put(key, new HashMap<int[], int[]>());
1560 assemblyMappings.get(key).put(queryRange, mapping);
1566 * If we already have a 1:1 contiguous mapping which subsumes the given query
1567 * range, this method just calculates and returns the subset of that mapping,
1568 * else it returns null. In practical terms, if a gene has a contiguous
1569 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
1570 * subsidiary exons occupy unchanged relative positions, and just compute
1571 * these as offsets, rather than do another lookup of the mapping.
1573 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
1574 * simply remove this method or let it always return null.
1576 * Warning: many rapid calls to the /map service map result in a 429 overload
1586 protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
1587 String species, String fromRef, String toRef)
1589 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1590 if (assemblyMappings.containsKey(key))
1592 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
1593 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
1595 int[] fromRange = mappedRange.getKey();
1596 int[] toRange = mappedRange.getValue();
1597 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
1600 * mapping is 1:1 in length, so we trust it to have no discontinuities
1602 if (MappingUtils.rangeContains(fromRange, queryRange))
1605 * fromRange subsumes our query range
1607 int offset = queryRange[0] - fromRange[0];
1608 int mappedRangeFrom = toRange[0] + offset;
1609 int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
1610 return new int[] { mappedRangeFrom, mappedRangeTo };
1619 * Transfers the sequence feature to the target sequence, locating its start
1620 * and end range based on the mapping. Features which do not overlap the
1621 * target sequence are ignored.
1624 * @param targetSequence
1626 * mapping from the feature's coordinates to the target sequence
1628 protected void transferFeature(SequenceFeature sf,
1629 SequenceI targetSequence, MapList mapping)
1631 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1633 if (mappedRange != null)
1635 String group = sf.getFeatureGroup();
1636 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1637 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1638 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1639 group, sf.getScore());
1640 targetSequence.addSequenceFeature(copy);
1645 * Formats a ranges map lookup key
1653 protected static String makeRangesKey(String chromosome, String species,
1654 String fromRef, String toRef)
1656 return species + EXCL + chromosome + EXCL + fromRef + EXCL