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.SortedMap;
31 import java.util.TreeMap;
32 import java.util.regex.Pattern;
33 import java.util.regex.PatternSyntaxException;
35 import htsjdk.samtools.SAMException;
36 import htsjdk.samtools.SAMSequenceDictionary;
37 import htsjdk.samtools.SAMSequenceRecord;
38 import htsjdk.samtools.util.CloseableIterator;
39 import htsjdk.variant.variantcontext.Allele;
40 import htsjdk.variant.variantcontext.VariantContext;
41 import htsjdk.variant.vcf.VCFHeader;
42 import htsjdk.variant.vcf.VCFHeaderLine;
43 import htsjdk.variant.vcf.VCFHeaderLineCount;
44 import htsjdk.variant.vcf.VCFHeaderLineType;
45 import htsjdk.variant.vcf.VCFInfoHeaderLine;
48 * A class to read VCF data (using the htsjdk) and add variants as sequence
49 * features on dna and any related protein product sequences
53 public class VCFLoader
56 * A class to model the mapping from sequence to VCF coordinates. Cases include
58 * <li>a direct 1:1 mapping where the sequence is one of the VCF contigs</li>
59 * <li>a mapping of sequence to chromosomal coordinates, where sequence and VCF
60 * use the same reference assembly</li>
61 * <li>a modified mapping of sequence to chromosomal coordinates, where sequence
62 * and VCF use different reference assembles</li>
67 final String chromosome;
71 VCFMap(String chr, MapList m)
79 * Lookup keys, and default values, for Preference entries that describe
80 * patterns for VCF and VEP fields to capture
82 private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
84 private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
86 private static final String DEFAULT_VCF_FIELDS = ".*";
88 private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
91 * keys to fields of VEP CSQ consequence data
92 * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
94 private static final String ALLELE_KEY = "Allele";
96 private static final String ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref), 1...
97 private static final String FEATURE_KEY = "Feature"; // Ensembl stable id
100 * default VCF INFO key for VEP consequence data
101 * NB this can be overridden running VEP with --vcf_info_field
102 * - we don't handle this case (require identifier to be CSQ)
104 private static final String CSQ_FIELD = "CSQ";
107 * separator for fields in consequence data is '|'
109 private static final String PIPE_REGEX = "\\|";
112 * key for Allele Frequency output by VEP
113 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
115 private static final String ALLELE_FREQUENCY_KEY = "AF";
118 * delimiter that separates multiple consequence data blocks
120 private static final String COMMA = ",";
123 * the feature group assigned to a VCF variant in Jalview
125 private static final String FEATURE_GROUP_VCF = "VCF";
128 * internal delimiter used to build keys for assemblyMappings
131 private static final String EXCL = "!";
134 * the alignment we are associating VCF data with
136 private AlignmentI al;
139 * mappings between VCF and sequence reference assembly regions, as
140 * key = "species!chromosome!fromAssembly!toAssembly
141 * value = Map{fromRange, toRange}
143 private Map<String, Map<int[], int[]>> assemblyMappings;
146 * holds details of the VCF header lines (metadata)
148 private VCFHeader header;
151 * a Dictionary of contigs (if present) referenced in the VCF file
153 private SAMSequenceDictionary dictionary;
156 * the position (0...) of field in each block of
157 * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
158 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
160 private int csqAlleleFieldIndex = -1;
161 private int csqAlleleNumberFieldIndex = -1;
162 private int csqFeatureFieldIndex = -1;
165 * a unique identifier under which to save metadata about feature
166 * attributes (selected INFO field data)
168 private String sourceId;
171 * The INFO IDs of data that is both present in the VCF file, and
172 * also matched by any filters for data of interest
174 List<String> vcfFieldsOfInterest;
177 * The field offsets and identifiers for VEP (CSQ) data that is both present
178 * in the VCF file, and also matched by any filters for data of interest
179 * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
181 Map<Integer, String> vepFieldsOfInterest;
184 * Constructor given an alignment context
188 public VCFLoader(AlignmentI alignment)
192 // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
193 assemblyMappings = new HashMap<>();
197 * Starts a new thread to query and load VCF variant data on to the alignment
199 * This method is not thread safe - concurrent threads should use separate
200 * instances of this class.
205 public void loadVCF(final String filePath,
206 final AlignViewControllerGuiI gui)
210 gui.setStatus(MessageManager.getString("label.searching_vcf"));
219 VCFLoader.this.doLoad(filePath, gui);
226 * Loads VCF on to an alignment - provided it can be related to one or more
227 * sequence's chromosomal coordinates
231 * optional callback handler for messages
233 protected void doLoad(String filePath, AlignViewControllerGuiI gui)
235 VCFReader reader = null;
238 // long start = System.currentTimeMillis();
239 reader = new VCFReader(filePath);
241 header = reader.getFileHeader();
245 dictionary = header.getSequenceDictionary();
246 } catch (SAMException e)
248 // ignore - thrown if any contig line lacks length info
253 saveMetadata(sourceId);
256 * get offset of CSQ ALLELE_NUM and Feature if declared
260 VCFHeaderLine ref = header
261 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
262 String vcfAssembly = ref.getValue();
268 * query for VCF overlapping each sequence in turn
270 for (SequenceI seq : al.getSequences())
272 int added = loadSequenceVCF(seq, reader, vcfAssembly);
277 transferAddedFeatures(seq);
282 // long elapsed = System.currentTimeMillis() - start;
283 String msg = MessageManager.formatMessage("label.added_vcf",
286 if (gui.getFeatureSettingsUI() != null)
288 gui.getFeatureSettingsUI().discoverAllFeatureData();
291 } catch (Throwable e)
293 System.err.println("Error processing VCF: " + e.getMessage());
297 gui.setStatus("Error occurred - see console for details");
306 } catch (IOException e)
317 * Reads metadata (such as INFO field descriptions and datatypes) and saves
318 * them for future reference
322 void saveMetadata(String theSourceId)
324 List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
326 vcfFieldsOfInterest = new ArrayList<>();
328 FeatureSource metadata = new FeatureSource(theSourceId);
330 for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
332 String attributeId = info.getID();
333 String desc = info.getDescription();
334 VCFHeaderLineType type = info.getType();
335 FeatureAttributeType attType = null;
339 attType = FeatureAttributeType.Character;
342 attType = FeatureAttributeType.Flag;
345 attType = FeatureAttributeType.Float;
348 attType = FeatureAttributeType.Integer;
351 attType = FeatureAttributeType.String;
354 metadata.setAttributeName(attributeId, desc);
355 metadata.setAttributeType(attributeId, attType);
357 if (isFieldWanted(attributeId, vcfFieldPatterns))
359 vcfFieldsOfInterest.add(attributeId);
363 FeatureSources.getInstance().addSource(theSourceId, metadata);
367 * Answers true if the field id is matched by any of the filter patterns, else
368 * false. Matching is against regular expression patterns, and is not
375 private boolean isFieldWanted(String id, List<Pattern> filters)
377 for (Pattern p : filters)
379 if (p.matcher(id.toUpperCase()).matches())
388 * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
389 * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
390 * required for processing.
392 * CSQ fields are declared in the CSQ INFO Description e.g.
394 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
396 protected void parseCsqHeader()
398 List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
400 vepFieldsOfInterest = new HashMap<>();
402 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
409 * parse out the pipe-separated list of CSQ fields; we assume here that
410 * these form the last part of the description, and contain no spaces
412 String desc = csqInfo.getDescription();
413 int spacePos = desc.lastIndexOf(" ");
414 desc = desc.substring(spacePos + 1);
418 String[] format = desc.split(PIPE_REGEX);
420 for (String field : format)
422 if (ALLELE_NUM_KEY.equals(field))
424 csqAlleleNumberFieldIndex = index;
426 if (ALLELE_KEY.equals(field))
428 csqAlleleFieldIndex = index;
430 if (FEATURE_KEY.equals(field))
432 csqFeatureFieldIndex = index;
435 if (isFieldWanted(field, vepFieldFilters))
437 vepFieldsOfInterest.put(index, field);
446 * Reads the Preference value for the given key, with default specified if no
447 * preference set. The value is interpreted as a comma-separated list of
448 * regular expressions, and converted into a list of compiled patterns ready
449 * for matching. Patterns are forced to upper-case for non-case-sensitive
452 * This supports user-defined filters for fields of interest to capture while
453 * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
454 * fields with an ID of AF, or starting with AC, would be matched.
460 private List<Pattern> getFieldMatchers(String key, String def)
462 String pref = Cache.getDefault(key, def);
463 List<Pattern> patterns = new ArrayList<>();
464 String[] tokens = pref.split(",");
465 for (String token : tokens)
469 patterns.add(Pattern.compile(token.toUpperCase()));
470 } catch (PatternSyntaxException e)
472 System.err.println("Invalid pattern ignored: " + token);
479 * Transfers VCF features to sequences to which this sequence has a mapping.
480 * If the mapping is 3:1, computes peptide variants from nucleotide variants.
484 protected void transferAddedFeatures(SequenceI seq)
486 DBRefEntry[] dbrefs = seq.getDBRefs();
491 for (DBRefEntry dbref : dbrefs)
493 Mapping mapping = dbref.getMap();
494 if (mapping == null || mapping.getTo() == null)
499 SequenceI mapTo = mapping.getTo();
500 MapList map = mapping.getMap();
501 if (map.getFromRatio() == 3)
504 * dna-to-peptide product mapping
506 AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
511 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
513 List<SequenceFeature> features = seq.getFeatures()
514 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
515 for (SequenceFeature sf : features)
517 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
519 transferFeature(sf, mapTo, map);
527 * Tries to add overlapping variants read from a VCF file to the given
528 * sequence, and returns the number of variant features added. Note that this
529 * requires the sequence to hold information as to its species, chromosomal
530 * positions and reference assembly, in order to be able to map the VCF
531 * variants to the sequence (or not)
538 protected int loadSequenceVCF(SequenceI seq, VCFReader reader,
541 VCFMap vcfMap = getVcfMap(seq, vcfAssembly);
547 return addVcfVariants(seq, reader, vcfMap, vcfAssembly);
551 * Answers a map from sequence coordinates to VCF chromosome ranges
557 private VCFMap getVcfMap(SequenceI seq, String vcfAssembly)
560 * simplest case: sequence has id and length matching a VCF contig
562 VCFMap vcfMap = null;
563 if (dictionary != null)
565 vcfMap = getContigMap(seq);
573 * otherwise, map to VCF from chromosomal coordinates
574 * of the sequence (if known)
576 GeneLociI seqCoords = seq.getGeneLoci();
577 if (seqCoords == null)
579 Cache.log.warn(String.format(
580 "Can't query VCF for %s as chromosome coordinates not known",
585 String species = seqCoords.getSpeciesId();
586 String chromosome = seqCoords.getChromosomeId();
587 String seqRef = seqCoords.getAssemblyId();
588 MapList map = seqCoords.getMap();
590 if (!vcfSpeciesMatchesSequence(vcfAssembly, species))
595 if (vcfAssemblyMatchesSequence(vcfAssembly, seqRef))
597 return new VCFMap(chromosome, map);
600 if (!"GRCh38".equalsIgnoreCase(seqRef) // Ensembl
601 || !vcfAssembly.contains("Homo_sapiens_assembly19")) // gnomAD
607 * map chromosomal coordinates from sequence to VCF if the VCF
608 * data has a different reference assembly to the sequence
610 // TODO generalise for cases other than GRCh38 -> GRCh37 !
611 // - or get the user to choose in a dialog
613 List<int[]> toVcfRanges = new ArrayList<>();
614 List<int[]> fromSequenceRanges = new ArrayList<>();
615 String toRef = "GRCh37";
617 for (int[] range : map.getToRanges())
619 int[] fromRange = map.locateInFrom(range[0], range[1]);
620 if (fromRange == null)
626 int[] newRange = mapReferenceRange(range, chromosome, "human", seqRef,
628 if (newRange == null)
631 String.format("Failed to map %s:%s:%s:%d:%d to %s", species,
632 chromosome, seqRef, range[0], range[1], toRef));
637 toVcfRanges.add(newRange);
638 fromSequenceRanges.add(fromRange);
642 return new VCFMap(chromosome,
643 new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
647 * If the sequence id matches a contig declared in the VCF file, and the
648 * sequence length matches the contig length, then returns a 1:1 map of the
649 * sequence to the contig, else returns null
654 private VCFMap getContigMap(SequenceI seq)
656 String id = seq.getName();
657 SAMSequenceRecord contig = dictionary.getSequence(id);
660 int len = seq.getLength();
661 if (len == contig.getSequenceLength())
663 MapList map = new MapList(new int[] { 1, len },
666 return new VCFMap(id, map);
673 * Answers true if we determine that the VCF data uses the same reference
674 * assembly as the sequence, else false
680 private boolean vcfAssemblyMatchesSequence(String vcfAssembly,
683 // TODO improve on this stub, which handles gnomAD and
684 // hopes for the best for other cases
686 if ("GRCh38".equalsIgnoreCase(seqRef) // Ensembl
687 && vcfAssembly.contains("Homo_sapiens_assembly19")) // gnomAD
695 * Answers true if the species inferred from the VCF reference identifier
696 * matches that for the sequence
702 boolean vcfSpeciesMatchesSequence(String vcfAssembly, String speciesId)
705 // there are many aliases for species - how to equate one with another?
707 // VCF ##reference header is an unstructured URI - how to extract species?
708 // perhaps check if ref includes any (Ensembl) alias of speciesId??
709 // TODO ask the user to confirm this??
711 if (vcfAssembly.contains("Homo_sapiens") // gnomAD exome data example
712 && "HOMO_SAPIENS".equals(speciesId)) // Ensembl species id
717 if (vcfAssembly.contains("c_elegans") // VEP VCF response example
718 && "CAENORHABDITIS_ELEGANS".equals(speciesId)) // Ensembl
723 // this is not a sustainable solution...
729 * Queries the VCF reader for any variants that overlap the mapped chromosome
730 * ranges of the sequence, and adds as variant features. Returns the number of
731 * overlapping variants found.
736 * mapping from sequence to VCF coordinates
738 * the '##reference' identifier for the VCF reference assembly
741 protected int addVcfVariants(SequenceI seq, VCFReader reader,
742 VCFMap map, String vcfAssembly)
744 boolean forwardStrand = map.map.isToForwardStrand();
747 * query the VCF for overlaps of each contiguous chromosomal region
751 for (int[] range : map.map.getToRanges())
753 int vcfStart = Math.min(range[0], range[1]);
754 int vcfEnd = Math.max(range[0], range[1]);
755 CloseableIterator<VariantContext> variants = reader
756 .query(map.chromosome, vcfStart, vcfEnd);
757 while (variants.hasNext())
759 VariantContext variant = variants.next();
761 int[] featureRange = map.map.locateInFrom(variant.getStart(),
764 if (featureRange != null)
766 int featureStart = Math.min(featureRange[0], featureRange[1]);
767 int featureEnd = Math.max(featureRange[0], featureRange[1]);
768 count += addAlleleFeatures(seq, variant, featureStart, featureEnd,
779 * A convenience method to get the AF value for the given alternate allele
786 protected float getAlleleFrequency(VariantContext variant, int alleleIndex)
789 String attributeValue = getAttributeValue(variant,
790 ALLELE_FREQUENCY_KEY, alleleIndex);
791 if (attributeValue != null)
795 score = Float.parseFloat(attributeValue);
796 } catch (NumberFormatException e)
806 * A convenience method to get an attribute value for an alternate allele
809 * @param attributeName
813 protected String getAttributeValue(VariantContext variant,
814 String attributeName, int alleleIndex)
816 Object att = variant.getAttribute(attributeName);
818 if (att instanceof String)
822 else if (att instanceof ArrayList)
824 return ((List<String>) att).get(alleleIndex);
831 * Adds one variant feature for each allele in the VCF variant record, and
832 * returns the number of features added.
836 * @param featureStart
838 * @param forwardStrand
841 protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
842 int featureStart, int featureEnd, boolean forwardStrand)
847 * Javadoc says getAlternateAlleles() imposes no order on the list returned
848 * so we proceed defensively to get them in strict order
850 int altAlleleCount = variant.getAlternateAlleles().size();
851 for (int i = 0; i < altAlleleCount; i++)
853 added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
860 * Inspects one allele and attempts to add a variant feature for it to the
861 * sequence. We extract as much as possible of the additional data associated
862 * with this allele to store in the feature's key-value map. Answers the
863 * number of features added (0 or 1).
867 * @param altAlleleIndex
869 * @param featureStart
871 * @param forwardStrand
874 protected int addAlleleFeature(SequenceI seq, VariantContext variant,
875 int altAlleleIndex, int featureStart, int featureEnd,
876 boolean forwardStrand)
878 String reference = variant.getReference().getBaseString();
879 Allele alt = variant.getAlternateAllele(altAlleleIndex);
880 String allele = alt.getBaseString();
883 * build the ref,alt allele description e.g. "G,A", using the base
884 * complement if the sequence is on the reverse strand
886 // TODO check how structural variants are shown on reverse strand
887 StringBuilder sb = new StringBuilder();
888 sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
890 sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
891 String alleles = sb.toString(); // e.g. G,A
893 String type = SequenceOntologyI.SEQUENCE_VARIANT;
894 float score = getAlleleFrequency(variant, altAlleleIndex);
896 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
897 featureEnd, score, FEATURE_GROUP_VCF);
898 sf.setSource(sourceId);
900 sf.setValue(Gff3Helper.ALLELES, alleles);
902 addAlleleProperties(variant, seq, sf, altAlleleIndex);
904 seq.addSequenceFeature(sf);
910 * Add any allele-specific VCF key-value data to the sequence feature
915 * @param altAlelleIndex
918 protected void addAlleleProperties(VariantContext variant, SequenceI seq,
919 SequenceFeature sf, final int altAlelleIndex)
921 Map<String, Object> atts = variant.getAttributes();
923 for (Entry<String, Object> att : atts.entrySet())
925 String key = att.getKey();
928 * extract Consequence data (if present) that we are able to
929 * associated with the allele for this variant feature
931 if (CSQ_FIELD.equals(key))
933 addConsequences(variant, seq, sf, altAlelleIndex);
938 * filter out fields we don't want to capture
940 if (!vcfFieldsOfInterest.contains(key))
946 * we extract values for other data which are allele-specific;
947 * these may be per alternate allele (INFO[key].Number = 'A')
948 * or per allele including reference (INFO[key].Number = 'R')
950 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
951 if (infoHeader == null)
954 * can't be sure what data belongs to this allele, so
955 * play safe and don't take any
960 VCFHeaderLineCount number = infoHeader.getCountType();
961 int index = altAlelleIndex;
962 if (number == VCFHeaderLineCount.R)
965 * one value per allele including reference, so bump index
966 * e.g. the 3rd value is for the 2nd alternate allele
970 else if (number != VCFHeaderLineCount.A)
973 * don't save other values as not allele-related
979 * take the index'th value
981 String value = getAttributeValue(variant, key, index);
984 sf.setValue(key, value);
990 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
991 * feature for the current allele (and transcript if applicable)
993 * Allele matching: if field ALLELE_NUM is present, it must match
994 * altAlleleIndex. If not present, then field Allele value must match the VCF
997 * Transcript matching: if sequence name can be identified to at least one of
998 * the consequences' Feature values, then select only consequences that match
999 * the value (i.e. consequences for the current transcript sequence). If not,
1000 * take all consequences (this is the case when adding features to the gene
1006 * @param altAlelleIndex
1009 protected void addConsequences(VariantContext variant, SequenceI seq,
1010 SequenceFeature sf, int altAlelleIndex)
1012 Object value = variant.getAttribute(CSQ_FIELD);
1014 if (value == null || !(value instanceof ArrayList<?>))
1019 List<String> consequences = (List<String>) value;
1022 * if CSQ data includes 'Feature', and any value matches the sequence name,
1023 * then restrict consequence data to only the matching value (transcript)
1024 * i.e. just pick out consequences for the transcript the variant feature is on
1026 String seqName = seq.getName()== null ? "" : seq.getName().toLowerCase();
1027 String matchFeature = null;
1028 if (csqFeatureFieldIndex > -1)
1030 for (String consequence : consequences)
1032 String[] csqFields = consequence.split(PIPE_REGEX);
1033 if (csqFields.length > csqFeatureFieldIndex)
1035 String featureIdentifier = csqFields[csqFeatureFieldIndex];
1036 if (featureIdentifier.length() > 4
1037 && seqName.indexOf(featureIdentifier.toLowerCase()) > -1)
1039 matchFeature = featureIdentifier;
1046 * inspect CSQ consequences; where possible restrict to the consequence
1047 * associated with the current transcript (Feature)
1049 SortedMap<String, String> csqValues = new TreeMap<>(
1050 String.CASE_INSENSITIVE_ORDER);
1052 for (String consequence : consequences)
1054 String[] csqFields = consequence.split(PIPE_REGEX);
1056 if (includeConsequence(csqFields, matchFeature, variant,
1060 * inspect individual fields of this consequence, copying non-null
1061 * values which are 'fields of interest'
1064 for (String field : csqFields)
1066 if (field != null && field.length() > 0)
1068 String id = vepFieldsOfInterest.get(i);
1071 csqValues.put(id, field);
1079 if (!csqValues.isEmpty())
1081 sf.setValue(CSQ_FIELD, csqValues);
1086 * Answers true if we want to associate this block of consequence data with
1087 * the specified alternate allele of the VCF variant.
1089 * If consequence data includes the ALLELE_NUM field, then this has to match
1090 * altAlleleIndex. Otherwise the Allele field of the consequence data has to
1091 * match the allele value.
1093 * Optionally (if matchFeature is not null), restrict to only include
1094 * consequences whose Feature value matches. This allows us to attach
1095 * consequences to their respective transcripts.
1098 * @param matchFeature
1100 * @param altAlelleIndex
1104 protected boolean includeConsequence(String[] csqFields,
1105 String matchFeature, VariantContext variant, int altAlelleIndex)
1108 * check consequence is for the current transcript
1110 if (matchFeature != null)
1112 if (csqFields.length <= csqFeatureFieldIndex)
1116 String featureIdentifier = csqFields[csqFeatureFieldIndex];
1117 if (!featureIdentifier.equals(matchFeature))
1119 return false; // consequence is for a different transcript
1124 * if ALLELE_NUM is present, it must match altAlleleIndex
1125 * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1127 if (csqAlleleNumberFieldIndex > -1)
1129 if (csqFields.length <= csqAlleleNumberFieldIndex)
1133 String alleleNum = csqFields[csqAlleleNumberFieldIndex];
1134 return String.valueOf(altAlelleIndex + 1).equals(alleleNum);
1138 * else consequence allele must match variant allele
1140 if (csqAlleleFieldIndex > -1 && csqFields.length > csqAlleleFieldIndex)
1142 String csqAllele = csqFields[csqAlleleFieldIndex];
1143 String vcfAllele = variant.getAlternateAllele(altAlelleIndex)
1145 return csqAllele.equals(vcfAllele);
1152 * A convenience method to complement a dna base and return the string value
1158 protected String complement(byte[] reference)
1160 return String.valueOf(Dna.getComplement((char) reference[0]));
1164 * Determines the location of the query range (chromosome positions) in a
1165 * different reference assembly.
1167 * If the range is just a subregion of one for which we already have a mapping
1168 * (for example, an exon sub-region of a gene), then the mapping is just
1169 * computed arithmetically.
1171 * Otherwise, calls the Ensembl REST service that maps from one assembly
1172 * reference's coordinates to another's
1175 * start-end chromosomal range in 'fromRef' coordinates
1179 * assembly reference for the query coordinates
1181 * assembly reference we wish to translate to
1182 * @return the start-end range in 'toRef' coordinates
1184 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
1185 String species, String fromRef, String toRef)
1188 * first try shorcut of computing the mapping as a subregion of one
1189 * we already have (e.g. for an exon, if we have the gene mapping)
1191 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
1192 species, fromRef, toRef);
1193 if (mappedRange != null)
1199 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
1201 EnsemblMap mapper = new EnsemblMap();
1202 int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
1205 if (mapping == null)
1207 // mapping service failure
1212 * save mapping for possible future re-use
1214 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1215 if (!assemblyMappings.containsKey(key))
1217 assemblyMappings.put(key, new HashMap<int[], int[]>());
1220 assemblyMappings.get(key).put(queryRange, mapping);
1226 * If we already have a 1:1 contiguous mapping which subsumes the given query
1227 * range, this method just calculates and returns the subset of that mapping,
1228 * else it returns null. In practical terms, if a gene has a contiguous
1229 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
1230 * subsidiary exons occupy unchanged relative positions, and just compute
1231 * these as offsets, rather than do another lookup of the mapping.
1233 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
1234 * simply remove this method or let it always return null.
1236 * Warning: many rapid calls to the /map service map result in a 429 overload
1246 protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
1247 String species, String fromRef, String toRef)
1249 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1250 if (assemblyMappings.containsKey(key))
1252 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
1253 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
1255 int[] fromRange = mappedRange.getKey();
1256 int[] toRange = mappedRange.getValue();
1257 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
1260 * mapping is 1:1 in length, so we trust it to have no discontinuities
1262 if (MappingUtils.rangeContains(fromRange, queryRange))
1265 * fromRange subsumes our query range
1267 int offset = queryRange[0] - fromRange[0];
1268 int mappedRangeFrom = toRange[0] + offset;
1269 int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
1270 return new int[] { mappedRangeFrom, mappedRangeTo };
1279 * Transfers the sequence feature to the target sequence, locating its start
1280 * and end range based on the mapping. Features which do not overlap the
1281 * target sequence are ignored.
1284 * @param targetSequence
1286 * mapping from the feature's coordinates to the target sequence
1288 protected void transferFeature(SequenceFeature sf,
1289 SequenceI targetSequence, MapList mapping)
1291 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1293 if (mappedRange != null)
1295 String group = sf.getFeatureGroup();
1296 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1297 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1298 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1299 group, sf.getScore());
1300 targetSequence.addSequenceFeature(copy);
1305 * Formats a ranges map lookup key
1313 protected static String makeRangesKey(String chromosome, String species,
1314 String fromRef, String toRef)
1316 return species + EXCL + chromosome + EXCL + fromRef + EXCL