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)
269 System.err.println("Error opening VCF file: " + e.getMessage());
274 * Starts a new thread to query and load VCF variant data on to the given
277 * This method is not thread safe - concurrent threads should use separate
278 * instances of this class.
283 public void loadVCF(SequenceI[] seqs, final AlignViewControllerGuiI gui)
287 gui.setStatus(MessageManager.getString("label.searching_vcf"));
295 VCFLoader.this.doLoad(seqs, gui);
301 * Reads the specified contig sequence and adds its VCF variants to it
304 * the id of a single sequence (contig) to load
307 public SequenceI loadVCFContig(String contig)
309 VCFHeaderLine headerLine = header
310 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
311 if (headerLine == null)
313 Console.error("VCF reference header not found");
316 String ref = headerLine.getValue();
317 if (ref.startsWith("file://"))
319 ref = ref.substring(7);
321 setSpeciesAndAssembly(ref);
323 SequenceI seq = null;
324 File dbFile = new File(ref);
328 HtsContigDb db = new HtsContigDb("", dbFile);
329 seq = db.getSequenceProxy(contig);
330 loadSequenceVCF(seq);
335 Console.error("VCF reference not found: " + ref);
342 * Loads VCF on to one or more sequences
346 * optional callback handler for messages
348 protected void doLoad(SequenceI[] seqs, AlignViewControllerGuiI gui)
352 VCFHeaderLine ref = header
353 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
354 String reference = ref == null ? null : ref.getValue();
356 setSpeciesAndAssembly(reference);
362 * query for VCF overlapping each sequence in turn
364 for (SequenceI seq : seqs)
366 int added = loadSequenceVCF(seq);
371 transferAddedFeatures(seq);
376 String msg = MessageManager.formatMessage("label.added_vcf",
379 if (gui.getFeatureSettingsUI() != null)
381 gui.getFeatureSettingsUI().discoverAllFeatureData();
384 } catch (Throwable e)
386 System.err.println("Error processing VCF: " + e.getMessage());
390 gui.setStatus("Error occurred - see console for details");
399 } catch (IOException e)
410 * Attempts to determine and save the species and genome assembly version to
411 * which the VCF data applies. This may be done by parsing the
412 * {@code reference} header line, configured in a property file, or
413 * (potentially) confirmed interactively by the user.
415 * The saved values should be identifiers valid for Ensembl's REST service
416 * {@code map} endpoint, so they can be used (if necessary) to retrieve the
417 * mapping between VCF coordinates and sequence coordinates.
420 * @see https://rest.ensembl.org/documentation/info/assembly_map
421 * @see https://rest.ensembl.org/info/assembly/human?content-type=text/xml
422 * @see https://rest.ensembl.org/info/species?content-type=text/xml
424 protected void setSpeciesAndAssembly(String reference)
426 if (reference == null)
428 Console.error("No VCF ##reference found, defaulting to "
429 + DEFAULT_REFERENCE + ":" + DEFAULT_SPECIES);
430 reference = DEFAULT_REFERENCE; // default to GRCh37 if not specified
432 reference = reference.toLowerCase(Locale.ROOT);
435 * for a non-human species, or other assembly identifier,
436 * specify as a Jalview property file entry e.g.
437 * VCF_ASSEMBLY = hs37=GRCh37,assembly19=GRCh37
438 * VCF_SPECIES = c_elegans=celegans
439 * to map a token in the reference header to a value
441 String prop = Cache.getDefault(VCF_ASSEMBLY, DEFAULT_VCF_ASSEMBLY);
442 for (String token : prop.split(","))
444 String[] tokens = token.split("=");
445 if (tokens.length == 2)
447 if (reference.contains(tokens[0].trim().toLowerCase(Locale.ROOT)))
449 vcfAssembly = tokens[1].trim();
455 vcfSpecies = DEFAULT_SPECIES;
456 prop = Cache.getProperty(VCF_SPECIES);
459 for (String token : prop.split(","))
461 String[] tokens = token.split("=");
462 if (tokens.length == 2)
464 if (reference.contains(tokens[0].trim().toLowerCase(Locale.ROOT)))
466 vcfSpecies = tokens[1].trim();
475 * Opens the VCF file and parses header data
478 * @throws IOException
480 private void initialise(String filePath) throws IOException
482 vcfFilePath = filePath;
484 reader = new VCFReader(filePath);
486 header = reader.getFileHeader();
490 dictionary = header.getSequenceDictionary();
491 } catch (SAMException e)
493 // ignore - thrown if any contig line lacks length info
498 saveMetadata(sourceId);
501 * get offset of CSQ ALLELE_NUM and Feature if declared
507 * Reads metadata (such as INFO field descriptions and datatypes) and saves
508 * them for future reference
512 void saveMetadata(String theSourceId)
514 List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
516 vcfFieldsOfInterest = new ArrayList<>();
518 FeatureSource metadata = new FeatureSource(theSourceId);
520 for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
522 String attributeId = info.getID();
523 String desc = info.getDescription();
524 VCFHeaderLineType type = info.getType();
525 FeatureAttributeType attType = null;
529 attType = FeatureAttributeType.Character;
532 attType = FeatureAttributeType.Flag;
535 attType = FeatureAttributeType.Float;
538 attType = FeatureAttributeType.Integer;
541 attType = FeatureAttributeType.String;
544 metadata.setAttributeName(attributeId, desc);
545 metadata.setAttributeType(attributeId, attType);
547 if (isFieldWanted(attributeId, vcfFieldPatterns))
549 vcfFieldsOfInterest.add(attributeId);
553 FeatureSources.getInstance().addSource(theSourceId, metadata);
557 * Answers true if the field id is matched by any of the filter patterns, else
558 * false. Matching is against regular expression patterns, and is not
565 private boolean isFieldWanted(String id, List<Pattern> filters)
567 for (Pattern p : filters)
569 if (p.matcher(id.toUpperCase(Locale.ROOT)).matches())
578 * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
579 * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
580 * required for processing.
582 * CSQ fields are declared in the CSQ INFO Description e.g.
584 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
586 protected void parseCsqHeader()
588 List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
590 vepFieldsOfInterest = new HashMap<>();
592 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
599 * parse out the pipe-separated list of CSQ fields; we assume here that
600 * these form the last part of the description, and contain no spaces
602 String desc = csqInfo.getDescription();
603 int spacePos = desc.lastIndexOf(" ");
604 desc = desc.substring(spacePos + 1);
608 String[] format = desc.split(PIPE_REGEX);
610 for (String field : format)
612 if (CSQ_CONSEQUENCE_KEY.equals(field))
614 csqConsequenceFieldIndex = index;
616 if (CSQ_ALLELE_NUM_KEY.equals(field))
618 csqAlleleNumberFieldIndex = index;
620 if (CSQ_ALLELE_KEY.equals(field))
622 csqAlleleFieldIndex = index;
624 if (CSQ_FEATURE_KEY.equals(field))
626 csqFeatureFieldIndex = index;
629 if (isFieldWanted(field, vepFieldFilters))
631 vepFieldsOfInterest.put(index, field);
640 * Reads the Preference value for the given key, with default specified if no
641 * preference set. The value is interpreted as a comma-separated list of
642 * regular expressions, and converted into a list of compiled patterns ready
643 * for matching. Patterns are forced to upper-case for non-case-sensitive
646 * This supports user-defined filters for fields of interest to capture while
647 * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
648 * fields with an ID of AF, or starting with AC, would be matched.
654 private List<Pattern> getFieldMatchers(String key, String def)
656 String pref = Cache.getDefault(key, def);
657 List<Pattern> patterns = new ArrayList<>();
658 String[] tokens = pref.split(",");
659 for (String token : tokens)
663 patterns.add(Pattern.compile(token.toUpperCase(Locale.ROOT)));
664 } catch (PatternSyntaxException e)
666 System.err.println("Invalid pattern ignored: " + token);
673 * Transfers VCF features to sequences to which this sequence has a mapping.
677 protected void transferAddedFeatures(SequenceI seq)
679 List<DBRefEntry> dbrefs = seq.getDBRefs();
684 for (DBRefEntry dbref : dbrefs)
686 Mapping mapping = dbref.getMap();
687 if (mapping == null || mapping.getTo() == null)
692 SequenceI mapTo = mapping.getTo();
693 MapList map = mapping.getMap();
694 if (map.getFromRatio() == 3)
697 * dna-to-peptide product mapping
699 // JAL-3187 render on the fly instead
700 // AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
705 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
707 List<SequenceFeature> features = seq.getFeatures()
708 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
709 for (SequenceFeature sf : features)
711 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
713 transferFeature(sf, mapTo, map);
721 * Tries to add overlapping variants read from a VCF file to the given
722 * sequence, and returns the number of variant features added
727 protected int loadSequenceVCF(SequenceI seq)
729 VCFMap vcfMap = getVcfMap(seq);
736 * work with the dataset sequence here
738 SequenceI dss = seq.getDatasetSequence();
743 return addVcfVariants(dss, vcfMap);
747 * Answers a map from sequence coordinates to VCF chromosome ranges
752 private VCFMap getVcfMap(SequenceI seq)
755 * simplest case: sequence has id and length matching a VCF contig
757 VCFMap vcfMap = null;
758 if (dictionary != null)
760 vcfMap = getContigMap(seq);
768 * otherwise, map to VCF from chromosomal coordinates
769 * of the sequence (if known)
771 GeneLociI seqCoords = seq.getGeneLoci();
772 if (seqCoords == null)
774 Console.warn(String.format(
775 "Can't query VCF for %s as chromosome coordinates not known",
780 String species = seqCoords.getSpeciesId();
781 String chromosome = seqCoords.getChromosomeId();
782 String seqRef = seqCoords.getAssemblyId();
783 MapList map = seqCoords.getMapping();
785 // note this requires the configured species to match that
786 // returned with the Ensembl sequence; todo: support aliases?
787 if (!vcfSpecies.equalsIgnoreCase(species))
789 Console.warn("No VCF loaded to " + seq.getName()
790 + " as species not matched");
794 if (seqRef.equalsIgnoreCase(vcfAssembly))
796 return new VCFMap(chromosome, map);
799 return new VCFMap(chromosome,GenomicAssemblies.mapAssemblyFor(seqRef,"human",map,chromosome,vcfAssembly));
802 * If the sequence id matches a contig declared in the VCF file, and the
803 * sequence length matches the contig length, then returns a 1:1 map of the
804 * sequence to the contig, else returns null
809 private VCFMap getContigMap(SequenceI seq)
811 String id = seq.getName();
812 SAMSequenceRecord contig = dictionary.getSequence(id);
815 int len = seq.getLength();
816 if (len == contig.getSequenceLength())
818 MapList map = new MapList(new int[] { 1, len },
821 return new VCFMap(id, map);
828 * Queries the VCF reader for any variants that overlap the mapped chromosome
829 * ranges of the sequence, and adds as variant features. Returns the number of
830 * overlapping variants found.
834 * mapping from sequence to VCF coordinates
837 protected int addVcfVariants(SequenceI seq, VCFMap map)
839 boolean forwardStrand = map.map.isToForwardStrand();
842 * query the VCF for overlaps of each contiguous chromosomal region
846 for (int[] range : map.map.getToRanges())
848 int vcfStart = Math.min(range[0], range[1]);
849 int vcfEnd = Math.max(range[0], range[1]);
852 CloseableIterator<VariantContext> variants = reader
853 .query(map.chromosome, vcfStart, vcfEnd);
854 while (variants.hasNext())
856 VariantContext variant = variants.next();
858 int[] featureRange = map.map.locateInFrom(variant.getStart(),
862 * only take features whose range is fully mappable to sequence positions
864 if (featureRange != null)
866 int featureStart = Math.min(featureRange[0], featureRange[1]);
867 int featureEnd = Math.max(featureRange[0], featureRange[1]);
868 if (featureEnd - featureStart == variant.getEnd()
869 - variant.getStart())
871 count += addAlleleFeatures(seq, variant, featureStart,
872 featureEnd, forwardStrand);
877 } catch (TribbleException e)
880 * RuntimeException throwable by htsjdk
882 String msg = String.format("Error reading VCF for %s:%d-%d: %s ",
883 map.chromosome, vcfStart, vcfEnd, e.getLocalizedMessage());
892 * A convenience method to get an attribute value for an alternate allele
895 * @param attributeName
899 protected String getAttributeValue(VariantContext variant,
900 String attributeName, int alleleIndex)
902 Object att = variant.getAttribute(attributeName);
904 if (att instanceof String)
908 else if (att instanceof ArrayList)
910 return ((List<String>) att).get(alleleIndex);
917 * Adds one variant feature for each allele in the VCF variant record, and
918 * returns the number of features added.
922 * @param featureStart
924 * @param forwardStrand
927 protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
928 int featureStart, int featureEnd, boolean forwardStrand)
933 * Javadoc says getAlternateAlleles() imposes no order on the list returned
934 * so we proceed defensively to get them in strict order
936 int altAlleleCount = variant.getAlternateAlleles().size();
937 for (int i = 0; i < altAlleleCount; i++)
939 added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
946 * Inspects one allele and attempts to add a variant feature for it to the
947 * sequence. The additional data associated with this allele is extracted to
948 * store in the feature's key-value map. Answers the number of features added
953 * @param altAlleleIndex
955 * @param featureStart
957 * @param forwardStrand
960 protected int addAlleleFeature(SequenceI seq, VariantContext variant,
961 int altAlleleIndex, int featureStart, int featureEnd,
962 boolean forwardStrand)
964 String reference = variant.getReference().getBaseString();
965 Allele alt = variant.getAlternateAllele(altAlleleIndex);
966 String allele = alt.getBaseString();
969 * insertion after a genomic base, if on reverse strand, has to be
970 * converted to insertion of complement after the preceding position
972 int referenceLength = reference.length();
973 if (!forwardStrand && allele.length() > referenceLength
974 && allele.startsWith(reference))
976 featureStart -= referenceLength;
977 featureEnd = featureStart;
978 char insertAfter = seq.getCharAt(featureStart - seq.getStart());
979 reference = Dna.reverseComplement(String.valueOf(insertAfter));
980 allele = allele.substring(referenceLength) + reference;
984 * build the ref,alt allele description e.g. "G,A", using the base
985 * complement if the sequence is on the reverse strand
987 StringBuilder sb = new StringBuilder();
988 sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
990 sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
991 String alleles = sb.toString(); // e.g. G,A
994 * pick out the consequence data (if any) that is for the current allele
995 * and feature (transcript) that matches the current sequence
997 String consequence = getConsequenceForAlleleAndFeature(variant,
998 CSQ_FIELD, altAlleleIndex, csqAlleleFieldIndex,
999 csqAlleleNumberFieldIndex,
1000 seq.getName().toLowerCase(Locale.ROOT), csqFeatureFieldIndex);
1003 * pick out the ontology term for the consequence type
1005 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1006 if (consequence != null)
1008 type = getOntologyTerm(consequence);
1011 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
1012 featureEnd, FEATURE_GROUP_VCF);
1013 sf.setSource(sourceId);
1016 * save the derived alleles as a named attribute; this will be
1017 * needed when Jalview computes derived peptide variants
1019 addFeatureAttribute(sf, Gff3Helper.ALLELES, alleles);
1022 * add selected VCF fixed column data as feature attributes
1024 addFeatureAttribute(sf, VCF_POS, String.valueOf(variant.getStart()));
1025 addFeatureAttribute(sf, VCF_ID, variant.getID());
1026 addFeatureAttribute(sf, VCF_QUAL,
1027 String.valueOf(variant.getPhredScaledQual()));
1028 addFeatureAttribute(sf, VCF_FILTER, getFilter(variant));
1030 addAlleleProperties(variant, sf, altAlleleIndex, consequence);
1032 seq.addSequenceFeature(sf);
1038 * Answers the VCF FILTER value for the variant - or an approximation to it.
1039 * This field is either PASS, or a semi-colon separated list of filters not
1040 * passed. htsjdk saves filters as a HashSet, so the order when reassembled
1041 * into a list may be different.
1046 String getFilter(VariantContext variant)
1048 Set<String> filters = variant.getFilters();
1049 if (filters.isEmpty())
1053 Iterator<String> iterator = filters.iterator();
1054 String first = iterator.next();
1055 if (filters.size() == 1)
1060 StringBuilder sb = new StringBuilder(first);
1061 while (iterator.hasNext())
1063 sb.append(";").append(iterator.next());
1066 return sb.toString();
1070 * Adds one feature attribute unless the value is null, empty or '.'
1076 void addFeatureAttribute(SequenceFeature sf, String key, String value)
1078 if (value != null && !value.isEmpty() && !NO_VALUE.equals(value))
1080 sf.setValue(key, value);
1085 * Determines the Sequence Ontology term to use for the variant feature type
1086 * in Jalview. The default is 'sequence_variant', but a more specific term is
1089 * <li>VEP (or SnpEff) Consequence annotation is included in the VCF</li>
1090 * <li>sequence id can be matched to VEP Feature (or SnpEff Feature_ID)</li>
1093 * @param consequence
1095 * @see http://www.sequenceontology.org/browser/current_svn/term/SO:0001060
1097 String getOntologyTerm(String consequence)
1099 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1102 * could we associate Consequence data with this allele and feature (transcript)?
1103 * if so, prefer the consequence term from that data
1105 if (csqAlleleFieldIndex == -1) // && snpEffAlleleFieldIndex == -1
1108 * no Consequence data so we can't refine the ontology term
1113 if (consequence != null)
1115 String[] csqFields = consequence.split(PIPE_REGEX);
1116 if (csqFields.length > csqConsequenceFieldIndex)
1118 type = csqFields[csqConsequenceFieldIndex];
1123 // todo the same for SnpEff consequence data matching if wanted
1127 * if of the form (e.g.) missense_variant&splice_region_variant,
1128 * just take the first ('most severe') consequence
1132 int pos = type.indexOf('&');
1135 type = type.substring(0, pos);
1142 * Returns matched consequence data if it can be found, else null.
1144 * <li>inspects the VCF data for key 'vcfInfoId'</li>
1145 * <li>splits this on comma (to distinct consequences)</li>
1146 * <li>returns the first consequence (if any) where</li>
1148 * <li>the allele matches the altAlleleIndex'th allele of variant</li>
1149 * <li>the feature matches the sequence name (e.g. transcript id)</li>
1152 * If matched, the consequence is returned (as pipe-delimited fields).
1156 * @param altAlleleIndex
1157 * @param alleleFieldIndex
1158 * @param alleleNumberFieldIndex
1160 * @param featureFieldIndex
1163 private String getConsequenceForAlleleAndFeature(VariantContext variant,
1164 String vcfInfoId, int altAlleleIndex, int alleleFieldIndex,
1165 int alleleNumberFieldIndex, String seqName, int featureFieldIndex)
1167 if (alleleFieldIndex == -1 || featureFieldIndex == -1)
1171 Object value = variant.getAttribute(vcfInfoId);
1173 if (value == null || !(value instanceof List<?>))
1179 * inspect each consequence in turn (comma-separated blocks
1180 * extracted by htsjdk)
1182 List<String> consequences = (List<String>) value;
1184 for (String consequence : consequences)
1186 String[] csqFields = consequence.split(PIPE_REGEX);
1187 if (csqFields.length > featureFieldIndex)
1189 String featureIdentifier = csqFields[featureFieldIndex];
1190 if (featureIdentifier.length() > 4 && seqName
1191 .indexOf(featureIdentifier.toLowerCase(Locale.ROOT)) > -1)
1194 * feature (transcript) matched - now check for allele match
1196 if (matchAllele(variant, altAlleleIndex, csqFields,
1197 alleleFieldIndex, alleleNumberFieldIndex))
1207 private boolean matchAllele(VariantContext variant, int altAlleleIndex,
1208 String[] csqFields, int alleleFieldIndex,
1209 int alleleNumberFieldIndex)
1212 * if ALLELE_NUM is present, it must match altAlleleIndex
1213 * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1215 if (alleleNumberFieldIndex > -1)
1217 if (csqFields.length <= alleleNumberFieldIndex)
1221 String alleleNum = csqFields[alleleNumberFieldIndex];
1222 return String.valueOf(altAlleleIndex + 1).equals(alleleNum);
1226 * else consequence allele must match variant allele
1228 if (alleleFieldIndex > -1 && csqFields.length > alleleFieldIndex)
1230 String csqAllele = csqFields[alleleFieldIndex];
1231 String vcfAllele = variant.getAlternateAllele(altAlleleIndex)
1233 return csqAllele.equals(vcfAllele);
1239 * Add any allele-specific VCF key-value data to the sequence feature
1243 * @param altAlelleIndex
1245 * @param consequence
1246 * if not null, the consequence specific to this sequence (transcript
1247 * feature) and allele
1249 protected void addAlleleProperties(VariantContext variant,
1250 SequenceFeature sf, final int altAlelleIndex, String consequence)
1252 Map<String, Object> atts = variant.getAttributes();
1254 for (Entry<String, Object> att : atts.entrySet())
1256 String key = att.getKey();
1259 * extract Consequence data (if present) that we are able to
1260 * associated with the allele for this variant feature
1262 if (CSQ_FIELD.equals(key))
1264 addConsequences(variant, sf, consequence);
1269 * filter out fields we don't want to capture
1271 if (!vcfFieldsOfInterest.contains(key))
1277 * we extract values for other data which are allele-specific;
1278 * these may be per alternate allele (INFO[key].Number = 'A')
1279 * or per allele including reference (INFO[key].Number = 'R')
1281 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
1282 if (infoHeader == null)
1285 * can't be sure what data belongs to this allele, so
1286 * play safe and don't take any
1291 VCFHeaderLineCount number = infoHeader.getCountType();
1292 int index = altAlelleIndex;
1293 if (number == VCFHeaderLineCount.R)
1296 * one value per allele including reference, so bump index
1297 * e.g. the 3rd value is for the 2nd alternate allele
1301 else if (number != VCFHeaderLineCount.A)
1304 * don't save other values as not allele-related
1310 * take the index'th value
1312 String value = getAttributeValue(variant, key, index);
1313 if (value != null && isValid(variant, key, value))
1316 * decode colon, semicolon, equals sign, percent sign, comma (only)
1317 * as required by the VCF specification (para 1.2)
1319 value = StringUtils.urlDecode(value, VCF_ENCODABLE);
1320 addFeatureAttribute(sf, key, value);
1326 * Answers true for '.', null, or an empty value, or if the INFO type is
1327 * String. If the INFO type is Integer or Float, answers false if the value is
1328 * not in valid format.
1335 protected boolean isValid(VariantContext variant, String infoId,
1338 if (value == null || value.isEmpty() || NO_VALUE.equals(value))
1342 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(infoId);
1343 if (infoHeader == null)
1345 Console.error("Field " + infoId + " has no INFO header");
1348 VCFHeaderLineType infoType = infoHeader.getType();
1351 if (infoType == VCFHeaderLineType.Integer)
1353 Integer.parseInt(value);
1355 else if (infoType == VCFHeaderLineType.Float)
1357 Float.parseFloat(value);
1359 } catch (NumberFormatException e)
1361 logInvalidValue(variant, infoId, value);
1368 * Logs an error message for malformed data; duplicate messages (same id and
1369 * value) are not logged
1375 private void logInvalidValue(VariantContext variant, String infoId,
1378 if (badData == null)
1380 badData = new HashSet<>();
1382 String token = infoId + ":" + value;
1383 if (!badData.contains(token))
1386 Console.error(String.format("Invalid VCF data at %s:%d %s=%s",
1387 variant.getContig(), variant.getStart(), infoId, value));
1392 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
1395 * If <code>myConsequence</code> is not null, then this is the specific
1396 * consequence data (pipe-delimited fields) that is for the current allele and
1397 * transcript (sequence) being processed)
1401 * @param myConsequence
1403 protected void addConsequences(VariantContext variant, SequenceFeature sf,
1404 String myConsequence)
1406 Object value = variant.getAttribute(CSQ_FIELD);
1408 if (value == null || !(value instanceof List<?>))
1413 List<String> consequences = (List<String>) value;
1416 * inspect CSQ consequences; restrict to the consequence
1417 * associated with the current transcript (Feature)
1419 Map<String, String> csqValues = new HashMap<>();
1421 for (String consequence : consequences)
1423 if (myConsequence == null || myConsequence.equals(consequence))
1425 String[] csqFields = consequence.split(PIPE_REGEX);
1428 * inspect individual fields of this consequence, copying non-null
1429 * values which are 'fields of interest'
1432 for (String field : csqFields)
1434 if (field != null && field.length() > 0)
1436 String id = vepFieldsOfInterest.get(i);
1440 * VCF spec requires encoding of special characters e.g. '='
1441 * so decode them here before storing
1443 field = StringUtils.urlDecode(field, VCF_ENCODABLE);
1444 csqValues.put(id, field);
1452 if (!csqValues.isEmpty())
1454 sf.setValue(CSQ_FIELD, csqValues);
1459 * A convenience method to complement a dna base and return the string value
1465 protected String complement(byte[] reference)
1467 return String.valueOf(Dna.getComplement((char) reference[0]));
1471 * Transfers the sequence feature to the target sequence, locating its start
1472 * and end range based on the mapping. Features which do not overlap the
1473 * target sequence are ignored.
1476 * @param targetSequence
1478 * mapping from the feature's coordinates to the target sequence
1480 protected void transferFeature(SequenceFeature sf,
1481 SequenceI targetSequence, MapList mapping)
1483 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1485 if (mappedRange != null)
1487 String group = sf.getFeatureGroup();
1488 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1489 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1490 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1491 group, sf.getScore());
1492 targetSequence.addSequenceFeature(copy);