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;
24 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.List;
31 import java.util.Map.Entry;
33 import java.util.regex.Pattern;
34 import java.util.regex.PatternSyntaxException;
36 import htsjdk.samtools.SAMException;
37 import htsjdk.samtools.SAMSequenceDictionary;
38 import htsjdk.samtools.SAMSequenceRecord;
39 import htsjdk.samtools.util.CloseableIterator;
40 import htsjdk.tribble.TribbleException;
41 import htsjdk.variant.variantcontext.Allele;
42 import htsjdk.variant.variantcontext.VariantContext;
43 import htsjdk.variant.vcf.VCFConstants;
44 import htsjdk.variant.vcf.VCFHeader;
45 import htsjdk.variant.vcf.VCFHeaderLine;
46 import htsjdk.variant.vcf.VCFHeaderLineCount;
47 import htsjdk.variant.vcf.VCFHeaderLineType;
48 import htsjdk.variant.vcf.VCFInfoHeaderLine;
49 import jalview.analysis.Dna;
50 import jalview.api.AlignViewControllerGuiI;
51 import jalview.bin.Cache;
52 import jalview.datamodel.DBRefEntry;
53 import jalview.datamodel.GeneLociI;
54 import jalview.datamodel.Mapping;
55 import jalview.datamodel.SequenceFeature;
56 import jalview.datamodel.SequenceI;
57 import jalview.datamodel.features.FeatureAttributeType;
58 import jalview.datamodel.features.FeatureSource;
59 import jalview.datamodel.features.FeatureSources;
60 import jalview.ext.ensembl.EnsemblMap;
61 import jalview.ext.htsjdk.HtsContigDb;
62 import jalview.ext.htsjdk.VCFReader;
63 import jalview.io.gff.Gff3Helper;
64 import jalview.io.gff.SequenceOntologyI;
65 import jalview.util.MapList;
66 import jalview.util.MappingUtils;
67 import jalview.util.MessageManager;
68 import jalview.util.StringUtils;
71 * A class to read VCF data (using the htsjdk) and add variants as sequence
72 * features on dna and any related protein product sequences
76 public class VCFLoader
78 private static final String VCF_ENCODABLE = ":;=%,";
81 * Jalview feature attributes for VCF fixed column data
83 private static final String VCF_POS = "POS";
85 private static final String VCF_ID = "ID";
87 private static final String VCF_QUAL = "QUAL";
89 private static final String VCF_FILTER = "FILTER";
91 private static final String NO_VALUE = VCFConstants.MISSING_VALUE_v4; // '.'
93 private static final String DEFAULT_SPECIES = "homo_sapiens";
96 * A class to model the mapping from sequence to VCF coordinates. Cases include
98 * <li>a direct 1:1 mapping where the sequence is one of the VCF contigs</li>
99 * <li>a mapping of sequence to chromosomal coordinates, where sequence and VCF
100 * use the same reference assembly</li>
101 * <li>a modified mapping of sequence to chromosomal coordinates, where sequence
102 * and VCF use different reference assembles</li>
107 final String chromosome;
111 VCFMap(String chr, MapList m)
118 public String toString()
120 return chromosome + ":" + map.toString();
125 * Lookup keys, and default values, for Preference entries that describe
126 * patterns for VCF and VEP fields to capture
128 private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
130 private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
132 private static final String DEFAULT_VCF_FIELDS = ".*";
134 private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
137 * Lookup keys, and default values, for Preference entries that give
138 * mappings from tokens in the 'reference' header to species or assembly
140 private static final String VCF_ASSEMBLY = "VCF_ASSEMBLY";
142 private static final String DEFAULT_VCF_ASSEMBLY = "assembly19=GRCh37,hs37=GRCh37,grch37=GRCh37,grch38=GRCh38";
144 private static final String VCF_SPECIES = "VCF_SPECIES"; // default is human
146 private static final String DEFAULT_REFERENCE = "grch37"; // fallback default is human GRCh37
149 * keys to fields of VEP CSQ consequence data
150 * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
152 private static final String CSQ_CONSEQUENCE_KEY = "Consequence";
153 private static final String CSQ_ALLELE_KEY = "Allele";
154 private static final String CSQ_ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref), 1...
155 private static final String CSQ_FEATURE_KEY = "Feature"; // Ensembl stable id
158 * default VCF INFO key for VEP consequence data
159 * NB this can be overridden running VEP with --vcf_info_field
160 * - we don't handle this case (require identifier to be CSQ)
162 private static final String CSQ_FIELD = "CSQ";
165 * separator for fields in consequence data is '|'
167 private static final String PIPE_REGEX = "\\|";
170 * delimiter that separates multiple consequence data blocks
172 private static final String COMMA = ",";
175 * the feature group assigned to a VCF variant in Jalview
177 private static final String FEATURE_GROUP_VCF = "VCF";
180 * internal delimiter used to build keys for assemblyMappings
183 private static final String EXCL = "!";
186 * the VCF file we are processing
188 protected String vcfFilePath;
191 * mappings between VCF and sequence reference assembly regions, as
192 * key = "species!chromosome!fromAssembly!toAssembly
193 * value = Map{fromRange, toRange}
195 private Map<String, Map<int[], int[]>> assemblyMappings;
197 private VCFReader reader;
200 * holds details of the VCF header lines (metadata)
202 private VCFHeader header;
205 * species (as a valid Ensembl term) the VCF is for
207 private String vcfSpecies;
210 * genome assembly version (as a valid Ensembl identifier) the VCF is for
212 private String vcfAssembly;
215 * a Dictionary of contigs (if present) referenced in the VCF file
217 private SAMSequenceDictionary dictionary;
220 * the position (0...) of field in each block of
221 * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
222 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
224 private int csqConsequenceFieldIndex = -1;
225 private int csqAlleleFieldIndex = -1;
226 private int csqAlleleNumberFieldIndex = -1;
227 private int csqFeatureFieldIndex = -1;
229 // todo the same fields for SnpEff ANN data if wanted
230 // see http://snpeff.sourceforge.net/SnpEff_manual.html#input
233 * a unique identifier under which to save metadata about feature
234 * attributes (selected INFO field data)
236 private String sourceId;
239 * The INFO IDs of data that is both present in the VCF file, and
240 * also matched by any filters for data of interest
242 List<String> vcfFieldsOfInterest;
245 * The field offsets and identifiers for VEP (CSQ) data that is both present
246 * in the VCF file, and also matched by any filters for data of interest
247 * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
249 Map<Integer, String> vepFieldsOfInterest;
252 * key:value for which rejected data has been seen
253 * (the error is logged only once for each combination)
255 private Set<String> badData;
258 * Constructor given a VCF file
262 public VCFLoader(String vcfFile)
267 } catch (IOException e)
269 System.err.println("Error opening VCF file: " + e.getMessage());
272 // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
273 assemblyMappings = new HashMap<>();
277 * Starts a new thread to query and load VCF variant data on to the given
280 * This method is not thread safe - concurrent threads should use separate
281 * instances of this class.
286 public void loadVCF(SequenceI[] seqs, final AlignViewControllerGuiI gui)
290 gui.setStatus(MessageManager.getString("label.searching_vcf"));
298 VCFLoader.this.doLoad(seqs, gui);
304 * Reads the specified contig sequence and adds its VCF variants to it
307 * the id of a single sequence (contig) to load
310 public SequenceI loadVCFContig(String contig)
312 VCFHeaderLine headerLine = header.getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
313 if (headerLine == null)
315 Cache.log.error("VCF reference header not found");
318 String ref = headerLine.getValue();
319 if (ref.startsWith("file://"))
321 ref = ref.substring(7);
323 setSpeciesAndAssembly(ref);
325 SequenceI seq = null;
326 File dbFile = new File(ref);
330 HtsContigDb db = new HtsContigDb("", dbFile);
331 seq = db.getSequenceProxy(contig);
332 loadSequenceVCF(seq);
337 Cache.log.error("VCF reference not found: " + ref);
344 * Loads VCF on to one or more sequences
348 * optional callback handler for messages
350 protected void doLoad(SequenceI[] seqs, AlignViewControllerGuiI gui)
354 VCFHeaderLine ref = header
355 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
356 String reference = ref == null ? null : ref.getValue();
358 setSpeciesAndAssembly(reference);
364 * query for VCF overlapping each sequence in turn
366 for (SequenceI seq : seqs)
368 int added = loadSequenceVCF(seq);
373 transferAddedFeatures(seq);
378 String msg = MessageManager.formatMessage("label.added_vcf",
381 if (gui.getFeatureSettingsUI() != null)
383 gui.getFeatureSettingsUI().discoverAllFeatureData();
386 } catch (Throwable e)
388 System.err.println("Error processing VCF: " + e.getMessage());
392 gui.setStatus("Error occurred - see console for details");
401 } catch (IOException e)
412 * Attempts to determine and save the species and genome assembly version to
413 * which the VCF data applies. This may be done by parsing the {@code reference}
414 * header line, configured in a property file, or (potentially) confirmed
415 * interactively by the user.
417 * The saved values should be identifiers valid for Ensembl's REST service
418 * {@code map} endpoint, so they can be used (if necessary) to retrieve the
419 * mapping between VCF coordinates and sequence coordinates.
422 * @see https://rest.ensembl.org/documentation/info/assembly_map
423 * @see https://rest.ensembl.org/info/assembly/human?content-type=text/xml
424 * @see https://rest.ensembl.org/info/species?content-type=text/xml
426 protected void setSpeciesAndAssembly(String reference)
428 if (reference == null)
430 Cache.log.error("No VCF ##reference found, defaulting to "
431 + DEFAULT_REFERENCE + ":" + DEFAULT_SPECIES);
432 reference = DEFAULT_REFERENCE; // default to GRCh37 if not specified
434 reference = reference.toLowerCase();
437 * for a non-human species, or other assembly identifier,
438 * specify as a Jalview property file entry e.g.
439 * VCF_ASSEMBLY = hs37=GRCh37,assembly19=GRCh37
440 * VCF_SPECIES = c_elegans=celegans
441 * to map a token in the reference header to a value
443 String prop = Cache.getDefault(VCF_ASSEMBLY, DEFAULT_VCF_ASSEMBLY);
444 for (String token : prop.split(","))
446 String[] tokens = token.split("=");
447 if (tokens.length == 2)
449 if (reference.contains(tokens[0].trim().toLowerCase()))
451 vcfAssembly = tokens[1].trim();
457 vcfSpecies = DEFAULT_SPECIES;
458 prop = Cache.getProperty(VCF_SPECIES);
461 for (String token : prop.split(","))
463 String[] tokens = token.split("=");
464 if (tokens.length == 2)
466 if (reference.contains(tokens[0].trim().toLowerCase()))
468 vcfSpecies = tokens[1].trim();
477 * Opens the VCF file and parses header data
480 * @throws IOException
482 private void initialise(String filePath) throws IOException
484 vcfFilePath = filePath;
486 reader = new VCFReader(filePath);
488 header = reader.getFileHeader();
492 dictionary = header.getSequenceDictionary();
493 } catch (SAMException e)
495 // ignore - thrown if any contig line lacks length info
500 saveMetadata(sourceId);
503 * get offset of CSQ ALLELE_NUM and Feature if declared
509 * Reads metadata (such as INFO field descriptions and datatypes) and saves
510 * them for future reference
514 void saveMetadata(String theSourceId)
516 List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
518 vcfFieldsOfInterest = new ArrayList<>();
520 FeatureSource metadata = new FeatureSource(theSourceId);
522 for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
524 String attributeId = info.getID();
525 String desc = info.getDescription();
526 VCFHeaderLineType type = info.getType();
527 FeatureAttributeType attType = null;
531 attType = FeatureAttributeType.Character;
534 attType = FeatureAttributeType.Flag;
537 attType = FeatureAttributeType.Float;
540 attType = FeatureAttributeType.Integer;
543 attType = FeatureAttributeType.String;
546 metadata.setAttributeName(attributeId, desc);
547 metadata.setAttributeType(attributeId, attType);
549 if (isFieldWanted(attributeId, vcfFieldPatterns))
551 vcfFieldsOfInterest.add(attributeId);
555 FeatureSources.getInstance().addSource(theSourceId, metadata);
559 * Answers true if the field id is matched by any of the filter patterns, else
560 * false. Matching is against regular expression patterns, and is not
567 private boolean isFieldWanted(String id, List<Pattern> filters)
569 for (Pattern p : filters)
571 if (p.matcher(id.toUpperCase()).matches())
580 * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
581 * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
582 * required for processing.
584 * CSQ fields are declared in the CSQ INFO Description e.g.
586 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
588 protected void parseCsqHeader()
590 List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
592 vepFieldsOfInterest = new HashMap<>();
594 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
601 * parse out the pipe-separated list of CSQ fields; we assume here that
602 * these form the last part of the description, and contain no spaces
604 String desc = csqInfo.getDescription();
605 int spacePos = desc.lastIndexOf(" ");
606 desc = desc.substring(spacePos + 1);
610 String[] format = desc.split(PIPE_REGEX);
612 for (String field : format)
614 if (CSQ_CONSEQUENCE_KEY.equals(field))
616 csqConsequenceFieldIndex = index;
618 if (CSQ_ALLELE_NUM_KEY.equals(field))
620 csqAlleleNumberFieldIndex = index;
622 if (CSQ_ALLELE_KEY.equals(field))
624 csqAlleleFieldIndex = index;
626 if (CSQ_FEATURE_KEY.equals(field))
628 csqFeatureFieldIndex = index;
631 if (isFieldWanted(field, vepFieldFilters))
633 vepFieldsOfInterest.put(index, field);
642 * Reads the Preference value for the given key, with default specified if no
643 * preference set. The value is interpreted as a comma-separated list of
644 * regular expressions, and converted into a list of compiled patterns ready
645 * for matching. Patterns are forced to upper-case for non-case-sensitive
648 * This supports user-defined filters for fields of interest to capture while
649 * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
650 * fields with an ID of AF, or starting with AC, would be matched.
656 private List<Pattern> getFieldMatchers(String key, String def)
658 String pref = Cache.getDefault(key, def);
659 List<Pattern> patterns = new ArrayList<>();
660 String[] tokens = pref.split(",");
661 for (String token : tokens)
665 patterns.add(Pattern.compile(token.toUpperCase()));
666 } catch (PatternSyntaxException e)
668 System.err.println("Invalid pattern ignored: " + token);
675 * Transfers VCF features to sequences to which this sequence has a mapping.
679 protected void transferAddedFeatures(SequenceI seq)
681 List<DBRefEntry> dbrefs = seq.getDBRefs();
686 for (DBRefEntry dbref : dbrefs)
688 Mapping mapping = dbref.getMap();
689 if (mapping == null || mapping.getTo() == null)
694 SequenceI mapTo = mapping.getTo();
695 MapList map = mapping.getMap();
696 if (map.getFromRatio() == 3)
699 * dna-to-peptide product mapping
701 // JAL-3187 render on the fly instead
702 // AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
707 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
709 List<SequenceFeature> features = seq.getFeatures()
710 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
711 for (SequenceFeature sf : features)
713 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
715 transferFeature(sf, mapTo, map);
723 * Tries to add overlapping variants read from a VCF file to the given sequence,
724 * and returns the number of variant features added
729 protected int loadSequenceVCF(SequenceI seq)
731 VCFMap vcfMap = getVcfMap(seq);
738 * work with the dataset sequence here
740 SequenceI dss = seq.getDatasetSequence();
745 return addVcfVariants(dss, vcfMap);
749 * Answers a map from sequence coordinates to VCF chromosome ranges
754 private VCFMap getVcfMap(SequenceI seq)
757 * simplest case: sequence has id and length matching a VCF contig
759 VCFMap vcfMap = null;
760 if (dictionary != null)
762 vcfMap = getContigMap(seq);
770 * otherwise, map to VCF from chromosomal coordinates
771 * of the sequence (if known)
773 GeneLociI seqCoords = seq.getGeneLoci();
774 if (seqCoords == null)
776 Cache.log.warn(String.format(
777 "Can't query VCF for %s as chromosome coordinates not known",
782 String species = seqCoords.getSpeciesId();
783 String chromosome = seqCoords.getChromosomeId();
784 String seqRef = seqCoords.getAssemblyId();
785 MapList map = seqCoords.getMapping();
787 // note this requires the configured species to match that
788 // returned with the Ensembl sequence; todo: support aliases?
789 if (!vcfSpecies.equalsIgnoreCase(species))
791 Cache.log.warn("No VCF loaded to " + seq.getName()
792 + " as species not matched");
796 if (seqRef.equalsIgnoreCase(vcfAssembly))
798 return new VCFMap(chromosome, map);
802 * VCF data has a different reference assembly to the sequence:
803 * query Ensembl to map chromosomal coordinates from sequence to VCF
805 List<int[]> toVcfRanges = new ArrayList<>();
806 List<int[]> fromSequenceRanges = new ArrayList<>();
808 for (int[] range : map.getToRanges())
810 int[] fromRange = map.locateInFrom(range[0], range[1]);
811 if (fromRange == null)
817 int[] newRange = mapReferenceRange(range, chromosome, "human", seqRef,
819 if (newRange == null)
822 String.format("Failed to map %s:%s:%s:%d:%d to %s", species,
823 chromosome, seqRef, range[0], range[1],
829 toVcfRanges.add(newRange);
830 fromSequenceRanges.add(fromRange);
834 return new VCFMap(chromosome,
835 new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
839 * If the sequence id matches a contig declared in the VCF file, and the
840 * sequence length matches the contig length, then returns a 1:1 map of the
841 * sequence to the contig, else returns null
846 private VCFMap getContigMap(SequenceI seq)
848 String id = seq.getName();
849 SAMSequenceRecord contig = dictionary.getSequence(id);
852 int len = seq.getLength();
853 if (len == contig.getSequenceLength())
855 MapList map = new MapList(new int[] { 1, len },
858 return new VCFMap(id, map);
865 * Queries the VCF reader for any variants that overlap the mapped chromosome
866 * ranges of the sequence, and adds as variant features. Returns the number of
867 * overlapping variants found.
871 * mapping from sequence to VCF coordinates
874 protected int addVcfVariants(SequenceI seq, VCFMap map)
876 boolean forwardStrand = map.map.isToForwardStrand();
879 * query the VCF for overlaps of each contiguous chromosomal region
883 for (int[] range : map.map.getToRanges())
885 int vcfStart = Math.min(range[0], range[1]);
886 int vcfEnd = Math.max(range[0], range[1]);
889 CloseableIterator<VariantContext> variants = reader
890 .query(map.chromosome, vcfStart, vcfEnd);
891 while (variants.hasNext())
893 VariantContext variant = variants.next();
895 int[] featureRange = map.map.locateInFrom(variant.getStart(),
899 * only take features whose range is fully mappable to sequence positions
901 if (featureRange != null)
903 int featureStart = Math.min(featureRange[0], featureRange[1]);
904 int featureEnd = Math.max(featureRange[0], featureRange[1]);
905 if (featureEnd - featureStart == variant.getEnd()
906 - variant.getStart())
908 count += addAlleleFeatures(seq, variant, featureStart,
909 featureEnd, forwardStrand);
914 } catch (TribbleException e)
917 * RuntimeException throwable by htsjdk
919 String msg = String.format("Error reading VCF for %s:%d-%d: %s ",
920 map.chromosome, vcfStart, vcfEnd,e.getLocalizedMessage());
921 Cache.log.error(msg);
929 * A convenience method to get an attribute value for an alternate allele
932 * @param attributeName
936 protected String getAttributeValue(VariantContext variant,
937 String attributeName, int alleleIndex)
939 Object att = variant.getAttribute(attributeName);
941 if (att instanceof String)
945 else if (att instanceof ArrayList)
947 return ((List<String>) att).get(alleleIndex);
954 * Adds one variant feature for each allele in the VCF variant record, and
955 * returns the number of features added.
959 * @param featureStart
961 * @param forwardStrand
964 protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
965 int featureStart, int featureEnd, boolean forwardStrand)
970 * Javadoc says getAlternateAlleles() imposes no order on the list returned
971 * so we proceed defensively to get them in strict order
973 int altAlleleCount = variant.getAlternateAlleles().size();
974 for (int i = 0; i < altAlleleCount; i++)
976 added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
983 * Inspects one allele and attempts to add a variant feature for it to the
984 * sequence. The additional data associated with this allele is extracted to
985 * store in the feature's key-value map. Answers the number of features added (0
990 * @param altAlleleIndex
992 * @param featureStart
994 * @param forwardStrand
997 protected int addAlleleFeature(SequenceI seq, VariantContext variant,
998 int altAlleleIndex, int featureStart, int featureEnd,
999 boolean forwardStrand)
1001 String reference = variant.getReference().getBaseString();
1002 Allele alt = variant.getAlternateAllele(altAlleleIndex);
1003 String allele = alt.getBaseString();
1006 * insertion after a genomic base, if on reverse strand, has to be
1007 * converted to insertion of complement after the preceding position
1009 int referenceLength = reference.length();
1010 if (!forwardStrand && allele.length() > referenceLength
1011 && allele.startsWith(reference))
1013 featureStart -= referenceLength;
1014 featureEnd = featureStart;
1015 char insertAfter = seq.getCharAt(featureStart - seq.getStart());
1016 reference = Dna.reverseComplement(String.valueOf(insertAfter));
1017 allele = allele.substring(referenceLength) + reference;
1021 * build the ref,alt allele description e.g. "G,A", using the base
1022 * complement if the sequence is on the reverse strand
1024 StringBuilder sb = new StringBuilder();
1025 sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
1027 sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
1028 String alleles = sb.toString(); // e.g. G,A
1031 * pick out the consequence data (if any) that is for the current allele
1032 * and feature (transcript) that matches the current sequence
1034 String consequence = getConsequenceForAlleleAndFeature(variant, CSQ_FIELD,
1035 altAlleleIndex, csqAlleleFieldIndex,
1036 csqAlleleNumberFieldIndex, seq.getName().toLowerCase(),
1037 csqFeatureFieldIndex);
1040 * pick out the ontology term for the consequence type
1042 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1043 if (consequence != null)
1045 type = getOntologyTerm(consequence);
1048 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
1049 featureEnd, FEATURE_GROUP_VCF);
1050 sf.setSource(sourceId);
1053 * save the derived alleles as a named attribute; this will be
1054 * needed when Jalview computes derived peptide variants
1056 addFeatureAttribute(sf, Gff3Helper.ALLELES, alleles);
1059 * add selected VCF fixed column data as feature attributes
1061 addFeatureAttribute(sf, VCF_POS, String.valueOf(variant.getStart()));
1062 addFeatureAttribute(sf, VCF_ID, variant.getID());
1063 addFeatureAttribute(sf, VCF_QUAL,
1064 String.valueOf(variant.getPhredScaledQual()));
1065 addFeatureAttribute(sf, VCF_FILTER, getFilter(variant));
1067 addAlleleProperties(variant, sf, altAlleleIndex, consequence);
1069 seq.addSequenceFeature(sf);
1075 * Answers the VCF FILTER value for the variant - or an approximation to it.
1076 * This field is either PASS, or a semi-colon separated list of filters not
1077 * passed. htsjdk saves filters as a HashSet, so the order when reassembled into
1078 * a list may be different.
1083 String getFilter(VariantContext variant)
1085 Set<String> filters = variant.getFilters();
1086 if (filters.isEmpty())
1090 Iterator<String> iterator = filters.iterator();
1091 String first = iterator.next();
1092 if (filters.size() == 1)
1097 StringBuilder sb = new StringBuilder(first);
1098 while (iterator.hasNext())
1100 sb.append(";").append(iterator.next());
1103 return sb.toString();
1107 * Adds one feature attribute unless the value is null, empty or '.'
1113 void addFeatureAttribute(SequenceFeature sf, String key, String value)
1115 if (value != null && !value.isEmpty() && !NO_VALUE.equals(value))
1117 sf.setValue(key, value);
1122 * Determines the Sequence Ontology term to use for the variant feature type in
1123 * Jalview. The default is 'sequence_variant', but a more specific term is used
1126 * <li>VEP (or SnpEff) Consequence annotation is included in the VCF</li>
1127 * <li>sequence id can be matched to VEP Feature (or SnpEff Feature_ID)</li>
1130 * @param consequence
1132 * @see http://www.sequenceontology.org/browser/current_svn/term/SO:0001060
1134 String getOntologyTerm(String consequence)
1136 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1139 * could we associate Consequence data with this allele and feature (transcript)?
1140 * if so, prefer the consequence term from that data
1142 if (csqAlleleFieldIndex == -1) // && snpEffAlleleFieldIndex == -1
1145 * no Consequence data so we can't refine the ontology term
1150 if (consequence != null)
1152 String[] csqFields = consequence.split(PIPE_REGEX);
1153 if (csqFields.length > csqConsequenceFieldIndex)
1155 type = csqFields[csqConsequenceFieldIndex];
1160 // todo the same for SnpEff consequence data matching if wanted
1164 * if of the form (e.g.) missense_variant&splice_region_variant,
1165 * just take the first ('most severe') consequence
1169 int pos = type.indexOf('&');
1172 type = type.substring(0, pos);
1179 * Returns matched consequence data if it can be found, else null.
1181 * <li>inspects the VCF data for key 'vcfInfoId'</li>
1182 * <li>splits this on comma (to distinct consequences)</li>
1183 * <li>returns the first consequence (if any) where</li>
1185 * <li>the allele matches the altAlleleIndex'th allele of variant</li>
1186 * <li>the feature matches the sequence name (e.g. transcript id)</li>
1189 * If matched, the consequence is returned (as pipe-delimited fields).
1193 * @param altAlleleIndex
1194 * @param alleleFieldIndex
1195 * @param alleleNumberFieldIndex
1197 * @param featureFieldIndex
1200 private String getConsequenceForAlleleAndFeature(VariantContext variant,
1201 String vcfInfoId, int altAlleleIndex, int alleleFieldIndex,
1202 int alleleNumberFieldIndex,
1203 String seqName, int featureFieldIndex)
1205 if (alleleFieldIndex == -1 || featureFieldIndex == -1)
1209 Object value = variant.getAttribute(vcfInfoId);
1211 if (value == null || !(value instanceof List<?>))
1217 * inspect each consequence in turn (comma-separated blocks
1218 * extracted by htsjdk)
1220 List<String> consequences = (List<String>) value;
1222 for (String consequence : consequences)
1224 String[] csqFields = consequence.split(PIPE_REGEX);
1225 if (csqFields.length > featureFieldIndex)
1227 String featureIdentifier = csqFields[featureFieldIndex];
1228 if (featureIdentifier.length() > 4
1229 && seqName.indexOf(featureIdentifier.toLowerCase()) > -1)
1232 * feature (transcript) matched - now check for allele match
1234 if (matchAllele(variant, altAlleleIndex, csqFields,
1235 alleleFieldIndex, alleleNumberFieldIndex))
1245 private boolean matchAllele(VariantContext variant, int altAlleleIndex,
1246 String[] csqFields, int alleleFieldIndex,
1247 int alleleNumberFieldIndex)
1250 * if ALLELE_NUM is present, it must match altAlleleIndex
1251 * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1253 if (alleleNumberFieldIndex > -1)
1255 if (csqFields.length <= alleleNumberFieldIndex)
1259 String alleleNum = csqFields[alleleNumberFieldIndex];
1260 return String.valueOf(altAlleleIndex + 1).equals(alleleNum);
1264 * else consequence allele must match variant allele
1266 if (alleleFieldIndex > -1 && csqFields.length > alleleFieldIndex)
1268 String csqAllele = csqFields[alleleFieldIndex];
1269 String vcfAllele = variant.getAlternateAllele(altAlleleIndex)
1271 return csqAllele.equals(vcfAllele);
1277 * Add any allele-specific VCF key-value data to the sequence feature
1281 * @param altAlelleIndex
1283 * @param consequence
1284 * if not null, the consequence specific to this sequence (transcript
1285 * feature) and allele
1287 protected void addAlleleProperties(VariantContext variant,
1288 SequenceFeature sf, final int altAlelleIndex, String consequence)
1290 Map<String, Object> atts = variant.getAttributes();
1292 for (Entry<String, Object> att : atts.entrySet())
1294 String key = att.getKey();
1297 * extract Consequence data (if present) that we are able to
1298 * associated with the allele for this variant feature
1300 if (CSQ_FIELD.equals(key))
1302 addConsequences(variant, sf, consequence);
1307 * filter out fields we don't want to capture
1309 if (!vcfFieldsOfInterest.contains(key))
1315 * we extract values for other data which are allele-specific;
1316 * these may be per alternate allele (INFO[key].Number = 'A')
1317 * or per allele including reference (INFO[key].Number = 'R')
1319 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
1320 if (infoHeader == null)
1323 * can't be sure what data belongs to this allele, so
1324 * play safe and don't take any
1329 VCFHeaderLineCount number = infoHeader.getCountType();
1330 int index = altAlelleIndex;
1331 if (number == VCFHeaderLineCount.R)
1334 * one value per allele including reference, so bump index
1335 * e.g. the 3rd value is for the 2nd alternate allele
1339 else if (number != VCFHeaderLineCount.A)
1342 * don't save other values as not allele-related
1348 * take the index'th value
1350 String value = getAttributeValue(variant, key, index);
1351 if (value != null && isValid(variant, key, value))
1354 * decode colon, semicolon, equals sign, percent sign, comma (only)
1355 * as required by the VCF specification (para 1.2)
1357 value = StringUtils.urlDecode(value, VCF_ENCODABLE);
1358 addFeatureAttribute(sf, key, value);
1364 * Answers true for '.', null, or an empty value, or if the INFO type is String.
1365 * If the INFO type is Integer or Float, answers false if the value is not in
1373 protected boolean isValid(VariantContext variant, String infoId,
1376 if (value == null || value.isEmpty() || NO_VALUE.equals(value))
1380 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(infoId);
1381 if (infoHeader == null)
1383 Cache.log.error("Field " + infoId + " has no INFO header");
1386 VCFHeaderLineType infoType = infoHeader.getType();
1389 if (infoType == VCFHeaderLineType.Integer)
1391 Integer.parseInt(value);
1393 else if (infoType == VCFHeaderLineType.Float)
1395 Float.parseFloat(value);
1397 } catch (NumberFormatException e)
1399 logInvalidValue(variant, infoId, value);
1406 * Logs an error message for malformed data; duplicate messages (same id and
1407 * value) are not logged
1413 private void logInvalidValue(VariantContext variant, String infoId,
1416 if (badData == null)
1418 badData = new HashSet<>();
1420 String token = infoId + ":" + value;
1421 if (!badData.contains(token))
1424 Cache.log.error(String.format("Invalid VCF data at %s:%d %s=%s",
1425 variant.getContig(), variant.getStart(), infoId, value));
1430 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
1433 * If <code>myConsequence</code> is not null, then this is the specific
1434 * consequence data (pipe-delimited fields) that is for the current allele and
1435 * transcript (sequence) being processed)
1439 * @param myConsequence
1441 protected void addConsequences(VariantContext variant, SequenceFeature sf,
1442 String myConsequence)
1444 Object value = variant.getAttribute(CSQ_FIELD);
1446 if (value == null || !(value instanceof List<?>))
1451 List<String> consequences = (List<String>) value;
1454 * inspect CSQ consequences; restrict to the consequence
1455 * associated with the current transcript (Feature)
1457 Map<String, String> csqValues = new HashMap<>();
1459 for (String consequence : consequences)
1461 if (myConsequence == null || myConsequence.equals(consequence))
1463 String[] csqFields = consequence.split(PIPE_REGEX);
1466 * inspect individual fields of this consequence, copying non-null
1467 * values which are 'fields of interest'
1470 for (String field : csqFields)
1472 if (field != null && field.length() > 0)
1474 String id = vepFieldsOfInterest.get(i);
1478 * VCF spec requires encoding of special characters e.g. '='
1479 * so decode them here before storing
1481 field = StringUtils.urlDecode(field, VCF_ENCODABLE);
1482 csqValues.put(id, field);
1490 if (!csqValues.isEmpty())
1492 sf.setValue(CSQ_FIELD, csqValues);
1497 * A convenience method to complement a dna base and return the string value
1503 protected String complement(byte[] reference)
1505 return String.valueOf(Dna.getComplement((char) reference[0]));
1509 * Determines the location of the query range (chromosome positions) in a
1510 * different reference assembly.
1512 * If the range is just a subregion of one for which we already have a mapping
1513 * (for example, an exon sub-region of a gene), then the mapping is just
1514 * computed arithmetically.
1516 * Otherwise, calls the Ensembl REST service that maps from one assembly
1517 * reference's coordinates to another's
1520 * start-end chromosomal range in 'fromRef' coordinates
1524 * assembly reference for the query coordinates
1526 * assembly reference we wish to translate to
1527 * @return the start-end range in 'toRef' coordinates
1529 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
1530 String species, String fromRef, String toRef)
1533 * first try shorcut of computing the mapping as a subregion of one
1534 * we already have (e.g. for an exon, if we have the gene mapping)
1536 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
1537 species, fromRef, toRef);
1538 if (mappedRange != null)
1544 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
1546 EnsemblMap mapper = new EnsemblMap();
1547 int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
1550 if (mapping == null)
1552 // mapping service failure
1557 * save mapping for possible future re-use
1559 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1560 if (!assemblyMappings.containsKey(key))
1562 assemblyMappings.put(key, new HashMap<int[], int[]>());
1565 assemblyMappings.get(key).put(queryRange, mapping);
1571 * If we already have a 1:1 contiguous mapping which subsumes the given query
1572 * range, this method just calculates and returns the subset of that mapping,
1573 * else it returns null. In practical terms, if a gene has a contiguous
1574 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
1575 * subsidiary exons occupy unchanged relative positions, and just compute
1576 * these as offsets, rather than do another lookup of the mapping.
1578 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
1579 * simply remove this method or let it always return null.
1581 * Warning: many rapid calls to the /map service map result in a 429 overload
1591 protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
1592 String species, String fromRef, String toRef)
1594 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1595 if (assemblyMappings.containsKey(key))
1597 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
1598 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
1600 int[] fromRange = mappedRange.getKey();
1601 int[] toRange = mappedRange.getValue();
1602 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
1605 * mapping is 1:1 in length, so we trust it to have no discontinuities
1607 if (MappingUtils.rangeContains(fromRange, queryRange))
1610 * fromRange subsumes our query range
1612 int offset = queryRange[0] - fromRange[0];
1613 int mappedRangeFrom = toRange[0] + offset;
1614 int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
1615 return new int[] { mappedRangeFrom, mappedRangeTo };
1624 * Transfers the sequence feature to the target sequence, locating its start
1625 * and end range based on the mapping. Features which do not overlap the
1626 * target sequence are ignored.
1629 * @param targetSequence
1631 * mapping from the feature's coordinates to the target sequence
1633 protected void transferFeature(SequenceFeature sf,
1634 SequenceI targetSequence, MapList mapping)
1636 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1638 if (mappedRange != null)
1640 String group = sf.getFeatureGroup();
1641 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1642 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1643 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1644 group, sf.getScore());
1645 targetSequence.addSequenceFeature(copy);
1650 * Formats a ranges map lookup key
1658 protected static String makeRangesKey(String chromosome, String species,
1659 String fromRef, String toRef)
1661 return species + EXCL + chromosome + EXCL + fromRef + EXCL