1 package jalview.io.vcf;
3 import jalview.analysis.Dna;
4 import jalview.api.AlignViewControllerGuiI;
5 import jalview.bin.Cache;
6 import jalview.datamodel.DBRefEntry;
7 import jalview.datamodel.GeneLociI;
8 import jalview.datamodel.Mapping;
9 import jalview.datamodel.SequenceFeature;
10 import jalview.datamodel.SequenceI;
11 import jalview.datamodel.features.FeatureAttributeType;
12 import jalview.datamodel.features.FeatureSource;
13 import jalview.datamodel.features.FeatureSources;
14 import jalview.ext.ensembl.EnsemblMap;
15 import jalview.ext.htsjdk.HtsContigDb;
16 import jalview.ext.htsjdk.VCFReader;
17 import jalview.io.gff.Gff3Helper;
18 import jalview.io.gff.SequenceOntologyI;
19 import jalview.util.MapList;
20 import jalview.util.MappingUtils;
21 import jalview.util.MessageManager;
22 import jalview.util.StringUtils;
25 import java.io.IOException;
26 import java.io.UnsupportedEncodingException;
27 import java.net.URLDecoder;
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.Iterator;
32 import java.util.List;
34 import java.util.Map.Entry;
36 import java.util.regex.Pattern;
37 import java.util.regex.PatternSyntaxException;
39 import htsjdk.samtools.SAMException;
40 import htsjdk.samtools.SAMSequenceDictionary;
41 import htsjdk.samtools.SAMSequenceRecord;
42 import htsjdk.samtools.util.CloseableIterator;
43 import htsjdk.tribble.TribbleException;
44 import htsjdk.variant.variantcontext.Allele;
45 import htsjdk.variant.variantcontext.VariantContext;
46 import htsjdk.variant.vcf.VCFConstants;
47 import htsjdk.variant.vcf.VCFHeader;
48 import htsjdk.variant.vcf.VCFHeaderLine;
49 import htsjdk.variant.vcf.VCFHeaderLineCount;
50 import htsjdk.variant.vcf.VCFHeaderLineType;
51 import htsjdk.variant.vcf.VCFInfoHeaderLine;
54 * A class to read VCF data (using the htsjdk) and add variants as sequence
55 * features on dna and any related protein product sequences
59 public class VCFLoader
61 private static final String ENCODED_COMMA = "%2C";
63 private static final String ENCODED_PERCENT = "%25";
65 private static final String ENCODED_EQUALS = "%3D";
67 private static final String ENCODED_SEMICOLON = "%3B";
69 private static final String ENCODED_COLON = "%3A";
71 private static final String UTF_8 = "UTF-8";
74 * Jalview feature attributes for VCF fixed column data
76 private static final String VCF_POS = "POS";
78 private static final String VCF_ID = "ID";
80 private static final String VCF_QUAL = "QUAL";
82 private static final String VCF_FILTER = "FILTER";
84 private static final String NO_VALUE = VCFConstants.MISSING_VALUE_v4; // '.'
86 private static final String DEFAULT_SPECIES = "homo_sapiens";
89 * A class to model the mapping from sequence to VCF coordinates. Cases include
91 * <li>a direct 1:1 mapping where the sequence is one of the VCF contigs</li>
92 * <li>a mapping of sequence to chromosomal coordinates, where sequence and VCF
93 * use the same reference assembly</li>
94 * <li>a modified mapping of sequence to chromosomal coordinates, where sequence
95 * and VCF use different reference assembles</li>
100 final String chromosome;
104 VCFMap(String chr, MapList m)
111 public String toString()
113 return chromosome + ":" + map.toString();
118 * Lookup keys, and default values, for Preference entries that describe
119 * patterns for VCF and VEP fields to capture
121 private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
123 private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
125 private static final String DEFAULT_VCF_FIELDS = ".*";
127 private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
130 * Lookup keys, and default values, for Preference entries that give
131 * mappings from tokens in the 'reference' header to species or assembly
133 private static final String VCF_ASSEMBLY = "VCF_ASSEMBLY";
135 private static final String DEFAULT_VCF_ASSEMBLY = "assembly19=GRCh37,hs37=GRCh37,grch37=GRCh37,grch38=GRCh38";
137 private static final String VCF_SPECIES = "VCF_SPECIES"; // default is human
139 private static final String DEFAULT_REFERENCE = "grch37"; // fallback default is human GRCh37
142 * keys to fields of VEP CSQ consequence data
143 * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
145 private static final String CSQ_CONSEQUENCE_KEY = "Consequence";
146 private static final String CSQ_ALLELE_KEY = "Allele";
147 private static final String CSQ_ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref), 1...
148 private static final String CSQ_FEATURE_KEY = "Feature"; // Ensembl stable id
151 * default VCF INFO key for VEP consequence data
152 * NB this can be overridden running VEP with --vcf_info_field
153 * - we don't handle this case (require identifier to be CSQ)
155 private static final String CSQ_FIELD = "CSQ";
158 * separator for fields in consequence data is '|'
160 private static final String PIPE_REGEX = "\\|";
163 * delimiter that separates multiple consequence data blocks
165 private static final String COMMA = ",";
168 * the feature group assigned to a VCF variant in Jalview
170 private static final String FEATURE_GROUP_VCF = "VCF";
173 * internal delimiter used to build keys for assemblyMappings
176 private static final String EXCL = "!";
179 * the VCF file we are processing
181 protected String vcfFilePath;
184 * mappings between VCF and sequence reference assembly regions, as
185 * key = "species!chromosome!fromAssembly!toAssembly
186 * value = Map{fromRange, toRange}
188 private Map<String, Map<int[], int[]>> assemblyMappings;
190 private VCFReader reader;
193 * holds details of the VCF header lines (metadata)
195 private VCFHeader header;
198 * species (as a valid Ensembl term) the VCF is for
200 private String vcfSpecies;
203 * genome assembly version (as a valid Ensembl identifier) the VCF is for
205 private String vcfAssembly;
208 * a Dictionary of contigs (if present) referenced in the VCF file
210 private SAMSequenceDictionary dictionary;
213 * the position (0...) of field in each block of
214 * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
215 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
217 private int csqConsequenceFieldIndex = -1;
218 private int csqAlleleFieldIndex = -1;
219 private int csqAlleleNumberFieldIndex = -1;
220 private int csqFeatureFieldIndex = -1;
222 // todo the same fields for SnpEff ANN data if wanted
223 // see http://snpeff.sourceforge.net/SnpEff_manual.html#input
226 * a unique identifier under which to save metadata about feature
227 * attributes (selected INFO field data)
229 private String sourceId;
232 * The INFO IDs of data that is both present in the VCF file, and
233 * also matched by any filters for data of interest
235 List<String> vcfFieldsOfInterest;
238 * The field offsets and identifiers for VEP (CSQ) data that is both present
239 * in the VCF file, and also matched by any filters for data of interest
240 * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
242 Map<Integer, String> vepFieldsOfInterest;
245 * key:value for which rejected data has been seen
246 * (the error is logged only once for each combination)
248 private Set<String> badData;
251 * Constructor given a path to a VCF file
255 public VCFLoader(String vcfFile)
260 } catch (IOException e)
262 System.err.println("Error opening VCF file: " + e.getMessage());
265 // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
266 assemblyMappings = new HashMap<>();
270 * Starts a new thread to query and load VCF variant data on to the given
273 * This method is not thread safe - concurrent threads should use separate
274 * instances of this class.
279 public void loadVCF(SequenceI[] seqs, final AlignViewControllerGuiI gui)
283 gui.setStatus(MessageManager.getString("label.searching_vcf"));
291 VCFLoader.this.doLoad(seqs, gui);
297 * Reads the specified contig sequence and adds its VCF variants to it
300 * the id of a single sequence (contig) to load
303 public SequenceI loadVCFContig(String contig)
305 VCFHeaderLine headerLine = header.getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
306 if (headerLine == null)
308 Cache.log.error("VCF reference header not found");
311 String ref = headerLine.getValue();
312 if (ref.startsWith("file://"))
314 ref = ref.substring(7);
316 setSpeciesAndAssembly(ref);
318 SequenceI seq = null;
319 File dbFile = new File(ref);
323 HtsContigDb db = new HtsContigDb("", dbFile);
324 seq = db.getSequenceProxy(contig);
325 loadSequenceVCF(seq);
330 Cache.log.error("VCF reference not found: " + ref);
337 * Loads VCF on to one or more sequences
341 * optional callback handler for messages
343 protected void doLoad(SequenceI[] seqs, AlignViewControllerGuiI gui)
347 VCFHeaderLine ref = header
348 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
349 String reference = ref == null ? null : ref.getValue();
351 setSpeciesAndAssembly(reference);
357 * query for VCF overlapping each sequence in turn
359 for (SequenceI seq : seqs)
361 int added = loadSequenceVCF(seq);
366 transferAddedFeatures(seq);
371 String msg = MessageManager.formatMessage("label.added_vcf",
374 if (gui.getFeatureSettingsUI() != null)
376 gui.getFeatureSettingsUI().discoverAllFeatureData();
379 } catch (Throwable e)
381 System.err.println("Error processing VCF: " + e.getMessage());
385 gui.setStatus("Error occurred - see console for details");
394 } catch (IOException e)
405 * Attempts to determine and save the species and genome assembly version to
406 * which the VCF data applies. This may be done by parsing the {@code reference}
407 * header line, configured in a property file, or (potentially) confirmed
408 * interactively by the user.
410 * The saved values should be identifiers valid for Ensembl's REST service
411 * {@code map} endpoint, so they can be used (if necessary) to retrieve the
412 * mapping between VCF coordinates and sequence coordinates.
415 * @see https://rest.ensembl.org/documentation/info/assembly_map
416 * @see https://rest.ensembl.org/info/assembly/human?content-type=text/xml
417 * @see https://rest.ensembl.org/info/species?content-type=text/xml
419 protected void setSpeciesAndAssembly(String reference)
421 if (reference == null)
423 Cache.log.error("No VCF ##reference found, defaulting to "
424 + DEFAULT_REFERENCE + ":" + DEFAULT_SPECIES);
425 reference = DEFAULT_REFERENCE; // default to GRCh37 if not specified
427 reference = reference.toLowerCase();
430 * for a non-human species, or other assembly identifier,
431 * specify as a Jalview property file entry e.g.
432 * VCF_ASSEMBLY = hs37=GRCh37,assembly19=GRCh37
433 * VCF_SPECIES = c_elegans=celegans
434 * to map a token in the reference header to a value
436 String prop = Cache.getDefault(VCF_ASSEMBLY, DEFAULT_VCF_ASSEMBLY);
437 for (String token : prop.split(","))
439 String[] tokens = token.split("=");
440 if (tokens.length == 2)
442 if (reference.contains(tokens[0].trim().toLowerCase()))
444 vcfAssembly = tokens[1].trim();
450 vcfSpecies = DEFAULT_SPECIES;
451 prop = Cache.getProperty(VCF_SPECIES);
454 for (String token : prop.split(","))
456 String[] tokens = token.split("=");
457 if (tokens.length == 2)
459 if (reference.contains(tokens[0].trim().toLowerCase()))
461 vcfSpecies = tokens[1].trim();
470 * Opens the VCF file and parses header data
473 * @throws IOException
475 private void initialise(String filePath) throws IOException
477 vcfFilePath = filePath;
479 reader = new VCFReader(filePath);
481 header = reader.getFileHeader();
485 dictionary = header.getSequenceDictionary();
486 } catch (SAMException e)
488 // ignore - thrown if any contig line lacks length info
493 saveMetadata(sourceId);
496 * get offset of CSQ ALLELE_NUM and Feature if declared
502 * Reads metadata (such as INFO field descriptions and datatypes) and saves
503 * them for future reference
507 void saveMetadata(String theSourceId)
509 List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
511 vcfFieldsOfInterest = new ArrayList<>();
513 FeatureSource metadata = new FeatureSource(theSourceId);
515 for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
517 String attributeId = info.getID();
518 String desc = info.getDescription();
519 VCFHeaderLineType type = info.getType();
520 FeatureAttributeType attType = null;
524 attType = FeatureAttributeType.Character;
527 attType = FeatureAttributeType.Flag;
530 attType = FeatureAttributeType.Float;
533 attType = FeatureAttributeType.Integer;
536 attType = FeatureAttributeType.String;
539 metadata.setAttributeName(attributeId, desc);
540 metadata.setAttributeType(attributeId, attType);
542 if (isFieldWanted(attributeId, vcfFieldPatterns))
544 vcfFieldsOfInterest.add(attributeId);
548 FeatureSources.getInstance().addSource(theSourceId, metadata);
552 * Answers true if the field id is matched by any of the filter patterns, else
553 * false. Matching is against regular expression patterns, and is not
560 private boolean isFieldWanted(String id, List<Pattern> filters)
562 for (Pattern p : filters)
564 if (p.matcher(id.toUpperCase()).matches())
573 * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
574 * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
575 * required for processing.
577 * CSQ fields are declared in the CSQ INFO Description e.g.
579 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
581 protected void parseCsqHeader()
583 List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
585 vepFieldsOfInterest = new HashMap<>();
587 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
594 * parse out the pipe-separated list of CSQ fields; we assume here that
595 * these form the last part of the description, and contain no spaces
597 String desc = csqInfo.getDescription();
598 int spacePos = desc.lastIndexOf(" ");
599 desc = desc.substring(spacePos + 1);
603 String[] format = desc.split(PIPE_REGEX);
605 for (String field : format)
607 if (CSQ_CONSEQUENCE_KEY.equals(field))
609 csqConsequenceFieldIndex = index;
611 if (CSQ_ALLELE_NUM_KEY.equals(field))
613 csqAlleleNumberFieldIndex = index;
615 if (CSQ_ALLELE_KEY.equals(field))
617 csqAlleleFieldIndex = index;
619 if (CSQ_FEATURE_KEY.equals(field))
621 csqFeatureFieldIndex = index;
624 if (isFieldWanted(field, vepFieldFilters))
626 vepFieldsOfInterest.put(index, field);
635 * Reads the Preference value for the given key, with default specified if no
636 * preference set. The value is interpreted as a comma-separated list of
637 * regular expressions, and converted into a list of compiled patterns ready
638 * for matching. Patterns are forced to upper-case for non-case-sensitive
641 * This supports user-defined filters for fields of interest to capture while
642 * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
643 * fields with an ID of AF, or starting with AC, would be matched.
649 private List<Pattern> getFieldMatchers(String key, String def)
651 String pref = Cache.getDefault(key, def);
652 List<Pattern> patterns = new ArrayList<>();
653 String[] tokens = pref.split(",");
654 for (String token : tokens)
658 patterns.add(Pattern.compile(token.toUpperCase()));
659 } catch (PatternSyntaxException e)
661 System.err.println("Invalid pattern ignored: " + token);
668 * Transfers VCF features to sequences to which this sequence has a mapping.
669 * If the mapping is 3:1, computes peptide variants from nucleotide variants.
673 protected void transferAddedFeatures(SequenceI seq)
675 DBRefEntry[] dbrefs = seq.getDBRefs();
680 for (DBRefEntry dbref : dbrefs)
682 Mapping mapping = dbref.getMap();
683 if (mapping == null || mapping.getTo() == null)
688 SequenceI mapTo = mapping.getTo();
689 MapList map = mapping.getMap();
690 if (map.getFromRatio() == 3)
693 * dna-to-peptide product mapping
695 // JAL-3187 render on the fly instead
696 // AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
701 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
703 List<SequenceFeature> features = seq.getFeatures()
704 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
705 for (SequenceFeature sf : features)
707 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
709 transferFeature(sf, mapTo, map);
717 * Tries to add overlapping variants read from a VCF file to the given sequence,
718 * and returns the number of variant features added
723 protected int loadSequenceVCF(SequenceI seq)
725 VCFMap vcfMap = getVcfMap(seq);
732 * work with the dataset sequence here
734 SequenceI dss = seq.getDatasetSequence();
739 return addVcfVariants(dss, vcfMap);
743 * Answers a map from sequence coordinates to VCF chromosome ranges
748 private VCFMap getVcfMap(SequenceI seq)
751 * simplest case: sequence has id and length matching a VCF contig
753 VCFMap vcfMap = null;
754 if (dictionary != null)
756 vcfMap = getContigMap(seq);
764 * otherwise, map to VCF from chromosomal coordinates
765 * of the sequence (if known)
767 GeneLociI seqCoords = seq.getGeneLoci();
768 if (seqCoords == null)
770 Cache.log.warn(String.format(
771 "Can't query VCF for %s as chromosome coordinates not known",
776 String species = seqCoords.getSpeciesId();
777 String chromosome = seqCoords.getChromosomeId();
778 String seqRef = seqCoords.getAssemblyId();
779 MapList map = seqCoords.getMapping();
781 // note this requires the configured species to match that
782 // returned with the Ensembl sequence; todo: support aliases?
783 if (!vcfSpecies.equalsIgnoreCase(species))
785 Cache.log.warn("No VCF loaded to " + seq.getName()
786 + " as species not matched");
790 if (seqRef.equalsIgnoreCase(vcfAssembly))
792 return new VCFMap(chromosome, map);
796 * VCF data has a different reference assembly to the sequence:
797 * query Ensembl to map chromosomal coordinates from sequence to VCF
799 List<int[]> toVcfRanges = new ArrayList<>();
800 List<int[]> fromSequenceRanges = new ArrayList<>();
802 for (int[] range : map.getToRanges())
804 int[] fromRange = map.locateInFrom(range[0], range[1]);
805 if (fromRange == null)
811 int[] newRange = mapReferenceRange(range, chromosome, "human", seqRef,
813 if (newRange == null)
816 String.format("Failed to map %s:%s:%s:%d:%d to %s", species,
817 chromosome, seqRef, range[0], range[1],
823 toVcfRanges.add(newRange);
824 fromSequenceRanges.add(fromRange);
828 return new VCFMap(chromosome,
829 new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
833 * If the sequence id matches a contig declared in the VCF file, and the
834 * sequence length matches the contig length, then returns a 1:1 map of the
835 * sequence to the contig, else returns null
840 private VCFMap getContigMap(SequenceI seq)
842 String id = seq.getName();
843 SAMSequenceRecord contig = dictionary.getSequence(id);
846 int len = seq.getLength();
847 if (len == contig.getSequenceLength())
849 MapList map = new MapList(new int[] { 1, len },
852 return new VCFMap(id, map);
859 * Queries the VCF reader for any variants that overlap the mapped chromosome
860 * ranges of the sequence, and adds as variant features. Returns the number of
861 * overlapping variants found.
865 * mapping from sequence to VCF coordinates
868 protected int addVcfVariants(SequenceI seq, VCFMap map)
870 boolean forwardStrand = map.map.isToForwardStrand();
873 * query the VCF for overlaps of each contiguous chromosomal region
877 for (int[] range : map.map.getToRanges())
879 int vcfStart = Math.min(range[0], range[1]);
880 int vcfEnd = Math.max(range[0], range[1]);
883 CloseableIterator<VariantContext> variants = reader
884 .query(map.chromosome, vcfStart, vcfEnd);
885 while (variants.hasNext())
887 VariantContext variant = variants.next();
889 int[] featureRange = map.map.locateInFrom(variant.getStart(),
892 if (featureRange != null)
894 int featureStart = Math.min(featureRange[0], featureRange[1]);
895 int featureEnd = Math.max(featureRange[0], featureRange[1]);
896 count += addAlleleFeatures(seq, variant, featureStart,
897 featureEnd, forwardStrand);
901 } catch (TribbleException e)
904 * RuntimeException throwable by htsjdk
906 String msg = String.format("Error reading VCF for %s:%d-%d: %s ",
907 map.chromosome, vcfStart, vcfEnd);
908 Cache.log.error(msg);
916 * A convenience method to get an attribute value for an alternate allele.
917 * {@code alleleIndex} is the position in the list of values for the allele.
918 * If {@alleleIndex == -1} then all values are concatenated (comma-separated).
919 * This is the case for fields declared with "Number=." i.e. values are not
920 * related to specific alleles.
923 * @param attributeName
927 protected String getAttributeValue(VariantContext variant,
928 String attributeName, int alleleIndex)
930 Object att = variant.getAttribute(attributeName);
932 String result = null;
933 if (att instanceof String)
935 result = (String) att;
937 else if (att instanceof List<?>)
939 List<String> theList = (List<String>) att;
940 if (alleleIndex == -1)
942 result = StringUtils.listToDelimitedString(theList, ",");
946 result = theList.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.UNBOUNDED) // .
1343 else if (number != VCFHeaderLineCount.A)
1346 * don't save other values as not allele-related
1352 * take the index'th value
1354 String value = getAttributeValue(variant, key, index);
1355 if (value != null && isValid(variant, key, value))
1357 value = decodeSpecialCharacters(value);
1358 addFeatureAttribute(sf, key, value);
1364 * Decodes colon, semicolon, equals sign, percent sign, comma to their decoded
1365 * form. The VCF specification (para 1.2) requires these to be encoded where not
1366 * used with their special meaning in the VCF syntax. Note that general URL
1367 * decoding should not be applied, since this would incorrectly decode (for
1368 * example) a '+' sign.
1373 protected static String decodeSpecialCharacters(String value)
1376 * avoid regex compilation if it is not needed!
1378 if (!value.contains(ENCODED_COLON) && !value.contains(ENCODED_SEMICOLON)
1379 && !value.contains(ENCODED_EQUALS)
1380 && !value.contains(ENCODED_PERCENT)
1381 && !value.contains(ENCODED_COMMA))
1386 value = value.replace(ENCODED_COLON, ":")
1387 .replace(ENCODED_SEMICOLON, ";").replace(ENCODED_EQUALS, "=")
1388 .replace(ENCODED_PERCENT, "%").replace(ENCODED_COMMA, ",");
1393 * Answers true for '.', null, or an empty value, or if the INFO type is String.
1394 * If the INFO type is Integer or Float, answers false if the value is not in
1402 protected boolean isValid(VariantContext variant, String infoId,
1405 if (value == null || value.isEmpty() || NO_VALUE.equals(value))
1409 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(infoId);
1410 if (infoHeader == null)
1412 Cache.log.error("Field " + infoId + " has no INFO header");
1415 VCFHeaderLineType infoType = infoHeader.getType();
1418 if (infoType == VCFHeaderLineType.Integer)
1420 Integer.parseInt(value);
1422 else if (infoType == VCFHeaderLineType.Float)
1424 Float.parseFloat(value);
1426 } catch (NumberFormatException e)
1428 logInvalidValue(variant, infoId, value);
1435 * Logs an error message for malformed data; duplicate messages (same id and
1436 * value) are not logged
1442 private void logInvalidValue(VariantContext variant, String infoId,
1445 if (badData == null)
1447 badData = new HashSet<>();
1449 String token = infoId + ":" + value;
1450 if (!badData.contains(token))
1453 Cache.log.error(String.format("Invalid VCF data at %s:%d %s=%s",
1454 variant.getContig(), variant.getStart(), infoId, value));
1459 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
1462 * If <code>myConsequence</code> is not null, then this is the specific
1463 * consequence data (pipe-delimited fields) that is for the current allele and
1464 * transcript (sequence) being processed)
1468 * @param myConsequence
1470 protected void addConsequences(VariantContext variant, SequenceFeature sf,
1471 String myConsequence)
1473 Object value = variant.getAttribute(CSQ_FIELD);
1475 if (value == null || !(value instanceof List<?>))
1480 List<String> consequences = (List<String>) value;
1483 * inspect CSQ consequences; restrict to the consequence
1484 * associated with the current transcript (Feature)
1486 Map<String, String> csqValues = new HashMap<>();
1488 for (String consequence : consequences)
1490 if (myConsequence == null || myConsequence.equals(consequence))
1492 String[] csqFields = consequence.split(PIPE_REGEX);
1495 * inspect individual fields of this consequence, copying non-null
1496 * values which are 'fields of interest'
1499 for (String field : csqFields)
1501 if (field != null && field.length() > 0)
1503 String id = vepFieldsOfInterest.get(i);
1507 * VCF spec requires encoding of special characters e.g. '='
1508 * so decode them here before storing
1512 field = URLDecoder.decode(field, UTF_8);
1513 } catch (UnsupportedEncodingException e)
1516 csqValues.put(id, field);
1524 if (!csqValues.isEmpty())
1526 sf.setValue(CSQ_FIELD, csqValues);
1531 * A convenience method to complement a dna base and return the string value
1537 protected String complement(byte[] reference)
1539 return String.valueOf(Dna.getComplement((char) reference[0]));
1543 * Determines the location of the query range (chromosome positions) in a
1544 * different reference assembly.
1546 * If the range is just a subregion of one for which we already have a mapping
1547 * (for example, an exon sub-region of a gene), then the mapping is just
1548 * computed arithmetically.
1550 * Otherwise, calls the Ensembl REST service that maps from one assembly
1551 * reference's coordinates to another's
1554 * start-end chromosomal range in 'fromRef' coordinates
1558 * assembly reference for the query coordinates
1560 * assembly reference we wish to translate to
1561 * @return the start-end range in 'toRef' coordinates
1563 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
1564 String species, String fromRef, String toRef)
1567 * first try shorcut of computing the mapping as a subregion of one
1568 * we already have (e.g. for an exon, if we have the gene mapping)
1570 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
1571 species, fromRef, toRef);
1572 if (mappedRange != null)
1578 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
1580 EnsemblMap mapper = new EnsemblMap();
1581 int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
1584 if (mapping == null)
1586 // mapping service failure
1591 * save mapping for possible future re-use
1593 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1594 if (!assemblyMappings.containsKey(key))
1596 assemblyMappings.put(key, new HashMap<int[], int[]>());
1599 assemblyMappings.get(key).put(queryRange, mapping);
1605 * If we already have a 1:1 contiguous mapping which subsumes the given query
1606 * range, this method just calculates and returns the subset of that mapping,
1607 * else it returns null. In practical terms, if a gene has a contiguous
1608 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
1609 * subsidiary exons occupy unchanged relative positions, and just compute
1610 * these as offsets, rather than do another lookup of the mapping.
1612 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
1613 * simply remove this method or let it always return null.
1615 * Warning: many rapid calls to the /map service map result in a 429 overload
1625 protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
1626 String species, String fromRef, String toRef)
1628 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1629 if (assemblyMappings.containsKey(key))
1631 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
1632 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
1634 int[] fromRange = mappedRange.getKey();
1635 int[] toRange = mappedRange.getValue();
1636 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
1639 * mapping is 1:1 in length, so we trust it to have no discontinuities
1641 if (MappingUtils.rangeContains(fromRange, queryRange))
1644 * fromRange subsumes our query range
1646 int offset = queryRange[0] - fromRange[0];
1647 int mappedRangeFrom = toRange[0] + offset;
1648 int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
1649 return new int[] { mappedRangeFrom, mappedRangeTo };
1658 * Transfers the sequence feature to the target sequence, locating its start
1659 * and end range based on the mapping. Features which do not overlap the
1660 * target sequence are ignored.
1663 * @param targetSequence
1665 * mapping from the feature's coordinates to the target sequence
1667 protected void transferFeature(SequenceFeature sf,
1668 SequenceI targetSequence, MapList mapping)
1670 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1672 if (mappedRange != null)
1674 String group = sf.getFeatureGroup();
1675 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1676 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1677 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1678 group, sf.getScore());
1679 targetSequence.addSequenceFeature(copy);
1684 * Formats a ranges map lookup key
1692 protected static String makeRangesKey(String chromosome, String species,
1693 String fromRef, String toRef)
1695 return species + EXCL + chromosome + EXCL + fromRef + EXCL