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 UTF_8 = "UTF-8";
57 private static final String DEFAULT_SPECIES = "homo_sapiens";
60 * A class to model the mapping from sequence to VCF coordinates. Cases include
62 * <li>a direct 1:1 mapping where the sequence is one of the VCF contigs</li>
63 * <li>a mapping of sequence to chromosomal coordinates, where sequence and VCF
64 * use the same reference assembly</li>
65 * <li>a modified mapping of sequence to chromosomal coordinates, where sequence
66 * and VCF use different reference assembles</li>
71 final String chromosome;
75 VCFMap(String chr, MapList m)
82 public String toString()
84 return chromosome + ":" + map.toString();
89 * Lookup keys, and default values, for Preference entries that describe
90 * patterns for VCF and VEP fields to capture
92 private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
94 private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
96 private static final String DEFAULT_VCF_FIELDS = ".*";
98 private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
101 * Lookup keys, and default values, for Preference entries that give
102 * mappings from tokens in the 'reference' header to species or assembly
104 private static final String VCF_ASSEMBLY = "VCF_ASSEMBLY";
106 private static final String DEFAULT_VCF_ASSEMBLY = "assembly19=GRCh37,hs37=GRCh37,grch37=GRCh37,grch38=GRCh38";
108 private static final String VCF_SPECIES = "VCF_SPECIES"; // default is human
110 private static final String DEFAULT_REFERENCE = "grch37"; // fallback default is human GRCh37
113 * keys to fields of VEP CSQ consequence data
114 * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
116 private static final String CSQ_CONSEQUENCE_KEY = "Consequence";
117 private static final String CSQ_ALLELE_KEY = "Allele";
118 private static final String CSQ_ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref), 1...
119 private static final String CSQ_FEATURE_KEY = "Feature"; // Ensembl stable id
122 * default VCF INFO key for VEP consequence data
123 * NB this can be overridden running VEP with --vcf_info_field
124 * - we don't handle this case (require identifier to be CSQ)
126 private static final String CSQ_FIELD = "CSQ";
129 * separator for fields in consequence data is '|'
131 private static final String PIPE_REGEX = "\\|";
134 * delimiter that separates multiple consequence data blocks
136 private static final String COMMA = ",";
139 * the feature group assigned to a VCF variant in Jalview
141 private static final String FEATURE_GROUP_VCF = "VCF";
144 * internal delimiter used to build keys for assemblyMappings
147 private static final String EXCL = "!";
150 * the VCF file we are processing
152 protected String vcfFilePath;
155 * mappings between VCF and sequence reference assembly regions, as
156 * key = "species!chromosome!fromAssembly!toAssembly
157 * value = Map{fromRange, toRange}
159 private Map<String, Map<int[], int[]>> assemblyMappings;
161 private VCFReader reader;
164 * holds details of the VCF header lines (metadata)
166 private VCFHeader header;
169 * species (as a valid Ensembl term) the VCF is for
171 private String vcfSpecies;
174 * genome assembly version (as a valid Ensembl identifier) the VCF is for
176 private String vcfAssembly;
179 * a Dictionary of contigs (if present) referenced in the VCF file
181 private SAMSequenceDictionary dictionary;
184 * the position (0...) of field in each block of
185 * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
186 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
188 private int csqConsequenceFieldIndex = -1;
189 private int csqAlleleFieldIndex = -1;
190 private int csqAlleleNumberFieldIndex = -1;
191 private int csqFeatureFieldIndex = -1;
193 // todo the same fields for SnpEff ANN data if wanted
194 // see http://snpeff.sourceforge.net/SnpEff_manual.html#input
197 * a unique identifier under which to save metadata about feature
198 * attributes (selected INFO field data)
200 private String sourceId;
203 * The INFO IDs of data that is both present in the VCF file, and
204 * also matched by any filters for data of interest
206 List<String> vcfFieldsOfInterest;
209 * The field offsets and identifiers for VEP (CSQ) data that is both present
210 * in the VCF file, and also matched by any filters for data of interest
211 * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
213 Map<Integer, String> vepFieldsOfInterest;
216 * Constructor given a VCF file
220 public VCFLoader(String vcfFile)
225 } catch (IOException e)
227 System.err.println("Error opening VCF file: " + e.getMessage());
230 // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
231 assemblyMappings = new HashMap<>();
235 * Starts a new thread to query and load VCF variant data on to the given
238 * This method is not thread safe - concurrent threads should use separate
239 * instances of this class.
244 public void loadVCF(SequenceI[] seqs, final AlignViewControllerGuiI gui)
248 gui.setStatus(MessageManager.getString("label.searching_vcf"));
256 VCFLoader.this.doLoad(seqs, gui);
262 * Reads the specified contig sequence and adds its VCF variants to it
265 * the id of a single sequence (contig) to load
268 public SequenceI loadVCFContig(String contig)
270 VCFHeaderLine headerLine = header.getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
271 if (headerLine == null)
273 Cache.log.error("VCF reference header not found");
276 String ref = headerLine.getValue();
277 if (ref.startsWith("file://"))
279 ref = ref.substring(7);
281 setSpeciesAndAssembly(ref);
283 SequenceI seq = null;
284 File dbFile = new File(ref);
288 HtsContigDb db = new HtsContigDb("", dbFile);
289 seq = db.getSequenceProxy(contig);
290 loadSequenceVCF(seq);
295 Cache.log.error("VCF reference not found: " + ref);
302 * Loads VCF on to one or more sequences
306 * optional callback handler for messages
308 protected void doLoad(SequenceI[] seqs, AlignViewControllerGuiI gui)
312 VCFHeaderLine ref = header
313 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
314 String reference = ref == null ? null : ref.getValue();
316 setSpeciesAndAssembly(reference);
322 * query for VCF overlapping each sequence in turn
324 for (SequenceI seq : seqs)
326 int added = loadSequenceVCF(seq);
331 transferAddedFeatures(seq);
336 String msg = MessageManager.formatMessage("label.added_vcf",
339 if (gui.getFeatureSettingsUI() != null)
341 gui.getFeatureSettingsUI().discoverAllFeatureData();
344 } catch (Throwable e)
346 System.err.println("Error processing VCF: " + e.getMessage());
350 gui.setStatus("Error occurred - see console for details");
359 } catch (IOException e)
370 * Attempts to determine and save the species and genome assembly version to
371 * which the VCF data applies. This may be done by parsing the {@code reference}
372 * header line, configured in a property file, or (potentially) confirmed
373 * interactively by the user.
375 * The saved values should be identifiers valid for Ensembl's REST service
376 * {@code map} endpoint, so they can be used (if necessary) to retrieve the
377 * mapping between VCF coordinates and sequence coordinates.
380 * @see https://rest.ensembl.org/documentation/info/assembly_map
381 * @see https://rest.ensembl.org/info/assembly/human?content-type=text/xml
382 * @see https://rest.ensembl.org/info/species?content-type=text/xml
384 protected void setSpeciesAndAssembly(String reference)
386 if (reference == null)
388 Cache.log.error("No VCF ##reference found, defaulting to "
389 + DEFAULT_REFERENCE + ":" + DEFAULT_SPECIES);
390 reference = DEFAULT_REFERENCE; // default to GRCh37 if not specified
392 reference = reference.toLowerCase();
395 * for a non-human species, or other assembly identifier,
396 * specify as a Jalview property file entry e.g.
397 * VCF_ASSEMBLY = hs37=GRCh37,assembly19=GRCh37
398 * VCF_SPECIES = c_elegans=celegans
399 * to map a token in the reference header to a value
401 String prop = Cache.getDefault(VCF_ASSEMBLY, DEFAULT_VCF_ASSEMBLY);
402 for (String token : prop.split(","))
404 String[] tokens = token.split("=");
405 if (tokens.length == 2)
407 if (reference.contains(tokens[0].trim().toLowerCase()))
409 vcfAssembly = tokens[1].trim();
415 vcfSpecies = DEFAULT_SPECIES;
416 prop = Cache.getProperty(VCF_SPECIES);
419 for (String token : prop.split(","))
421 String[] tokens = token.split("=");
422 if (tokens.length == 2)
424 if (reference.contains(tokens[0].trim().toLowerCase()))
426 vcfSpecies = tokens[1].trim();
435 * Opens the VCF file and parses header data
438 * @throws IOException
440 private void initialise(String filePath) throws IOException
442 vcfFilePath = filePath;
444 reader = new VCFReader(filePath);
446 header = reader.getFileHeader();
450 dictionary = header.getSequenceDictionary();
451 } catch (SAMException e)
453 // ignore - thrown if any contig line lacks length info
458 saveMetadata(sourceId);
461 * get offset of CSQ ALLELE_NUM and Feature if declared
467 * Reads metadata (such as INFO field descriptions and datatypes) and saves
468 * them for future reference
472 void saveMetadata(String theSourceId)
474 List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
476 vcfFieldsOfInterest = new ArrayList<>();
478 FeatureSource metadata = new FeatureSource(theSourceId);
480 for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
482 String attributeId = info.getID();
483 String desc = info.getDescription();
484 VCFHeaderLineType type = info.getType();
485 FeatureAttributeType attType = null;
489 attType = FeatureAttributeType.Character;
492 attType = FeatureAttributeType.Flag;
495 attType = FeatureAttributeType.Float;
498 attType = FeatureAttributeType.Integer;
501 attType = FeatureAttributeType.String;
504 metadata.setAttributeName(attributeId, desc);
505 metadata.setAttributeType(attributeId, attType);
507 if (isFieldWanted(attributeId, vcfFieldPatterns))
509 vcfFieldsOfInterest.add(attributeId);
513 FeatureSources.getInstance().addSource(theSourceId, metadata);
517 * Answers true if the field id is matched by any of the filter patterns, else
518 * false. Matching is against regular expression patterns, and is not
525 private boolean isFieldWanted(String id, List<Pattern> filters)
527 for (Pattern p : filters)
529 if (p.matcher(id.toUpperCase()).matches())
538 * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
539 * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
540 * required for processing.
542 * CSQ fields are declared in the CSQ INFO Description e.g.
544 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
546 protected void parseCsqHeader()
548 List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
550 vepFieldsOfInterest = new HashMap<>();
552 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
559 * parse out the pipe-separated list of CSQ fields; we assume here that
560 * these form the last part of the description, and contain no spaces
562 String desc = csqInfo.getDescription();
563 int spacePos = desc.lastIndexOf(" ");
564 desc = desc.substring(spacePos + 1);
568 String[] format = desc.split(PIPE_REGEX);
570 for (String field : format)
572 if (CSQ_CONSEQUENCE_KEY.equals(field))
574 csqConsequenceFieldIndex = index;
576 if (CSQ_ALLELE_NUM_KEY.equals(field))
578 csqAlleleNumberFieldIndex = index;
580 if (CSQ_ALLELE_KEY.equals(field))
582 csqAlleleFieldIndex = index;
584 if (CSQ_FEATURE_KEY.equals(field))
586 csqFeatureFieldIndex = index;
589 if (isFieldWanted(field, vepFieldFilters))
591 vepFieldsOfInterest.put(index, field);
600 * Reads the Preference value for the given key, with default specified if no
601 * preference set. The value is interpreted as a comma-separated list of
602 * regular expressions, and converted into a list of compiled patterns ready
603 * for matching. Patterns are forced to upper-case for non-case-sensitive
606 * This supports user-defined filters for fields of interest to capture while
607 * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
608 * fields with an ID of AF, or starting with AC, would be matched.
614 private List<Pattern> getFieldMatchers(String key, String def)
616 String pref = Cache.getDefault(key, def);
617 List<Pattern> patterns = new ArrayList<>();
618 String[] tokens = pref.split(",");
619 for (String token : tokens)
623 patterns.add(Pattern.compile(token.toUpperCase()));
624 } catch (PatternSyntaxException e)
626 System.err.println("Invalid pattern ignored: " + token);
633 * Transfers VCF features to sequences to which this sequence has a mapping.
634 * If the mapping is 3:1, computes peptide variants from nucleotide variants.
638 protected void transferAddedFeatures(SequenceI seq)
640 DBRefEntry[] dbrefs = seq.getDBRefs();
645 for (DBRefEntry dbref : dbrefs)
647 Mapping mapping = dbref.getMap();
648 if (mapping == null || mapping.getTo() == null)
653 SequenceI mapTo = mapping.getTo();
654 MapList map = mapping.getMap();
655 if (map.getFromRatio() == 3)
658 * dna-to-peptide product mapping
660 // JAL-3187 render on the fly instead
661 // AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
666 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
668 List<SequenceFeature> features = seq.getFeatures()
669 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
670 for (SequenceFeature sf : features)
672 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
674 transferFeature(sf, mapTo, map);
682 * Tries to add overlapping variants read from a VCF file to the given sequence,
683 * and returns the number of variant features added
688 protected int loadSequenceVCF(SequenceI seq)
690 VCFMap vcfMap = getVcfMap(seq);
697 * work with the dataset sequence here
699 SequenceI dss = seq.getDatasetSequence();
704 return addVcfVariants(dss, vcfMap);
708 * Answers a map from sequence coordinates to VCF chromosome ranges
713 private VCFMap getVcfMap(SequenceI seq)
716 * simplest case: sequence has id and length matching a VCF contig
718 VCFMap vcfMap = null;
719 if (dictionary != null)
721 vcfMap = getContigMap(seq);
729 * otherwise, map to VCF from chromosomal coordinates
730 * of the sequence (if known)
732 GeneLociI seqCoords = seq.getGeneLoci();
733 if (seqCoords == null)
735 Cache.log.warn(String.format(
736 "Can't query VCF for %s as chromosome coordinates not known",
741 String species = seqCoords.getSpeciesId();
742 String chromosome = seqCoords.getChromosomeId();
743 String seqRef = seqCoords.getAssemblyId();
744 MapList map = seqCoords.getMapping();
746 // note this requires the configured species to match that
747 // returned with the Ensembl sequence; todo: support aliases?
748 if (!vcfSpecies.equalsIgnoreCase(species))
750 Cache.log.warn("No VCF loaded to " + seq.getName()
751 + " as species not matched");
755 if (seqRef.equalsIgnoreCase(vcfAssembly))
757 return new VCFMap(chromosome, map);
761 * VCF data has a different reference assembly to the sequence:
762 * query Ensembl to map chromosomal coordinates from sequence to VCF
764 List<int[]> toVcfRanges = new ArrayList<>();
765 List<int[]> fromSequenceRanges = new ArrayList<>();
767 for (int[] range : map.getToRanges())
769 int[] fromRange = map.locateInFrom(range[0], range[1]);
770 if (fromRange == null)
776 int[] newRange = mapReferenceRange(range, chromosome, "human", seqRef,
778 if (newRange == null)
781 String.format("Failed to map %s:%s:%s:%d:%d to %s", species,
782 chromosome, seqRef, range[0], range[1],
788 toVcfRanges.add(newRange);
789 fromSequenceRanges.add(fromRange);
793 return new VCFMap(chromosome,
794 new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
798 * If the sequence id matches a contig declared in the VCF file, and the
799 * sequence length matches the contig length, then returns a 1:1 map of the
800 * sequence to the contig, else returns null
805 private VCFMap getContigMap(SequenceI seq)
807 String id = seq.getName();
808 SAMSequenceRecord contig = dictionary.getSequence(id);
811 int len = seq.getLength();
812 if (len == contig.getSequenceLength())
814 MapList map = new MapList(new int[] { 1, len },
817 return new VCFMap(id, map);
824 * Queries the VCF reader for any variants that overlap the mapped chromosome
825 * ranges of the sequence, and adds as variant features. Returns the number of
826 * overlapping variants found.
830 * mapping from sequence to VCF coordinates
833 protected int addVcfVariants(SequenceI seq, VCFMap map)
835 boolean forwardStrand = map.map.isToForwardStrand();
838 * query the VCF for overlaps of each contiguous chromosomal region
842 for (int[] range : map.map.getToRanges())
844 int vcfStart = Math.min(range[0], range[1]);
845 int vcfEnd = Math.max(range[0], range[1]);
846 CloseableIterator<VariantContext> variants = reader
847 .query(map.chromosome, vcfStart, vcfEnd);
848 while (variants.hasNext())
850 VariantContext variant = variants.next();
852 int[] featureRange = map.map.locateInFrom(variant.getStart(),
855 if (featureRange != null)
857 int featureStart = Math.min(featureRange[0], featureRange[1]);
858 int featureEnd = Math.max(featureRange[0], featureRange[1]);
859 count += addAlleleFeatures(seq, variant, featureStart, featureEnd,
870 * A convenience method to get an attribute value for an alternate allele
873 * @param attributeName
877 protected String getAttributeValue(VariantContext variant,
878 String attributeName, int alleleIndex)
880 Object att = variant.getAttribute(attributeName);
882 if (att instanceof String)
886 else if (att instanceof ArrayList)
888 return ((List<String>) att).get(alleleIndex);
895 * Adds one variant feature for each allele in the VCF variant record, and
896 * returns the number of features added.
900 * @param featureStart
902 * @param forwardStrand
905 protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
906 int featureStart, int featureEnd, boolean forwardStrand)
911 * Javadoc says getAlternateAlleles() imposes no order on the list returned
912 * so we proceed defensively to get them in strict order
914 int altAlleleCount = variant.getAlternateAlleles().size();
915 for (int i = 0; i < altAlleleCount; i++)
917 added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
924 * Inspects one allele and attempts to add a variant feature for it to the
925 * sequence. The additional data associated with this allele is extracted to
926 * store in the feature's key-value map. Answers the number of features added (0
931 * @param altAlleleIndex
933 * @param featureStart
935 * @param forwardStrand
938 protected int addAlleleFeature(SequenceI seq, VariantContext variant,
939 int altAlleleIndex, int featureStart, int featureEnd,
940 boolean forwardStrand)
942 String reference = variant.getReference().getBaseString();
943 Allele alt = variant.getAlternateAllele(altAlleleIndex);
944 String allele = alt.getBaseString();
947 * insertion after a genomic base, if on reverse strand, has to be
948 * converted to insertion of complement after the preceding position
950 int referenceLength = reference.length();
951 if (!forwardStrand && allele.length() > referenceLength
952 && allele.startsWith(reference))
954 featureStart -= referenceLength;
955 featureEnd = featureStart;
956 char insertAfter = seq.getCharAt(featureStart - seq.getStart());
957 reference = Dna.reverseComplement(String.valueOf(insertAfter));
958 allele = allele.substring(referenceLength) + reference;
962 * build the ref,alt allele description e.g. "G,A", using the base
963 * complement if the sequence is on the reverse strand
965 StringBuilder sb = new StringBuilder();
966 sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
968 sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
969 String alleles = sb.toString(); // e.g. G,A
972 * pick out the consequence data (if any) that is for the current allele
973 * and feature (transcript) that matches the current sequence
975 String consequence = getConsequenceForAlleleAndFeature(variant, CSQ_FIELD,
976 altAlleleIndex, csqAlleleFieldIndex,
977 csqAlleleNumberFieldIndex, seq.getName().toLowerCase(),
978 csqFeatureFieldIndex);
981 * pick out the ontology term for the consequence type
983 String type = SequenceOntologyI.SEQUENCE_VARIANT;
984 if (consequence != null)
986 type = getOntologyTerm(consequence);
989 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
990 featureEnd, FEATURE_GROUP_VCF);
991 sf.setSource(sourceId);
993 sf.setValue(Gff3Helper.ALLELES, alleles);
995 addAlleleProperties(variant, sf, altAlleleIndex, consequence);
997 seq.addSequenceFeature(sf);
1003 * Determines the Sequence Ontology term to use for the variant feature type in
1004 * Jalview. The default is 'sequence_variant', but a more specific term is used
1007 * <li>VEP (or SnpEff) Consequence annotation is included in the VCF</li>
1008 * <li>sequence id can be matched to VEP Feature (or SnpEff Feature_ID)</li>
1011 * @param consequence
1013 * @see http://www.sequenceontology.org/browser/current_svn/term/SO:0001060
1015 String getOntologyTerm(String consequence)
1017 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1020 * could we associate Consequence data with this allele and feature (transcript)?
1021 * if so, prefer the consequence term from that data
1023 if (csqAlleleFieldIndex == -1) // && snpEffAlleleFieldIndex == -1
1026 * no Consequence data so we can't refine the ontology term
1031 if (consequence != null)
1033 String[] csqFields = consequence.split(PIPE_REGEX);
1034 if (csqFields.length > csqConsequenceFieldIndex)
1036 type = csqFields[csqConsequenceFieldIndex];
1041 // todo the same for SnpEff consequence data matching if wanted
1045 * if of the form (e.g.) missense_variant&splice_region_variant,
1046 * just take the first ('most severe') consequence
1050 int pos = type.indexOf('&');
1053 type = type.substring(0, pos);
1060 * Returns matched consequence data if it can be found, else null.
1062 * <li>inspects the VCF data for key 'vcfInfoId'</li>
1063 * <li>splits this on comma (to distinct consequences)</li>
1064 * <li>returns the first consequence (if any) where</li>
1066 * <li>the allele matches the altAlleleIndex'th allele of variant</li>
1067 * <li>the feature matches the sequence name (e.g. transcript id)</li>
1070 * If matched, the consequence is returned (as pipe-delimited fields).
1074 * @param altAlleleIndex
1075 * @param alleleFieldIndex
1076 * @param alleleNumberFieldIndex
1078 * @param featureFieldIndex
1081 private String getConsequenceForAlleleAndFeature(VariantContext variant,
1082 String vcfInfoId, int altAlleleIndex, int alleleFieldIndex,
1083 int alleleNumberFieldIndex,
1084 String seqName, int featureFieldIndex)
1086 if (alleleFieldIndex == -1 || featureFieldIndex == -1)
1090 Object value = variant.getAttribute(vcfInfoId);
1092 if (value == null || !(value instanceof List<?>))
1098 * inspect each consequence in turn (comma-separated blocks
1099 * extracted by htsjdk)
1101 List<String> consequences = (List<String>) value;
1103 for (String consequence : consequences)
1105 String[] csqFields = consequence.split(PIPE_REGEX);
1106 if (csqFields.length > featureFieldIndex)
1108 String featureIdentifier = csqFields[featureFieldIndex];
1109 if (featureIdentifier.length() > 4
1110 && seqName.indexOf(featureIdentifier.toLowerCase()) > -1)
1113 * feature (transcript) matched - now check for allele match
1115 if (matchAllele(variant, altAlleleIndex, csqFields,
1116 alleleFieldIndex, alleleNumberFieldIndex))
1126 private boolean matchAllele(VariantContext variant, int altAlleleIndex,
1127 String[] csqFields, int alleleFieldIndex,
1128 int alleleNumberFieldIndex)
1131 * if ALLELE_NUM is present, it must match altAlleleIndex
1132 * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1134 if (alleleNumberFieldIndex > -1)
1136 if (csqFields.length <= alleleNumberFieldIndex)
1140 String alleleNum = csqFields[alleleNumberFieldIndex];
1141 return String.valueOf(altAlleleIndex + 1).equals(alleleNum);
1145 * else consequence allele must match variant allele
1147 if (alleleFieldIndex > -1 && csqFields.length > alleleFieldIndex)
1149 String csqAllele = csqFields[alleleFieldIndex];
1150 String vcfAllele = variant.getAlternateAllele(altAlleleIndex)
1152 return csqAllele.equals(vcfAllele);
1158 * Add any allele-specific VCF key-value data to the sequence feature
1162 * @param altAlelleIndex
1164 * @param consequence
1165 * if not null, the consequence specific to this sequence (transcript
1166 * feature) and allele
1168 protected void addAlleleProperties(VariantContext variant,
1169 SequenceFeature sf, final int altAlelleIndex, String consequence)
1171 Map<String, Object> atts = variant.getAttributes();
1173 for (Entry<String, Object> att : atts.entrySet())
1175 String key = att.getKey();
1178 * extract Consequence data (if present) that we are able to
1179 * associated with the allele for this variant feature
1181 if (CSQ_FIELD.equals(key))
1183 addConsequences(variant, sf, consequence);
1188 * filter out fields we don't want to capture
1190 if (!vcfFieldsOfInterest.contains(key))
1196 * we extract values for other data which are allele-specific;
1197 * these may be per alternate allele (INFO[key].Number = 'A')
1198 * or per allele including reference (INFO[key].Number = 'R')
1200 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
1201 if (infoHeader == null)
1204 * can't be sure what data belongs to this allele, so
1205 * play safe and don't take any
1210 VCFHeaderLineCount number = infoHeader.getCountType();
1211 int index = altAlelleIndex;
1212 if (number == VCFHeaderLineCount.R)
1215 * one value per allele including reference, so bump index
1216 * e.g. the 3rd value is for the 2nd alternate allele
1220 else if (number != VCFHeaderLineCount.A)
1223 * don't save other values as not allele-related
1229 * take the index'th value
1231 String value = getAttributeValue(variant, key, index);
1235 * VCF spec requires encoding of special characters e.g. '='
1236 * so decode them here before storing
1240 value = URLDecoder.decode(value, UTF_8);
1241 } catch (UnsupportedEncodingException e)
1244 sf.setValue(key, value);
1250 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
1253 * If <code>myConsequence</code> is not null, then this is the specific
1254 * consequence data (pipe-delimited fields) that is for the current allele and
1255 * transcript (sequence) being processed)
1259 * @param myConsequence
1261 protected void addConsequences(VariantContext variant, SequenceFeature sf,
1262 String myConsequence)
1264 Object value = variant.getAttribute(CSQ_FIELD);
1266 if (value == null || !(value instanceof List<?>))
1271 List<String> consequences = (List<String>) value;
1274 * inspect CSQ consequences; restrict to the consequence
1275 * associated with the current transcript (Feature)
1277 Map<String, String> csqValues = new HashMap<>();
1279 for (String consequence : consequences)
1281 if (myConsequence == null || myConsequence.equals(consequence))
1283 String[] csqFields = consequence.split(PIPE_REGEX);
1286 * inspect individual fields of this consequence, copying non-null
1287 * values which are 'fields of interest'
1290 for (String field : csqFields)
1292 if (field != null && field.length() > 0)
1294 String id = vepFieldsOfInterest.get(i);
1298 * VCF spec requires encoding of special characters e.g. '='
1299 * so decode them here before storing
1303 field = URLDecoder.decode(field, UTF_8);
1304 } catch (UnsupportedEncodingException e)
1307 csqValues.put(id, field);
1315 if (!csqValues.isEmpty())
1317 sf.setValue(CSQ_FIELD, csqValues);
1322 * A convenience method to complement a dna base and return the string value
1328 protected String complement(byte[] reference)
1330 return String.valueOf(Dna.getComplement((char) reference[0]));
1334 * Determines the location of the query range (chromosome positions) in a
1335 * different reference assembly.
1337 * If the range is just a subregion of one for which we already have a mapping
1338 * (for example, an exon sub-region of a gene), then the mapping is just
1339 * computed arithmetically.
1341 * Otherwise, calls the Ensembl REST service that maps from one assembly
1342 * reference's coordinates to another's
1345 * start-end chromosomal range in 'fromRef' coordinates
1349 * assembly reference for the query coordinates
1351 * assembly reference we wish to translate to
1352 * @return the start-end range in 'toRef' coordinates
1354 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
1355 String species, String fromRef, String toRef)
1358 * first try shorcut of computing the mapping as a subregion of one
1359 * we already have (e.g. for an exon, if we have the gene mapping)
1361 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
1362 species, fromRef, toRef);
1363 if (mappedRange != null)
1369 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
1371 EnsemblMap mapper = new EnsemblMap();
1372 int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
1375 if (mapping == null)
1377 // mapping service failure
1382 * save mapping for possible future re-use
1384 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1385 if (!assemblyMappings.containsKey(key))
1387 assemblyMappings.put(key, new HashMap<int[], int[]>());
1390 assemblyMappings.get(key).put(queryRange, mapping);
1396 * If we already have a 1:1 contiguous mapping which subsumes the given query
1397 * range, this method just calculates and returns the subset of that mapping,
1398 * else it returns null. In practical terms, if a gene has a contiguous
1399 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
1400 * subsidiary exons occupy unchanged relative positions, and just compute
1401 * these as offsets, rather than do another lookup of the mapping.
1403 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
1404 * simply remove this method or let it always return null.
1406 * Warning: many rapid calls to the /map service map result in a 429 overload
1416 protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
1417 String species, String fromRef, String toRef)
1419 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1420 if (assemblyMappings.containsKey(key))
1422 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
1423 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
1425 int[] fromRange = mappedRange.getKey();
1426 int[] toRange = mappedRange.getValue();
1427 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
1430 * mapping is 1:1 in length, so we trust it to have no discontinuities
1432 if (MappingUtils.rangeContains(fromRange, queryRange))
1435 * fromRange subsumes our query range
1437 int offset = queryRange[0] - fromRange[0];
1438 int mappedRangeFrom = toRange[0] + offset;
1439 int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
1440 return new int[] { mappedRangeFrom, mappedRangeTo };
1449 * Transfers the sequence feature to the target sequence, locating its start
1450 * and end range based on the mapping. Features which do not overlap the
1451 * target sequence are ignored.
1454 * @param targetSequence
1456 * mapping from the feature's coordinates to the target sequence
1458 protected void transferFeature(SequenceFeature sf,
1459 SequenceI targetSequence, MapList mapping)
1461 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1463 if (mappedRange != null)
1465 String group = sf.getFeatureGroup();
1466 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1467 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1468 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1469 group, sf.getScore());
1470 targetSequence.addSequenceFeature(copy);
1475 * Formats a ranges map lookup key
1483 protected static String makeRangesKey(String chromosome, String species,
1484 String fromRef, String toRef)
1486 return species + EXCL + chromosome + EXCL + fromRef + EXCL