1 package jalview.io.vcf;
3 import jalview.analysis.AlignmentUtils;
4 import jalview.analysis.Dna;
5 import jalview.api.AlignViewControllerGuiI;
6 import jalview.bin.Cache;
7 import jalview.datamodel.DBRefEntry;
8 import jalview.datamodel.GeneLociI;
9 import jalview.datamodel.Mapping;
10 import jalview.datamodel.SequenceFeature;
11 import jalview.datamodel.SequenceI;
12 import jalview.datamodel.features.FeatureAttributeType;
13 import jalview.datamodel.features.FeatureSource;
14 import jalview.datamodel.features.FeatureSources;
15 import jalview.ext.ensembl.EnsemblMap;
16 import jalview.ext.htsjdk.HtsContigDb;
17 import jalview.ext.htsjdk.VCFReader;
18 import jalview.io.gff.Gff3Helper;
19 import jalview.io.gff.SequenceOntologyI;
20 import jalview.util.MapList;
21 import jalview.util.MappingUtils;
22 import jalview.util.MessageManager;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.List;
31 import java.util.Map.Entry;
33 import java.util.regex.Pattern;
34 import java.util.regex.PatternSyntaxException;
36 import htsjdk.samtools.SAMException;
37 import htsjdk.samtools.SAMSequenceDictionary;
38 import htsjdk.samtools.SAMSequenceRecord;
39 import htsjdk.samtools.util.CloseableIterator;
40 import htsjdk.tribble.TribbleException;
41 import htsjdk.variant.variantcontext.Allele;
42 import htsjdk.variant.variantcontext.VariantContext;
43 import htsjdk.variant.vcf.VCFConstants;
44 import htsjdk.variant.vcf.VCFHeader;
45 import htsjdk.variant.vcf.VCFHeaderLine;
46 import htsjdk.variant.vcf.VCFHeaderLineCount;
47 import htsjdk.variant.vcf.VCFHeaderLineType;
48 import htsjdk.variant.vcf.VCFInfoHeaderLine;
51 * A class to read VCF data (using the htsjdk) and add variants as sequence
52 * features on dna and any related protein product sequences
56 public class VCFLoader
58 private static final String NO_VALUE = VCFConstants.MISSING_VALUE_v4; // '.'
60 private static final String DEFAULT_SPECIES = "homo_sapiens";
63 * A class to model the mapping from sequence to VCF coordinates. Cases include
65 * <li>a direct 1:1 mapping where the sequence is one of the VCF contigs</li>
66 * <li>a mapping of sequence to chromosomal coordinates, where sequence and VCF
67 * use the same reference assembly</li>
68 * <li>a modified mapping of sequence to chromosomal coordinates, where sequence
69 * and VCF use different reference assembles</li>
74 final String chromosome;
78 VCFMap(String chr, MapList m)
85 public String toString()
87 return chromosome + ":" + map.toString();
92 * Lookup keys, and default values, for Preference entries that describe
93 * patterns for VCF and VEP fields to capture
95 private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
97 private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
99 private static final String DEFAULT_VCF_FIELDS = ".*";
101 private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
104 * Lookup keys, and default values, for Preference entries that give
105 * mappings from tokens in the 'reference' header to species or assembly
107 private static final String VCF_ASSEMBLY = "VCF_ASSEMBLY";
109 private static final String DEFAULT_VCF_ASSEMBLY = "assembly19=GRCh37,hs37=GRCh37,grch37=GRCh37,grch38=GRCh38";
111 private static final String VCF_SPECIES = "VCF_SPECIES"; // default is human
113 private static final String DEFAULT_REFERENCE = "grch37"; // fallback default is human GRCh37
116 * keys to fields of VEP CSQ consequence data
117 * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
119 private static final String CSQ_CONSEQUENCE_KEY = "Consequence";
120 private static final String CSQ_ALLELE_KEY = "Allele";
121 private static final String CSQ_ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref), 1...
122 private static final String CSQ_FEATURE_KEY = "Feature"; // Ensembl stable id
125 * default VCF INFO key for VEP consequence data
126 * NB this can be overridden running VEP with --vcf_info_field
127 * - we don't handle this case (require identifier to be CSQ)
129 private static final String CSQ_FIELD = "CSQ";
132 * separator for fields in consequence data is '|'
134 private static final String PIPE_REGEX = "\\|";
137 * delimiter that separates multiple consequence data blocks
139 private static final String COMMA = ",";
142 * the feature group assigned to a VCF variant in Jalview
144 private static final String FEATURE_GROUP_VCF = "VCF";
147 * internal delimiter used to build keys for assemblyMappings
150 private static final String EXCL = "!";
153 * the VCF file we are processing
155 protected String vcfFilePath;
158 * mappings between VCF and sequence reference assembly regions, as
159 * key = "species!chromosome!fromAssembly!toAssembly
160 * value = Map{fromRange, toRange}
162 private Map<String, Map<int[], int[]>> assemblyMappings;
164 private VCFReader reader;
167 * holds details of the VCF header lines (metadata)
169 private VCFHeader header;
172 * species (as a valid Ensembl term) the VCF is for
174 private String vcfSpecies;
177 * genome assembly version (as a valid Ensembl identifier) the VCF is for
179 private String vcfAssembly;
182 * a Dictionary of contigs (if present) referenced in the VCF file
184 private SAMSequenceDictionary dictionary;
187 * the position (0...) of field in each block of
188 * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
189 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
191 private int csqConsequenceFieldIndex = -1;
192 private int csqAlleleFieldIndex = -1;
193 private int csqAlleleNumberFieldIndex = -1;
194 private int csqFeatureFieldIndex = -1;
196 // todo the same fields for SnpEff ANN data if wanted
197 // see http://snpeff.sourceforge.net/SnpEff_manual.html#input
200 * a unique identifier under which to save metadata about feature
201 * attributes (selected INFO field data)
203 private String sourceId;
206 * The INFO IDs of data that is both present in the VCF file, and
207 * also matched by any filters for data of interest
209 List<String> vcfFieldsOfInterest;
212 * The field offsets and identifiers for VEP (CSQ) data that is both present
213 * in the VCF file, and also matched by any filters for data of interest
214 * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
216 Map<Integer, String> vepFieldsOfInterest;
219 * key:value for which rejected data has been seen
220 * (the error is logged only once for each combination)
222 private Set<String> badData;
225 * Constructor given a VCF file
229 public VCFLoader(String vcfFile)
234 } catch (IOException e)
236 System.err.println("Error opening VCF file: " + e.getMessage());
239 // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
240 assemblyMappings = new HashMap<>();
244 * Starts a new thread to query and load VCF variant data on to the given
247 * This method is not thread safe - concurrent threads should use separate
248 * instances of this class.
253 public void loadVCF(SequenceI[] seqs, final AlignViewControllerGuiI gui)
257 gui.setStatus(MessageManager.getString("label.searching_vcf"));
265 VCFLoader.this.doLoad(seqs, gui);
271 * Reads the specified contig sequence and adds its VCF variants to it
274 * the id of a single sequence (contig) to load
277 public SequenceI loadVCFContig(String contig)
279 VCFHeaderLine headerLine = header.getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
280 if (headerLine == null)
282 Cache.log.error("VCF reference header not found");
285 String ref = headerLine.getValue();
286 if (ref.startsWith("file://"))
288 ref = ref.substring(7);
290 setSpeciesAndAssembly(ref);
292 SequenceI seq = null;
293 File dbFile = new File(ref);
297 HtsContigDb db = new HtsContigDb("", dbFile);
298 seq = db.getSequenceProxy(contig);
299 loadSequenceVCF(seq);
304 Cache.log.error("VCF reference not found: " + ref);
311 * Loads VCF on to one or more sequences
315 * optional callback handler for messages
317 protected void doLoad(SequenceI[] seqs, AlignViewControllerGuiI gui)
321 VCFHeaderLine ref = header
322 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
323 String reference = ref == null ? null : ref.getValue();
325 setSpeciesAndAssembly(reference);
331 * query for VCF overlapping each sequence in turn
333 for (SequenceI seq : seqs)
335 int added = loadSequenceVCF(seq);
340 transferAddedFeatures(seq);
345 String msg = MessageManager.formatMessage("label.added_vcf",
348 if (gui.getFeatureSettingsUI() != null)
350 gui.getFeatureSettingsUI().discoverAllFeatureData();
353 } catch (Throwable e)
355 System.err.println("Error processing VCF: " + e.getMessage());
359 gui.setStatus("Error occurred - see console for details");
368 } catch (IOException e)
379 * Attempts to determine and save the species and genome assembly version to
380 * which the VCF data applies. This may be done by parsing the {@code reference}
381 * header line, configured in a property file, or (potentially) confirmed
382 * interactively by the user.
384 * The saved values should be identifiers valid for Ensembl's REST service
385 * {@code map} endpoint, so they can be used (if necessary) to retrieve the
386 * mapping between VCF coordinates and sequence coordinates.
389 * @see https://rest.ensembl.org/documentation/info/assembly_map
390 * @see https://rest.ensembl.org/info/assembly/human?content-type=text/xml
391 * @see https://rest.ensembl.org/info/species?content-type=text/xml
393 protected void setSpeciesAndAssembly(String reference)
395 if (reference == null)
397 Cache.log.error("No VCF ##reference found, defaulting to "
398 + DEFAULT_REFERENCE + ":" + DEFAULT_SPECIES);
399 reference = DEFAULT_REFERENCE; // default to GRCh37 if not specified
401 reference = reference.toLowerCase();
404 * for a non-human species, or other assembly identifier,
405 * specify as a Jalview property file entry e.g.
406 * VCF_ASSEMBLY = hs37=GRCh37,assembly19=GRCh37
407 * VCF_SPECIES = c_elegans=celegans
408 * to map a token in the reference header to a value
410 String prop = Cache.getDefault(VCF_ASSEMBLY, DEFAULT_VCF_ASSEMBLY);
411 for (String token : prop.split(","))
413 String[] tokens = token.split("=");
414 if (tokens.length == 2)
416 if (reference.contains(tokens[0].trim().toLowerCase()))
418 vcfAssembly = tokens[1].trim();
424 vcfSpecies = DEFAULT_SPECIES;
425 prop = Cache.getProperty(VCF_SPECIES);
428 for (String token : prop.split(","))
430 String[] tokens = token.split("=");
431 if (tokens.length == 2)
433 if (reference.contains(tokens[0].trim().toLowerCase()))
435 vcfSpecies = tokens[1].trim();
444 * Opens the VCF file and parses header data
447 * @throws IOException
449 private void initialise(String filePath) throws IOException
451 vcfFilePath = filePath;
453 reader = new VCFReader(filePath);
455 header = reader.getFileHeader();
459 dictionary = header.getSequenceDictionary();
460 } catch (SAMException e)
462 // ignore - thrown if any contig line lacks length info
467 saveMetadata(sourceId);
470 * get offset of CSQ ALLELE_NUM and Feature if declared
476 * Reads metadata (such as INFO field descriptions and datatypes) and saves
477 * them for future reference
481 void saveMetadata(String theSourceId)
483 List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
485 vcfFieldsOfInterest = new ArrayList<>();
487 FeatureSource metadata = new FeatureSource(theSourceId);
489 for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
491 String attributeId = info.getID();
492 String desc = info.getDescription();
493 VCFHeaderLineType type = info.getType();
494 FeatureAttributeType attType = null;
498 attType = FeatureAttributeType.Character;
501 attType = FeatureAttributeType.Flag;
504 attType = FeatureAttributeType.Float;
507 attType = FeatureAttributeType.Integer;
510 attType = FeatureAttributeType.String;
513 metadata.setAttributeName(attributeId, desc);
514 metadata.setAttributeType(attributeId, attType);
516 if (isFieldWanted(attributeId, vcfFieldPatterns))
518 vcfFieldsOfInterest.add(attributeId);
522 FeatureSources.getInstance().addSource(theSourceId, metadata);
526 * Answers true if the field id is matched by any of the filter patterns, else
527 * false. Matching is against regular expression patterns, and is not
534 private boolean isFieldWanted(String id, List<Pattern> filters)
536 for (Pattern p : filters)
538 if (p.matcher(id.toUpperCase()).matches())
547 * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
548 * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
549 * required for processing.
551 * CSQ fields are declared in the CSQ INFO Description e.g.
553 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
555 protected void parseCsqHeader()
557 List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
559 vepFieldsOfInterest = new HashMap<>();
561 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
568 * parse out the pipe-separated list of CSQ fields; we assume here that
569 * these form the last part of the description, and contain no spaces
571 String desc = csqInfo.getDescription();
572 int spacePos = desc.lastIndexOf(" ");
573 desc = desc.substring(spacePos + 1);
577 String[] format = desc.split(PIPE_REGEX);
579 for (String field : format)
581 if (CSQ_CONSEQUENCE_KEY.equals(field))
583 csqConsequenceFieldIndex = index;
585 if (CSQ_ALLELE_NUM_KEY.equals(field))
587 csqAlleleNumberFieldIndex = index;
589 if (CSQ_ALLELE_KEY.equals(field))
591 csqAlleleFieldIndex = index;
593 if (CSQ_FEATURE_KEY.equals(field))
595 csqFeatureFieldIndex = index;
598 if (isFieldWanted(field, vepFieldFilters))
600 vepFieldsOfInterest.put(index, field);
609 * Reads the Preference value for the given key, with default specified if no
610 * preference set. The value is interpreted as a comma-separated list of
611 * regular expressions, and converted into a list of compiled patterns ready
612 * for matching. Patterns are forced to upper-case for non-case-sensitive
615 * This supports user-defined filters for fields of interest to capture while
616 * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
617 * fields with an ID of AF, or starting with AC, would be matched.
623 private List<Pattern> getFieldMatchers(String key, String def)
625 String pref = Cache.getDefault(key, def);
626 List<Pattern> patterns = new ArrayList<>();
627 String[] tokens = pref.split(",");
628 for (String token : tokens)
632 patterns.add(Pattern.compile(token.toUpperCase()));
633 } catch (PatternSyntaxException e)
635 System.err.println("Invalid pattern ignored: " + token);
642 * Transfers VCF features to sequences to which this sequence has a mapping.
643 * If the mapping is 3:1, computes peptide variants from nucleotide variants.
647 protected void transferAddedFeatures(SequenceI seq)
649 DBRefEntry[] dbrefs = seq.getDBRefs();
654 for (DBRefEntry dbref : dbrefs)
656 Mapping mapping = dbref.getMap();
657 if (mapping == null || mapping.getTo() == null)
662 SequenceI mapTo = mapping.getTo();
663 MapList map = mapping.getMap();
664 if (map.getFromRatio() == 3)
667 * dna-to-peptide product mapping
669 AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
674 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
676 List<SequenceFeature> features = seq.getFeatures()
677 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
678 for (SequenceFeature sf : features)
680 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
682 transferFeature(sf, mapTo, map);
690 * Tries to add overlapping variants read from a VCF file to the given sequence,
691 * and returns the number of variant features added
696 protected int loadSequenceVCF(SequenceI seq)
698 VCFMap vcfMap = getVcfMap(seq);
705 * work with the dataset sequence here
707 SequenceI dss = seq.getDatasetSequence();
712 return addVcfVariants(dss, vcfMap);
716 * Answers a map from sequence coordinates to VCF chromosome ranges
721 private VCFMap getVcfMap(SequenceI seq)
724 * simplest case: sequence has id and length matching a VCF contig
726 VCFMap vcfMap = null;
727 if (dictionary != null)
729 vcfMap = getContigMap(seq);
737 * otherwise, map to VCF from chromosomal coordinates
738 * of the sequence (if known)
740 GeneLociI seqCoords = seq.getGeneLoci();
741 if (seqCoords == null)
743 Cache.log.warn(String.format(
744 "Can't query VCF for %s as chromosome coordinates not known",
749 String species = seqCoords.getSpeciesId();
750 String chromosome = seqCoords.getChromosomeId();
751 String seqRef = seqCoords.getAssemblyId();
752 MapList map = seqCoords.getMapping();
754 // note this requires the configured species to match that
755 // returned with the Ensembl sequence; todo: support aliases?
756 if (!vcfSpecies.equalsIgnoreCase(species))
758 Cache.log.warn("No VCF loaded to " + seq.getName()
759 + " as species not matched");
763 if (seqRef.equalsIgnoreCase(vcfAssembly))
765 return new VCFMap(chromosome, map);
769 * VCF data has a different reference assembly to the sequence:
770 * query Ensembl to map chromosomal coordinates from sequence to VCF
772 List<int[]> toVcfRanges = new ArrayList<>();
773 List<int[]> fromSequenceRanges = new ArrayList<>();
775 for (int[] range : map.getToRanges())
777 int[] fromRange = map.locateInFrom(range[0], range[1]);
778 if (fromRange == null)
784 int[] newRange = mapReferenceRange(range, chromosome, "human", seqRef,
786 if (newRange == null)
789 String.format("Failed to map %s:%s:%s:%d:%d to %s", species,
790 chromosome, seqRef, range[0], range[1],
796 toVcfRanges.add(newRange);
797 fromSequenceRanges.add(fromRange);
801 return new VCFMap(chromosome,
802 new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
806 * If the sequence id matches a contig declared in the VCF file, and the
807 * sequence length matches the contig length, then returns a 1:1 map of the
808 * sequence to the contig, else returns null
813 private VCFMap getContigMap(SequenceI seq)
815 String id = seq.getName();
816 SAMSequenceRecord contig = dictionary.getSequence(id);
819 int len = seq.getLength();
820 if (len == contig.getSequenceLength())
822 MapList map = new MapList(new int[] { 1, len },
825 return new VCFMap(id, map);
832 * Queries the VCF reader for any variants that overlap the mapped chromosome
833 * ranges of the sequence, and adds as variant features. Returns the number of
834 * overlapping variants found.
838 * mapping from sequence to VCF coordinates
841 protected int addVcfVariants(SequenceI seq, VCFMap map)
843 boolean forwardStrand = map.map.isToForwardStrand();
846 * query the VCF for overlaps of each contiguous chromosomal region
850 for (int[] range : map.map.getToRanges())
852 int vcfStart = Math.min(range[0], range[1]);
853 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,
870 featureEnd, forwardStrand);
874 } catch (TribbleException e)
877 * RuntimeException throwable by htsjdk
879 String msg = String.format("Error reading VCF for %s:%d-%d: %s ",
880 map.chromosome, vcfStart, vcfEnd);
881 Cache.log.error(msg);
889 * A convenience method to get an attribute value for an alternate allele
892 * @param attributeName
896 protected String getAttributeValue(VariantContext variant,
897 String attributeName, int alleleIndex)
899 Object att = variant.getAttribute(attributeName);
901 if (att instanceof String)
903 return NO_VALUE.equals(att) ? null : (String) att;
905 else if (att instanceof ArrayList)
907 return ((List<String>) att).get(alleleIndex);
914 * Adds one variant feature for each allele in the VCF variant record, and
915 * returns the number of features added.
919 * @param featureStart
921 * @param forwardStrand
924 protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
925 int featureStart, int featureEnd, boolean forwardStrand)
930 * Javadoc says getAlternateAlleles() imposes no order on the list returned
931 * so we proceed defensively to get them in strict order
933 int altAlleleCount = variant.getAlternateAlleles().size();
934 for (int i = 0; i < altAlleleCount; i++)
936 added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
943 * Inspects one allele and attempts to add a variant feature for it to the
944 * sequence. The additional data associated with this allele is extracted to
945 * store in the feature's key-value map. Answers the number of features added (0
950 * @param altAlleleIndex
952 * @param featureStart
954 * @param forwardStrand
957 protected int addAlleleFeature(SequenceI seq, VariantContext variant,
958 int altAlleleIndex, int featureStart, int featureEnd,
959 boolean forwardStrand)
961 String reference = variant.getReference().getBaseString();
962 Allele alt = variant.getAlternateAllele(altAlleleIndex);
963 String allele = alt.getBaseString();
966 * insertion after a genomic base, if on reverse strand, has to be
967 * converted to insertion of complement after the preceding position
969 int referenceLength = reference.length();
970 if (!forwardStrand && allele.length() > referenceLength
971 && allele.startsWith(reference))
973 featureStart -= referenceLength;
974 featureEnd = featureStart;
975 char insertAfter = seq.getCharAt(featureStart - seq.getStart());
976 reference = Dna.reverseComplement(String.valueOf(insertAfter));
977 allele = allele.substring(referenceLength) + reference;
981 * build the ref,alt allele description e.g. "G,A", using the base
982 * complement if the sequence is on the reverse strand
984 StringBuilder sb = new StringBuilder();
985 sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
987 sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
988 String alleles = sb.toString(); // e.g. G,A
991 * pick out the consequence data (if any) that is for the current allele
992 * and feature (transcript) that matches the current sequence
994 String consequence = getConsequenceForAlleleAndFeature(variant, CSQ_FIELD,
995 altAlleleIndex, csqAlleleFieldIndex,
996 csqAlleleNumberFieldIndex, seq.getName().toLowerCase(),
997 csqFeatureFieldIndex);
1000 * pick out the ontology term for the consequence type
1002 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1003 if (consequence != null)
1005 type = getOntologyTerm(consequence);
1008 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
1009 featureEnd, FEATURE_GROUP_VCF);
1010 sf.setSource(sourceId);
1012 sf.setValue(Gff3Helper.ALLELES, alleles);
1014 addAlleleProperties(variant, sf, altAlleleIndex, consequence);
1016 seq.addSequenceFeature(sf);
1022 * Determines the Sequence Ontology term to use for the variant feature type in
1023 * Jalview. The default is 'sequence_variant', but a more specific term is used
1026 * <li>VEP (or SnpEff) Consequence annotation is included in the VCF</li>
1027 * <li>sequence id can be matched to VEP Feature (or SnpEff Feature_ID)</li>
1030 * @param consequence
1032 * @see http://www.sequenceontology.org/browser/current_svn/term/SO:0001060
1034 String getOntologyTerm(String consequence)
1036 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1039 * could we associate Consequence data with this allele and feature (transcript)?
1040 * if so, prefer the consequence term from that data
1042 if (csqAlleleFieldIndex == -1) // && snpEffAlleleFieldIndex == -1
1045 * no Consequence data so we can't refine the ontology term
1050 if (consequence != null)
1052 String[] csqFields = consequence.split(PIPE_REGEX);
1053 if (csqFields.length > csqConsequenceFieldIndex)
1055 type = csqFields[csqConsequenceFieldIndex];
1060 // todo the same for SnpEff consequence data matching if wanted
1064 * if of the form (e.g.) missense_variant&splice_region_variant,
1065 * just take the first ('most severe') consequence
1069 int pos = type.indexOf('&');
1072 type = type.substring(0, pos);
1079 * Returns matched consequence data if it can be found, else null.
1081 * <li>inspects the VCF data for key 'vcfInfoId'</li>
1082 * <li>splits this on comma (to distinct consequences)</li>
1083 * <li>returns the first consequence (if any) where</li>
1085 * <li>the allele matches the altAlleleIndex'th allele of variant</li>
1086 * <li>the feature matches the sequence name (e.g. transcript id)</li>
1089 * If matched, the consequence is returned (as pipe-delimited fields).
1093 * @param altAlleleIndex
1094 * @param alleleFieldIndex
1095 * @param alleleNumberFieldIndex
1097 * @param featureFieldIndex
1100 private String getConsequenceForAlleleAndFeature(VariantContext variant,
1101 String vcfInfoId, int altAlleleIndex, int alleleFieldIndex,
1102 int alleleNumberFieldIndex,
1103 String seqName, int featureFieldIndex)
1105 if (alleleFieldIndex == -1 || featureFieldIndex == -1)
1109 Object value = variant.getAttribute(vcfInfoId);
1111 if (value == null || !(value instanceof List<?>))
1117 * inspect each consequence in turn (comma-separated blocks
1118 * extracted by htsjdk)
1120 List<String> consequences = (List<String>) value;
1122 for (String consequence : consequences)
1124 String[] csqFields = consequence.split(PIPE_REGEX);
1125 if (csqFields.length > featureFieldIndex)
1127 String featureIdentifier = csqFields[featureFieldIndex];
1128 if (featureIdentifier.length() > 4
1129 && seqName.indexOf(featureIdentifier.toLowerCase()) > -1)
1132 * feature (transcript) matched - now check for allele match
1134 if (matchAllele(variant, altAlleleIndex, csqFields,
1135 alleleFieldIndex, alleleNumberFieldIndex))
1145 private boolean matchAllele(VariantContext variant, int altAlleleIndex,
1146 String[] csqFields, int alleleFieldIndex,
1147 int alleleNumberFieldIndex)
1150 * if ALLELE_NUM is present, it must match altAlleleIndex
1151 * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1153 if (alleleNumberFieldIndex > -1)
1155 if (csqFields.length <= alleleNumberFieldIndex)
1159 String alleleNum = csqFields[alleleNumberFieldIndex];
1160 return String.valueOf(altAlleleIndex + 1).equals(alleleNum);
1164 * else consequence allele must match variant allele
1166 if (alleleFieldIndex > -1 && csqFields.length > alleleFieldIndex)
1168 String csqAllele = csqFields[alleleFieldIndex];
1169 String vcfAllele = variant.getAlternateAllele(altAlleleIndex)
1171 return csqAllele.equals(vcfAllele);
1177 * Add any allele-specific VCF key-value data to the sequence feature
1181 * @param altAlelleIndex
1183 * @param consequence
1184 * if not null, the consequence specific to this sequence (transcript
1185 * feature) and allele
1187 protected void addAlleleProperties(VariantContext variant,
1188 SequenceFeature sf, final int altAlelleIndex, String consequence)
1190 Map<String, Object> atts = variant.getAttributes();
1192 for (Entry<String, Object> att : atts.entrySet())
1194 String key = att.getKey();
1197 * extract Consequence data (if present) that we are able to
1198 * associated with the allele for this variant feature
1200 if (CSQ_FIELD.equals(key))
1202 addConsequences(variant, sf, consequence);
1207 * filter out fields we don't want to capture
1209 if (!vcfFieldsOfInterest.contains(key))
1215 * filter out fields we don't want to capture
1217 if (!vcfFieldsOfInterest.contains(key))
1223 * we extract values for other data which are allele-specific;
1224 * these may be per alternate allele (INFO[key].Number = 'A')
1225 * or per allele including reference (INFO[key].Number = 'R')
1227 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
1228 if (infoHeader == null)
1231 * can't be sure what data belongs to this allele, so
1232 * play safe and don't take any
1237 VCFHeaderLineCount number = infoHeader.getCountType();
1238 int index = altAlelleIndex;
1239 if (number == VCFHeaderLineCount.R)
1242 * one value per allele including reference, so bump index
1243 * e.g. the 3rd value is for the 2nd alternate allele
1247 else if (number != VCFHeaderLineCount.A)
1250 * don't save other values as not allele-related
1256 * take the index'th value
1258 String value = getAttributeValue(variant, key, index);
1259 if (value != null && isValid(variant, key, value))
1261 sf.setValue(key, value);
1267 * Answers true for '.', null, or an empty value, or if the INFO type is String.
1268 * If the INFO type is Integer or Float, answers false if the value is not in
1276 protected boolean isValid(VariantContext variant, String infoId,
1279 if (value == null || value.isEmpty() || NO_VALUE.equals(value))
1283 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(infoId);
1284 if (infoHeader == null)
1286 Cache.log.error("Field " + infoId + " has no INFO header");
1289 VCFHeaderLineType infoType = infoHeader.getType();
1292 if (infoType == VCFHeaderLineType.Integer)
1294 Integer.parseInt(value);
1296 else if (infoType == VCFHeaderLineType.Float)
1298 Float.parseFloat(value);
1300 } catch (NumberFormatException e)
1302 logInvalidValue(variant, infoId, value);
1309 * Logs an error message for malformed data; duplicate messages (same id and
1310 * value) are not logged
1316 private void logInvalidValue(VariantContext variant, String infoId,
1319 if (badData == null)
1321 badData = new HashSet<>();
1323 String token = infoId + ":" + value;
1324 if (!badData.contains(token))
1327 Cache.log.error(String.format("Invalid VCF data at %s:%d %s=%s",
1328 variant.getContig(), variant.getStart(), infoId, value));
1333 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
1336 * If <code>myConsequence</code> is not null, then this is the specific
1337 * consequence data (pipe-delimited fields) that is for the current allele and
1338 * transcript (sequence) being processed)
1342 * @param myConsequence
1344 protected void addConsequences(VariantContext variant, SequenceFeature sf,
1345 String myConsequence)
1347 Object value = variant.getAttribute(CSQ_FIELD);
1349 if (value == null || !(value instanceof List<?>))
1354 List<String> consequences = (List<String>) value;
1357 * inspect CSQ consequences; restrict to the consequence
1358 * associated with the current transcript (Feature)
1360 Map<String, String> csqValues = new HashMap<>();
1362 for (String consequence : consequences)
1364 if (myConsequence == null || myConsequence.equals(consequence))
1366 String[] csqFields = consequence.split(PIPE_REGEX);
1369 * inspect individual fields of this consequence, copying non-null
1370 * values which are 'fields of interest'
1373 for (String field : csqFields)
1375 if (field != null && field.length() > 0)
1377 String id = vepFieldsOfInterest.get(i);
1380 csqValues.put(id, field);
1388 if (!csqValues.isEmpty())
1390 sf.setValue(CSQ_FIELD, csqValues);
1395 * A convenience method to complement a dna base and return the string value
1401 protected String complement(byte[] reference)
1403 return String.valueOf(Dna.getComplement((char) reference[0]));
1407 * Determines the location of the query range (chromosome positions) in a
1408 * different reference assembly.
1410 * If the range is just a subregion of one for which we already have a mapping
1411 * (for example, an exon sub-region of a gene), then the mapping is just
1412 * computed arithmetically.
1414 * Otherwise, calls the Ensembl REST service that maps from one assembly
1415 * reference's coordinates to another's
1418 * start-end chromosomal range in 'fromRef' coordinates
1422 * assembly reference for the query coordinates
1424 * assembly reference we wish to translate to
1425 * @return the start-end range in 'toRef' coordinates
1427 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
1428 String species, String fromRef, String toRef)
1431 * first try shorcut of computing the mapping as a subregion of one
1432 * we already have (e.g. for an exon, if we have the gene mapping)
1434 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
1435 species, fromRef, toRef);
1436 if (mappedRange != null)
1442 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
1444 EnsemblMap mapper = new EnsemblMap();
1445 int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
1448 if (mapping == null)
1450 // mapping service failure
1455 * save mapping for possible future re-use
1457 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1458 if (!assemblyMappings.containsKey(key))
1460 assemblyMappings.put(key, new HashMap<int[], int[]>());
1463 assemblyMappings.get(key).put(queryRange, mapping);
1469 * If we already have a 1:1 contiguous mapping which subsumes the given query
1470 * range, this method just calculates and returns the subset of that mapping,
1471 * else it returns null. In practical terms, if a gene has a contiguous
1472 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
1473 * subsidiary exons occupy unchanged relative positions, and just compute
1474 * these as offsets, rather than do another lookup of the mapping.
1476 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
1477 * simply remove this method or let it always return null.
1479 * Warning: many rapid calls to the /map service map result in a 429 overload
1489 protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
1490 String species, String fromRef, String toRef)
1492 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1493 if (assemblyMappings.containsKey(key))
1495 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
1496 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
1498 int[] fromRange = mappedRange.getKey();
1499 int[] toRange = mappedRange.getValue();
1500 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
1503 * mapping is 1:1 in length, so we trust it to have no discontinuities
1505 if (MappingUtils.rangeContains(fromRange, queryRange))
1508 * fromRange subsumes our query range
1510 int offset = queryRange[0] - fromRange[0];
1511 int mappedRangeFrom = toRange[0] + offset;
1512 int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
1513 return new int[] { mappedRangeFrom, mappedRangeTo };
1522 * Transfers the sequence feature to the target sequence, locating its start
1523 * and end range based on the mapping. Features which do not overlap the
1524 * target sequence are ignored.
1527 * @param targetSequence
1529 * mapping from the feature's coordinates to the target sequence
1531 protected void transferFeature(SequenceFeature sf,
1532 SequenceI targetSequence, MapList mapping)
1534 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1536 if (mappedRange != null)
1538 String group = sf.getFeatureGroup();
1539 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1540 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1541 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1542 group, sf.getScore());
1543 targetSequence.addSequenceFeature(copy);
1548 * Formats a ranges map lookup key
1556 protected static String makeRangesKey(String chromosome, String species,
1557 String fromRef, String toRef)
1559 return species + EXCL + chromosome + EXCL + fromRef + EXCL