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;
24 import java.io.IOException;
25 import java.io.UnsupportedEncodingException;
26 import java.net.URLDecoder;
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;
53 * A class to read VCF data (using the htsjdk) and add variants as sequence
54 * features on dna and any related protein product sequences
58 public class VCFLoader
60 private static final String ENCODED_COMMA = "%2C";
62 private static final String ENCODED_PERCENT = "%25";
64 private static final String ENCODED_EQUALS = "%3D";
66 private static final String ENCODED_SEMICOLON = "%3B";
68 private static final String ENCODED_COLON = "%3A";
70 private static final String UTF_8 = "UTF-8";
73 * Jalview feature attributes for VCF fixed column data
75 private static final String VCF_POS = "POS";
77 private static final String VCF_ID = "ID";
79 private static final String VCF_QUAL = "QUAL";
81 private static final String VCF_FILTER = "FILTER";
83 private static final String NO_VALUE = VCFConstants.MISSING_VALUE_v4; // '.'
85 private static final String DEFAULT_SPECIES = "homo_sapiens";
88 * A class to model the mapping from sequence to VCF coordinates. Cases include
90 * <li>a direct 1:1 mapping where the sequence is one of the VCF contigs</li>
91 * <li>a mapping of sequence to chromosomal coordinates, where sequence and VCF
92 * use the same reference assembly</li>
93 * <li>a modified mapping of sequence to chromosomal coordinates, where sequence
94 * and VCF use different reference assembles</li>
99 final String chromosome;
103 VCFMap(String chr, MapList m)
110 public String toString()
112 return chromosome + ":" + map.toString();
117 * Lookup keys, and default values, for Preference entries that describe
118 * patterns for VCF and VEP fields to capture
120 private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
122 private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
124 private static final String DEFAULT_VCF_FIELDS = ".*";
126 private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
129 * Lookup keys, and default values, for Preference entries that give
130 * mappings from tokens in the 'reference' header to species or assembly
132 private static final String VCF_ASSEMBLY = "VCF_ASSEMBLY";
134 private static final String DEFAULT_VCF_ASSEMBLY = "assembly19=GRCh37,hs37=GRCh37,grch37=GRCh37,grch38=GRCh38";
136 private static final String VCF_SPECIES = "VCF_SPECIES"; // default is human
138 private static final String DEFAULT_REFERENCE = "grch37"; // fallback default is human GRCh37
141 * keys to fields of VEP CSQ consequence data
142 * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
144 private static final String CSQ_CONSEQUENCE_KEY = "Consequence";
145 private static final String CSQ_ALLELE_KEY = "Allele";
146 private static final String CSQ_ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref), 1...
147 private static final String CSQ_FEATURE_KEY = "Feature"; // Ensembl stable id
150 * default VCF INFO key for VEP consequence data
151 * NB this can be overridden running VEP with --vcf_info_field
152 * - we don't handle this case (require identifier to be CSQ)
154 private static final String CSQ_FIELD = "CSQ";
157 * separator for fields in consequence data is '|'
159 private static final String PIPE_REGEX = "\\|";
162 * delimiter that separates multiple consequence data blocks
164 private static final String COMMA = ",";
167 * the feature group assigned to a VCF variant in Jalview
169 private static final String FEATURE_GROUP_VCF = "VCF";
172 * internal delimiter used to build keys for assemblyMappings
175 private static final String EXCL = "!";
178 * the VCF file we are processing
180 protected String vcfFilePath;
183 * mappings between VCF and sequence reference assembly regions, as
184 * key = "species!chromosome!fromAssembly!toAssembly
185 * value = Map{fromRange, toRange}
187 private Map<String, Map<int[], int[]>> assemblyMappings;
189 private VCFReader reader;
192 * holds details of the VCF header lines (metadata)
194 private VCFHeader header;
197 * species (as a valid Ensembl term) the VCF is for
199 private String vcfSpecies;
202 * genome assembly version (as a valid Ensembl identifier) the VCF is for
204 private String vcfAssembly;
207 * a Dictionary of contigs (if present) referenced in the VCF file
209 private SAMSequenceDictionary dictionary;
212 * the position (0...) of field in each block of
213 * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
214 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
216 private int csqConsequenceFieldIndex = -1;
217 private int csqAlleleFieldIndex = -1;
218 private int csqAlleleNumberFieldIndex = -1;
219 private int csqFeatureFieldIndex = -1;
221 // todo the same fields for SnpEff ANN data if wanted
222 // see http://snpeff.sourceforge.net/SnpEff_manual.html#input
225 * a unique identifier under which to save metadata about feature
226 * attributes (selected INFO field data)
228 private String sourceId;
231 * The INFO IDs of data that is both present in the VCF file, and
232 * also matched by any filters for data of interest
234 List<String> vcfFieldsOfInterest;
237 * The field offsets and identifiers for VEP (CSQ) data that is both present
238 * in the VCF file, and also matched by any filters for data of interest
239 * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
241 Map<Integer, String> vepFieldsOfInterest;
244 * key:value for which rejected data has been seen
245 * (the error is logged only once for each combination)
247 private Set<String> badData;
250 * Constructor given a VCF file
254 public VCFLoader(String vcfFile)
259 } catch (IOException e)
261 System.err.println("Error opening VCF file: " + e.getMessage());
264 // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
265 assemblyMappings = new HashMap<>();
269 * Starts a new thread to query and load VCF variant data on to the given
272 * This method is not thread safe - concurrent threads should use separate
273 * instances of this class.
278 public void loadVCF(SequenceI[] seqs, final AlignViewControllerGuiI gui)
282 gui.setStatus(MessageManager.getString("label.searching_vcf"));
290 VCFLoader.this.doLoad(seqs, gui);
296 * Reads the specified contig sequence and adds its VCF variants to it
299 * the id of a single sequence (contig) to load
302 public SequenceI loadVCFContig(String contig)
304 VCFHeaderLine headerLine = header.getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
305 if (headerLine == null)
307 Cache.log.error("VCF reference header not found");
310 String ref = headerLine.getValue();
311 if (ref.startsWith("file://"))
313 ref = ref.substring(7);
315 setSpeciesAndAssembly(ref);
317 SequenceI seq = null;
318 File dbFile = new File(ref);
322 HtsContigDb db = new HtsContigDb("", dbFile);
323 seq = db.getSequenceProxy(contig);
324 loadSequenceVCF(seq);
329 Cache.log.error("VCF reference not found: " + ref);
336 * Loads VCF on to one or more sequences
340 * optional callback handler for messages
342 protected void doLoad(SequenceI[] seqs, AlignViewControllerGuiI gui)
346 VCFHeaderLine ref = header
347 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
348 String reference = ref == null ? null : ref.getValue();
350 setSpeciesAndAssembly(reference);
356 * query for VCF overlapping each sequence in turn
358 for (SequenceI seq : seqs)
360 int added = loadSequenceVCF(seq);
365 transferAddedFeatures(seq);
370 String msg = MessageManager.formatMessage("label.added_vcf",
373 if (gui.getFeatureSettingsUI() != null)
375 gui.getFeatureSettingsUI().discoverAllFeatureData();
378 } catch (Throwable e)
380 System.err.println("Error processing VCF: " + e.getMessage());
384 gui.setStatus("Error occurred - see console for details");
393 } catch (IOException e)
404 * Attempts to determine and save the species and genome assembly version to
405 * which the VCF data applies. This may be done by parsing the {@code reference}
406 * header line, configured in a property file, or (potentially) confirmed
407 * interactively by the user.
409 * The saved values should be identifiers valid for Ensembl's REST service
410 * {@code map} endpoint, so they can be used (if necessary) to retrieve the
411 * mapping between VCF coordinates and sequence coordinates.
414 * @see https://rest.ensembl.org/documentation/info/assembly_map
415 * @see https://rest.ensembl.org/info/assembly/human?content-type=text/xml
416 * @see https://rest.ensembl.org/info/species?content-type=text/xml
418 protected void setSpeciesAndAssembly(String reference)
420 if (reference == null)
422 Cache.log.error("No VCF ##reference found, defaulting to "
423 + DEFAULT_REFERENCE + ":" + DEFAULT_SPECIES);
424 reference = DEFAULT_REFERENCE; // default to GRCh37 if not specified
426 reference = reference.toLowerCase();
429 * for a non-human species, or other assembly identifier,
430 * specify as a Jalview property file entry e.g.
431 * VCF_ASSEMBLY = hs37=GRCh37,assembly19=GRCh37
432 * VCF_SPECIES = c_elegans=celegans
433 * to map a token in the reference header to a value
435 String prop = Cache.getDefault(VCF_ASSEMBLY, DEFAULT_VCF_ASSEMBLY);
436 for (String token : prop.split(","))
438 String[] tokens = token.split("=");
439 if (tokens.length == 2)
441 if (reference.contains(tokens[0].trim().toLowerCase()))
443 vcfAssembly = tokens[1].trim();
449 vcfSpecies = DEFAULT_SPECIES;
450 prop = Cache.getProperty(VCF_SPECIES);
453 for (String token : prop.split(","))
455 String[] tokens = token.split("=");
456 if (tokens.length == 2)
458 if (reference.contains(tokens[0].trim().toLowerCase()))
460 vcfSpecies = tokens[1].trim();
469 * Opens the VCF file and parses header data
472 * @throws IOException
474 private void initialise(String filePath) throws IOException
476 vcfFilePath = filePath;
478 reader = new VCFReader(filePath);
480 header = reader.getFileHeader();
484 dictionary = header.getSequenceDictionary();
485 } catch (SAMException e)
487 // ignore - thrown if any contig line lacks length info
492 saveMetadata(sourceId);
495 * get offset of CSQ ALLELE_NUM and Feature if declared
501 * Reads metadata (such as INFO field descriptions and datatypes) and saves
502 * them for future reference
506 void saveMetadata(String theSourceId)
508 List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
510 vcfFieldsOfInterest = new ArrayList<>();
512 FeatureSource metadata = new FeatureSource(theSourceId);
514 for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
516 String attributeId = info.getID();
517 String desc = info.getDescription();
518 VCFHeaderLineType type = info.getType();
519 FeatureAttributeType attType = null;
523 attType = FeatureAttributeType.Character;
526 attType = FeatureAttributeType.Flag;
529 attType = FeatureAttributeType.Float;
532 attType = FeatureAttributeType.Integer;
535 attType = FeatureAttributeType.String;
538 metadata.setAttributeName(attributeId, desc);
539 metadata.setAttributeType(attributeId, attType);
541 if (isFieldWanted(attributeId, vcfFieldPatterns))
543 vcfFieldsOfInterest.add(attributeId);
547 FeatureSources.getInstance().addSource(theSourceId, metadata);
551 * Answers true if the field id is matched by any of the filter patterns, else
552 * false. Matching is against regular expression patterns, and is not
559 private boolean isFieldWanted(String id, List<Pattern> filters)
561 for (Pattern p : filters)
563 if (p.matcher(id.toUpperCase()).matches())
572 * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
573 * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
574 * required for processing.
576 * CSQ fields are declared in the CSQ INFO Description e.g.
578 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
580 protected void parseCsqHeader()
582 List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
584 vepFieldsOfInterest = new HashMap<>();
586 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
593 * parse out the pipe-separated list of CSQ fields; we assume here that
594 * these form the last part of the description, and contain no spaces
596 String desc = csqInfo.getDescription();
597 int spacePos = desc.lastIndexOf(" ");
598 desc = desc.substring(spacePos + 1);
602 String[] format = desc.split(PIPE_REGEX);
604 for (String field : format)
606 if (CSQ_CONSEQUENCE_KEY.equals(field))
608 csqConsequenceFieldIndex = index;
610 if (CSQ_ALLELE_NUM_KEY.equals(field))
612 csqAlleleNumberFieldIndex = index;
614 if (CSQ_ALLELE_KEY.equals(field))
616 csqAlleleFieldIndex = index;
618 if (CSQ_FEATURE_KEY.equals(field))
620 csqFeatureFieldIndex = index;
623 if (isFieldWanted(field, vepFieldFilters))
625 vepFieldsOfInterest.put(index, field);
634 * Reads the Preference value for the given key, with default specified if no
635 * preference set. The value is interpreted as a comma-separated list of
636 * regular expressions, and converted into a list of compiled patterns ready
637 * for matching. Patterns are forced to upper-case for non-case-sensitive
640 * This supports user-defined filters for fields of interest to capture while
641 * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
642 * fields with an ID of AF, or starting with AC, would be matched.
648 private List<Pattern> getFieldMatchers(String key, String def)
650 String pref = Cache.getDefault(key, def);
651 List<Pattern> patterns = new ArrayList<>();
652 String[] tokens = pref.split(",");
653 for (String token : tokens)
657 patterns.add(Pattern.compile(token.toUpperCase()));
658 } catch (PatternSyntaxException e)
660 System.err.println("Invalid pattern ignored: " + token);
667 * Transfers VCF features to sequences to which this sequence has a mapping.
668 * If the mapping is 3:1, computes peptide variants from nucleotide variants.
672 protected void transferAddedFeatures(SequenceI seq)
674 DBRefEntry[] dbrefs = seq.getDBRefs();
679 for (DBRefEntry dbref : dbrefs)
681 Mapping mapping = dbref.getMap();
682 if (mapping == null || mapping.getTo() == null)
687 SequenceI mapTo = mapping.getTo();
688 MapList map = mapping.getMap();
689 if (map.getFromRatio() == 3)
692 * dna-to-peptide product mapping
694 // JAL-3187 render on the fly instead
695 // AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
700 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
702 List<SequenceFeature> features = seq.getFeatures()
703 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
704 for (SequenceFeature sf : features)
706 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
708 transferFeature(sf, mapTo, map);
716 * Tries to add overlapping variants read from a VCF file to the given sequence,
717 * and returns the number of variant features added
722 protected int loadSequenceVCF(SequenceI seq)
724 VCFMap vcfMap = getVcfMap(seq);
731 * work with the dataset sequence here
733 SequenceI dss = seq.getDatasetSequence();
738 return addVcfVariants(dss, vcfMap);
742 * Answers a map from sequence coordinates to VCF chromosome ranges
747 private VCFMap getVcfMap(SequenceI seq)
750 * simplest case: sequence has id and length matching a VCF contig
752 VCFMap vcfMap = null;
753 if (dictionary != null)
755 vcfMap = getContigMap(seq);
763 * otherwise, map to VCF from chromosomal coordinates
764 * of the sequence (if known)
766 GeneLociI seqCoords = seq.getGeneLoci();
767 if (seqCoords == null)
769 Cache.log.warn(String.format(
770 "Can't query VCF for %s as chromosome coordinates not known",
775 String species = seqCoords.getSpeciesId();
776 String chromosome = seqCoords.getChromosomeId();
777 String seqRef = seqCoords.getAssemblyId();
778 MapList map = seqCoords.getMapping();
780 // note this requires the configured species to match that
781 // returned with the Ensembl sequence; todo: support aliases?
782 if (!vcfSpecies.equalsIgnoreCase(species))
784 Cache.log.warn("No VCF loaded to " + seq.getName()
785 + " as species not matched");
789 if (seqRef.equalsIgnoreCase(vcfAssembly))
791 return new VCFMap(chromosome, map);
795 * VCF data has a different reference assembly to the sequence:
796 * query Ensembl to map chromosomal coordinates from sequence to VCF
798 List<int[]> toVcfRanges = new ArrayList<>();
799 List<int[]> fromSequenceRanges = new ArrayList<>();
801 for (int[] range : map.getToRanges())
803 int[] fromRange = map.locateInFrom(range[0], range[1]);
804 if (fromRange == null)
810 int[] newRange = mapReferenceRange(range, chromosome, "human", seqRef,
812 if (newRange == null)
815 String.format("Failed to map %s:%s:%s:%d:%d to %s", species,
816 chromosome, seqRef, range[0], range[1],
822 toVcfRanges.add(newRange);
823 fromSequenceRanges.add(fromRange);
827 return new VCFMap(chromosome,
828 new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
832 * If the sequence id matches a contig declared in the VCF file, and the
833 * sequence length matches the contig length, then returns a 1:1 map of the
834 * sequence to the contig, else returns null
839 private VCFMap getContigMap(SequenceI seq)
841 String id = seq.getName();
842 SAMSequenceRecord contig = dictionary.getSequence(id);
845 int len = seq.getLength();
846 if (len == contig.getSequenceLength())
848 MapList map = new MapList(new int[] { 1, len },
851 return new VCFMap(id, map);
858 * Queries the VCF reader for any variants that overlap the mapped chromosome
859 * ranges of the sequence, and adds as variant features. Returns the number of
860 * overlapping variants found.
864 * mapping from sequence to VCF coordinates
867 protected int addVcfVariants(SequenceI seq, VCFMap map)
869 boolean forwardStrand = map.map.isToForwardStrand();
872 * query the VCF for overlaps of each contiguous chromosomal region
876 for (int[] range : map.map.getToRanges())
878 int vcfStart = Math.min(range[0], range[1]);
879 int vcfEnd = Math.max(range[0], range[1]);
882 CloseableIterator<VariantContext> variants = reader
883 .query(map.chromosome, vcfStart, vcfEnd);
884 while (variants.hasNext())
886 VariantContext variant = variants.next();
888 int[] featureRange = map.map.locateInFrom(variant.getStart(),
891 if (featureRange != null)
893 int featureStart = Math.min(featureRange[0], featureRange[1]);
894 int featureEnd = Math.max(featureRange[0], featureRange[1]);
895 count += addAlleleFeatures(seq, variant, featureStart,
896 featureEnd, forwardStrand);
900 } catch (TribbleException e)
903 * RuntimeException throwable by htsjdk
905 String msg = String.format("Error reading VCF for %s:%d-%d: %s ",
906 map.chromosome, vcfStart, vcfEnd);
907 Cache.log.error(msg);
915 * A convenience method to get an attribute value for an alternate allele
918 * @param attributeName
922 protected String getAttributeValue(VariantContext variant,
923 String attributeName, int alleleIndex)
925 Object att = variant.getAttribute(attributeName);
927 if (att instanceof String)
931 else if (att instanceof ArrayList)
933 return ((List<String>) att).get(alleleIndex);
940 * Adds one variant feature for each allele in the VCF variant record, and
941 * returns the number of features added.
945 * @param featureStart
947 * @param forwardStrand
950 protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
951 int featureStart, int featureEnd, boolean forwardStrand)
956 * Javadoc says getAlternateAlleles() imposes no order on the list returned
957 * so we proceed defensively to get them in strict order
959 int altAlleleCount = variant.getAlternateAlleles().size();
960 for (int i = 0; i < altAlleleCount; i++)
962 added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
969 * Inspects one allele and attempts to add a variant feature for it to the
970 * sequence. The additional data associated with this allele is extracted to
971 * store in the feature's key-value map. Answers the number of features added (0
976 * @param altAlleleIndex
978 * @param featureStart
980 * @param forwardStrand
983 protected int addAlleleFeature(SequenceI seq, VariantContext variant,
984 int altAlleleIndex, int featureStart, int featureEnd,
985 boolean forwardStrand)
987 String reference = variant.getReference().getBaseString();
988 Allele alt = variant.getAlternateAllele(altAlleleIndex);
989 String allele = alt.getBaseString();
992 * insertion after a genomic base, if on reverse strand, has to be
993 * converted to insertion of complement after the preceding position
995 int referenceLength = reference.length();
996 if (!forwardStrand && allele.length() > referenceLength
997 && allele.startsWith(reference))
999 featureStart -= referenceLength;
1000 featureEnd = featureStart;
1001 char insertAfter = seq.getCharAt(featureStart - seq.getStart());
1002 reference = Dna.reverseComplement(String.valueOf(insertAfter));
1003 allele = allele.substring(referenceLength) + reference;
1007 * build the ref,alt allele description e.g. "G,A", using the base
1008 * complement if the sequence is on the reverse strand
1010 StringBuilder sb = new StringBuilder();
1011 sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
1013 sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
1014 String alleles = sb.toString(); // e.g. G,A
1017 * pick out the consequence data (if any) that is for the current allele
1018 * and feature (transcript) that matches the current sequence
1020 String consequence = getConsequenceForAlleleAndFeature(variant, CSQ_FIELD,
1021 altAlleleIndex, csqAlleleFieldIndex,
1022 csqAlleleNumberFieldIndex, seq.getName().toLowerCase(),
1023 csqFeatureFieldIndex);
1026 * pick out the ontology term for the consequence type
1028 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1029 if (consequence != null)
1031 type = getOntologyTerm(consequence);
1034 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
1035 featureEnd, FEATURE_GROUP_VCF);
1036 sf.setSource(sourceId);
1039 * save the derived alleles as a named attribute; this will be
1040 * needed when Jalview computes derived peptide variants
1042 addFeatureAttribute(sf, Gff3Helper.ALLELES, alleles);
1045 * add selected VCF fixed column data as feature attributes
1047 addFeatureAttribute(sf, VCF_POS, String.valueOf(variant.getStart()));
1048 addFeatureAttribute(sf, VCF_ID, variant.getID());
1049 addFeatureAttribute(sf, VCF_QUAL,
1050 String.valueOf(variant.getPhredScaledQual()));
1051 addFeatureAttribute(sf, VCF_FILTER, getFilter(variant));
1053 addAlleleProperties(variant, sf, altAlleleIndex, consequence);
1055 seq.addSequenceFeature(sf);
1061 * Answers the VCF FILTER value for the variant - or an approximation to it.
1062 * This field is either PASS, or a semi-colon separated list of filters not
1063 * passed. htsjdk saves filters as a HashSet, so the order when reassembled into
1064 * a list may be different.
1069 String getFilter(VariantContext variant)
1071 Set<String> filters = variant.getFilters();
1072 if (filters.isEmpty())
1076 Iterator<String> iterator = filters.iterator();
1077 String first = iterator.next();
1078 if (filters.size() == 1)
1083 StringBuilder sb = new StringBuilder(first);
1084 while (iterator.hasNext())
1086 sb.append(";").append(iterator.next());
1089 return sb.toString();
1093 * Adds one feature attribute unless the value is null, empty or '.'
1099 void addFeatureAttribute(SequenceFeature sf, String key, String value)
1101 if (value != null && !value.isEmpty() && !NO_VALUE.equals(value))
1103 sf.setValue(key, value);
1108 * Determines the Sequence Ontology term to use for the variant feature type in
1109 * Jalview. The default is 'sequence_variant', but a more specific term is used
1112 * <li>VEP (or SnpEff) Consequence annotation is included in the VCF</li>
1113 * <li>sequence id can be matched to VEP Feature (or SnpEff Feature_ID)</li>
1116 * @param consequence
1118 * @see http://www.sequenceontology.org/browser/current_svn/term/SO:0001060
1120 String getOntologyTerm(String consequence)
1122 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1125 * could we associate Consequence data with this allele and feature (transcript)?
1126 * if so, prefer the consequence term from that data
1128 if (csqAlleleFieldIndex == -1) // && snpEffAlleleFieldIndex == -1
1131 * no Consequence data so we can't refine the ontology term
1136 if (consequence != null)
1138 String[] csqFields = consequence.split(PIPE_REGEX);
1139 if (csqFields.length > csqConsequenceFieldIndex)
1141 type = csqFields[csqConsequenceFieldIndex];
1146 // todo the same for SnpEff consequence data matching if wanted
1150 * if of the form (e.g.) missense_variant&splice_region_variant,
1151 * just take the first ('most severe') consequence
1155 int pos = type.indexOf('&');
1158 type = type.substring(0, pos);
1165 * Returns matched consequence data if it can be found, else null.
1167 * <li>inspects the VCF data for key 'vcfInfoId'</li>
1168 * <li>splits this on comma (to distinct consequences)</li>
1169 * <li>returns the first consequence (if any) where</li>
1171 * <li>the allele matches the altAlleleIndex'th allele of variant</li>
1172 * <li>the feature matches the sequence name (e.g. transcript id)</li>
1175 * If matched, the consequence is returned (as pipe-delimited fields).
1179 * @param altAlleleIndex
1180 * @param alleleFieldIndex
1181 * @param alleleNumberFieldIndex
1183 * @param featureFieldIndex
1186 private String getConsequenceForAlleleAndFeature(VariantContext variant,
1187 String vcfInfoId, int altAlleleIndex, int alleleFieldIndex,
1188 int alleleNumberFieldIndex,
1189 String seqName, int featureFieldIndex)
1191 if (alleleFieldIndex == -1 || featureFieldIndex == -1)
1195 Object value = variant.getAttribute(vcfInfoId);
1197 if (value == null || !(value instanceof List<?>))
1203 * inspect each consequence in turn (comma-separated blocks
1204 * extracted by htsjdk)
1206 List<String> consequences = (List<String>) value;
1208 for (String consequence : consequences)
1210 String[] csqFields = consequence.split(PIPE_REGEX);
1211 if (csqFields.length > featureFieldIndex)
1213 String featureIdentifier = csqFields[featureFieldIndex];
1214 if (featureIdentifier.length() > 4
1215 && seqName.indexOf(featureIdentifier.toLowerCase()) > -1)
1218 * feature (transcript) matched - now check for allele match
1220 if (matchAllele(variant, altAlleleIndex, csqFields,
1221 alleleFieldIndex, alleleNumberFieldIndex))
1231 private boolean matchAllele(VariantContext variant, int altAlleleIndex,
1232 String[] csqFields, int alleleFieldIndex,
1233 int alleleNumberFieldIndex)
1236 * if ALLELE_NUM is present, it must match altAlleleIndex
1237 * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1239 if (alleleNumberFieldIndex > -1)
1241 if (csqFields.length <= alleleNumberFieldIndex)
1245 String alleleNum = csqFields[alleleNumberFieldIndex];
1246 return String.valueOf(altAlleleIndex + 1).equals(alleleNum);
1250 * else consequence allele must match variant allele
1252 if (alleleFieldIndex > -1 && csqFields.length > alleleFieldIndex)
1254 String csqAllele = csqFields[alleleFieldIndex];
1255 String vcfAllele = variant.getAlternateAllele(altAlleleIndex)
1257 return csqAllele.equals(vcfAllele);
1263 * Add any allele-specific VCF key-value data to the sequence feature
1267 * @param altAlelleIndex
1269 * @param consequence
1270 * if not null, the consequence specific to this sequence (transcript
1271 * feature) and allele
1273 protected void addAlleleProperties(VariantContext variant,
1274 SequenceFeature sf, final int altAlelleIndex, String consequence)
1276 Map<String, Object> atts = variant.getAttributes();
1278 for (Entry<String, Object> att : atts.entrySet())
1280 String key = att.getKey();
1283 * extract Consequence data (if present) that we are able to
1284 * associated with the allele for this variant feature
1286 if (CSQ_FIELD.equals(key))
1288 addConsequences(variant, sf, consequence);
1293 * filter out fields we don't want to capture
1295 if (!vcfFieldsOfInterest.contains(key))
1301 * we extract values for other data which are allele-specific;
1302 * these may be per alternate allele (INFO[key].Number = 'A')
1303 * or per allele including reference (INFO[key].Number = 'R')
1305 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
1306 if (infoHeader == null)
1309 * can't be sure what data belongs to this allele, so
1310 * play safe and don't take any
1315 VCFHeaderLineCount number = infoHeader.getCountType();
1316 int index = altAlelleIndex;
1317 if (number == VCFHeaderLineCount.R)
1320 * one value per allele including reference, so bump index
1321 * e.g. the 3rd value is for the 2nd alternate allele
1325 else if (number != VCFHeaderLineCount.A)
1328 * don't save other values as not allele-related
1334 * take the index'th value
1336 String value = getAttributeValue(variant, key, index);
1337 if (value != null && isValid(variant, key, value))
1339 value = decodeSpecialCharacters(value);
1340 addFeatureAttribute(sf, key, value);
1346 * Decodes colon, semicolon, equals sign, percent sign, comma to their decoded
1347 * form. The VCF specification (para 1.2) requires these to be encoded where not
1348 * used with their special meaning in the VCF syntax. Note that general URL
1349 * decoding should not be applied, since this would incorrectly decode (for
1350 * example) a '+' sign.
1355 protected static String decodeSpecialCharacters(String value)
1358 * avoid regex compilation if it is not needed!
1360 if (!value.contains(ENCODED_COLON) && !value.contains(ENCODED_SEMICOLON)
1361 && !value.contains(ENCODED_EQUALS)
1362 && !value.contains(ENCODED_PERCENT)
1363 && !value.contains(ENCODED_COMMA))
1368 value = value.replace(ENCODED_COLON, ":")
1369 .replace(ENCODED_SEMICOLON, ";").replace(ENCODED_EQUALS, "=")
1370 .replace(ENCODED_PERCENT, "%").replace(ENCODED_COMMA, ",");
1375 * Answers true for '.', null, or an empty value, or if the INFO type is String.
1376 * If the INFO type is Integer or Float, answers false if the value is not in
1384 protected boolean isValid(VariantContext variant, String infoId,
1387 if (value == null || value.isEmpty() || NO_VALUE.equals(value))
1391 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(infoId);
1392 if (infoHeader == null)
1394 Cache.log.error("Field " + infoId + " has no INFO header");
1397 VCFHeaderLineType infoType = infoHeader.getType();
1400 if (infoType == VCFHeaderLineType.Integer)
1402 Integer.parseInt(value);
1404 else if (infoType == VCFHeaderLineType.Float)
1406 Float.parseFloat(value);
1408 } catch (NumberFormatException e)
1410 logInvalidValue(variant, infoId, value);
1417 * Logs an error message for malformed data; duplicate messages (same id and
1418 * value) are not logged
1424 private void logInvalidValue(VariantContext variant, String infoId,
1427 if (badData == null)
1429 badData = new HashSet<>();
1431 String token = infoId + ":" + value;
1432 if (!badData.contains(token))
1435 Cache.log.error(String.format("Invalid VCF data at %s:%d %s=%s",
1436 variant.getContig(), variant.getStart(), infoId, value));
1441 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
1444 * If <code>myConsequence</code> is not null, then this is the specific
1445 * consequence data (pipe-delimited fields) that is for the current allele and
1446 * transcript (sequence) being processed)
1450 * @param myConsequence
1452 protected void addConsequences(VariantContext variant, SequenceFeature sf,
1453 String myConsequence)
1455 Object value = variant.getAttribute(CSQ_FIELD);
1457 if (value == null || !(value instanceof List<?>))
1462 List<String> consequences = (List<String>) value;
1465 * inspect CSQ consequences; restrict to the consequence
1466 * associated with the current transcript (Feature)
1468 Map<String, String> csqValues = new HashMap<>();
1470 for (String consequence : consequences)
1472 if (myConsequence == null || myConsequence.equals(consequence))
1474 String[] csqFields = consequence.split(PIPE_REGEX);
1477 * inspect individual fields of this consequence, copying non-null
1478 * values which are 'fields of interest'
1481 for (String field : csqFields)
1483 if (field != null && field.length() > 0)
1485 String id = vepFieldsOfInterest.get(i);
1489 * VCF spec requires encoding of special characters e.g. '='
1490 * so decode them here before storing
1494 field = URLDecoder.decode(field, UTF_8);
1495 } catch (UnsupportedEncodingException e)
1498 csqValues.put(id, field);
1506 if (!csqValues.isEmpty())
1508 sf.setValue(CSQ_FIELD, csqValues);
1513 * A convenience method to complement a dna base and return the string value
1519 protected String complement(byte[] reference)
1521 return String.valueOf(Dna.getComplement((char) reference[0]));
1525 * Determines the location of the query range (chromosome positions) in a
1526 * different reference assembly.
1528 * If the range is just a subregion of one for which we already have a mapping
1529 * (for example, an exon sub-region of a gene), then the mapping is just
1530 * computed arithmetically.
1532 * Otherwise, calls the Ensembl REST service that maps from one assembly
1533 * reference's coordinates to another's
1536 * start-end chromosomal range in 'fromRef' coordinates
1540 * assembly reference for the query coordinates
1542 * assembly reference we wish to translate to
1543 * @return the start-end range in 'toRef' coordinates
1545 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
1546 String species, String fromRef, String toRef)
1549 * first try shorcut of computing the mapping as a subregion of one
1550 * we already have (e.g. for an exon, if we have the gene mapping)
1552 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
1553 species, fromRef, toRef);
1554 if (mappedRange != null)
1560 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
1562 EnsemblMap mapper = new EnsemblMap();
1563 int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
1566 if (mapping == null)
1568 // mapping service failure
1573 * save mapping for possible future re-use
1575 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1576 if (!assemblyMappings.containsKey(key))
1578 assemblyMappings.put(key, new HashMap<int[], int[]>());
1581 assemblyMappings.get(key).put(queryRange, mapping);
1587 * If we already have a 1:1 contiguous mapping which subsumes the given query
1588 * range, this method just calculates and returns the subset of that mapping,
1589 * else it returns null. In practical terms, if a gene has a contiguous
1590 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
1591 * subsidiary exons occupy unchanged relative positions, and just compute
1592 * these as offsets, rather than do another lookup of the mapping.
1594 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
1595 * simply remove this method or let it always return null.
1597 * Warning: many rapid calls to the /map service map result in a 429 overload
1607 protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
1608 String species, String fromRef, String toRef)
1610 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1611 if (assemblyMappings.containsKey(key))
1613 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
1614 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
1616 int[] fromRange = mappedRange.getKey();
1617 int[] toRange = mappedRange.getValue();
1618 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
1621 * mapping is 1:1 in length, so we trust it to have no discontinuities
1623 if (MappingUtils.rangeContains(fromRange, queryRange))
1626 * fromRange subsumes our query range
1628 int offset = queryRange[0] - fromRange[0];
1629 int mappedRangeFrom = toRange[0] + offset;
1630 int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
1631 return new int[] { mappedRangeFrom, mappedRangeTo };
1640 * Transfers the sequence feature to the target sequence, locating its start
1641 * and end range based on the mapping. Features which do not overlap the
1642 * target sequence are ignored.
1645 * @param targetSequence
1647 * mapping from the feature's coordinates to the target sequence
1649 protected void transferFeature(SequenceFeature sf,
1650 SequenceI targetSequence, MapList mapping)
1652 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1654 if (mappedRange != null)
1656 String group = sf.getFeatureGroup();
1657 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1658 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1659 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1660 group, sf.getScore());
1661 targetSequence.addSequenceFeature(copy);
1666 * Formats a ranges map lookup key
1674 protected static String makeRangesKey(String chromosome, String species,
1675 String fromRef, String toRef)
1677 return species + EXCL + chromosome + EXCL + fromRef + EXCL