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.List;
31 import java.util.Map.Entry;
32 import java.util.regex.Pattern;
33 import java.util.regex.PatternSyntaxException;
35 import htsjdk.samtools.SAMException;
36 import htsjdk.samtools.SAMSequenceDictionary;
37 import htsjdk.samtools.SAMSequenceRecord;
38 import htsjdk.samtools.util.CloseableIterator;
39 import htsjdk.variant.variantcontext.Allele;
40 import htsjdk.variant.variantcontext.VariantContext;
41 import htsjdk.variant.vcf.VCFHeader;
42 import htsjdk.variant.vcf.VCFHeaderLine;
43 import htsjdk.variant.vcf.VCFHeaderLineCount;
44 import htsjdk.variant.vcf.VCFHeaderLineType;
45 import htsjdk.variant.vcf.VCFInfoHeaderLine;
48 * A class to read VCF data (using the htsjdk) and add variants as sequence
49 * features on dna and any related protein product sequences
53 public class VCFLoader
55 private static final String ENCODED_COMMA = "%2C";
57 private static final String ENCODED_PERCENT = "%25";
59 private static final String ENCODED_EQUALS = "%3D";
61 private static final String ENCODED_SEMICOLON = "%3B";
63 private static final String ENCODED_COLON = "%3A";
65 private static final String UTF_8 = "UTF-8";
67 private static final String DEFAULT_SPECIES = "homo_sapiens";
70 * A class to model the mapping from sequence to VCF coordinates. Cases include
72 * <li>a direct 1:1 mapping where the sequence is one of the VCF contigs</li>
73 * <li>a mapping of sequence to chromosomal coordinates, where sequence and VCF
74 * use the same reference assembly</li>
75 * <li>a modified mapping of sequence to chromosomal coordinates, where sequence
76 * and VCF use different reference assembles</li>
81 final String chromosome;
85 VCFMap(String chr, MapList m)
92 public String toString()
94 return chromosome + ":" + map.toString();
99 * Lookup keys, and default values, for Preference entries that describe
100 * patterns for VCF and VEP fields to capture
102 private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
104 private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
106 private static final String DEFAULT_VCF_FIELDS = ".*";
108 private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
111 * Lookup keys, and default values, for Preference entries that give
112 * mappings from tokens in the 'reference' header to species or assembly
114 private static final String VCF_ASSEMBLY = "VCF_ASSEMBLY";
116 private static final String DEFAULT_VCF_ASSEMBLY = "assembly19=GRCh37,hs37=GRCh37,grch37=GRCh37,grch38=GRCh38";
118 private static final String VCF_SPECIES = "VCF_SPECIES"; // default is human
120 private static final String DEFAULT_REFERENCE = "grch37"; // fallback default is human GRCh37
123 * keys to fields of VEP CSQ consequence data
124 * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
126 private static final String CSQ_CONSEQUENCE_KEY = "Consequence";
127 private static final String CSQ_ALLELE_KEY = "Allele";
128 private static final String CSQ_ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref), 1...
129 private static final String CSQ_FEATURE_KEY = "Feature"; // Ensembl stable id
132 * default VCF INFO key for VEP consequence data
133 * NB this can be overridden running VEP with --vcf_info_field
134 * - we don't handle this case (require identifier to be CSQ)
136 private static final String CSQ_FIELD = "CSQ";
139 * separator for fields in consequence data is '|'
141 private static final String PIPE_REGEX = "\\|";
144 * delimiter that separates multiple consequence data blocks
146 private static final String COMMA = ",";
149 * the feature group assigned to a VCF variant in Jalview
151 private static final String FEATURE_GROUP_VCF = "VCF";
154 * internal delimiter used to build keys for assemblyMappings
157 private static final String EXCL = "!";
160 * the VCF file we are processing
162 protected String vcfFilePath;
165 * mappings between VCF and sequence reference assembly regions, as
166 * key = "species!chromosome!fromAssembly!toAssembly
167 * value = Map{fromRange, toRange}
169 private Map<String, Map<int[], int[]>> assemblyMappings;
171 private VCFReader reader;
174 * holds details of the VCF header lines (metadata)
176 private VCFHeader header;
179 * species (as a valid Ensembl term) the VCF is for
181 private String vcfSpecies;
184 * genome assembly version (as a valid Ensembl identifier) the VCF is for
186 private String vcfAssembly;
189 * a Dictionary of contigs (if present) referenced in the VCF file
191 private SAMSequenceDictionary dictionary;
194 * the position (0...) of field in each block of
195 * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
196 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
198 private int csqConsequenceFieldIndex = -1;
199 private int csqAlleleFieldIndex = -1;
200 private int csqAlleleNumberFieldIndex = -1;
201 private int csqFeatureFieldIndex = -1;
203 // todo the same fields for SnpEff ANN data if wanted
204 // see http://snpeff.sourceforge.net/SnpEff_manual.html#input
207 * a unique identifier under which to save metadata about feature
208 * attributes (selected INFO field data)
210 private String sourceId;
213 * The INFO IDs of data that is both present in the VCF file, and
214 * also matched by any filters for data of interest
216 List<String> vcfFieldsOfInterest;
219 * The field offsets and identifiers for VEP (CSQ) data that is both present
220 * in the VCF file, and also matched by any filters for data of interest
221 * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
223 Map<Integer, String> vepFieldsOfInterest;
226 * Constructor given a VCF file
230 public VCFLoader(String vcfFile)
235 } catch (IOException e)
237 System.err.println("Error opening VCF file: " + e.getMessage());
240 // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
241 assemblyMappings = new HashMap<>();
245 * Starts a new thread to query and load VCF variant data on to the given
248 * This method is not thread safe - concurrent threads should use separate
249 * instances of this class.
254 public void loadVCF(SequenceI[] seqs, final AlignViewControllerGuiI gui)
258 gui.setStatus(MessageManager.getString("label.searching_vcf"));
266 VCFLoader.this.doLoad(seqs, gui);
272 * Reads the specified contig sequence and adds its VCF variants to it
275 * the id of a single sequence (contig) to load
278 public SequenceI loadVCFContig(String contig)
280 VCFHeaderLine headerLine = header.getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
281 if (headerLine == null)
283 Cache.log.error("VCF reference header not found");
286 String ref = headerLine.getValue();
287 if (ref.startsWith("file://"))
289 ref = ref.substring(7);
291 setSpeciesAndAssembly(ref);
293 SequenceI seq = null;
294 File dbFile = new File(ref);
298 HtsContigDb db = new HtsContigDb("", dbFile);
299 seq = db.getSequenceProxy(contig);
300 loadSequenceVCF(seq);
305 Cache.log.error("VCF reference not found: " + ref);
312 * Loads VCF on to one or more sequences
316 * optional callback handler for messages
318 protected void doLoad(SequenceI[] seqs, AlignViewControllerGuiI gui)
322 VCFHeaderLine ref = header
323 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
324 String reference = ref == null ? null : ref.getValue();
326 setSpeciesAndAssembly(reference);
332 * query for VCF overlapping each sequence in turn
334 for (SequenceI seq : seqs)
336 int added = loadSequenceVCF(seq);
341 transferAddedFeatures(seq);
346 String msg = MessageManager.formatMessage("label.added_vcf",
349 if (gui.getFeatureSettingsUI() != null)
351 gui.getFeatureSettingsUI().discoverAllFeatureData();
354 } catch (Throwable e)
356 System.err.println("Error processing VCF: " + e.getMessage());
360 gui.setStatus("Error occurred - see console for details");
369 } catch (IOException e)
380 * Attempts to determine and save the species and genome assembly version to
381 * which the VCF data applies. This may be done by parsing the {@code reference}
382 * header line, configured in a property file, or (potentially) confirmed
383 * interactively by the user.
385 * The saved values should be identifiers valid for Ensembl's REST service
386 * {@code map} endpoint, so they can be used (if necessary) to retrieve the
387 * mapping between VCF coordinates and sequence coordinates.
390 * @see https://rest.ensembl.org/documentation/info/assembly_map
391 * @see https://rest.ensembl.org/info/assembly/human?content-type=text/xml
392 * @see https://rest.ensembl.org/info/species?content-type=text/xml
394 protected void setSpeciesAndAssembly(String reference)
396 if (reference == null)
398 Cache.log.error("No VCF ##reference found, defaulting to "
399 + DEFAULT_REFERENCE + ":" + DEFAULT_SPECIES);
400 reference = DEFAULT_REFERENCE; // default to GRCh37 if not specified
402 reference = reference.toLowerCase();
405 * for a non-human species, or other assembly identifier,
406 * specify as a Jalview property file entry e.g.
407 * VCF_ASSEMBLY = hs37=GRCh37,assembly19=GRCh37
408 * VCF_SPECIES = c_elegans=celegans
409 * to map a token in the reference header to a value
411 String prop = Cache.getDefault(VCF_ASSEMBLY, DEFAULT_VCF_ASSEMBLY);
412 for (String token : prop.split(","))
414 String[] tokens = token.split("=");
415 if (tokens.length == 2)
417 if (reference.contains(tokens[0].trim().toLowerCase()))
419 vcfAssembly = tokens[1].trim();
425 vcfSpecies = DEFAULT_SPECIES;
426 prop = Cache.getProperty(VCF_SPECIES);
429 for (String token : prop.split(","))
431 String[] tokens = token.split("=");
432 if (tokens.length == 2)
434 if (reference.contains(tokens[0].trim().toLowerCase()))
436 vcfSpecies = tokens[1].trim();
445 * Opens the VCF file and parses header data
448 * @throws IOException
450 private void initialise(String filePath) throws IOException
452 vcfFilePath = filePath;
454 reader = new VCFReader(filePath);
456 header = reader.getFileHeader();
460 dictionary = header.getSequenceDictionary();
461 } catch (SAMException e)
463 // ignore - thrown if any contig line lacks length info
468 saveMetadata(sourceId);
471 * get offset of CSQ ALLELE_NUM and Feature if declared
477 * Reads metadata (such as INFO field descriptions and datatypes) and saves
478 * them for future reference
482 void saveMetadata(String theSourceId)
484 List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
486 vcfFieldsOfInterest = new ArrayList<>();
488 FeatureSource metadata = new FeatureSource(theSourceId);
490 for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
492 String attributeId = info.getID();
493 String desc = info.getDescription();
494 VCFHeaderLineType type = info.getType();
495 FeatureAttributeType attType = null;
499 attType = FeatureAttributeType.Character;
502 attType = FeatureAttributeType.Flag;
505 attType = FeatureAttributeType.Float;
508 attType = FeatureAttributeType.Integer;
511 attType = FeatureAttributeType.String;
514 metadata.setAttributeName(attributeId, desc);
515 metadata.setAttributeType(attributeId, attType);
517 if (isFieldWanted(attributeId, vcfFieldPatterns))
519 vcfFieldsOfInterest.add(attributeId);
523 FeatureSources.getInstance().addSource(theSourceId, metadata);
527 * Answers true if the field id is matched by any of the filter patterns, else
528 * false. Matching is against regular expression patterns, and is not
535 private boolean isFieldWanted(String id, List<Pattern> filters)
537 for (Pattern p : filters)
539 if (p.matcher(id.toUpperCase()).matches())
548 * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
549 * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
550 * required for processing.
552 * CSQ fields are declared in the CSQ INFO Description e.g.
554 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
556 protected void parseCsqHeader()
558 List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
560 vepFieldsOfInterest = new HashMap<>();
562 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
569 * parse out the pipe-separated list of CSQ fields; we assume here that
570 * these form the last part of the description, and contain no spaces
572 String desc = csqInfo.getDescription();
573 int spacePos = desc.lastIndexOf(" ");
574 desc = desc.substring(spacePos + 1);
578 String[] format = desc.split(PIPE_REGEX);
580 for (String field : format)
582 if (CSQ_CONSEQUENCE_KEY.equals(field))
584 csqConsequenceFieldIndex = index;
586 if (CSQ_ALLELE_NUM_KEY.equals(field))
588 csqAlleleNumberFieldIndex = index;
590 if (CSQ_ALLELE_KEY.equals(field))
592 csqAlleleFieldIndex = index;
594 if (CSQ_FEATURE_KEY.equals(field))
596 csqFeatureFieldIndex = index;
599 if (isFieldWanted(field, vepFieldFilters))
601 vepFieldsOfInterest.put(index, field);
610 * Reads the Preference value for the given key, with default specified if no
611 * preference set. The value is interpreted as a comma-separated list of
612 * regular expressions, and converted into a list of compiled patterns ready
613 * for matching. Patterns are forced to upper-case for non-case-sensitive
616 * This supports user-defined filters for fields of interest to capture while
617 * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
618 * fields with an ID of AF, or starting with AC, would be matched.
624 private List<Pattern> getFieldMatchers(String key, String def)
626 String pref = Cache.getDefault(key, def);
627 List<Pattern> patterns = new ArrayList<>();
628 String[] tokens = pref.split(",");
629 for (String token : tokens)
633 patterns.add(Pattern.compile(token.toUpperCase()));
634 } catch (PatternSyntaxException e)
636 System.err.println("Invalid pattern ignored: " + token);
643 * Transfers VCF features to sequences to which this sequence has a mapping.
644 * If the mapping is 3:1, computes peptide variants from nucleotide variants.
648 protected void transferAddedFeatures(SequenceI seq)
650 DBRefEntry[] dbrefs = seq.getDBRefs();
655 for (DBRefEntry dbref : dbrefs)
657 Mapping mapping = dbref.getMap();
658 if (mapping == null || mapping.getTo() == null)
663 SequenceI mapTo = mapping.getTo();
664 MapList map = mapping.getMap();
665 if (map.getFromRatio() == 3)
668 * dna-to-peptide product mapping
670 // JAL-3187 render on the fly instead
671 // AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
676 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
678 List<SequenceFeature> features = seq.getFeatures()
679 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
680 for (SequenceFeature sf : features)
682 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
684 transferFeature(sf, mapTo, map);
692 * Tries to add overlapping variants read from a VCF file to the given sequence,
693 * and returns the number of variant features added
698 protected int loadSequenceVCF(SequenceI seq)
700 VCFMap vcfMap = getVcfMap(seq);
707 * work with the dataset sequence here
709 SequenceI dss = seq.getDatasetSequence();
714 return addVcfVariants(dss, vcfMap);
718 * Answers a map from sequence coordinates to VCF chromosome ranges
723 private VCFMap getVcfMap(SequenceI seq)
726 * simplest case: sequence has id and length matching a VCF contig
728 VCFMap vcfMap = null;
729 if (dictionary != null)
731 vcfMap = getContigMap(seq);
739 * otherwise, map to VCF from chromosomal coordinates
740 * of the sequence (if known)
742 GeneLociI seqCoords = seq.getGeneLoci();
743 if (seqCoords == null)
745 Cache.log.warn(String.format(
746 "Can't query VCF for %s as chromosome coordinates not known",
751 String species = seqCoords.getSpeciesId();
752 String chromosome = seqCoords.getChromosomeId();
753 String seqRef = seqCoords.getAssemblyId();
754 MapList map = seqCoords.getMapping();
756 // note this requires the configured species to match that
757 // returned with the Ensembl sequence; todo: support aliases?
758 if (!vcfSpecies.equalsIgnoreCase(species))
760 Cache.log.warn("No VCF loaded to " + seq.getName()
761 + " as species not matched");
765 if (seqRef.equalsIgnoreCase(vcfAssembly))
767 return new VCFMap(chromosome, map);
771 * VCF data has a different reference assembly to the sequence:
772 * query Ensembl to map chromosomal coordinates from sequence to VCF
774 List<int[]> toVcfRanges = new ArrayList<>();
775 List<int[]> fromSequenceRanges = new ArrayList<>();
777 for (int[] range : map.getToRanges())
779 int[] fromRange = map.locateInFrom(range[0], range[1]);
780 if (fromRange == null)
786 int[] newRange = mapReferenceRange(range, chromosome, "human", seqRef,
788 if (newRange == null)
791 String.format("Failed to map %s:%s:%s:%d:%d to %s", species,
792 chromosome, seqRef, range[0], range[1],
798 toVcfRanges.add(newRange);
799 fromSequenceRanges.add(fromRange);
803 return new VCFMap(chromosome,
804 new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
808 * If the sequence id matches a contig declared in the VCF file, and the
809 * sequence length matches the contig length, then returns a 1:1 map of the
810 * sequence to the contig, else returns null
815 private VCFMap getContigMap(SequenceI seq)
817 String id = seq.getName();
818 SAMSequenceRecord contig = dictionary.getSequence(id);
821 int len = seq.getLength();
822 if (len == contig.getSequenceLength())
824 MapList map = new MapList(new int[] { 1, len },
827 return new VCFMap(id, map);
834 * Queries the VCF reader for any variants that overlap the mapped chromosome
835 * ranges of the sequence, and adds as variant features. Returns the number of
836 * overlapping variants found.
840 * mapping from sequence to VCF coordinates
843 protected int addVcfVariants(SequenceI seq, VCFMap map)
845 boolean forwardStrand = map.map.isToForwardStrand();
848 * query the VCF for overlaps of each contiguous chromosomal region
852 for (int[] range : map.map.getToRanges())
854 int vcfStart = Math.min(range[0], range[1]);
855 int vcfEnd = Math.max(range[0], range[1]);
856 CloseableIterator<VariantContext> variants = reader
857 .query(map.chromosome, vcfStart, vcfEnd);
858 while (variants.hasNext())
860 VariantContext variant = variants.next();
862 int[] featureRange = map.map.locateInFrom(variant.getStart(),
865 if (featureRange != null)
867 int featureStart = Math.min(featureRange[0], featureRange[1]);
868 int featureEnd = Math.max(featureRange[0], featureRange[1]);
869 count += addAlleleFeatures(seq, variant, featureStart, featureEnd,
880 * A convenience method to get an attribute value for an alternate allele
883 * @param attributeName
887 protected String getAttributeValue(VariantContext variant,
888 String attributeName, int alleleIndex)
890 Object att = variant.getAttribute(attributeName);
892 if (att instanceof String)
896 else if (att instanceof ArrayList)
898 return ((List<String>) att).get(alleleIndex);
905 * Adds one variant feature for each allele in the VCF variant record, and
906 * returns the number of features added.
910 * @param featureStart
912 * @param forwardStrand
915 protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
916 int featureStart, int featureEnd, boolean forwardStrand)
921 * Javadoc says getAlternateAlleles() imposes no order on the list returned
922 * so we proceed defensively to get them in strict order
924 int altAlleleCount = variant.getAlternateAlleles().size();
925 for (int i = 0; i < altAlleleCount; i++)
927 added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
934 * Inspects one allele and attempts to add a variant feature for it to the
935 * sequence. The additional data associated with this allele is extracted to
936 * store in the feature's key-value map. Answers the number of features added (0
941 * @param altAlleleIndex
943 * @param featureStart
945 * @param forwardStrand
948 protected int addAlleleFeature(SequenceI seq, VariantContext variant,
949 int altAlleleIndex, int featureStart, int featureEnd,
950 boolean forwardStrand)
952 String reference = variant.getReference().getBaseString();
953 Allele alt = variant.getAlternateAllele(altAlleleIndex);
954 String allele = alt.getBaseString();
957 * insertion after a genomic base, if on reverse strand, has to be
958 * converted to insertion of complement after the preceding position
960 int referenceLength = reference.length();
961 if (!forwardStrand && allele.length() > referenceLength
962 && allele.startsWith(reference))
964 featureStart -= referenceLength;
965 featureEnd = featureStart;
966 char insertAfter = seq.getCharAt(featureStart - seq.getStart());
967 reference = Dna.reverseComplement(String.valueOf(insertAfter));
968 allele = allele.substring(referenceLength) + reference;
972 * build the ref,alt allele description e.g. "G,A", using the base
973 * complement if the sequence is on the reverse strand
975 StringBuilder sb = new StringBuilder();
976 sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
978 sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
979 String alleles = sb.toString(); // e.g. G,A
982 * pick out the consequence data (if any) that is for the current allele
983 * and feature (transcript) that matches the current sequence
985 String consequence = getConsequenceForAlleleAndFeature(variant, CSQ_FIELD,
986 altAlleleIndex, csqAlleleFieldIndex,
987 csqAlleleNumberFieldIndex, seq.getName().toLowerCase(),
988 csqFeatureFieldIndex);
991 * pick out the ontology term for the consequence type
993 String type = SequenceOntologyI.SEQUENCE_VARIANT;
994 if (consequence != null)
996 type = getOntologyTerm(consequence);
999 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
1000 featureEnd, FEATURE_GROUP_VCF);
1001 sf.setSource(sourceId);
1003 sf.setValue(Gff3Helper.ALLELES, alleles);
1005 addAlleleProperties(variant, sf, altAlleleIndex, consequence);
1007 seq.addSequenceFeature(sf);
1013 * Determines the Sequence Ontology term to use for the variant feature type in
1014 * Jalview. The default is 'sequence_variant', but a more specific term is used
1017 * <li>VEP (or SnpEff) Consequence annotation is included in the VCF</li>
1018 * <li>sequence id can be matched to VEP Feature (or SnpEff Feature_ID)</li>
1021 * @param consequence
1023 * @see http://www.sequenceontology.org/browser/current_svn/term/SO:0001060
1025 String getOntologyTerm(String consequence)
1027 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1030 * could we associate Consequence data with this allele and feature (transcript)?
1031 * if so, prefer the consequence term from that data
1033 if (csqAlleleFieldIndex == -1) // && snpEffAlleleFieldIndex == -1
1036 * no Consequence data so we can't refine the ontology term
1041 if (consequence != null)
1043 String[] csqFields = consequence.split(PIPE_REGEX);
1044 if (csqFields.length > csqConsequenceFieldIndex)
1046 type = csqFields[csqConsequenceFieldIndex];
1051 // todo the same for SnpEff consequence data matching if wanted
1055 * if of the form (e.g.) missense_variant&splice_region_variant,
1056 * just take the first ('most severe') consequence
1060 int pos = type.indexOf('&');
1063 type = type.substring(0, pos);
1070 * Returns matched consequence data if it can be found, else null.
1072 * <li>inspects the VCF data for key 'vcfInfoId'</li>
1073 * <li>splits this on comma (to distinct consequences)</li>
1074 * <li>returns the first consequence (if any) where</li>
1076 * <li>the allele matches the altAlleleIndex'th allele of variant</li>
1077 * <li>the feature matches the sequence name (e.g. transcript id)</li>
1080 * If matched, the consequence is returned (as pipe-delimited fields).
1084 * @param altAlleleIndex
1085 * @param alleleFieldIndex
1086 * @param alleleNumberFieldIndex
1088 * @param featureFieldIndex
1091 private String getConsequenceForAlleleAndFeature(VariantContext variant,
1092 String vcfInfoId, int altAlleleIndex, int alleleFieldIndex,
1093 int alleleNumberFieldIndex,
1094 String seqName, int featureFieldIndex)
1096 if (alleleFieldIndex == -1 || featureFieldIndex == -1)
1100 Object value = variant.getAttribute(vcfInfoId);
1102 if (value == null || !(value instanceof List<?>))
1108 * inspect each consequence in turn (comma-separated blocks
1109 * extracted by htsjdk)
1111 List<String> consequences = (List<String>) value;
1113 for (String consequence : consequences)
1115 String[] csqFields = consequence.split(PIPE_REGEX);
1116 if (csqFields.length > featureFieldIndex)
1118 String featureIdentifier = csqFields[featureFieldIndex];
1119 if (featureIdentifier.length() > 4
1120 && seqName.indexOf(featureIdentifier.toLowerCase()) > -1)
1123 * feature (transcript) matched - now check for allele match
1125 if (matchAllele(variant, altAlleleIndex, csqFields,
1126 alleleFieldIndex, alleleNumberFieldIndex))
1136 private boolean matchAllele(VariantContext variant, int altAlleleIndex,
1137 String[] csqFields, int alleleFieldIndex,
1138 int alleleNumberFieldIndex)
1141 * if ALLELE_NUM is present, it must match altAlleleIndex
1142 * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1144 if (alleleNumberFieldIndex > -1)
1146 if (csqFields.length <= alleleNumberFieldIndex)
1150 String alleleNum = csqFields[alleleNumberFieldIndex];
1151 return String.valueOf(altAlleleIndex + 1).equals(alleleNum);
1155 * else consequence allele must match variant allele
1157 if (alleleFieldIndex > -1 && csqFields.length > alleleFieldIndex)
1159 String csqAllele = csqFields[alleleFieldIndex];
1160 String vcfAllele = variant.getAlternateAllele(altAlleleIndex)
1162 return csqAllele.equals(vcfAllele);
1168 * Add any allele-specific VCF key-value data to the sequence feature
1172 * @param altAlelleIndex
1174 * @param consequence
1175 * if not null, the consequence specific to this sequence (transcript
1176 * feature) and allele
1178 protected void addAlleleProperties(VariantContext variant,
1179 SequenceFeature sf, final int altAlelleIndex, String consequence)
1181 Map<String, Object> atts = variant.getAttributes();
1183 for (Entry<String, Object> att : atts.entrySet())
1185 String key = att.getKey();
1188 * extract Consequence data (if present) that we are able to
1189 * associated with the allele for this variant feature
1191 if (CSQ_FIELD.equals(key))
1193 addConsequences(variant, sf, consequence);
1198 * filter out fields we don't want to capture
1200 if (!vcfFieldsOfInterest.contains(key))
1206 * we extract values for other data which are allele-specific;
1207 * these may be per alternate allele (INFO[key].Number = 'A')
1208 * or per allele including reference (INFO[key].Number = 'R')
1210 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
1211 if (infoHeader == null)
1214 * can't be sure what data belongs to this allele, so
1215 * play safe and don't take any
1220 VCFHeaderLineCount number = infoHeader.getCountType();
1221 int index = altAlelleIndex;
1222 if (number == VCFHeaderLineCount.R)
1225 * one value per allele including reference, so bump index
1226 * e.g. the 3rd value is for the 2nd alternate allele
1230 else if (number != VCFHeaderLineCount.A)
1233 * don't save other values as not allele-related
1239 * take the index'th value
1241 String value = getAttributeValue(variant, key, index);
1244 value = decodeSpecialCharacters(value);
1245 sf.setValue(key, value);
1251 * Decodes colon, semicolon, equals sign, percent sign, comma to their decoded
1252 * form. The VCF specification (para 1.2) requires these to be encoded where not
1253 * used with their special meaning in the VCF syntax. Note that general URL
1254 * decoding should not be applied, since this would incorrectly decode (for
1255 * example) a '+' sign.
1260 protected static String decodeSpecialCharacters(String value)
1263 * avoid regex compilation if it is not needed!
1265 if (!value.contains(ENCODED_COLON) && !value.contains(ENCODED_SEMICOLON)
1266 && !value.contains(ENCODED_EQUALS)
1267 && !value.contains(ENCODED_PERCENT)
1268 && !value.contains(ENCODED_COMMA))
1273 value = value.replace(ENCODED_COLON, ":")
1274 .replace(ENCODED_SEMICOLON, ";").replace(ENCODED_EQUALS, "=")
1275 .replace(ENCODED_PERCENT, "%").replace(ENCODED_COMMA, ",");
1280 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
1283 * If <code>myConsequence</code> is not null, then this is the specific
1284 * consequence data (pipe-delimited fields) that is for the current allele and
1285 * transcript (sequence) being processed)
1289 * @param myConsequence
1291 protected void addConsequences(VariantContext variant, SequenceFeature sf,
1292 String myConsequence)
1294 Object value = variant.getAttribute(CSQ_FIELD);
1296 if (value == null || !(value instanceof List<?>))
1301 List<String> consequences = (List<String>) value;
1304 * inspect CSQ consequences; restrict to the consequence
1305 * associated with the current transcript (Feature)
1307 Map<String, String> csqValues = new HashMap<>();
1309 for (String consequence : consequences)
1311 if (myConsequence == null || myConsequence.equals(consequence))
1313 String[] csqFields = consequence.split(PIPE_REGEX);
1316 * inspect individual fields of this consequence, copying non-null
1317 * values which are 'fields of interest'
1320 for (String field : csqFields)
1322 if (field != null && field.length() > 0)
1324 String id = vepFieldsOfInterest.get(i);
1328 * VCF spec requires encoding of special characters e.g. '='
1329 * so decode them here before storing
1333 field = URLDecoder.decode(field, UTF_8);
1334 } catch (UnsupportedEncodingException e)
1337 csqValues.put(id, field);
1345 if (!csqValues.isEmpty())
1347 sf.setValue(CSQ_FIELD, csqValues);
1352 * A convenience method to complement a dna base and return the string value
1358 protected String complement(byte[] reference)
1360 return String.valueOf(Dna.getComplement((char) reference[0]));
1364 * Determines the location of the query range (chromosome positions) in a
1365 * different reference assembly.
1367 * If the range is just a subregion of one for which we already have a mapping
1368 * (for example, an exon sub-region of a gene), then the mapping is just
1369 * computed arithmetically.
1371 * Otherwise, calls the Ensembl REST service that maps from one assembly
1372 * reference's coordinates to another's
1375 * start-end chromosomal range in 'fromRef' coordinates
1379 * assembly reference for the query coordinates
1381 * assembly reference we wish to translate to
1382 * @return the start-end range in 'toRef' coordinates
1384 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
1385 String species, String fromRef, String toRef)
1388 * first try shorcut of computing the mapping as a subregion of one
1389 * we already have (e.g. for an exon, if we have the gene mapping)
1391 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
1392 species, fromRef, toRef);
1393 if (mappedRange != null)
1399 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
1401 EnsemblMap mapper = new EnsemblMap();
1402 int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
1405 if (mapping == null)
1407 // mapping service failure
1412 * save mapping for possible future re-use
1414 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1415 if (!assemblyMappings.containsKey(key))
1417 assemblyMappings.put(key, new HashMap<int[], int[]>());
1420 assemblyMappings.get(key).put(queryRange, mapping);
1426 * If we already have a 1:1 contiguous mapping which subsumes the given query
1427 * range, this method just calculates and returns the subset of that mapping,
1428 * else it returns null. In practical terms, if a gene has a contiguous
1429 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
1430 * subsidiary exons occupy unchanged relative positions, and just compute
1431 * these as offsets, rather than do another lookup of the mapping.
1433 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
1434 * simply remove this method or let it always return null.
1436 * Warning: many rapid calls to the /map service map result in a 429 overload
1446 protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
1447 String species, String fromRef, String toRef)
1449 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1450 if (assemblyMappings.containsKey(key))
1452 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
1453 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
1455 int[] fromRange = mappedRange.getKey();
1456 int[] toRange = mappedRange.getValue();
1457 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
1460 * mapping is 1:1 in length, so we trust it to have no discontinuities
1462 if (MappingUtils.rangeContains(fromRange, queryRange))
1465 * fromRange subsumes our query range
1467 int offset = queryRange[0] - fromRange[0];
1468 int mappedRangeFrom = toRange[0] + offset;
1469 int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
1470 return new int[] { mappedRangeFrom, mappedRangeTo };
1479 * Transfers the sequence feature to the target sequence, locating its start
1480 * and end range based on the mapping. Features which do not overlap the
1481 * target sequence are ignored.
1484 * @param targetSequence
1486 * mapping from the feature's coordinates to the target sequence
1488 protected void transferFeature(SequenceFeature sf,
1489 SequenceI targetSequence, MapList mapping)
1491 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1493 if (mappedRange != null)
1495 String group = sf.getFeatureGroup();
1496 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1497 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1498 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1499 group, sf.getScore());
1500 targetSequence.addSequenceFeature(copy);
1505 * Formats a ranges map lookup key
1513 protected static String makeRangesKey(String chromosome, String species,
1514 String fromRef, String toRef)
1516 return species + EXCL + chromosome + EXCL + fromRef + EXCL