1 package jalview.io.vcf;
3 import jalview.analysis.AlignmentUtils;
4 import jalview.analysis.Dna;
5 import jalview.api.AlignViewControllerGuiI;
6 import jalview.bin.Cache;
7 import jalview.datamodel.AlignmentI;
8 import jalview.datamodel.DBRefEntry;
9 import jalview.datamodel.GeneLociI;
10 import jalview.datamodel.Mapping;
11 import jalview.datamodel.SequenceFeature;
12 import jalview.datamodel.SequenceI;
13 import jalview.datamodel.features.FeatureAttributeType;
14 import jalview.datamodel.features.FeatureSource;
15 import jalview.datamodel.features.FeatureSources;
16 import jalview.ext.ensembl.EnsemblMap;
17 import jalview.ext.htsjdk.VCFReader;
18 import jalview.io.gff.Gff3Helper;
19 import jalview.io.gff.SequenceOntologyI;
20 import jalview.util.MapList;
21 import jalview.util.MappingUtils;
22 import jalview.util.MessageManager;
24 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
29 import java.util.Map.Entry;
30 import java.util.regex.Pattern;
31 import java.util.regex.PatternSyntaxException;
33 import htsjdk.samtools.SAMException;
34 import htsjdk.samtools.SAMSequenceDictionary;
35 import htsjdk.samtools.SAMSequenceRecord;
36 import htsjdk.samtools.util.CloseableIterator;
37 import htsjdk.variant.variantcontext.Allele;
38 import htsjdk.variant.variantcontext.VariantContext;
39 import htsjdk.variant.vcf.VCFHeader;
40 import htsjdk.variant.vcf.VCFHeaderLine;
41 import htsjdk.variant.vcf.VCFHeaderLineCount;
42 import htsjdk.variant.vcf.VCFHeaderLineType;
43 import htsjdk.variant.vcf.VCFInfoHeaderLine;
46 * A class to read VCF data (using the htsjdk) and add variants as sequence
47 * features on dna and any related protein product sequences
51 public class VCFLoader
54 * A class to model the mapping from sequence to VCF coordinates. Cases include
56 * <li>a direct 1:1 mapping where the sequence is one of the VCF contigs</li>
57 * <li>a mapping of sequence to chromosomal coordinates, where sequence and VCF
58 * use the same reference assembly</li>
59 * <li>a modified mapping of sequence to chromosomal coordinates, where sequence
60 * and VCF use different reference assembles</li>
65 final String chromosome;
69 VCFMap(String chr, MapList m)
76 public String toString()
78 return chromosome + ":" + map.toString();
83 * Lookup keys, and default values, for Preference entries that describe
84 * patterns for VCF and VEP fields to capture
86 private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
88 private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
90 private static final String DEFAULT_VCF_FIELDS = ".*";
92 private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
95 * keys to fields of VEP CSQ consequence data
96 * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
98 private static final String CSQ_CONSEQUENCE_KEY = "Consequence";
99 private static final String CSQ_ALLELE_KEY = "Allele";
100 private static final String CSQ_ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref), 1...
101 private static final String CSQ_FEATURE_KEY = "Feature"; // Ensembl stable id
104 * default VCF INFO key for VEP consequence data
105 * NB this can be overridden running VEP with --vcf_info_field
106 * - we don't handle this case (require identifier to be CSQ)
108 private static final String CSQ_FIELD = "CSQ";
111 * separator for fields in consequence data is '|'
113 private static final String PIPE_REGEX = "\\|";
116 * key for Allele Frequency output by VEP
117 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
119 private static final String ALLELE_FREQUENCY_KEY = "AF";
122 * delimiter that separates multiple consequence data blocks
124 private static final String COMMA = ",";
127 * the feature group assigned to a VCF variant in Jalview
129 private static final String FEATURE_GROUP_VCF = "VCF";
132 * internal delimiter used to build keys for assemblyMappings
135 private static final String EXCL = "!";
138 * the alignment we are associating VCF data with
140 private AlignmentI al;
143 * mappings between VCF and sequence reference assembly regions, as
144 * key = "species!chromosome!fromAssembly!toAssembly
145 * value = Map{fromRange, toRange}
147 private Map<String, Map<int[], int[]>> assemblyMappings;
150 * holds details of the VCF header lines (metadata)
152 private VCFHeader header;
155 * a Dictionary of contigs (if present) referenced in the VCF file
157 private SAMSequenceDictionary dictionary;
160 * the position (0...) of field in each block of
161 * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
162 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
164 private int csqConsequenceFieldIndex = -1;
165 private int csqAlleleFieldIndex = -1;
166 private int csqAlleleNumberFieldIndex = -1;
167 private int csqFeatureFieldIndex = -1;
169 // todo the same fields for SnpEff ANN data if wanted
170 // see http://snpeff.sourceforge.net/SnpEff_manual.html#input
173 * a unique identifier under which to save metadata about feature
174 * attributes (selected INFO field data)
176 private String sourceId;
179 * The INFO IDs of data that is both present in the VCF file, and
180 * also matched by any filters for data of interest
182 List<String> vcfFieldsOfInterest;
185 * The field offsets and identifiers for VEP (CSQ) data that is both present
186 * in the VCF file, and also matched by any filters for data of interest
187 * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
189 Map<Integer, String> vepFieldsOfInterest;
192 * Constructor given an alignment context
196 public VCFLoader(AlignmentI alignment)
200 // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
201 assemblyMappings = new HashMap<>();
205 * Starts a new thread to query and load VCF variant data on to the alignment
207 * This method is not thread safe - concurrent threads should use separate
208 * instances of this class.
213 public void loadVCF(final String filePath,
214 final AlignViewControllerGuiI gui)
218 gui.setStatus(MessageManager.getString("label.searching_vcf"));
227 VCFLoader.this.doLoad(filePath, gui);
234 * Loads VCF on to an alignment - provided it can be related to one or more
235 * sequence's chromosomal coordinates
239 * optional callback handler for messages
241 protected void doLoad(String filePath, AlignViewControllerGuiI gui)
243 VCFReader reader = null;
246 // long start = System.currentTimeMillis();
247 reader = new VCFReader(filePath);
249 header = reader.getFileHeader();
253 dictionary = header.getSequenceDictionary();
254 } catch (SAMException e)
256 // ignore - thrown if any contig line lacks length info
261 saveMetadata(sourceId);
264 * get offset of CSQ ALLELE_NUM and Feature if declared
268 VCFHeaderLine ref = header
269 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
270 String vcfAssembly = ref.getValue();
276 * query for VCF overlapping each sequence in turn
278 for (SequenceI seq : al.getSequences())
280 int added = loadSequenceVCF(seq, reader, vcfAssembly);
285 transferAddedFeatures(seq);
290 // long elapsed = System.currentTimeMillis() - start;
291 String msg = MessageManager.formatMessage("label.added_vcf",
294 if (gui.getFeatureSettingsUI() != null)
296 gui.getFeatureSettingsUI().discoverAllFeatureData();
299 } catch (Throwable e)
301 System.err.println("Error processing VCF: " + e.getMessage());
305 gui.setStatus("Error occurred - see console for details");
314 } catch (IOException e)
325 * Reads metadata (such as INFO field descriptions and datatypes) and saves
326 * them for future reference
330 void saveMetadata(String theSourceId)
332 List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
334 vcfFieldsOfInterest = new ArrayList<>();
336 FeatureSource metadata = new FeatureSource(theSourceId);
338 for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
340 String attributeId = info.getID();
341 String desc = info.getDescription();
342 VCFHeaderLineType type = info.getType();
343 FeatureAttributeType attType = null;
347 attType = FeatureAttributeType.Character;
350 attType = FeatureAttributeType.Flag;
353 attType = FeatureAttributeType.Float;
356 attType = FeatureAttributeType.Integer;
359 attType = FeatureAttributeType.String;
362 metadata.setAttributeName(attributeId, desc);
363 metadata.setAttributeType(attributeId, attType);
365 if (isFieldWanted(attributeId, vcfFieldPatterns))
367 vcfFieldsOfInterest.add(attributeId);
371 FeatureSources.getInstance().addSource(theSourceId, metadata);
375 * Answers true if the field id is matched by any of the filter patterns, else
376 * false. Matching is against regular expression patterns, and is not
383 private boolean isFieldWanted(String id, List<Pattern> filters)
385 for (Pattern p : filters)
387 if (p.matcher(id.toUpperCase()).matches())
396 * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
397 * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
398 * required for processing.
400 * CSQ fields are declared in the CSQ INFO Description e.g.
402 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
404 protected void parseCsqHeader()
406 List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
408 vepFieldsOfInterest = new HashMap<>();
410 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
417 * parse out the pipe-separated list of CSQ fields; we assume here that
418 * these form the last part of the description, and contain no spaces
420 String desc = csqInfo.getDescription();
421 int spacePos = desc.lastIndexOf(" ");
422 desc = desc.substring(spacePos + 1);
426 String[] format = desc.split(PIPE_REGEX);
428 for (String field : format)
430 if (CSQ_CONSEQUENCE_KEY.equals(field))
432 csqConsequenceFieldIndex = index;
434 if (CSQ_ALLELE_NUM_KEY.equals(field))
436 csqAlleleNumberFieldIndex = index;
438 if (CSQ_ALLELE_KEY.equals(field))
440 csqAlleleFieldIndex = index;
442 if (CSQ_FEATURE_KEY.equals(field))
444 csqFeatureFieldIndex = index;
447 if (isFieldWanted(field, vepFieldFilters))
449 vepFieldsOfInterest.put(index, field);
458 * Reads the Preference value for the given key, with default specified if no
459 * preference set. The value is interpreted as a comma-separated list of
460 * regular expressions, and converted into a list of compiled patterns ready
461 * for matching. Patterns are forced to upper-case for non-case-sensitive
464 * This supports user-defined filters for fields of interest to capture while
465 * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
466 * fields with an ID of AF, or starting with AC, would be matched.
472 private List<Pattern> getFieldMatchers(String key, String def)
474 String pref = Cache.getDefault(key, def);
475 List<Pattern> patterns = new ArrayList<>();
476 String[] tokens = pref.split(",");
477 for (String token : tokens)
481 patterns.add(Pattern.compile(token.toUpperCase()));
482 } catch (PatternSyntaxException e)
484 System.err.println("Invalid pattern ignored: " + token);
491 * Transfers VCF features to sequences to which this sequence has a mapping.
492 * If the mapping is 3:1, computes peptide variants from nucleotide variants.
496 protected void transferAddedFeatures(SequenceI seq)
498 DBRefEntry[] dbrefs = seq.getDBRefs();
503 for (DBRefEntry dbref : dbrefs)
505 Mapping mapping = dbref.getMap();
506 if (mapping == null || mapping.getTo() == null)
511 SequenceI mapTo = mapping.getTo();
512 MapList map = mapping.getMap();
513 if (map.getFromRatio() == 3)
516 * dna-to-peptide product mapping
518 AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
523 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
525 List<SequenceFeature> features = seq.getFeatures()
526 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
527 for (SequenceFeature sf : features)
529 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
531 transferFeature(sf, mapTo, map);
539 * Tries to add overlapping variants read from a VCF file to the given
540 * sequence, and returns the number of variant features added. Note that this
541 * requires the sequence to hold information as to its species, chromosomal
542 * positions and reference assembly, in order to be able to map the VCF
543 * variants to the sequence (or not)
550 protected int loadSequenceVCF(SequenceI seq, VCFReader reader,
553 VCFMap vcfMap = getVcfMap(seq, vcfAssembly);
559 return addVcfVariants(seq, reader, vcfMap, vcfAssembly);
563 * Answers a map from sequence coordinates to VCF chromosome ranges
569 private VCFMap getVcfMap(SequenceI seq, String vcfAssembly)
572 * simplest case: sequence has id and length matching a VCF contig
574 VCFMap vcfMap = null;
575 if (dictionary != null)
577 vcfMap = getContigMap(seq);
585 * otherwise, map to VCF from chromosomal coordinates
586 * of the sequence (if known)
588 GeneLociI seqCoords = seq.getGeneLoci();
589 if (seqCoords == null)
591 Cache.log.warn(String.format(
592 "Can't query VCF for %s as chromosome coordinates not known",
597 String species = seqCoords.getSpeciesId();
598 String chromosome = seqCoords.getChromosomeId();
599 String seqRef = seqCoords.getAssemblyId();
600 MapList map = seqCoords.getMap();
602 if (!vcfSpeciesMatchesSequence(vcfAssembly, species))
607 if (vcfAssemblyMatchesSequence(vcfAssembly, seqRef))
609 return new VCFMap(chromosome, map);
612 if (!"GRCh38".equalsIgnoreCase(seqRef) // Ensembl
613 || !vcfAssembly.contains("Homo_sapiens_assembly19")) // gnomAD
619 * map chromosomal coordinates from sequence to VCF if the VCF
620 * data has a different reference assembly to the sequence
622 // TODO generalise for cases other than GRCh38 -> GRCh37 !
623 // - or get the user to choose in a dialog
625 List<int[]> toVcfRanges = new ArrayList<>();
626 List<int[]> fromSequenceRanges = new ArrayList<>();
627 String toRef = "GRCh37";
629 for (int[] range : map.getToRanges())
631 int[] fromRange = map.locateInFrom(range[0], range[1]);
632 if (fromRange == null)
638 int[] newRange = mapReferenceRange(range, chromosome, "human", seqRef,
640 if (newRange == null)
643 String.format("Failed to map %s:%s:%s:%d:%d to %s", species,
644 chromosome, seqRef, range[0], range[1], toRef));
649 toVcfRanges.add(newRange);
650 fromSequenceRanges.add(fromRange);
654 return new VCFMap(chromosome,
655 new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
659 * If the sequence id matches a contig declared in the VCF file, and the
660 * sequence length matches the contig length, then returns a 1:1 map of the
661 * sequence to the contig, else returns null
666 private VCFMap getContigMap(SequenceI seq)
668 String id = seq.getName();
669 SAMSequenceRecord contig = dictionary.getSequence(id);
672 int len = seq.getLength();
673 if (len == contig.getSequenceLength())
675 MapList map = new MapList(new int[] { 1, len },
678 return new VCFMap(id, map);
685 * Answers true if we determine that the VCF data uses the same reference
686 * assembly as the sequence, else false
692 private boolean vcfAssemblyMatchesSequence(String vcfAssembly,
695 // TODO improve on this stub, which handles gnomAD and
696 // hopes for the best for other cases
698 if ("GRCh38".equalsIgnoreCase(seqRef) // Ensembl
699 && vcfAssembly.contains("Homo_sapiens_assembly19")) // gnomAD
707 * Answers true if the species inferred from the VCF reference identifier
708 * matches that for the sequence
714 boolean vcfSpeciesMatchesSequence(String vcfAssembly, String speciesId)
717 // there are many aliases for species - how to equate one with another?
719 // VCF ##reference header is an unstructured URI - how to extract species?
720 // perhaps check if ref includes any (Ensembl) alias of speciesId??
721 // TODO ask the user to confirm this??
723 if (vcfAssembly.contains("Homo_sapiens") // gnomAD exome data example
724 && "HOMO_SAPIENS".equals(speciesId)) // Ensembl species id
729 if (vcfAssembly.contains("c_elegans") // VEP VCF response example
730 && "CAENORHABDITIS_ELEGANS".equals(speciesId)) // Ensembl
735 // this is not a sustainable solution...
741 * Queries the VCF reader for any variants that overlap the mapped chromosome
742 * ranges of the sequence, and adds as variant features. Returns the number of
743 * overlapping variants found.
748 * mapping from sequence to VCF coordinates
750 * the '##reference' identifier for the VCF reference assembly
753 protected int addVcfVariants(SequenceI seq, VCFReader reader,
754 VCFMap map, String vcfAssembly)
756 boolean forwardStrand = map.map.isToForwardStrand();
759 * query the VCF for overlaps of each contiguous chromosomal region
763 for (int[] range : map.map.getToRanges())
765 int vcfStart = Math.min(range[0], range[1]);
766 int vcfEnd = Math.max(range[0], range[1]);
767 CloseableIterator<VariantContext> variants = reader
768 .query(map.chromosome, vcfStart, vcfEnd);
769 while (variants.hasNext())
771 VariantContext variant = variants.next();
773 int[] featureRange = map.map.locateInFrom(variant.getStart(),
776 if (featureRange != null)
778 int featureStart = Math.min(featureRange[0], featureRange[1]);
779 int featureEnd = Math.max(featureRange[0], featureRange[1]);
780 count += addAlleleFeatures(seq, variant, featureStart, featureEnd,
791 * A convenience method to get the AF value for the given alternate allele
798 protected float getAlleleFrequency(VariantContext variant, int alleleIndex)
801 String attributeValue = getAttributeValue(variant,
802 ALLELE_FREQUENCY_KEY, alleleIndex);
803 if (attributeValue != null)
807 score = Float.parseFloat(attributeValue);
808 } catch (NumberFormatException e)
818 * A convenience method to get an attribute value for an alternate allele
821 * @param attributeName
825 protected String getAttributeValue(VariantContext variant,
826 String attributeName, int alleleIndex)
828 Object att = variant.getAttribute(attributeName);
830 if (att instanceof String)
834 else if (att instanceof ArrayList)
836 return ((List<String>) att).get(alleleIndex);
843 * Adds one variant feature for each allele in the VCF variant record, and
844 * returns the number of features added.
848 * @param featureStart
850 * @param forwardStrand
853 protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
854 int featureStart, int featureEnd, boolean forwardStrand)
859 * Javadoc says getAlternateAlleles() imposes no order on the list returned
860 * so we proceed defensively to get them in strict order
862 int altAlleleCount = variant.getAlternateAlleles().size();
863 for (int i = 0; i < altAlleleCount; i++)
865 added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
872 * Inspects one allele and attempts to add a variant feature for it to the
873 * sequence. The additional data associated with this allele is extracted to
874 * store in the feature's key-value map. Answers the number of features added (0
879 * @param altAlleleIndex
881 * @param featureStart
883 * @param forwardStrand
886 protected int addAlleleFeature(SequenceI seq, VariantContext variant,
887 int altAlleleIndex, int featureStart, int featureEnd,
888 boolean forwardStrand)
890 String reference = variant.getReference().getBaseString();
891 Allele alt = variant.getAlternateAllele(altAlleleIndex);
892 String allele = alt.getBaseString();
895 * build the ref,alt allele description e.g. "G,A", using the base
896 * complement if the sequence is on the reverse strand
898 // FIXME correctly handle insertions on reverse strand JAL-2845
899 StringBuilder sb = new StringBuilder();
900 sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
902 sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
903 String alleles = sb.toString(); // e.g. G,A
906 * pick out the consequence data (if any) that is for the current allele
907 * and feature (transcript) that matches the current sequence
909 String consequence = getConsequenceForAlleleAndFeature(variant, CSQ_FIELD,
910 altAlleleIndex, csqAlleleFieldIndex,
911 csqAlleleNumberFieldIndex, seq.getName().toLowerCase(),
912 csqFeatureFieldIndex);
915 * pick out the ontology term for the consequence type
917 String type = SequenceOntologyI.SEQUENCE_VARIANT;
918 if (consequence != null)
920 type = getOntologyTerm(seq, variant, altAlleleIndex,
924 float score = getAlleleFrequency(variant, altAlleleIndex);
926 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
927 featureEnd, score, FEATURE_GROUP_VCF);
928 sf.setSource(sourceId);
930 sf.setValue(Gff3Helper.ALLELES, alleles);
932 addAlleleProperties(variant, seq, sf, altAlleleIndex, consequence);
934 seq.addSequenceFeature(sf);
940 * Determines the Sequence Ontology term to use for the variant feature type in
941 * Jalview. The default is 'sequence_variant', but a more specific term is used
944 * <li>VEP (or SnpEff) Consequence annotation is included in the VCF</li>
945 * <li>sequence id can be matched to VEP Feature (or SnpEff Feature_ID)</li>
950 * @param altAlleleIndex
953 * @see http://www.sequenceontology.org/browser/current_svn/term/SO:0001060
955 String getOntologyTerm(SequenceI seq, VariantContext variant,
956 int altAlleleIndex, String consequence)
958 String type = SequenceOntologyI.SEQUENCE_VARIANT;
960 if (csqAlleleFieldIndex == -1) // && snpEffAlleleFieldIndex == -1
963 * no Consequence data so we can't refine the ontology term
969 * can we associate Consequence data with this allele and feature (transcript)?
970 * if so, prefer the consequence term from that data
972 if (consequence != null)
974 String[] csqFields = consequence.split(PIPE_REGEX);
975 if (csqFields.length > csqConsequenceFieldIndex)
977 type = csqFields[csqConsequenceFieldIndex];
982 // todo the same for SnpEff consequence data matching if wanted
986 * if of the form (e.g.) missense_variant&splice_region_variant,
987 * just take the first ('most severe') consequence
991 int pos = type.indexOf('&');
994 type = type.substring(0, pos);
1001 * Returns matched consequence data if it can be found, else null.
1003 * <li>inspects the VCF data for key 'vcfInfoId'</li>
1004 * <li>splits this on comma (to distinct consequences)</li>
1005 * <li>returns the first consequence (if any) where</li>
1007 * <li>the allele matches the altAlleleIndex'th allele of variant</li>
1008 * <li>the feature matches the sequence name (e.g. transcript id)</li>
1011 * If matched, the consequence is returned (as pipe-delimited fields).
1015 * @param altAlleleIndex
1016 * @param alleleFieldIndex
1017 * @param alleleNumberFieldIndex
1019 * @param featureFieldIndex
1022 private String getConsequenceForAlleleAndFeature(VariantContext variant,
1023 String vcfInfoId, int altAlleleIndex, int alleleFieldIndex,
1024 int alleleNumberFieldIndex,
1025 String seqName, int featureFieldIndex)
1027 if (alleleFieldIndex == -1 || featureFieldIndex == -1)
1031 Object value = variant.getAttribute(vcfInfoId);
1033 if (value == null || !(value instanceof List<?>))
1039 * inspect each consequence in turn (comma-separated blocks
1040 * extracted by htsjdk)
1042 List<String> consequences = (List<String>) value;
1044 for (String consequence : consequences)
1046 String[] csqFields = consequence.split(PIPE_REGEX);
1047 if (csqFields.length > featureFieldIndex)
1049 String featureIdentifier = csqFields[featureFieldIndex];
1050 if (featureIdentifier.length() > 4
1051 && seqName.indexOf(featureIdentifier.toLowerCase()) > -1)
1054 * feature (transcript) matched - now check for allele match
1056 if (matchAllele(variant, altAlleleIndex, csqFields,
1057 alleleFieldIndex, alleleNumberFieldIndex))
1067 private boolean matchAllele(VariantContext variant, int altAlleleIndex,
1068 String[] csqFields, int alleleFieldIndex,
1069 int alleleNumberFieldIndex)
1072 * if ALLELE_NUM is present, it must match altAlleleIndex
1073 * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1075 if (alleleNumberFieldIndex > -1)
1077 if (csqFields.length <= alleleNumberFieldIndex)
1081 String alleleNum = csqFields[alleleNumberFieldIndex];
1082 return String.valueOf(altAlleleIndex + 1).equals(alleleNum);
1086 * else consequence allele must match variant allele
1088 if (alleleFieldIndex > -1 && csqFields.length > alleleFieldIndex)
1090 String csqAllele = csqFields[alleleFieldIndex];
1091 String vcfAllele = variant.getAlternateAllele(altAlleleIndex)
1093 return csqAllele.equals(vcfAllele);
1099 * Add any allele-specific VCF key-value data to the sequence feature
1104 * @param altAlelleIndex
1106 * @param consequence
1107 * if not null, the consequence specific to this sequence (transcript
1108 * feature) and allele
1110 protected void addAlleleProperties(VariantContext variant, SequenceI seq,
1111 SequenceFeature sf, final int altAlelleIndex, String consequence)
1113 Map<String, Object> atts = variant.getAttributes();
1115 for (Entry<String, Object> att : atts.entrySet())
1117 String key = att.getKey();
1120 * extract Consequence data (if present) that we are able to
1121 * associated with the allele for this variant feature
1123 if (CSQ_FIELD.equals(key))
1125 addConsequences(variant, seq, sf, consequence);
1130 * filter out fields we don't want to capture
1132 if (!vcfFieldsOfInterest.contains(key))
1138 * we extract values for other data which are allele-specific;
1139 * these may be per alternate allele (INFO[key].Number = 'A')
1140 * or per allele including reference (INFO[key].Number = 'R')
1142 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
1143 if (infoHeader == null)
1146 * can't be sure what data belongs to this allele, so
1147 * play safe and don't take any
1152 VCFHeaderLineCount number = infoHeader.getCountType();
1153 int index = altAlelleIndex;
1154 if (number == VCFHeaderLineCount.R)
1157 * one value per allele including reference, so bump index
1158 * e.g. the 3rd value is for the 2nd alternate allele
1162 else if (number != VCFHeaderLineCount.A)
1165 * don't save other values as not allele-related
1171 * take the index'th value
1173 String value = getAttributeValue(variant, key, index);
1176 sf.setValue(key, value);
1182 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
1185 * If <code>myConsequence</code> is not null, then this is the specific
1186 * consequence data (pipe-delimited fields) that is for the current allele and
1187 * transcript (sequence) being processed)
1192 * @param myConsequence
1194 protected void addConsequences(VariantContext variant, SequenceI seq,
1195 SequenceFeature sf, String myConsequence)
1197 Object value = variant.getAttribute(CSQ_FIELD);
1198 // TODO if CSQ not present, try ANN (for SnpEff consequence data)?
1200 if (value == null || !(value instanceof List<?>))
1205 List<String> consequences = (List<String>) value;
1208 * inspect CSQ consequences; restrict to the consequence
1209 * associated with the current transcript (Feature)
1211 Map<String, String> csqValues = new HashMap<>();
1213 for (String consequence : consequences)
1215 if (myConsequence == null || myConsequence.equals(consequence))
1217 String[] csqFields = consequence.split(PIPE_REGEX);
1220 * inspect individual fields of this consequence, copying non-null
1221 * values which are 'fields of interest'
1224 for (String field : csqFields)
1226 if (field != null && field.length() > 0)
1228 String id = vepFieldsOfInterest.get(i);
1231 csqValues.put(id, field);
1239 if (!csqValues.isEmpty())
1241 sf.setValue(CSQ_FIELD, csqValues);
1246 * A convenience method to complement a dna base and return the string value
1252 protected String complement(byte[] reference)
1254 return String.valueOf(Dna.getComplement((char) reference[0]));
1258 * Determines the location of the query range (chromosome positions) in a
1259 * different reference assembly.
1261 * If the range is just a subregion of one for which we already have a mapping
1262 * (for example, an exon sub-region of a gene), then the mapping is just
1263 * computed arithmetically.
1265 * Otherwise, calls the Ensembl REST service that maps from one assembly
1266 * reference's coordinates to another's
1269 * start-end chromosomal range in 'fromRef' coordinates
1273 * assembly reference for the query coordinates
1275 * assembly reference we wish to translate to
1276 * @return the start-end range in 'toRef' coordinates
1278 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
1279 String species, String fromRef, String toRef)
1282 * first try shorcut of computing the mapping as a subregion of one
1283 * we already have (e.g. for an exon, if we have the gene mapping)
1285 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
1286 species, fromRef, toRef);
1287 if (mappedRange != null)
1293 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
1295 EnsemblMap mapper = new EnsemblMap();
1296 int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
1299 if (mapping == null)
1301 // mapping service failure
1306 * save mapping for possible future re-use
1308 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1309 if (!assemblyMappings.containsKey(key))
1311 assemblyMappings.put(key, new HashMap<int[], int[]>());
1314 assemblyMappings.get(key).put(queryRange, mapping);
1320 * If we already have a 1:1 contiguous mapping which subsumes the given query
1321 * range, this method just calculates and returns the subset of that mapping,
1322 * else it returns null. In practical terms, if a gene has a contiguous
1323 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
1324 * subsidiary exons occupy unchanged relative positions, and just compute
1325 * these as offsets, rather than do another lookup of the mapping.
1327 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
1328 * simply remove this method or let it always return null.
1330 * Warning: many rapid calls to the /map service map result in a 429 overload
1340 protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
1341 String species, String fromRef, String toRef)
1343 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1344 if (assemblyMappings.containsKey(key))
1346 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
1347 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
1349 int[] fromRange = mappedRange.getKey();
1350 int[] toRange = mappedRange.getValue();
1351 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
1354 * mapping is 1:1 in length, so we trust it to have no discontinuities
1356 if (MappingUtils.rangeContains(fromRange, queryRange))
1359 * fromRange subsumes our query range
1361 int offset = queryRange[0] - fromRange[0];
1362 int mappedRangeFrom = toRange[0] + offset;
1363 int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
1364 return new int[] { mappedRangeFrom, mappedRangeTo };
1373 * Transfers the sequence feature to the target sequence, locating its start
1374 * and end range based on the mapping. Features which do not overlap the
1375 * target sequence are ignored.
1378 * @param targetSequence
1380 * mapping from the feature's coordinates to the target sequence
1382 protected void transferFeature(SequenceFeature sf,
1383 SequenceI targetSequence, MapList mapping)
1385 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1387 if (mappedRange != null)
1389 String group = sf.getFeatureGroup();
1390 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1391 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1392 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1393 group, sf.getScore());
1394 targetSequence.addSequenceFeature(copy);
1399 * Formats a ranges map lookup key
1407 protected static String makeRangesKey(String chromosome, String species,
1408 String fromRef, String toRef)
1410 return species + EXCL + chromosome + EXCL + fromRef + EXCL