1 package jalview.io.vcf;
3 import jalview.analysis.Dna;
4 import jalview.api.AlignViewControllerGuiI;
5 import jalview.bin.Cache;
6 import jalview.datamodel.DBRefEntry;
7 import jalview.datamodel.GeneLociI;
8 import jalview.datamodel.Mapping;
9 import jalview.datamodel.SequenceFeature;
10 import jalview.datamodel.SequenceI;
11 import jalview.datamodel.features.FeatureAttributeType;
12 import jalview.datamodel.features.FeatureSource;
13 import jalview.datamodel.features.FeatureSources;
14 import jalview.ext.ensembl.EnsemblMap;
15 import jalview.ext.htsjdk.HtsContigDb;
16 import jalview.ext.htsjdk.VCFReader;
17 import jalview.io.gff.Gff3Helper;
18 import jalview.io.gff.SequenceOntologyI;
19 import jalview.util.MapList;
20 import jalview.util.MappingUtils;
21 import jalview.util.MessageManager;
22 import jalview.util.StringUtils;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.Iterator;
30 import java.util.List;
32 import java.util.Map.Entry;
34 import java.util.regex.Pattern;
35 import java.util.regex.PatternSyntaxException;
37 import htsjdk.samtools.SAMException;
38 import htsjdk.samtools.SAMSequenceDictionary;
39 import htsjdk.samtools.SAMSequenceRecord;
40 import htsjdk.samtools.util.CloseableIterator;
41 import htsjdk.tribble.TribbleException;
42 import htsjdk.variant.variantcontext.Allele;
43 import htsjdk.variant.variantcontext.VariantContext;
44 import htsjdk.variant.vcf.VCFConstants;
45 import htsjdk.variant.vcf.VCFHeader;
46 import htsjdk.variant.vcf.VCFHeaderLine;
47 import htsjdk.variant.vcf.VCFHeaderLineCount;
48 import htsjdk.variant.vcf.VCFHeaderLineType;
49 import htsjdk.variant.vcf.VCFInfoHeaderLine;
52 * A class to read VCF data (using the htsjdk) and add variants as sequence
53 * features on dna and any related protein product sequences
57 public class VCFLoader
59 private static final String VCF_ENCODABLE = ":;=%,";
62 * Jalview feature attributes for VCF fixed column data
64 private static final String VCF_POS = "POS";
66 private static final String VCF_ID = "ID";
68 private static final String VCF_QUAL = "QUAL";
70 private static final String VCF_FILTER = "FILTER";
72 private static final String NO_VALUE = VCFConstants.MISSING_VALUE_v4; // '.'
74 private static final String DEFAULT_SPECIES = "homo_sapiens";
77 * A class to model the mapping from sequence to VCF coordinates. Cases include
79 * <li>a direct 1:1 mapping where the sequence is one of the VCF contigs</li>
80 * <li>a mapping of sequence to chromosomal coordinates, where sequence and VCF
81 * use the same reference assembly</li>
82 * <li>a modified mapping of sequence to chromosomal coordinates, where sequence
83 * and VCF use different reference assembles</li>
88 final String chromosome;
92 VCFMap(String chr, MapList m)
99 public String toString()
101 return chromosome + ":" + map.toString();
106 * Lookup keys, and default values, for Preference entries that describe
107 * patterns for VCF and VEP fields to capture
109 private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
111 private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
113 private static final String DEFAULT_VCF_FIELDS = ".*";
115 private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
118 * Lookup keys, and default values, for Preference entries that give
119 * mappings from tokens in the 'reference' header to species or assembly
121 private static final String VCF_ASSEMBLY = "VCF_ASSEMBLY";
123 private static final String DEFAULT_VCF_ASSEMBLY = "assembly19=GRCh37,hs37=GRCh37,grch37=GRCh37,grch38=GRCh38";
125 private static final String VCF_SPECIES = "VCF_SPECIES"; // default is human
127 private static final String DEFAULT_REFERENCE = "grch37"; // fallback default is human GRCh37
130 * keys to fields of VEP CSQ consequence data
131 * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
133 private static final String CSQ_CONSEQUENCE_KEY = "Consequence";
134 private static final String CSQ_ALLELE_KEY = "Allele";
135 private static final String CSQ_ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref), 1...
136 private static final String CSQ_FEATURE_KEY = "Feature"; // Ensembl stable id
139 * default VCF INFO key for VEP consequence data
140 * NB this can be overridden running VEP with --vcf_info_field
141 * - we don't handle this case (require identifier to be CSQ)
143 private static final String CSQ_FIELD = "CSQ";
146 * separator for fields in consequence data is '|'
148 private static final String PIPE_REGEX = "\\|";
151 * delimiter that separates multiple consequence data blocks
153 private static final String COMMA = ",";
156 * the feature group assigned to a VCF variant in Jalview
158 private static final String FEATURE_GROUP_VCF = "VCF";
161 * internal delimiter used to build keys for assemblyMappings
164 private static final String EXCL = "!";
167 * the VCF file we are processing
169 protected String vcfFilePath;
172 * mappings between VCF and sequence reference assembly regions, as
173 * key = "species!chromosome!fromAssembly!toAssembly
174 * value = Map{fromRange, toRange}
176 private Map<String, Map<int[], int[]>> assemblyMappings;
178 private VCFReader reader;
181 * holds details of the VCF header lines (metadata)
183 private VCFHeader header;
186 * species (as a valid Ensembl term) the VCF is for
188 private String vcfSpecies;
191 * genome assembly version (as a valid Ensembl identifier) the VCF is for
193 private String vcfAssembly;
196 * a Dictionary of contigs (if present) referenced in the VCF file
198 private SAMSequenceDictionary dictionary;
201 * the position (0...) of field in each block of
202 * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
203 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
205 private int csqConsequenceFieldIndex = -1;
206 private int csqAlleleFieldIndex = -1;
207 private int csqAlleleNumberFieldIndex = -1;
208 private int csqFeatureFieldIndex = -1;
210 // todo the same fields for SnpEff ANN data if wanted
211 // see http://snpeff.sourceforge.net/SnpEff_manual.html#input
214 * a unique identifier under which to save metadata about feature
215 * attributes (selected INFO field data)
217 private String sourceId;
220 * The INFO IDs of data that is both present in the VCF file, and
221 * also matched by any filters for data of interest
223 List<String> vcfFieldsOfInterest;
226 * The field offsets and identifiers for VEP (CSQ) data that is both present
227 * in the VCF file, and also matched by any filters for data of interest
228 * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
230 Map<Integer, String> vepFieldsOfInterest;
233 * key:value for which rejected data has been seen
234 * (the error is logged only once for each combination)
236 private Set<String> badData;
239 * Constructor given a VCF file
243 public VCFLoader(String vcfFile)
248 } catch (IOException e)
250 System.err.println("Error opening VCF file: " + e.getMessage());
253 // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
254 assemblyMappings = new HashMap<>();
258 * Starts a new thread to query and load VCF variant data on to the given
261 * This method is not thread safe - concurrent threads should use separate
262 * instances of this class.
267 public void loadVCF(SequenceI[] seqs, final AlignViewControllerGuiI gui)
271 gui.setStatus(MessageManager.getString("label.searching_vcf"));
279 VCFLoader.this.doLoad(seqs, gui);
285 * Reads the specified contig sequence and adds its VCF variants to it
288 * the id of a single sequence (contig) to load
291 public SequenceI loadVCFContig(String contig)
293 VCFHeaderLine headerLine = header.getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
294 if (headerLine == null)
296 Cache.log.error("VCF reference header not found");
299 String ref = headerLine.getValue();
300 if (ref.startsWith("file://"))
302 ref = ref.substring(7);
304 setSpeciesAndAssembly(ref);
306 SequenceI seq = null;
307 File dbFile = new File(ref);
311 HtsContigDb db = new HtsContigDb("", dbFile);
312 seq = db.getSequenceProxy(contig);
313 loadSequenceVCF(seq);
318 Cache.log.error("VCF reference not found: " + ref);
325 * Loads VCF on to one or more sequences
329 * optional callback handler for messages
331 protected void doLoad(SequenceI[] seqs, AlignViewControllerGuiI gui)
335 VCFHeaderLine ref = header
336 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
337 String reference = ref == null ? null : ref.getValue();
339 setSpeciesAndAssembly(reference);
345 * query for VCF overlapping each sequence in turn
347 for (SequenceI seq : seqs)
349 int added = loadSequenceVCF(seq);
354 transferAddedFeatures(seq);
359 String msg = MessageManager.formatMessage("label.added_vcf",
362 if (gui.getFeatureSettingsUI() != null)
364 gui.getFeatureSettingsUI().discoverAllFeatureData();
367 } catch (Throwable e)
369 System.err.println("Error processing VCF: " + e.getMessage());
373 gui.setStatus("Error occurred - see console for details");
382 } catch (IOException e)
393 * Attempts to determine and save the species and genome assembly version to
394 * which the VCF data applies. This may be done by parsing the {@code reference}
395 * header line, configured in a property file, or (potentially) confirmed
396 * interactively by the user.
398 * The saved values should be identifiers valid for Ensembl's REST service
399 * {@code map} endpoint, so they can be used (if necessary) to retrieve the
400 * mapping between VCF coordinates and sequence coordinates.
403 * @see https://rest.ensembl.org/documentation/info/assembly_map
404 * @see https://rest.ensembl.org/info/assembly/human?content-type=text/xml
405 * @see https://rest.ensembl.org/info/species?content-type=text/xml
407 protected void setSpeciesAndAssembly(String reference)
409 if (reference == null)
411 Cache.log.error("No VCF ##reference found, defaulting to "
412 + DEFAULT_REFERENCE + ":" + DEFAULT_SPECIES);
413 reference = DEFAULT_REFERENCE; // default to GRCh37 if not specified
415 reference = reference.toLowerCase();
418 * for a non-human species, or other assembly identifier,
419 * specify as a Jalview property file entry e.g.
420 * VCF_ASSEMBLY = hs37=GRCh37,assembly19=GRCh37
421 * VCF_SPECIES = c_elegans=celegans
422 * to map a token in the reference header to a value
424 String prop = Cache.getDefault(VCF_ASSEMBLY, DEFAULT_VCF_ASSEMBLY);
425 for (String token : prop.split(","))
427 String[] tokens = token.split("=");
428 if (tokens.length == 2)
430 if (reference.contains(tokens[0].trim().toLowerCase()))
432 vcfAssembly = tokens[1].trim();
438 vcfSpecies = DEFAULT_SPECIES;
439 prop = Cache.getProperty(VCF_SPECIES);
442 for (String token : prop.split(","))
444 String[] tokens = token.split("=");
445 if (tokens.length == 2)
447 if (reference.contains(tokens[0].trim().toLowerCase()))
449 vcfSpecies = tokens[1].trim();
458 * Opens the VCF file and parses header data
461 * @throws IOException
463 private void initialise(String filePath) throws IOException
465 vcfFilePath = filePath;
467 reader = new VCFReader(filePath);
469 header = reader.getFileHeader();
473 dictionary = header.getSequenceDictionary();
474 } catch (SAMException e)
476 // ignore - thrown if any contig line lacks length info
481 saveMetadata(sourceId);
484 * get offset of CSQ ALLELE_NUM and Feature if declared
490 * Reads metadata (such as INFO field descriptions and datatypes) and saves
491 * them for future reference
495 void saveMetadata(String theSourceId)
497 List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
499 vcfFieldsOfInterest = new ArrayList<>();
501 FeatureSource metadata = new FeatureSource(theSourceId);
503 for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
505 String attributeId = info.getID();
506 String desc = info.getDescription();
507 VCFHeaderLineType type = info.getType();
508 FeatureAttributeType attType = null;
512 attType = FeatureAttributeType.Character;
515 attType = FeatureAttributeType.Flag;
518 attType = FeatureAttributeType.Float;
521 attType = FeatureAttributeType.Integer;
524 attType = FeatureAttributeType.String;
527 metadata.setAttributeName(attributeId, desc);
528 metadata.setAttributeType(attributeId, attType);
530 if (isFieldWanted(attributeId, vcfFieldPatterns))
532 vcfFieldsOfInterest.add(attributeId);
536 FeatureSources.getInstance().addSource(theSourceId, metadata);
540 * Answers true if the field id is matched by any of the filter patterns, else
541 * false. Matching is against regular expression patterns, and is not
548 private boolean isFieldWanted(String id, List<Pattern> filters)
550 for (Pattern p : filters)
552 if (p.matcher(id.toUpperCase()).matches())
561 * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
562 * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
563 * required for processing.
565 * CSQ fields are declared in the CSQ INFO Description e.g.
567 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
569 protected void parseCsqHeader()
571 List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
573 vepFieldsOfInterest = new HashMap<>();
575 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
582 * parse out the pipe-separated list of CSQ fields; we assume here that
583 * these form the last part of the description, and contain no spaces
585 String desc = csqInfo.getDescription();
586 int spacePos = desc.lastIndexOf(" ");
587 desc = desc.substring(spacePos + 1);
591 String[] format = desc.split(PIPE_REGEX);
593 for (String field : format)
595 if (CSQ_CONSEQUENCE_KEY.equals(field))
597 csqConsequenceFieldIndex = index;
599 if (CSQ_ALLELE_NUM_KEY.equals(field))
601 csqAlleleNumberFieldIndex = index;
603 if (CSQ_ALLELE_KEY.equals(field))
605 csqAlleleFieldIndex = index;
607 if (CSQ_FEATURE_KEY.equals(field))
609 csqFeatureFieldIndex = index;
612 if (isFieldWanted(field, vepFieldFilters))
614 vepFieldsOfInterest.put(index, field);
623 * Reads the Preference value for the given key, with default specified if no
624 * preference set. The value is interpreted as a comma-separated list of
625 * regular expressions, and converted into a list of compiled patterns ready
626 * for matching. Patterns are forced to upper-case for non-case-sensitive
629 * This supports user-defined filters for fields of interest to capture while
630 * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
631 * fields with an ID of AF, or starting with AC, would be matched.
637 private List<Pattern> getFieldMatchers(String key, String def)
639 String pref = Cache.getDefault(key, def);
640 List<Pattern> patterns = new ArrayList<>();
641 String[] tokens = pref.split(",");
642 for (String token : tokens)
646 patterns.add(Pattern.compile(token.toUpperCase()));
647 } catch (PatternSyntaxException e)
649 System.err.println("Invalid pattern ignored: " + token);
656 * Transfers VCF features to sequences to which this sequence has a mapping.
657 * If the mapping is 3:1, computes peptide variants from nucleotide variants.
661 protected void transferAddedFeatures(SequenceI seq)
663 DBRefEntry[] dbrefs = seq.getDBRefs();
668 for (DBRefEntry dbref : dbrefs)
670 Mapping mapping = dbref.getMap();
671 if (mapping == null || mapping.getTo() == null)
676 SequenceI mapTo = mapping.getTo();
677 MapList map = mapping.getMap();
678 if (map.getFromRatio() == 3)
681 * dna-to-peptide product mapping
683 // JAL-3187 render on the fly instead
684 // AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
689 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
691 List<SequenceFeature> features = seq.getFeatures()
692 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
693 for (SequenceFeature sf : features)
695 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
697 transferFeature(sf, mapTo, map);
705 * Tries to add overlapping variants read from a VCF file to the given sequence,
706 * and returns the number of variant features added
711 protected int loadSequenceVCF(SequenceI seq)
713 VCFMap vcfMap = getVcfMap(seq);
720 * work with the dataset sequence here
722 SequenceI dss = seq.getDatasetSequence();
727 return addVcfVariants(dss, vcfMap);
731 * Answers a map from sequence coordinates to VCF chromosome ranges
736 private VCFMap getVcfMap(SequenceI seq)
739 * simplest case: sequence has id and length matching a VCF contig
741 VCFMap vcfMap = null;
742 if (dictionary != null)
744 vcfMap = getContigMap(seq);
752 * otherwise, map to VCF from chromosomal coordinates
753 * of the sequence (if known)
755 GeneLociI seqCoords = seq.getGeneLoci();
756 if (seqCoords == null)
758 Cache.log.warn(String.format(
759 "Can't query VCF for %s as chromosome coordinates not known",
764 String species = seqCoords.getSpeciesId();
765 String chromosome = seqCoords.getChromosomeId();
766 String seqRef = seqCoords.getAssemblyId();
767 MapList map = seqCoords.getMapping();
769 // note this requires the configured species to match that
770 // returned with the Ensembl sequence; todo: support aliases?
771 if (!vcfSpecies.equalsIgnoreCase(species))
773 Cache.log.warn("No VCF loaded to " + seq.getName()
774 + " as species not matched");
778 if (seqRef.equalsIgnoreCase(vcfAssembly))
780 return new VCFMap(chromosome, map);
784 * VCF data has a different reference assembly to the sequence:
785 * query Ensembl to map chromosomal coordinates from sequence to VCF
787 List<int[]> toVcfRanges = new ArrayList<>();
788 List<int[]> fromSequenceRanges = new ArrayList<>();
790 for (int[] range : map.getToRanges())
792 int[] fromRange = map.locateInFrom(range[0], range[1]);
793 if (fromRange == null)
799 int[] newRange = mapReferenceRange(range, chromosome, "human", seqRef,
801 if (newRange == null)
804 String.format("Failed to map %s:%s:%s:%d:%d to %s", species,
805 chromosome, seqRef, range[0], range[1],
811 toVcfRanges.add(newRange);
812 fromSequenceRanges.add(fromRange);
816 return new VCFMap(chromosome,
817 new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
821 * If the sequence id matches a contig declared in the VCF file, and the
822 * sequence length matches the contig length, then returns a 1:1 map of the
823 * sequence to the contig, else returns null
828 private VCFMap getContigMap(SequenceI seq)
830 String id = seq.getName();
831 SAMSequenceRecord contig = dictionary.getSequence(id);
834 int len = seq.getLength();
835 if (len == contig.getSequenceLength())
837 MapList map = new MapList(new int[] { 1, len },
840 return new VCFMap(id, map);
847 * Queries the VCF reader for any variants that overlap the mapped chromosome
848 * ranges of the sequence, and adds as variant features. Returns the number of
849 * overlapping variants found.
853 * mapping from sequence to VCF coordinates
856 protected int addVcfVariants(SequenceI seq, VCFMap map)
858 boolean forwardStrand = map.map.isToForwardStrand();
861 * query the VCF for overlaps of each contiguous chromosomal region
865 for (int[] range : map.map.getToRanges())
867 int vcfStart = Math.min(range[0], range[1]);
868 int vcfEnd = Math.max(range[0], range[1]);
871 CloseableIterator<VariantContext> variants = reader
872 .query(map.chromosome, vcfStart, vcfEnd);
873 while (variants.hasNext())
875 VariantContext variant = variants.next();
877 int[] featureRange = map.map.locateInFrom(variant.getStart(),
880 if (featureRange != null)
882 int featureStart = Math.min(featureRange[0], featureRange[1]);
883 int featureEnd = Math.max(featureRange[0], featureRange[1]);
884 count += addAlleleFeatures(seq, variant, featureStart,
885 featureEnd, forwardStrand);
889 } catch (TribbleException e)
892 * RuntimeException throwable by htsjdk
894 String msg = String.format("Error reading VCF for %s:%d-%d: %s ",
895 map.chromosome, vcfStart, vcfEnd);
896 Cache.log.error(msg);
904 * A convenience method to get an attribute value for an alternate allele
907 * @param attributeName
911 protected String getAttributeValue(VariantContext variant,
912 String attributeName, int alleleIndex)
914 Object att = variant.getAttribute(attributeName);
916 if (att instanceof String)
920 else if (att instanceof ArrayList)
922 return ((List<String>) att).get(alleleIndex);
929 * Adds one variant feature for each allele in the VCF variant record, and
930 * returns the number of features added.
934 * @param featureStart
936 * @param forwardStrand
939 protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
940 int featureStart, int featureEnd, boolean forwardStrand)
945 * Javadoc says getAlternateAlleles() imposes no order on the list returned
946 * so we proceed defensively to get them in strict order
948 int altAlleleCount = variant.getAlternateAlleles().size();
949 for (int i = 0; i < altAlleleCount; i++)
951 added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
958 * Inspects one allele and attempts to add a variant feature for it to the
959 * sequence. The additional data associated with this allele is extracted to
960 * store in the feature's key-value map. Answers the number of features added (0
965 * @param altAlleleIndex
967 * @param featureStart
969 * @param forwardStrand
972 protected int addAlleleFeature(SequenceI seq, VariantContext variant,
973 int altAlleleIndex, int featureStart, int featureEnd,
974 boolean forwardStrand)
976 String reference = variant.getReference().getBaseString();
977 Allele alt = variant.getAlternateAllele(altAlleleIndex);
978 String allele = alt.getBaseString();
981 * insertion after a genomic base, if on reverse strand, has to be
982 * converted to insertion of complement after the preceding position
984 int referenceLength = reference.length();
985 if (!forwardStrand && allele.length() > referenceLength
986 && allele.startsWith(reference))
988 featureStart -= referenceLength;
989 featureEnd = featureStart;
990 char insertAfter = seq.getCharAt(featureStart - seq.getStart());
991 reference = Dna.reverseComplement(String.valueOf(insertAfter));
992 allele = allele.substring(referenceLength) + reference;
996 * build the ref,alt allele description e.g. "G,A", using the base
997 * complement if the sequence is on the reverse strand
999 StringBuilder sb = new StringBuilder();
1000 sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
1002 sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
1003 String alleles = sb.toString(); // e.g. G,A
1006 * pick out the consequence data (if any) that is for the current allele
1007 * and feature (transcript) that matches the current sequence
1009 String consequence = getConsequenceForAlleleAndFeature(variant, CSQ_FIELD,
1010 altAlleleIndex, csqAlleleFieldIndex,
1011 csqAlleleNumberFieldIndex, seq.getName().toLowerCase(),
1012 csqFeatureFieldIndex);
1015 * pick out the ontology term for the consequence type
1017 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1018 if (consequence != null)
1020 type = getOntologyTerm(consequence);
1023 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
1024 featureEnd, FEATURE_GROUP_VCF);
1025 sf.setSource(sourceId);
1028 * save the derived alleles as a named attribute; this will be
1029 * needed when Jalview computes derived peptide variants
1031 addFeatureAttribute(sf, Gff3Helper.ALLELES, alleles);
1034 * add selected VCF fixed column data as feature attributes
1036 addFeatureAttribute(sf, VCF_POS, String.valueOf(variant.getStart()));
1037 addFeatureAttribute(sf, VCF_ID, variant.getID());
1038 addFeatureAttribute(sf, VCF_QUAL,
1039 String.valueOf(variant.getPhredScaledQual()));
1040 addFeatureAttribute(sf, VCF_FILTER, getFilter(variant));
1042 addAlleleProperties(variant, sf, altAlleleIndex, consequence);
1044 seq.addSequenceFeature(sf);
1050 * Answers the VCF FILTER value for the variant - or an approximation to it.
1051 * This field is either PASS, or a semi-colon separated list of filters not
1052 * passed. htsjdk saves filters as a HashSet, so the order when reassembled into
1053 * a list may be different.
1058 String getFilter(VariantContext variant)
1060 Set<String> filters = variant.getFilters();
1061 if (filters.isEmpty())
1065 Iterator<String> iterator = filters.iterator();
1066 String first = iterator.next();
1067 if (filters.size() == 1)
1072 StringBuilder sb = new StringBuilder(first);
1073 while (iterator.hasNext())
1075 sb.append(";").append(iterator.next());
1078 return sb.toString();
1082 * Adds one feature attribute unless the value is null, empty or '.'
1088 void addFeatureAttribute(SequenceFeature sf, String key, String value)
1090 if (value != null && !value.isEmpty() && !NO_VALUE.equals(value))
1092 sf.setValue(key, value);
1097 * Determines the Sequence Ontology term to use for the variant feature type in
1098 * Jalview. The default is 'sequence_variant', but a more specific term is used
1101 * <li>VEP (or SnpEff) Consequence annotation is included in the VCF</li>
1102 * <li>sequence id can be matched to VEP Feature (or SnpEff Feature_ID)</li>
1105 * @param consequence
1107 * @see http://www.sequenceontology.org/browser/current_svn/term/SO:0001060
1109 String getOntologyTerm(String consequence)
1111 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1114 * could we associate Consequence data with this allele and feature (transcript)?
1115 * if so, prefer the consequence term from that data
1117 if (csqAlleleFieldIndex == -1) // && snpEffAlleleFieldIndex == -1
1120 * no Consequence data so we can't refine the ontology term
1125 if (consequence != null)
1127 String[] csqFields = consequence.split(PIPE_REGEX);
1128 if (csqFields.length > csqConsequenceFieldIndex)
1130 type = csqFields[csqConsequenceFieldIndex];
1135 // todo the same for SnpEff consequence data matching if wanted
1139 * if of the form (e.g.) missense_variant&splice_region_variant,
1140 * just take the first ('most severe') consequence
1144 int pos = type.indexOf('&');
1147 type = type.substring(0, pos);
1154 * Returns matched consequence data if it can be found, else null.
1156 * <li>inspects the VCF data for key 'vcfInfoId'</li>
1157 * <li>splits this on comma (to distinct consequences)</li>
1158 * <li>returns the first consequence (if any) where</li>
1160 * <li>the allele matches the altAlleleIndex'th allele of variant</li>
1161 * <li>the feature matches the sequence name (e.g. transcript id)</li>
1164 * If matched, the consequence is returned (as pipe-delimited fields).
1168 * @param altAlleleIndex
1169 * @param alleleFieldIndex
1170 * @param alleleNumberFieldIndex
1172 * @param featureFieldIndex
1175 private String getConsequenceForAlleleAndFeature(VariantContext variant,
1176 String vcfInfoId, int altAlleleIndex, int alleleFieldIndex,
1177 int alleleNumberFieldIndex,
1178 String seqName, int featureFieldIndex)
1180 if (alleleFieldIndex == -1 || featureFieldIndex == -1)
1184 Object value = variant.getAttribute(vcfInfoId);
1186 if (value == null || !(value instanceof List<?>))
1192 * inspect each consequence in turn (comma-separated blocks
1193 * extracted by htsjdk)
1195 List<String> consequences = (List<String>) value;
1197 for (String consequence : consequences)
1199 String[] csqFields = consequence.split(PIPE_REGEX);
1200 if (csqFields.length > featureFieldIndex)
1202 String featureIdentifier = csqFields[featureFieldIndex];
1203 if (featureIdentifier.length() > 4
1204 && seqName.indexOf(featureIdentifier.toLowerCase()) > -1)
1207 * feature (transcript) matched - now check for allele match
1209 if (matchAllele(variant, altAlleleIndex, csqFields,
1210 alleleFieldIndex, alleleNumberFieldIndex))
1220 private boolean matchAllele(VariantContext variant, int altAlleleIndex,
1221 String[] csqFields, int alleleFieldIndex,
1222 int alleleNumberFieldIndex)
1225 * if ALLELE_NUM is present, it must match altAlleleIndex
1226 * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1228 if (alleleNumberFieldIndex > -1)
1230 if (csqFields.length <= alleleNumberFieldIndex)
1234 String alleleNum = csqFields[alleleNumberFieldIndex];
1235 return String.valueOf(altAlleleIndex + 1).equals(alleleNum);
1239 * else consequence allele must match variant allele
1241 if (alleleFieldIndex > -1 && csqFields.length > alleleFieldIndex)
1243 String csqAllele = csqFields[alleleFieldIndex];
1244 String vcfAllele = variant.getAlternateAllele(altAlleleIndex)
1246 return csqAllele.equals(vcfAllele);
1252 * Add any allele-specific VCF key-value data to the sequence feature
1256 * @param altAlelleIndex
1258 * @param consequence
1259 * if not null, the consequence specific to this sequence (transcript
1260 * feature) and allele
1262 protected void addAlleleProperties(VariantContext variant,
1263 SequenceFeature sf, final int altAlelleIndex, String consequence)
1265 Map<String, Object> atts = variant.getAttributes();
1267 for (Entry<String, Object> att : atts.entrySet())
1269 String key = att.getKey();
1272 * extract Consequence data (if present) that we are able to
1273 * associated with the allele for this variant feature
1275 if (CSQ_FIELD.equals(key))
1277 addConsequences(variant, sf, consequence);
1282 * filter out fields we don't want to capture
1284 if (!vcfFieldsOfInterest.contains(key))
1290 * we extract values for other data which are allele-specific;
1291 * these may be per alternate allele (INFO[key].Number = 'A')
1292 * or per allele including reference (INFO[key].Number = 'R')
1294 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
1295 if (infoHeader == null)
1298 * can't be sure what data belongs to this allele, so
1299 * play safe and don't take any
1304 VCFHeaderLineCount number = infoHeader.getCountType();
1305 int index = altAlelleIndex;
1306 if (number == VCFHeaderLineCount.R)
1309 * one value per allele including reference, so bump index
1310 * e.g. the 3rd value is for the 2nd alternate allele
1314 else if (number != VCFHeaderLineCount.A)
1317 * don't save other values as not allele-related
1323 * take the index'th value
1325 String value = getAttributeValue(variant, key, index);
1326 if (value != null && isValid(variant, key, value))
1329 * decode colon, semicolon, equals sign, percent sign, comma (only)
1330 * as required by the VCF specification (para 1.2)
1332 value = StringUtils.urlDecode(value, VCF_ENCODABLE);
1333 addFeatureAttribute(sf, key, value);
1339 * Answers true for '.', null, or an empty value, or if the INFO type is String.
1340 * If the INFO type is Integer or Float, answers false if the value is not in
1348 protected boolean isValid(VariantContext variant, String infoId,
1351 if (value == null || value.isEmpty() || NO_VALUE.equals(value))
1355 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(infoId);
1356 if (infoHeader == null)
1358 Cache.log.error("Field " + infoId + " has no INFO header");
1361 VCFHeaderLineType infoType = infoHeader.getType();
1364 if (infoType == VCFHeaderLineType.Integer)
1366 Integer.parseInt(value);
1368 else if (infoType == VCFHeaderLineType.Float)
1370 Float.parseFloat(value);
1372 } catch (NumberFormatException e)
1374 logInvalidValue(variant, infoId, value);
1381 * Logs an error message for malformed data; duplicate messages (same id and
1382 * value) are not logged
1388 private void logInvalidValue(VariantContext variant, String infoId,
1391 if (badData == null)
1393 badData = new HashSet<>();
1395 String token = infoId + ":" + value;
1396 if (!badData.contains(token))
1399 Cache.log.error(String.format("Invalid VCF data at %s:%d %s=%s",
1400 variant.getContig(), variant.getStart(), infoId, value));
1405 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
1408 * If <code>myConsequence</code> is not null, then this is the specific
1409 * consequence data (pipe-delimited fields) that is for the current allele and
1410 * transcript (sequence) being processed)
1414 * @param myConsequence
1416 protected void addConsequences(VariantContext variant, SequenceFeature sf,
1417 String myConsequence)
1419 Object value = variant.getAttribute(CSQ_FIELD);
1421 if (value == null || !(value instanceof List<?>))
1426 List<String> consequences = (List<String>) value;
1429 * inspect CSQ consequences; restrict to the consequence
1430 * associated with the current transcript (Feature)
1432 Map<String, String> csqValues = new HashMap<>();
1434 for (String consequence : consequences)
1436 if (myConsequence == null || myConsequence.equals(consequence))
1438 String[] csqFields = consequence.split(PIPE_REGEX);
1441 * inspect individual fields of this consequence, copying non-null
1442 * values which are 'fields of interest'
1445 for (String field : csqFields)
1447 if (field != null && field.length() > 0)
1449 String id = vepFieldsOfInterest.get(i);
1453 * VCF spec requires encoding of special characters e.g. '='
1454 * so decode them here before storing
1456 field = StringUtils.urlDecode(field, VCF_ENCODABLE);
1457 csqValues.put(id, field);
1465 if (!csqValues.isEmpty())
1467 sf.setValue(CSQ_FIELD, csqValues);
1472 * A convenience method to complement a dna base and return the string value
1478 protected String complement(byte[] reference)
1480 return String.valueOf(Dna.getComplement((char) reference[0]));
1484 * Determines the location of the query range (chromosome positions) in a
1485 * different reference assembly.
1487 * If the range is just a subregion of one for which we already have a mapping
1488 * (for example, an exon sub-region of a gene), then the mapping is just
1489 * computed arithmetically.
1491 * Otherwise, calls the Ensembl REST service that maps from one assembly
1492 * reference's coordinates to another's
1495 * start-end chromosomal range in 'fromRef' coordinates
1499 * assembly reference for the query coordinates
1501 * assembly reference we wish to translate to
1502 * @return the start-end range in 'toRef' coordinates
1504 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
1505 String species, String fromRef, String toRef)
1508 * first try shorcut of computing the mapping as a subregion of one
1509 * we already have (e.g. for an exon, if we have the gene mapping)
1511 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
1512 species, fromRef, toRef);
1513 if (mappedRange != null)
1519 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
1521 EnsemblMap mapper = new EnsemblMap();
1522 int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
1525 if (mapping == null)
1527 // mapping service failure
1532 * save mapping for possible future re-use
1534 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1535 if (!assemblyMappings.containsKey(key))
1537 assemblyMappings.put(key, new HashMap<int[], int[]>());
1540 assemblyMappings.get(key).put(queryRange, mapping);
1546 * If we already have a 1:1 contiguous mapping which subsumes the given query
1547 * range, this method just calculates and returns the subset of that mapping,
1548 * else it returns null. In practical terms, if a gene has a contiguous
1549 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
1550 * subsidiary exons occupy unchanged relative positions, and just compute
1551 * these as offsets, rather than do another lookup of the mapping.
1553 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
1554 * simply remove this method or let it always return null.
1556 * Warning: many rapid calls to the /map service map result in a 429 overload
1566 protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
1567 String species, String fromRef, String toRef)
1569 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1570 if (assemblyMappings.containsKey(key))
1572 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
1573 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
1575 int[] fromRange = mappedRange.getKey();
1576 int[] toRange = mappedRange.getValue();
1577 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
1580 * mapping is 1:1 in length, so we trust it to have no discontinuities
1582 if (MappingUtils.rangeContains(fromRange, queryRange))
1585 * fromRange subsumes our query range
1587 int offset = queryRange[0] - fromRange[0];
1588 int mappedRangeFrom = toRange[0] + offset;
1589 int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
1590 return new int[] { mappedRangeFrom, mappedRangeTo };
1599 * Transfers the sequence feature to the target sequence, locating its start
1600 * and end range based on the mapping. Features which do not overlap the
1601 * target sequence are ignored.
1604 * @param targetSequence
1606 * mapping from the feature's coordinates to the target sequence
1608 protected void transferFeature(SequenceFeature sf,
1609 SequenceI targetSequence, MapList mapping)
1611 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1613 if (mappedRange != null)
1615 String group = sf.getFeatureGroup();
1616 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1617 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1618 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1619 group, sf.getScore());
1620 targetSequence.addSequenceFeature(copy);
1625 * Formats a ranges map lookup key
1633 protected static String makeRangesKey(String chromosome, String species,
1634 String fromRef, String toRef)
1636 return species + EXCL + chromosome + EXCL + fromRef + EXCL