2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.io.vcf;
23 import java.util.Locale;
26 import java.io.IOException;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.Iterator;
31 import java.util.List;
33 import java.util.Map.Entry;
35 import java.util.regex.Pattern;
36 import java.util.regex.PatternSyntaxException;
38 import htsjdk.samtools.SAMException;
39 import htsjdk.samtools.SAMSequenceDictionary;
40 import htsjdk.samtools.SAMSequenceRecord;
41 import htsjdk.samtools.util.CloseableIterator;
42 import htsjdk.tribble.TribbleException;
43 import htsjdk.variant.variantcontext.Allele;
44 import htsjdk.variant.variantcontext.VariantContext;
45 import htsjdk.variant.vcf.VCFConstants;
46 import htsjdk.variant.vcf.VCFHeader;
47 import htsjdk.variant.vcf.VCFHeaderLine;
48 import htsjdk.variant.vcf.VCFHeaderLineCount;
49 import htsjdk.variant.vcf.VCFHeaderLineType;
50 import htsjdk.variant.vcf.VCFInfoHeaderLine;
51 import jalview.analysis.Dna;
52 import jalview.api.AlignViewControllerGuiI;
53 import jalview.bin.Cache;
54 import jalview.bin.Console;
55 import jalview.datamodel.DBRefEntry;
56 import jalview.datamodel.GeneLociI;
57 import jalview.datamodel.Mapping;
58 import jalview.datamodel.SequenceFeature;
59 import jalview.datamodel.SequenceI;
60 import jalview.datamodel.features.FeatureAttributeType;
61 import jalview.datamodel.features.FeatureSource;
62 import jalview.datamodel.features.FeatureSources;
63 import jalview.ext.ensembl.EnsemblMap;
64 import jalview.ext.htsjdk.HtsContigDb;
65 import jalview.ext.htsjdk.VCFReader;
66 import jalview.io.gff.Gff3Helper;
67 import jalview.io.gff.SequenceOntologyI;
68 import jalview.util.MapList;
69 import jalview.util.MappingUtils;
70 import jalview.util.MessageManager;
71 import jalview.util.StringUtils;
74 * A class to read VCF data (using the htsjdk) and add variants as sequence
75 * features on dna and any related protein product sequences
79 public class VCFLoader
81 private static final String VCF_ENCODABLE = ":;=%,";
84 * Jalview feature attributes for VCF fixed column data
86 private static final String VCF_POS = "POS";
88 private static final String VCF_ID = "ID";
90 private static final String VCF_QUAL = "QUAL";
92 private static final String VCF_FILTER = "FILTER";
94 private static final String NO_VALUE = VCFConstants.MISSING_VALUE_v4; // '.'
96 private static final String DEFAULT_SPECIES = "homo_sapiens";
99 * A class to model the mapping from sequence to VCF coordinates. Cases
102 * <li>a direct 1:1 mapping where the sequence is one of the VCF contigs</li>
103 * <li>a mapping of sequence to chromosomal coordinates, where sequence and
104 * VCF use the same reference assembly</li>
105 * <li>a modified mapping of sequence to chromosomal coordinates, where
106 * sequence and VCF use different reference assembles</li>
111 final String chromosome;
115 VCFMap(String chr, MapList m)
122 public String toString()
124 return chromosome + ":" + map.toString();
129 * Lookup keys, and default values, for Preference entries that describe
130 * patterns for VCF and VEP fields to capture
132 private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
134 private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
136 private static final String DEFAULT_VCF_FIELDS = ".*";
138 private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
141 * Lookup keys, and default values, for Preference entries that give
142 * mappings from tokens in the 'reference' header to species or assembly
144 private static final String VCF_ASSEMBLY = "VCF_ASSEMBLY";
146 private static final String DEFAULT_VCF_ASSEMBLY = "assembly19=GRCh37,hs37=GRCh37,grch37=GRCh37,grch38=GRCh38";
148 private static final String VCF_SPECIES = "VCF_SPECIES"; // default is human
150 private static final String DEFAULT_REFERENCE = "grch37"; // fallback default
154 * keys to fields of VEP CSQ consequence data
155 * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
157 private static final String CSQ_CONSEQUENCE_KEY = "Consequence";
159 private static final String CSQ_ALLELE_KEY = "Allele";
161 private static final String CSQ_ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref),
164 private static final String CSQ_FEATURE_KEY = "Feature"; // Ensembl stable id
167 * default VCF INFO key for VEP consequence data
168 * NB this can be overridden running VEP with --vcf_info_field
169 * - we don't handle this case (require identifier to be CSQ)
171 private static final String CSQ_FIELD = "CSQ";
174 * separator for fields in consequence data is '|'
176 private static final String PIPE_REGEX = "\\|";
179 * delimiter that separates multiple consequence data blocks
181 private static final String COMMA = ",";
184 * the feature group assigned to a VCF variant in Jalview
186 private static final String FEATURE_GROUP_VCF = "VCF";
189 * internal delimiter used to build keys for assemblyMappings
192 private static final String EXCL = "!";
195 * the VCF file we are processing
197 protected String vcfFilePath;
200 * mappings between VCF and sequence reference assembly regions, as
201 * key = "species!chromosome!fromAssembly!toAssembly
202 * value = Map{fromRange, toRange}
204 private Map<String, Map<int[], int[]>> assemblyMappings;
206 private VCFReader reader;
209 * holds details of the VCF header lines (metadata)
211 private VCFHeader header;
214 * species (as a valid Ensembl term) the VCF is for
216 private String vcfSpecies;
219 * genome assembly version (as a valid Ensembl identifier) the VCF is for
221 private String vcfAssembly;
224 * a Dictionary of contigs (if present) referenced in the VCF file
226 private SAMSequenceDictionary dictionary;
229 * the position (0...) of field in each block of
230 * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
231 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
233 private int csqConsequenceFieldIndex = -1;
235 private int csqAlleleFieldIndex = -1;
237 private int csqAlleleNumberFieldIndex = -1;
239 private int csqFeatureFieldIndex = -1;
241 // todo the same fields for SnpEff ANN data if wanted
242 // see http://snpeff.sourceforge.net/SnpEff_manual.html#input
245 * a unique identifier under which to save metadata about feature
246 * attributes (selected INFO field data)
248 private String sourceId;
251 * The INFO IDs of data that is both present in the VCF file, and
252 * also matched by any filters for data of interest
254 List<String> vcfFieldsOfInterest;
257 * The field offsets and identifiers for VEP (CSQ) data that is both present
258 * in the VCF file, and also matched by any filters for data of interest
259 * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
261 Map<Integer, String> vepFieldsOfInterest;
264 * key:value for which rejected data has been seen
265 * (the error is logged only once for each combination)
267 private Set<String> badData;
270 * Constructor given a VCF file
274 public VCFLoader(String vcfFile)
279 } catch (IOException e)
282 .errPrintln("Error opening VCF file: " + e.getMessage());
285 // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
286 assemblyMappings = new HashMap<>();
290 * Starts a new thread to query and load VCF variant data on to the given
293 * This method is not thread safe - concurrent threads should use separate
294 * instances of this class.
299 public void loadVCF(SequenceI[] seqs, final AlignViewControllerGuiI gui)
303 gui.setStatus(MessageManager.getString("label.searching_vcf"));
311 VCFLoader.this.doLoad(seqs, gui);
317 * Reads the specified contig sequence and adds its VCF variants to it
320 * the id of a single sequence (contig) to load
323 public SequenceI loadVCFContig(String contig)
325 VCFHeaderLine headerLine = header
326 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
327 if (headerLine == null)
329 Console.error("VCF reference header not found");
332 String ref = headerLine.getValue();
333 if (ref.startsWith("file://"))
335 ref = ref.substring(7);
337 setSpeciesAndAssembly(ref);
339 SequenceI seq = null;
340 File dbFile = new File(ref);
344 HtsContigDb db = new HtsContigDb("", dbFile);
345 seq = db.getSequenceProxy(contig);
346 loadSequenceVCF(seq);
351 Console.error("VCF reference not found: " + ref);
358 * Loads VCF on to one or more sequences
362 * optional callback handler for messages
364 protected void doLoad(SequenceI[] seqs, AlignViewControllerGuiI gui)
368 VCFHeaderLine ref = header
369 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
370 String reference = ref == null ? null : ref.getValue();
372 setSpeciesAndAssembly(reference);
378 * query for VCF overlapping each sequence in turn
380 for (SequenceI seq : seqs)
382 int added = loadSequenceVCF(seq);
387 transferAddedFeatures(seq);
392 String msg = MessageManager.formatMessage("label.added_vcf",
395 if (gui.getFeatureSettingsUI() != null)
397 gui.getFeatureSettingsUI().discoverAllFeatureData();
400 } catch (Throwable e)
403 .errPrintln("Error processing VCF: " + e.getMessage());
407 gui.setStatus("Error occurred - see console for details");
416 } catch (IOException e)
427 * Attempts to determine and save the species and genome assembly version to
428 * which the VCF data applies. This may be done by parsing the
429 * {@code reference} header line, configured in a property file, or
430 * (potentially) confirmed interactively by the user.
432 * The saved values should be identifiers valid for Ensembl's REST service
433 * {@code map} endpoint, so they can be used (if necessary) to retrieve the
434 * mapping between VCF coordinates and sequence coordinates.
437 * @see https://rest.ensembl.org/documentation/info/assembly_map
438 * @see https://rest.ensembl.org/info/assembly/human?content-type=text/xml
439 * @see https://rest.ensembl.org/info/species?content-type=text/xml
441 protected void setSpeciesAndAssembly(String reference)
443 if (reference == null)
445 Console.error("No VCF ##reference found, defaulting to "
446 + DEFAULT_REFERENCE + ":" + DEFAULT_SPECIES);
447 reference = DEFAULT_REFERENCE; // default to GRCh37 if not specified
449 reference = reference.toLowerCase(Locale.ROOT);
452 * for a non-human species, or other assembly identifier,
453 * specify as a Jalview property file entry e.g.
454 * VCF_ASSEMBLY = hs37=GRCh37,assembly19=GRCh37
455 * VCF_SPECIES = c_elegans=celegans
456 * to map a token in the reference header to a value
458 String prop = Cache.getDefault(VCF_ASSEMBLY, DEFAULT_VCF_ASSEMBLY);
459 for (String token : prop.split(","))
461 String[] tokens = token.split("=");
462 if (tokens.length == 2)
464 if (reference.contains(tokens[0].trim().toLowerCase(Locale.ROOT)))
466 vcfAssembly = tokens[1].trim();
472 vcfSpecies = DEFAULT_SPECIES;
473 prop = Cache.getProperty(VCF_SPECIES);
476 for (String token : prop.split(","))
478 String[] tokens = token.split("=");
479 if (tokens.length == 2)
481 if (reference.contains(tokens[0].trim().toLowerCase(Locale.ROOT)))
483 vcfSpecies = tokens[1].trim();
492 * Opens the VCF file and parses header data
495 * @throws IOException
497 private void initialise(String filePath) throws IOException
499 vcfFilePath = filePath;
501 reader = new VCFReader(filePath);
503 header = reader.getFileHeader();
507 dictionary = header.getSequenceDictionary();
508 } catch (SAMException e)
510 // ignore - thrown if any contig line lacks length info
515 saveMetadata(sourceId);
518 * get offset of CSQ ALLELE_NUM and Feature if declared
524 * Reads metadata (such as INFO field descriptions and datatypes) and saves
525 * them for future reference
529 void saveMetadata(String theSourceId)
531 List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
533 vcfFieldsOfInterest = new ArrayList<>();
535 FeatureSource metadata = new FeatureSource(theSourceId);
537 for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
539 String attributeId = info.getID();
540 String desc = info.getDescription();
541 VCFHeaderLineType type = info.getType();
542 FeatureAttributeType attType = null;
546 attType = FeatureAttributeType.Character;
549 attType = FeatureAttributeType.Flag;
552 attType = FeatureAttributeType.Float;
555 attType = FeatureAttributeType.Integer;
558 attType = FeatureAttributeType.String;
561 metadata.setAttributeName(attributeId, desc);
562 metadata.setAttributeType(attributeId, attType);
564 if (isFieldWanted(attributeId, vcfFieldPatterns))
566 vcfFieldsOfInterest.add(attributeId);
570 FeatureSources.getInstance().addSource(theSourceId, metadata);
574 * Answers true if the field id is matched by any of the filter patterns, else
575 * false. Matching is against regular expression patterns, and is not
582 private boolean isFieldWanted(String id, List<Pattern> filters)
584 for (Pattern p : filters)
586 if (p.matcher(id.toUpperCase(Locale.ROOT)).matches())
595 * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
596 * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
597 * required for processing.
599 * CSQ fields are declared in the CSQ INFO Description e.g.
601 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
603 protected void parseCsqHeader()
605 List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
607 vepFieldsOfInterest = new HashMap<>();
609 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
616 * parse out the pipe-separated list of CSQ fields; we assume here that
617 * these form the last part of the description, and contain no spaces
619 String desc = csqInfo.getDescription();
620 int spacePos = desc.lastIndexOf(" ");
621 desc = desc.substring(spacePos + 1);
625 String[] format = desc.split(PIPE_REGEX);
627 for (String field : format)
629 if (CSQ_CONSEQUENCE_KEY.equals(field))
631 csqConsequenceFieldIndex = index;
633 if (CSQ_ALLELE_NUM_KEY.equals(field))
635 csqAlleleNumberFieldIndex = index;
637 if (CSQ_ALLELE_KEY.equals(field))
639 csqAlleleFieldIndex = index;
641 if (CSQ_FEATURE_KEY.equals(field))
643 csqFeatureFieldIndex = index;
646 if (isFieldWanted(field, vepFieldFilters))
648 vepFieldsOfInterest.put(index, field);
657 * Reads the Preference value for the given key, with default specified if no
658 * preference set. The value is interpreted as a comma-separated list of
659 * regular expressions, and converted into a list of compiled patterns ready
660 * for matching. Patterns are forced to upper-case for non-case-sensitive
663 * This supports user-defined filters for fields of interest to capture while
664 * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
665 * fields with an ID of AF, or starting with AC, would be matched.
671 private List<Pattern> getFieldMatchers(String key, String def)
673 String pref = Cache.getDefault(key, def);
674 List<Pattern> patterns = new ArrayList<>();
675 String[] tokens = pref.split(",");
676 for (String token : tokens)
680 patterns.add(Pattern.compile(token.toUpperCase(Locale.ROOT)));
681 } catch (PatternSyntaxException e)
683 jalview.bin.Console.errPrintln("Invalid pattern ignored: " + token);
690 * Transfers VCF features to sequences to which this sequence has a mapping.
694 protected void transferAddedFeatures(SequenceI seq)
696 List<DBRefEntry> dbrefs = seq.getDBRefs();
701 for (DBRefEntry dbref : dbrefs)
703 Mapping mapping = dbref.getMap();
704 if (mapping == null || mapping.getTo() == null)
709 SequenceI mapTo = mapping.getTo();
710 MapList map = mapping.getMap();
711 if (map.getFromRatio() == 3)
714 * dna-to-peptide product mapping
716 // JAL-3187 render on the fly instead
717 // AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
722 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
724 List<SequenceFeature> features = seq.getFeatures()
725 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
726 for (SequenceFeature sf : features)
728 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
730 transferFeature(sf, mapTo, map);
738 * Tries to add overlapping variants read from a VCF file to the given
739 * sequence, and returns the number of variant features added
744 protected int loadSequenceVCF(SequenceI seq)
746 VCFMap vcfMap = getVcfMap(seq);
753 * work with the dataset sequence here
755 SequenceI dss = seq.getDatasetSequence();
760 return addVcfVariants(dss, vcfMap);
764 * Answers a map from sequence coordinates to VCF chromosome ranges
769 private VCFMap getVcfMap(SequenceI seq)
772 * simplest case: sequence has id and length matching a VCF contig
774 VCFMap vcfMap = null;
775 if (dictionary != null)
777 vcfMap = getContigMap(seq);
785 * otherwise, map to VCF from chromosomal coordinates
786 * of the sequence (if known)
788 GeneLociI seqCoords = seq.getGeneLoci();
789 if (seqCoords == null)
791 Console.warn(String.format(
792 "Can't query VCF for %s as chromosome coordinates not known",
797 String species = seqCoords.getSpeciesId();
798 String chromosome = seqCoords.getChromosomeId();
799 String seqRef = seqCoords.getAssemblyId();
800 MapList map = seqCoords.getMapping();
802 // note this requires the configured species to match that
803 // returned with the Ensembl sequence; todo: support aliases?
804 if (!vcfSpecies.equalsIgnoreCase(species))
806 Console.warn("No VCF loaded to " + seq.getName()
807 + " as species not matched");
811 if (seqRef.equalsIgnoreCase(vcfAssembly))
813 return new VCFMap(chromosome, map);
817 * VCF data has a different reference assembly to the sequence:
818 * query Ensembl to map chromosomal coordinates from sequence to VCF
820 List<int[]> toVcfRanges = new ArrayList<>();
821 List<int[]> fromSequenceRanges = new ArrayList<>();
823 for (int[] range : map.getToRanges())
825 int[] fromRange = map.locateInFrom(range[0], range[1]);
826 if (fromRange == null)
832 int[] newRange = mapReferenceRange(range, chromosome, "human", seqRef,
834 if (newRange == null)
836 Console.error(String.format("Failed to map %s:%s:%s:%d:%d to %s",
837 species, chromosome, seqRef, range[0], range[1],
843 toVcfRanges.add(newRange);
844 fromSequenceRanges.add(fromRange);
848 return new VCFMap(chromosome,
849 new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
853 * If the sequence id matches a contig declared in the VCF file, and the
854 * sequence length matches the contig length, then returns a 1:1 map of the
855 * sequence to the contig, else returns null
860 private VCFMap getContigMap(SequenceI seq)
862 String id = seq.getName();
863 SAMSequenceRecord contig = dictionary.getSequence(id);
866 int len = seq.getLength();
867 if (len == contig.getSequenceLength())
869 MapList map = new MapList(new int[] { 1, len },
872 return new VCFMap(id, map);
879 * Queries the VCF reader for any variants that overlap the mapped chromosome
880 * ranges of the sequence, and adds as variant features. Returns the number of
881 * overlapping variants found.
885 * mapping from sequence to VCF coordinates
888 protected int addVcfVariants(SequenceI seq, VCFMap map)
890 boolean forwardStrand = map.map.isToForwardStrand();
893 * query the VCF for overlaps of each contiguous chromosomal region
897 for (int[] range : map.map.getToRanges())
899 int vcfStart = Math.min(range[0], range[1]);
900 int vcfEnd = Math.max(range[0], range[1]);
903 CloseableIterator<VariantContext> variants = reader
904 .query(map.chromosome, vcfStart, vcfEnd);
905 while (variants.hasNext())
907 VariantContext variant = variants.next();
909 int[] featureRange = map.map.locateInFrom(variant.getStart(),
913 * only take features whose range is fully mappable to sequence positions
915 if (featureRange != null)
917 int featureStart = Math.min(featureRange[0], featureRange[1]);
918 int featureEnd = Math.max(featureRange[0], featureRange[1]);
919 if (featureEnd - featureStart == variant.getEnd()
920 - variant.getStart())
922 count += addAlleleFeatures(seq, variant, featureStart,
923 featureEnd, forwardStrand);
928 } catch (TribbleException e)
931 * RuntimeException throwable by htsjdk
933 String msg = String.format("Error reading VCF for %s:%d-%d: %s ",
934 map.chromosome, vcfStart, vcfEnd, e.getLocalizedMessage());
943 * A convenience method to get an attribute value for an alternate allele
946 * @param attributeName
950 protected String getAttributeValue(VariantContext variant,
951 String attributeName, int alleleIndex)
953 Object att = variant.getAttribute(attributeName);
955 if (att instanceof String)
959 else if (att instanceof ArrayList)
961 return ((List<String>) att).get(alleleIndex);
968 * Adds one variant feature for each allele in the VCF variant record, and
969 * returns the number of features added.
973 * @param featureStart
975 * @param forwardStrand
978 protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
979 int featureStart, int featureEnd, boolean forwardStrand)
984 * Javadoc says getAlternateAlleles() imposes no order on the list returned
985 * so we proceed defensively to get them in strict order
987 int altAlleleCount = variant.getAlternateAlleles().size();
988 for (int i = 0; i < altAlleleCount; i++)
990 added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
997 * Inspects one allele and attempts to add a variant feature for it to the
998 * sequence. The additional data associated with this allele is extracted to
999 * store in the feature's key-value map. Answers the number of features added
1004 * @param altAlleleIndex
1006 * @param featureStart
1008 * @param forwardStrand
1011 protected int addAlleleFeature(SequenceI seq, VariantContext variant,
1012 int altAlleleIndex, int featureStart, int featureEnd,
1013 boolean forwardStrand)
1015 String reference = variant.getReference().getBaseString();
1016 Allele alt = variant.getAlternateAllele(altAlleleIndex);
1017 String allele = alt.getBaseString();
1020 * insertion after a genomic base, if on reverse strand, has to be
1021 * converted to insertion of complement after the preceding position
1023 int referenceLength = reference.length();
1024 if (!forwardStrand && allele.length() > referenceLength
1025 && allele.startsWith(reference))
1027 featureStart -= referenceLength;
1028 featureEnd = featureStart;
1029 char insertAfter = seq.getCharAt(featureStart - seq.getStart());
1030 reference = Dna.reverseComplement(String.valueOf(insertAfter));
1031 allele = allele.substring(referenceLength) + reference;
1035 * build the ref,alt allele description e.g. "G,A", using the base
1036 * complement if the sequence is on the reverse strand
1038 StringBuilder sb = new StringBuilder();
1039 sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
1041 sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
1042 String alleles = sb.toString(); // e.g. G,A
1045 * pick out the consequence data (if any) that is for the current allele
1046 * and feature (transcript) that matches the current sequence
1048 String consequence = getConsequenceForAlleleAndFeature(variant,
1049 CSQ_FIELD, altAlleleIndex, csqAlleleFieldIndex,
1050 csqAlleleNumberFieldIndex,
1051 seq.getName().toLowerCase(Locale.ROOT), csqFeatureFieldIndex);
1054 * pick out the ontology term for the consequence type
1056 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1057 if (consequence != null)
1059 type = getOntologyTerm(consequence);
1062 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
1063 featureEnd, FEATURE_GROUP_VCF);
1064 sf.setSource(sourceId);
1067 * save the derived alleles as a named attribute; this will be
1068 * needed when Jalview computes derived peptide variants
1070 addFeatureAttribute(sf, Gff3Helper.ALLELES, alleles);
1073 * add selected VCF fixed column data as feature attributes
1075 addFeatureAttribute(sf, VCF_POS, String.valueOf(variant.getStart()));
1076 addFeatureAttribute(sf, VCF_ID, variant.getID());
1077 addFeatureAttribute(sf, VCF_QUAL,
1078 String.valueOf(variant.getPhredScaledQual()));
1079 addFeatureAttribute(sf, VCF_FILTER, getFilter(variant));
1081 addAlleleProperties(variant, sf, altAlleleIndex, consequence);
1083 seq.addSequenceFeature(sf);
1089 * Answers the VCF FILTER value for the variant - or an approximation to it.
1090 * This field is either PASS, or a semi-colon separated list of filters not
1091 * passed. htsjdk saves filters as a HashSet, so the order when reassembled
1092 * into a list may be different.
1097 String getFilter(VariantContext variant)
1099 Set<String> filters = variant.getFilters();
1100 if (filters.isEmpty())
1104 Iterator<String> iterator = filters.iterator();
1105 String first = iterator.next();
1106 if (filters.size() == 1)
1111 StringBuilder sb = new StringBuilder(first);
1112 while (iterator.hasNext())
1114 sb.append(";").append(iterator.next());
1117 return sb.toString();
1121 * Adds one feature attribute unless the value is null, empty or '.'
1127 void addFeatureAttribute(SequenceFeature sf, String key, String value)
1129 if (value != null && !value.isEmpty() && !NO_VALUE.equals(value))
1131 sf.setValue(key, value);
1136 * Determines the Sequence Ontology term to use for the variant feature type
1137 * in Jalview. The default is 'sequence_variant', but a more specific term is
1140 * <li>VEP (or SnpEff) Consequence annotation is included in the VCF</li>
1141 * <li>sequence id can be matched to VEP Feature (or SnpEff Feature_ID)</li>
1144 * @param consequence
1146 * @see http://www.sequenceontology.org/browser/current_svn/term/SO:0001060
1148 String getOntologyTerm(String consequence)
1150 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1153 * could we associate Consequence data with this allele and feature (transcript)?
1154 * if so, prefer the consequence term from that data
1156 if (csqAlleleFieldIndex == -1) // && snpEffAlleleFieldIndex == -1
1159 * no Consequence data so we can't refine the ontology term
1164 if (consequence != null)
1166 String[] csqFields = consequence.split(PIPE_REGEX);
1167 if (csqFields.length > csqConsequenceFieldIndex)
1169 type = csqFields[csqConsequenceFieldIndex];
1174 // todo the same for SnpEff consequence data matching if wanted
1178 * if of the form (e.g.) missense_variant&splice_region_variant,
1179 * just take the first ('most severe') consequence
1183 int pos = type.indexOf('&');
1186 type = type.substring(0, pos);
1193 * Returns matched consequence data if it can be found, else null.
1195 * <li>inspects the VCF data for key 'vcfInfoId'</li>
1196 * <li>splits this on comma (to distinct consequences)</li>
1197 * <li>returns the first consequence (if any) where</li>
1199 * <li>the allele matches the altAlleleIndex'th allele of variant</li>
1200 * <li>the feature matches the sequence name (e.g. transcript id)</li>
1203 * If matched, the consequence is returned (as pipe-delimited fields).
1207 * @param altAlleleIndex
1208 * @param alleleFieldIndex
1209 * @param alleleNumberFieldIndex
1211 * @param featureFieldIndex
1214 private String getConsequenceForAlleleAndFeature(VariantContext variant,
1215 String vcfInfoId, int altAlleleIndex, int alleleFieldIndex,
1216 int alleleNumberFieldIndex, String seqName, int featureFieldIndex)
1218 if (alleleFieldIndex == -1 || featureFieldIndex == -1)
1222 Object value = variant.getAttribute(vcfInfoId);
1224 if (value == null || !(value instanceof List<?>))
1230 * inspect each consequence in turn (comma-separated blocks
1231 * extracted by htsjdk)
1233 List<String> consequences = (List<String>) value;
1235 for (String consequence : consequences)
1237 String[] csqFields = consequence.split(PIPE_REGEX);
1238 if (csqFields.length > featureFieldIndex)
1240 String featureIdentifier = csqFields[featureFieldIndex];
1241 if (featureIdentifier.length() > 4 && seqName
1242 .indexOf(featureIdentifier.toLowerCase(Locale.ROOT)) > -1)
1245 * feature (transcript) matched - now check for allele match
1247 if (matchAllele(variant, altAlleleIndex, csqFields,
1248 alleleFieldIndex, alleleNumberFieldIndex))
1258 private boolean matchAllele(VariantContext variant, int altAlleleIndex,
1259 String[] csqFields, int alleleFieldIndex,
1260 int alleleNumberFieldIndex)
1263 * if ALLELE_NUM is present, it must match altAlleleIndex
1264 * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1266 if (alleleNumberFieldIndex > -1)
1268 if (csqFields.length <= alleleNumberFieldIndex)
1272 String alleleNum = csqFields[alleleNumberFieldIndex];
1273 return String.valueOf(altAlleleIndex + 1).equals(alleleNum);
1277 * else consequence allele must match variant allele
1279 if (alleleFieldIndex > -1 && csqFields.length > alleleFieldIndex)
1281 String csqAllele = csqFields[alleleFieldIndex];
1282 String vcfAllele = variant.getAlternateAllele(altAlleleIndex)
1284 return csqAllele.equals(vcfAllele);
1290 * Add any allele-specific VCF key-value data to the sequence feature
1294 * @param altAlelleIndex
1296 * @param consequence
1297 * if not null, the consequence specific to this sequence (transcript
1298 * feature) and allele
1300 protected void addAlleleProperties(VariantContext variant,
1301 SequenceFeature sf, final int altAlelleIndex, String consequence)
1303 Map<String, Object> atts = variant.getAttributes();
1305 for (Entry<String, Object> att : atts.entrySet())
1307 String key = att.getKey();
1310 * extract Consequence data (if present) that we are able to
1311 * associated with the allele for this variant feature
1313 if (CSQ_FIELD.equals(key))
1315 addConsequences(variant, sf, consequence);
1320 * filter out fields we don't want to capture
1322 if (!vcfFieldsOfInterest.contains(key))
1328 * we extract values for other data which are allele-specific;
1329 * these may be per alternate allele (INFO[key].Number = 'A')
1330 * or per allele including reference (INFO[key].Number = 'R')
1332 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
1333 if (infoHeader == null)
1336 * can't be sure what data belongs to this allele, so
1337 * play safe and don't take any
1342 VCFHeaderLineCount number = infoHeader.getCountType();
1343 int index = altAlelleIndex;
1344 if (number == VCFHeaderLineCount.R)
1347 * one value per allele including reference, so bump index
1348 * e.g. the 3rd value is for the 2nd alternate allele
1352 else if (number != VCFHeaderLineCount.A)
1355 * don't save other values as not allele-related
1361 * take the index'th value
1363 String value = getAttributeValue(variant, key, index);
1364 if (value != null && isValid(variant, key, value))
1367 * decode colon, semicolon, equals sign, percent sign, comma (only)
1368 * as required by the VCF specification (para 1.2)
1370 value = StringUtils.urlDecode(value, VCF_ENCODABLE);
1371 addFeatureAttribute(sf, key, value);
1377 * Answers true for '.', null, or an empty value, or if the INFO type is
1378 * String. If the INFO type is Integer or Float, answers false if the value is
1379 * not in valid format.
1386 protected boolean isValid(VariantContext variant, String infoId,
1389 if (value == null || value.isEmpty() || NO_VALUE.equals(value))
1393 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(infoId);
1394 if (infoHeader == null)
1396 Console.error("Field " + infoId + " has no INFO header");
1399 VCFHeaderLineType infoType = infoHeader.getType();
1402 if (infoType == VCFHeaderLineType.Integer)
1404 Integer.parseInt(value);
1406 else if (infoType == VCFHeaderLineType.Float)
1408 Float.parseFloat(value);
1410 } catch (NumberFormatException e)
1412 logInvalidValue(variant, infoId, value);
1419 * Logs an error message for malformed data; duplicate messages (same id and
1420 * value) are not logged
1426 private void logInvalidValue(VariantContext variant, String infoId,
1429 if (badData == null)
1431 badData = new HashSet<>();
1433 String token = infoId + ":" + value;
1434 if (!badData.contains(token))
1437 Console.error(String.format("Invalid VCF data at %s:%d %s=%s",
1438 variant.getContig(), variant.getStart(), infoId, value));
1443 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
1446 * If <code>myConsequence</code> is not null, then this is the specific
1447 * consequence data (pipe-delimited fields) that is for the current allele and
1448 * transcript (sequence) being processed)
1452 * @param myConsequence
1454 protected void addConsequences(VariantContext variant, SequenceFeature sf,
1455 String myConsequence)
1457 Object value = variant.getAttribute(CSQ_FIELD);
1459 if (value == null || !(value instanceof List<?>))
1464 List<String> consequences = (List<String>) value;
1467 * inspect CSQ consequences; restrict to the consequence
1468 * associated with the current transcript (Feature)
1470 Map<String, String> csqValues = new HashMap<>();
1472 for (String consequence : consequences)
1474 if (myConsequence == null || myConsequence.equals(consequence))
1476 String[] csqFields = consequence.split(PIPE_REGEX);
1479 * inspect individual fields of this consequence, copying non-null
1480 * values which are 'fields of interest'
1483 for (String field : csqFields)
1485 if (field != null && field.length() > 0)
1487 String id = vepFieldsOfInterest.get(i);
1491 * VCF spec requires encoding of special characters e.g. '='
1492 * so decode them here before storing
1494 field = StringUtils.urlDecode(field, VCF_ENCODABLE);
1495 csqValues.put(id, field);
1503 if (!csqValues.isEmpty())
1505 sf.setValue(CSQ_FIELD, csqValues);
1510 * A convenience method to complement a dna base and return the string value
1516 protected String complement(byte[] reference)
1518 return String.valueOf(Dna.getComplement((char) reference[0]));
1522 * Determines the location of the query range (chromosome positions) in a
1523 * different reference assembly.
1525 * If the range is just a subregion of one for which we already have a mapping
1526 * (for example, an exon sub-region of a gene), then the mapping is just
1527 * computed arithmetically.
1529 * Otherwise, calls the Ensembl REST service that maps from one assembly
1530 * reference's coordinates to another's
1533 * start-end chromosomal range in 'fromRef' coordinates
1537 * assembly reference for the query coordinates
1539 * assembly reference we wish to translate to
1540 * @return the start-end range in 'toRef' coordinates
1542 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
1543 String species, String fromRef, String toRef)
1546 * first try shorcut of computing the mapping as a subregion of one
1547 * we already have (e.g. for an exon, if we have the gene mapping)
1549 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
1550 species, fromRef, toRef);
1551 if (mappedRange != null)
1557 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
1559 EnsemblMap mapper = new EnsemblMap();
1560 int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
1563 if (mapping == null)
1565 // mapping service failure
1570 * save mapping for possible future re-use
1572 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1573 if (!assemblyMappings.containsKey(key))
1575 assemblyMappings.put(key, new HashMap<int[], int[]>());
1578 assemblyMappings.get(key).put(queryRange, mapping);
1584 * If we already have a 1:1 contiguous mapping which subsumes the given query
1585 * range, this method just calculates and returns the subset of that mapping,
1586 * else it returns null. In practical terms, if a gene has a contiguous
1587 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
1588 * subsidiary exons occupy unchanged relative positions, and just compute
1589 * these as offsets, rather than do another lookup of the mapping.
1591 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
1592 * simply remove this method or let it always return null.
1594 * Warning: many rapid calls to the /map service map result in a 429 overload
1604 protected int[] findSubsumedRangeMapping(int[] queryRange,
1605 String chromosome, String species, String fromRef, String toRef)
1607 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1608 if (assemblyMappings.containsKey(key))
1610 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
1611 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
1613 int[] fromRange = mappedRange.getKey();
1614 int[] toRange = mappedRange.getValue();
1615 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
1618 * mapping is 1:1 in length, so we trust it to have no discontinuities
1620 if (MappingUtils.rangeContains(fromRange, queryRange))
1623 * fromRange subsumes our query range
1625 int offset = queryRange[0] - fromRange[0];
1626 int mappedRangeFrom = toRange[0] + offset;
1627 int mappedRangeTo = mappedRangeFrom
1628 + (queryRange[1] - queryRange[0]);
1629 return new int[] { mappedRangeFrom, mappedRangeTo };
1638 * Transfers the sequence feature to the target sequence, locating its start
1639 * and end range based on the mapping. Features which do not overlap the
1640 * target sequence are ignored.
1643 * @param targetSequence
1645 * mapping from the feature's coordinates to the target sequence
1647 protected void transferFeature(SequenceFeature sf,
1648 SequenceI targetSequence, MapList mapping)
1650 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1652 if (mappedRange != null)
1654 String group = sf.getFeatureGroup();
1655 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1656 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1657 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1658 group, sf.getScore());
1659 targetSequence.addSequenceFeature(copy);
1664 * Formats a ranges map lookup key
1672 protected static String makeRangesKey(String chromosome, String species,
1673 String fromRef, String toRef)
1675 return species + EXCL + chromosome + EXCL + fromRef + EXCL + toRef;