2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.io.vcf;
23 import java.util.Locale;
26 import java.io.IOException;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.Iterator;
31 import java.util.List;
33 import java.util.Map.Entry;
35 import java.util.regex.Pattern;
36 import java.util.regex.PatternSyntaxException;
38 import htsjdk.samtools.SAMException;
39 import htsjdk.samtools.SAMSequenceDictionary;
40 import htsjdk.samtools.SAMSequenceRecord;
41 import htsjdk.samtools.util.CloseableIterator;
42 import htsjdk.tribble.TribbleException;
43 import htsjdk.variant.variantcontext.Allele;
44 import htsjdk.variant.variantcontext.VariantContext;
45 import htsjdk.variant.vcf.VCFConstants;
46 import htsjdk.variant.vcf.VCFHeader;
47 import htsjdk.variant.vcf.VCFHeaderLine;
48 import htsjdk.variant.vcf.VCFHeaderLineCount;
49 import htsjdk.variant.vcf.VCFHeaderLineType;
50 import htsjdk.variant.vcf.VCFInfoHeaderLine;
51 import jalview.analysis.Dna;
52 import jalview.api.AlignViewControllerGuiI;
53 import jalview.bin.Cache;
54 import jalview.bin.Console;
55 import jalview.datamodel.DBRefEntry;
56 import jalview.datamodel.GeneLociI;
57 import jalview.datamodel.GenomicAssemblies;
58 import jalview.datamodel.Mapping;
59 import jalview.datamodel.SequenceFeature;
60 import jalview.datamodel.SequenceI;
61 import jalview.datamodel.features.FeatureAttributeType;
62 import jalview.datamodel.features.FeatureSource;
63 import jalview.datamodel.features.FeatureSources;
64 import jalview.ext.ensembl.EnsemblMap;
65 import jalview.ext.htsjdk.HtsContigDb;
66 import jalview.ext.htsjdk.VCFReader;
67 import jalview.io.gff.Gff3Helper;
68 import jalview.io.gff.SequenceOntologyI;
69 import jalview.util.MapList;
70 import jalview.util.MappingUtils;
71 import jalview.util.MessageManager;
72 import jalview.util.StringUtils;
75 * A class to read VCF data (using the htsjdk) and add variants as sequence
76 * features on dna and any related protein product sequences
80 public class VCFLoader
82 private static final String VCF_ENCODABLE = ":;=%,";
85 * Jalview feature attributes for VCF fixed column data
87 private static final String VCF_POS = "POS";
89 private static final String VCF_ID = "ID";
91 private static final String VCF_QUAL = "QUAL";
93 private static final String VCF_FILTER = "FILTER";
95 private static final String NO_VALUE = VCFConstants.MISSING_VALUE_v4; // '.'
97 private static final String DEFAULT_SPECIES = "homo_sapiens";
100 * A class to model the mapping from sequence to VCF coordinates. Cases
103 * <li>a direct 1:1 mapping where the sequence is one of the VCF contigs</li>
104 * <li>a mapping of sequence to chromosomal coordinates, where sequence and
105 * VCF use the same reference assembly</li>
106 * <li>a modified mapping of sequence to chromosomal coordinates, where
107 * sequence and VCF use different reference assembles</li>
112 final String chromosome;
116 VCFMap(String chr, MapList m)
123 public String toString()
125 return chromosome + ":" + map.toString();
130 * Lookup keys, and default values, for Preference entries that describe
131 * patterns for VCF and VEP fields to capture
133 private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
135 private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
137 private static final String DEFAULT_VCF_FIELDS = ".*";
139 private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
142 * Lookup keys, and default values, for Preference entries that give
143 * mappings from tokens in the 'reference' header to species or assembly
145 private static final String VCF_ASSEMBLY = "VCF_ASSEMBLY";
147 private static final String DEFAULT_VCF_ASSEMBLY = "assembly19=GRCh37,hs37=GRCh37,grch37=GRCh37,grch38=GRCh38";
149 private static final String VCF_SPECIES = "VCF_SPECIES"; // default is human
151 private static final String DEFAULT_REFERENCE = "grch37"; // fallback default
155 * keys to fields of VEP CSQ consequence data
156 * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
158 private static final String CSQ_CONSEQUENCE_KEY = "Consequence";
160 private static final String CSQ_ALLELE_KEY = "Allele";
162 private static final String CSQ_ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref),
165 private static final String CSQ_FEATURE_KEY = "Feature"; // Ensembl stable id
168 * default VCF INFO key for VEP consequence data
169 * NB this can be overridden running VEP with --vcf_info_field
170 * - we don't handle this case (require identifier to be CSQ)
172 private static final String CSQ_FIELD = "CSQ";
175 * separator for fields in consequence data is '|'
177 private static final String PIPE_REGEX = "\\|";
180 * delimiter that separates multiple consequence data blocks
182 private static final String COMMA = ",";
185 * the feature group assigned to a VCF variant in Jalview
187 private static final String FEATURE_GROUP_VCF = "VCF";
190 * the VCF file we are processing
192 protected String vcfFilePath;
194 private VCFReader reader;
197 * holds details of the VCF header lines (metadata)
199 private VCFHeader header;
202 * species (as a valid Ensembl term) the VCF is for
204 private String vcfSpecies;
207 * genome assembly version (as a valid Ensembl identifier) the VCF is for
209 private String vcfAssembly;
212 * a Dictionary of contigs (if present) referenced in the VCF file
214 private SAMSequenceDictionary dictionary;
217 * the position (0...) of field in each block of
218 * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
219 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
221 private int csqConsequenceFieldIndex = -1;
223 private int csqAlleleFieldIndex = -1;
225 private int csqAlleleNumberFieldIndex = -1;
227 private int csqFeatureFieldIndex = -1;
229 // todo the same fields for SnpEff ANN data if wanted
230 // see http://snpeff.sourceforge.net/SnpEff_manual.html#input
233 * a unique identifier under which to save metadata about feature
234 * attributes (selected INFO field data)
236 private String sourceId;
239 * The INFO IDs of data that is both present in the VCF file, and
240 * also matched by any filters for data of interest
242 List<String> vcfFieldsOfInterest;
245 * The field offsets and identifiers for VEP (CSQ) data that is both present
246 * in the VCF file, and also matched by any filters for data of interest
247 * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
249 Map<Integer, String> vepFieldsOfInterest;
252 * key:value for which rejected data has been seen
253 * (the error is logged only once for each combination)
255 private Set<String> badData;
258 * Constructor given a VCF file
262 public VCFLoader(String vcfFile)
267 } catch (IOException e)
270 .errPrintln("Error opening VCF file: " + e.getMessage());
275 * Starts a new thread to query and load VCF variant data on to the given
278 * This method is not thread safe - concurrent threads should use separate
279 * instances of this class.
284 public void loadVCF(SequenceI[] seqs, final AlignViewControllerGuiI gui)
288 gui.setStatus(MessageManager.getString("label.searching_vcf"));
296 VCFLoader.this.doLoad(seqs, gui);
302 * Reads the specified contig sequence and adds its VCF variants to it
305 * the id of a single sequence (contig) to load
308 public SequenceI loadVCFContig(String contig)
310 VCFHeaderLine headerLine = header
311 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
312 if (headerLine == null)
314 Console.error("VCF reference header not found");
317 String ref = headerLine.getValue();
318 if (ref.startsWith("file://"))
320 ref = ref.substring(7);
322 setSpeciesAndAssembly(ref);
324 SequenceI seq = null;
325 File dbFile = new File(ref);
329 HtsContigDb db = new HtsContigDb("", dbFile);
330 seq = db.getSequenceProxy(contig);
331 loadSequenceVCF(seq);
336 Console.error("VCF reference not found: " + ref);
343 * Loads VCF on to one or more sequences
347 * optional callback handler for messages
349 protected void doLoad(SequenceI[] seqs, AlignViewControllerGuiI gui)
353 VCFHeaderLine ref = header
354 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
355 String reference = ref == null ? null : ref.getValue();
357 setSpeciesAndAssembly(reference);
363 * query for VCF overlapping each sequence in turn
365 for (SequenceI seq : seqs)
367 int added = loadSequenceVCF(seq);
372 transferAddedFeatures(seq);
377 String msg = MessageManager.formatMessage("label.added_vcf",
380 if (gui.getFeatureSettingsUI() != null)
382 gui.getFeatureSettingsUI().discoverAllFeatureData();
385 } catch (Throwable e)
388 .errPrintln("Error processing VCF: " + e.getMessage());
392 gui.setStatus("Error occurred - see console for details");
401 } catch (IOException e)
412 * Attempts to determine and save the species and genome assembly version to
413 * which the VCF data applies. This may be done by parsing the
414 * {@code reference} header line, configured in a property file, or
415 * (potentially) confirmed interactively by the user.
417 * The saved values should be identifiers valid for Ensembl's REST service
418 * {@code map} endpoint, so they can be used (if necessary) to retrieve the
419 * mapping between VCF coordinates and sequence coordinates.
422 * @see https://rest.ensembl.org/documentation/info/assembly_map
423 * @see https://rest.ensembl.org/info/assembly/human?content-type=text/xml
424 * @see https://rest.ensembl.org/info/species?content-type=text/xml
426 protected void setSpeciesAndAssembly(String reference)
428 if (reference == null)
430 Console.error("No VCF ##reference found, defaulting to "
431 + DEFAULT_REFERENCE + ":" + DEFAULT_SPECIES);
432 reference = DEFAULT_REFERENCE; // default to GRCh37 if not specified
434 reference = reference.toLowerCase(Locale.ROOT);
437 * for a non-human species, or other assembly identifier,
438 * specify as a Jalview property file entry e.g.
439 * VCF_ASSEMBLY = hs37=GRCh37,assembly19=GRCh37
440 * VCF_SPECIES = c_elegans=celegans
441 * to map a token in the reference header to a value
443 String prop = Cache.getDefault(VCF_ASSEMBLY, DEFAULT_VCF_ASSEMBLY);
444 for (String token : prop.split(","))
446 String[] tokens = token.split("=");
447 if (tokens.length == 2)
449 if (reference.contains(tokens[0].trim().toLowerCase(Locale.ROOT)))
451 vcfAssembly = tokens[1].trim();
457 vcfSpecies = DEFAULT_SPECIES;
458 prop = Cache.getProperty(VCF_SPECIES);
461 for (String token : prop.split(","))
463 String[] tokens = token.split("=");
464 if (tokens.length == 2)
466 if (reference.contains(tokens[0].trim().toLowerCase(Locale.ROOT)))
468 vcfSpecies = tokens[1].trim();
477 * Opens the VCF file and parses header data
480 * @throws IOException
482 private void initialise(String filePath) throws IOException
484 vcfFilePath = filePath;
486 reader = new VCFReader(filePath);
488 header = reader.getFileHeader();
492 dictionary = header.getSequenceDictionary();
493 } catch (SAMException e)
495 // ignore - thrown if any contig line lacks length info
500 saveMetadata(sourceId);
503 * get offset of CSQ ALLELE_NUM and Feature if declared
509 * Reads metadata (such as INFO field descriptions and datatypes) and saves
510 * them for future reference
514 void saveMetadata(String theSourceId)
516 List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
518 vcfFieldsOfInterest = new ArrayList<>();
520 FeatureSource metadata = new FeatureSource(theSourceId);
522 for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
524 String attributeId = info.getID();
525 String desc = info.getDescription();
526 VCFHeaderLineType type = info.getType();
527 FeatureAttributeType attType = null;
531 attType = FeatureAttributeType.Character;
534 attType = FeatureAttributeType.Flag;
537 attType = FeatureAttributeType.Float;
540 attType = FeatureAttributeType.Integer;
543 attType = FeatureAttributeType.String;
546 metadata.setAttributeName(attributeId, desc);
547 metadata.setAttributeType(attributeId, attType);
549 if (isFieldWanted(attributeId, vcfFieldPatterns))
551 vcfFieldsOfInterest.add(attributeId);
555 FeatureSources.getInstance().addSource(theSourceId, metadata);
559 * Answers true if the field id is matched by any of the filter patterns, else
560 * false. Matching is against regular expression patterns, and is not
567 private boolean isFieldWanted(String id, List<Pattern> filters)
569 for (Pattern p : filters)
571 if (p.matcher(id.toUpperCase(Locale.ROOT)).matches())
580 * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
581 * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
582 * required for processing.
584 * CSQ fields are declared in the CSQ INFO Description e.g.
586 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
588 protected void parseCsqHeader()
590 List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
592 vepFieldsOfInterest = new HashMap<>();
594 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
601 * parse out the pipe-separated list of CSQ fields; we assume here that
602 * these form the last part of the description, and contain no spaces
604 String desc = csqInfo.getDescription();
605 int spacePos = desc.lastIndexOf(" ");
606 desc = desc.substring(spacePos + 1);
610 String[] format = desc.split(PIPE_REGEX);
612 for (String field : format)
614 if (CSQ_CONSEQUENCE_KEY.equals(field))
616 csqConsequenceFieldIndex = index;
618 if (CSQ_ALLELE_NUM_KEY.equals(field))
620 csqAlleleNumberFieldIndex = index;
622 if (CSQ_ALLELE_KEY.equals(field))
624 csqAlleleFieldIndex = index;
626 if (CSQ_FEATURE_KEY.equals(field))
628 csqFeatureFieldIndex = index;
631 if (isFieldWanted(field, vepFieldFilters))
633 vepFieldsOfInterest.put(index, field);
642 * Reads the Preference value for the given key, with default specified if no
643 * preference set. The value is interpreted as a comma-separated list of
644 * regular expressions, and converted into a list of compiled patterns ready
645 * for matching. Patterns are forced to upper-case for non-case-sensitive
648 * This supports user-defined filters for fields of interest to capture while
649 * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
650 * fields with an ID of AF, or starting with AC, would be matched.
656 private List<Pattern> getFieldMatchers(String key, String def)
658 String pref = Cache.getDefault(key, def);
659 List<Pattern> patterns = new ArrayList<>();
660 String[] tokens = pref.split(",");
661 for (String token : tokens)
665 patterns.add(Pattern.compile(token.toUpperCase(Locale.ROOT)));
666 } catch (PatternSyntaxException e)
668 jalview.bin.Console.errPrintln("Invalid pattern ignored: " + token);
675 * Transfers VCF features to sequences to which this sequence has a mapping.
679 protected void transferAddedFeatures(SequenceI seq)
681 List<DBRefEntry> dbrefs = seq.getDBRefs();
686 for (DBRefEntry dbref : dbrefs)
688 Mapping mapping = dbref.getMap();
689 if (mapping == null || mapping.getTo() == null)
694 SequenceI mapTo = mapping.getTo();
695 MapList map = mapping.getMap();
696 if (map.getFromRatio() == 3)
699 * dna-to-peptide product mapping
701 // JAL-3187 render on the fly instead
702 // AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
707 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
709 List<SequenceFeature> features = seq.getFeatures()
710 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
711 for (SequenceFeature sf : features)
713 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
715 transferFeature(sf, mapTo, map);
723 * Tries to add overlapping variants read from a VCF file to the given
724 * sequence, and returns the number of variant features added
729 protected int loadSequenceVCF(SequenceI seq)
731 VCFMap vcfMap = getVcfMap(seq);
738 * work with the dataset sequence here
740 SequenceI dss = seq.getDatasetSequence();
745 return addVcfVariants(dss, vcfMap);
749 * Answers a map from sequence coordinates to VCF chromosome ranges
754 private VCFMap getVcfMap(SequenceI seq)
757 * simplest case: sequence has id and length matching a VCF contig
759 VCFMap vcfMap = null;
760 if (dictionary != null)
762 vcfMap = getContigMap(seq);
770 * otherwise, map to VCF from chromosomal coordinates
771 * of the sequence (if known)
773 GeneLociI seqCoords = seq.getGeneLoci();
774 if (seqCoords == null)
776 Console.warn(String.format(
777 "Can't query VCF for %s as chromosome coordinates not known",
782 String species = seqCoords.getSpeciesId();
783 String chromosome = seqCoords.getChromosomeId();
784 String seqRef = seqCoords.getAssemblyId();
785 MapList map = seqCoords.getMapping();
787 // note this requires the configured species to match that
788 // returned with the Ensembl sequence; todo: support aliases?
789 if (!vcfSpecies.equalsIgnoreCase(species))
791 Console.warn("No VCF loaded to " + seq.getName()
792 + " as species not matched");
796 if (seqRef.equalsIgnoreCase(vcfAssembly))
798 return new VCFMap(chromosome, map);
802 * VCF data has a different reference assembly to the sequence:
803 * query Ensembl to map chromosomal coordinates from sequence to VCF
805 List<int[]> toVcfRanges = new ArrayList<>();
806 List<int[]> fromSequenceRanges = new ArrayList<>();
808 for (int[] range : map.getToRanges())
810 int[] fromRange = map.locateInFrom(range[0], range[1]);
811 if (fromRange == null)
817 int[] newRange = GenomicAssemblies.mapReferenceRange(range, chromosome, "human", seqRef,
819 if (newRange == null)
821 Console.error(String.format("Failed to map %s:%s:%s:%d:%d to %s",
822 species, chromosome, seqRef, range[0], range[1],
828 toVcfRanges.add(newRange);
829 fromSequenceRanges.add(fromRange);
833 return new VCFMap(chromosome,
834 new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
838 * If the sequence id matches a contig declared in the VCF file, and the
839 * sequence length matches the contig length, then returns a 1:1 map of the
840 * sequence to the contig, else returns null
845 private VCFMap getContigMap(SequenceI seq)
847 String id = seq.getName();
848 SAMSequenceRecord contig = dictionary.getSequence(id);
851 int len = seq.getLength();
852 if (len == contig.getSequenceLength())
854 MapList map = new MapList(new int[] { 1, len },
857 return new VCFMap(id, map);
864 * Queries the VCF reader for any variants that overlap the mapped chromosome
865 * ranges of the sequence, and adds as variant features. Returns the number of
866 * overlapping variants found.
870 * mapping from sequence to VCF coordinates
873 protected int addVcfVariants(SequenceI seq, VCFMap map)
875 boolean forwardStrand = map.map.isToForwardStrand();
878 * query the VCF for overlaps of each contiguous chromosomal region
882 for (int[] range : map.map.getToRanges())
884 int vcfStart = Math.min(range[0], range[1]);
885 int vcfEnd = Math.max(range[0], range[1]);
888 CloseableIterator<VariantContext> variants = reader
889 .query(map.chromosome, vcfStart, vcfEnd);
890 while (variants.hasNext())
892 VariantContext variant = variants.next();
894 int[] featureRange = map.map.locateInFrom(variant.getStart(),
898 * only take features whose range is fully mappable to sequence positions
900 if (featureRange != null)
902 int featureStart = Math.min(featureRange[0], featureRange[1]);
903 int featureEnd = Math.max(featureRange[0], featureRange[1]);
904 if (featureEnd - featureStart == variant.getEnd()
905 - variant.getStart())
907 count += addAlleleFeatures(seq, variant, featureStart,
908 featureEnd, forwardStrand);
913 } catch (TribbleException e)
916 * RuntimeException throwable by htsjdk
918 String msg = String.format("Error reading VCF for %s:%d-%d: %s ",
919 map.chromosome, vcfStart, vcfEnd, e.getLocalizedMessage());
928 * A convenience method to get an attribute value for an alternate allele
931 * @param attributeName
935 protected String getAttributeValue(VariantContext variant,
936 String attributeName, int alleleIndex)
938 Object att = variant.getAttribute(attributeName);
940 if (att instanceof String)
944 else if (att instanceof ArrayList)
946 return ((List<String>) att).get(alleleIndex);
953 * Adds one variant feature for each allele in the VCF variant record, and
954 * returns the number of features added.
958 * @param featureStart
960 * @param forwardStrand
963 protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
964 int featureStart, int featureEnd, boolean forwardStrand)
969 * Javadoc says getAlternateAlleles() imposes no order on the list returned
970 * so we proceed defensively to get them in strict order
972 int altAlleleCount = variant.getAlternateAlleles().size();
973 for (int i = 0; i < altAlleleCount; i++)
975 added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
982 * Inspects one allele and attempts to add a variant feature for it to the
983 * sequence. The additional data associated with this allele is extracted to
984 * store in the feature's key-value map. Answers the number of features added
989 * @param altAlleleIndex
991 * @param featureStart
993 * @param forwardStrand
996 protected int addAlleleFeature(SequenceI seq, VariantContext variant,
997 int altAlleleIndex, int featureStart, int featureEnd,
998 boolean forwardStrand)
1000 String reference = variant.getReference().getBaseString();
1001 Allele alt = variant.getAlternateAllele(altAlleleIndex);
1002 String allele = alt.getBaseString();
1005 * insertion after a genomic base, if on reverse strand, has to be
1006 * converted to insertion of complement after the preceding position
1008 int referenceLength = reference.length();
1009 if (!forwardStrand && allele.length() > referenceLength
1010 && allele.startsWith(reference))
1012 featureStart -= referenceLength;
1013 featureEnd = featureStart;
1014 char insertAfter = seq.getCharAt(featureStart - seq.getStart());
1015 reference = Dna.reverseComplement(String.valueOf(insertAfter));
1016 allele = allele.substring(referenceLength) + reference;
1020 * build the ref,alt allele description e.g. "G,A", using the base
1021 * complement if the sequence is on the reverse strand
1023 StringBuilder sb = new StringBuilder();
1024 sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
1026 sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
1027 String alleles = sb.toString(); // e.g. G,A
1030 * pick out the consequence data (if any) that is for the current allele
1031 * and feature (transcript) that matches the current sequence
1033 String consequence = getConsequenceForAlleleAndFeature(variant,
1034 CSQ_FIELD, altAlleleIndex, csqAlleleFieldIndex,
1035 csqAlleleNumberFieldIndex,
1036 seq.getName().toLowerCase(Locale.ROOT), csqFeatureFieldIndex);
1039 * pick out the ontology term for the consequence type
1041 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1042 if (consequence != null)
1044 type = getOntologyTerm(consequence);
1047 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
1048 featureEnd, FEATURE_GROUP_VCF);
1049 sf.setSource(sourceId);
1052 * save the derived alleles as a named attribute; this will be
1053 * needed when Jalview computes derived peptide variants
1055 addFeatureAttribute(sf, Gff3Helper.ALLELES, alleles);
1058 * add selected VCF fixed column data as feature attributes
1060 addFeatureAttribute(sf, VCF_POS, String.valueOf(variant.getStart()));
1061 addFeatureAttribute(sf, VCF_ID, variant.getID());
1062 addFeatureAttribute(sf, VCF_QUAL,
1063 String.valueOf(variant.getPhredScaledQual()));
1064 addFeatureAttribute(sf, VCF_FILTER, getFilter(variant));
1066 addAlleleProperties(variant, sf, altAlleleIndex, consequence);
1068 seq.addSequenceFeature(sf);
1074 * Answers the VCF FILTER value for the variant - or an approximation to it.
1075 * This field is either PASS, or a semi-colon separated list of filters not
1076 * passed. htsjdk saves filters as a HashSet, so the order when reassembled
1077 * into a list may be different.
1082 String getFilter(VariantContext variant)
1084 Set<String> filters = variant.getFilters();
1085 if (filters.isEmpty())
1089 Iterator<String> iterator = filters.iterator();
1090 String first = iterator.next();
1091 if (filters.size() == 1)
1096 StringBuilder sb = new StringBuilder(first);
1097 while (iterator.hasNext())
1099 sb.append(";").append(iterator.next());
1102 return sb.toString();
1106 * Adds one feature attribute unless the value is null, empty or '.'
1112 void addFeatureAttribute(SequenceFeature sf, String key, String value)
1114 if (value != null && !value.isEmpty() && !NO_VALUE.equals(value))
1116 sf.setValue(key, value);
1121 * Determines the Sequence Ontology term to use for the variant feature type
1122 * in Jalview. The default is 'sequence_variant', but a more specific term is
1125 * <li>VEP (or SnpEff) Consequence annotation is included in the VCF</li>
1126 * <li>sequence id can be matched to VEP Feature (or SnpEff Feature_ID)</li>
1129 * @param consequence
1131 * @see http://www.sequenceontology.org/browser/current_svn/term/SO:0001060
1133 String getOntologyTerm(String consequence)
1135 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1138 * could we associate Consequence data with this allele and feature (transcript)?
1139 * if so, prefer the consequence term from that data
1141 if (csqAlleleFieldIndex == -1) // && snpEffAlleleFieldIndex == -1
1144 * no Consequence data so we can't refine the ontology term
1149 if (consequence != null)
1151 String[] csqFields = consequence.split(PIPE_REGEX);
1152 if (csqFields.length > csqConsequenceFieldIndex)
1154 type = csqFields[csqConsequenceFieldIndex];
1159 // todo the same for SnpEff consequence data matching if wanted
1163 * if of the form (e.g.) missense_variant&splice_region_variant,
1164 * just take the first ('most severe') consequence
1168 int pos = type.indexOf('&');
1171 type = type.substring(0, pos);
1178 * Returns matched consequence data if it can be found, else null.
1180 * <li>inspects the VCF data for key 'vcfInfoId'</li>
1181 * <li>splits this on comma (to distinct consequences)</li>
1182 * <li>returns the first consequence (if any) where</li>
1184 * <li>the allele matches the altAlleleIndex'th allele of variant</li>
1185 * <li>the feature matches the sequence name (e.g. transcript id)</li>
1188 * If matched, the consequence is returned (as pipe-delimited fields).
1192 * @param altAlleleIndex
1193 * @param alleleFieldIndex
1194 * @param alleleNumberFieldIndex
1196 * @param featureFieldIndex
1199 private String getConsequenceForAlleleAndFeature(VariantContext variant,
1200 String vcfInfoId, int altAlleleIndex, int alleleFieldIndex,
1201 int alleleNumberFieldIndex, String seqName, int featureFieldIndex)
1203 if (alleleFieldIndex == -1 || featureFieldIndex == -1)
1207 Object value = variant.getAttribute(vcfInfoId);
1209 if (value == null || !(value instanceof List<?>))
1215 * inspect each consequence in turn (comma-separated blocks
1216 * extracted by htsjdk)
1218 List<String> consequences = (List<String>) value;
1220 for (String consequence : consequences)
1222 String[] csqFields = consequence.split(PIPE_REGEX);
1223 if (csqFields.length > featureFieldIndex)
1225 String featureIdentifier = csqFields[featureFieldIndex];
1226 if (featureIdentifier.length() > 4 && seqName
1227 .indexOf(featureIdentifier.toLowerCase(Locale.ROOT)) > -1)
1230 * feature (transcript) matched - now check for allele match
1232 if (matchAllele(variant, altAlleleIndex, csqFields,
1233 alleleFieldIndex, alleleNumberFieldIndex))
1243 private boolean matchAllele(VariantContext variant, int altAlleleIndex,
1244 String[] csqFields, int alleleFieldIndex,
1245 int alleleNumberFieldIndex)
1248 * if ALLELE_NUM is present, it must match altAlleleIndex
1249 * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1251 if (alleleNumberFieldIndex > -1)
1253 if (csqFields.length <= alleleNumberFieldIndex)
1257 String alleleNum = csqFields[alleleNumberFieldIndex];
1258 return String.valueOf(altAlleleIndex + 1).equals(alleleNum);
1262 * else consequence allele must match variant allele
1264 if (alleleFieldIndex > -1 && csqFields.length > alleleFieldIndex)
1266 String csqAllele = csqFields[alleleFieldIndex];
1267 String vcfAllele = variant.getAlternateAllele(altAlleleIndex)
1269 return csqAllele.equals(vcfAllele);
1275 * Add any allele-specific VCF key-value data to the sequence feature
1279 * @param altAlelleIndex
1281 * @param consequence
1282 * if not null, the consequence specific to this sequence (transcript
1283 * feature) and allele
1285 protected void addAlleleProperties(VariantContext variant,
1286 SequenceFeature sf, final int altAlelleIndex, String consequence)
1288 Map<String, Object> atts = variant.getAttributes();
1290 for (Entry<String, Object> att : atts.entrySet())
1292 String key = att.getKey();
1295 * extract Consequence data (if present) that we are able to
1296 * associated with the allele for this variant feature
1298 if (CSQ_FIELD.equals(key))
1300 addConsequences(variant, sf, consequence);
1305 * filter out fields we don't want to capture
1307 if (!vcfFieldsOfInterest.contains(key))
1313 * we extract values for other data which are allele-specific;
1314 * these may be per alternate allele (INFO[key].Number = 'A')
1315 * or per allele including reference (INFO[key].Number = 'R')
1317 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
1318 if (infoHeader == null)
1321 * can't be sure what data belongs to this allele, so
1322 * play safe and don't take any
1327 VCFHeaderLineCount number = infoHeader.getCountType();
1328 int index = altAlelleIndex;
1329 if (number == VCFHeaderLineCount.R)
1332 * one value per allele including reference, so bump index
1333 * e.g. the 3rd value is for the 2nd alternate allele
1337 else if (number != VCFHeaderLineCount.A)
1340 * don't save other values as not allele-related
1346 * take the index'th value
1348 String value = getAttributeValue(variant, key, index);
1349 if (value != null && isValid(variant, key, value))
1352 * decode colon, semicolon, equals sign, percent sign, comma (only)
1353 * as required by the VCF specification (para 1.2)
1355 value = StringUtils.urlDecode(value, VCF_ENCODABLE);
1356 addFeatureAttribute(sf, key, value);
1362 * Answers true for '.', null, or an empty value, or if the INFO type is
1363 * String. If the INFO type is Integer or Float, answers false if the value is
1364 * not in valid format.
1371 protected boolean isValid(VariantContext variant, String infoId,
1374 if (value == null || value.isEmpty() || NO_VALUE.equals(value))
1378 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(infoId);
1379 if (infoHeader == null)
1381 Console.error("Field " + infoId + " has no INFO header");
1384 VCFHeaderLineType infoType = infoHeader.getType();
1387 if (infoType == VCFHeaderLineType.Integer)
1389 Integer.parseInt(value);
1391 else if (infoType == VCFHeaderLineType.Float)
1393 Float.parseFloat(value);
1395 } catch (NumberFormatException e)
1397 logInvalidValue(variant, infoId, value);
1404 * Logs an error message for malformed data; duplicate messages (same id and
1405 * value) are not logged
1411 private void logInvalidValue(VariantContext variant, String infoId,
1414 if (badData == null)
1416 badData = new HashSet<>();
1418 String token = infoId + ":" + value;
1419 if (!badData.contains(token))
1422 Console.error(String.format("Invalid VCF data at %s:%d %s=%s",
1423 variant.getContig(), variant.getStart(), infoId, value));
1428 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
1431 * If <code>myConsequence</code> is not null, then this is the specific
1432 * consequence data (pipe-delimited fields) that is for the current allele and
1433 * transcript (sequence) being processed)
1437 * @param myConsequence
1439 protected void addConsequences(VariantContext variant, SequenceFeature sf,
1440 String myConsequence)
1442 Object value = variant.getAttribute(CSQ_FIELD);
1444 if (value == null || !(value instanceof List<?>))
1449 List<String> consequences = (List<String>) value;
1452 * inspect CSQ consequences; restrict to the consequence
1453 * associated with the current transcript (Feature)
1455 Map<String, String> csqValues = new HashMap<>();
1457 for (String consequence : consequences)
1459 if (myConsequence == null || myConsequence.equals(consequence))
1461 String[] csqFields = consequence.split(PIPE_REGEX);
1464 * inspect individual fields of this consequence, copying non-null
1465 * values which are 'fields of interest'
1468 for (String field : csqFields)
1470 if (field != null && field.length() > 0)
1472 String id = vepFieldsOfInterest.get(i);
1476 * VCF spec requires encoding of special characters e.g. '='
1477 * so decode them here before storing
1479 field = StringUtils.urlDecode(field, VCF_ENCODABLE);
1480 csqValues.put(id, field);
1488 if (!csqValues.isEmpty())
1490 sf.setValue(CSQ_FIELD, csqValues);
1495 * A convenience method to complement a dna base and return the string value
1501 protected String complement(byte[] reference)
1503 return String.valueOf(Dna.getComplement((char) reference[0]));
1507 * Transfers the sequence feature to the target sequence, locating its start
1508 * and end range based on the mapping. Features which do not overlap the
1509 * target sequence are ignored.
1512 * @param targetSequence
1514 * mapping from the feature's coordinates to the target sequence
1516 protected void transferFeature(SequenceFeature sf,
1517 SequenceI targetSequence, MapList mapping)
1519 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1521 if (mappedRange != null)
1523 String group = sf.getFeatureGroup();
1524 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1525 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1526 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1527 group, sf.getScore());
1528 targetSequence.addSequenceFeature(copy);