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.SAMSequenceRecord;
36 import htsjdk.samtools.util.CloseableIterator;
37 import htsjdk.variant.variantcontext.Allele;
38 import htsjdk.variant.variantcontext.VariantContext;
39 import htsjdk.variant.vcf.VCFContigHeaderLine;
40 import htsjdk.variant.vcf.VCFHeader;
41 import htsjdk.variant.vcf.VCFHeaderLine;
42 import htsjdk.variant.vcf.VCFHeaderLineCount;
43 import htsjdk.variant.vcf.VCFHeaderLineType;
44 import htsjdk.variant.vcf.VCFInfoHeaderLine;
47 * A class to read VCF data (using the htsjdk) and add variants as sequence
48 * features on dna and any related protein product sequences
52 public class VCFLoader
55 * A class to model the mapping from sequence to VCF coordinates. Cases include
57 * <li>a direct 1:1 mapping where the sequence is one of the VCF contigs</li>
58 * <li>a mapping of sequence to chromosomal coordinates, where sequence and VCF
59 * use the same reference assembly</li>
60 * <li>a modified mapping of sequence to chromosomal coordinates, where sequence
61 * and VCF use different reference assembles</li>
66 final String chromosome;
70 VCFMap(String chr, MapList m)
78 * Lookup keys, and default values, for Preference entries that describe
79 * patterns for VCF and VEP fields to capture
81 private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
83 private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
85 private static final String DEFAULT_VCF_FIELDS = ".*";
87 private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
90 * keys to fields of VEP CSQ consequence data
91 * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
93 private static final String ALLELE_KEY = "Allele";
95 private static final String ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref), 1...
96 private static final String FEATURE_KEY = "Feature"; // Ensembl stable id
99 * default VCF INFO key for VEP consequence data
100 * NB this can be overridden running VEP with --vcf_info_field
101 * - we don't handle this case (require identifier to be CSQ)
103 private static final String CSQ_FIELD = "CSQ";
106 * separator for fields in consequence data is '|'
108 private static final String PIPE_REGEX = "\\|";
111 * key for Allele Frequency output by VEP
112 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
114 private static final String ALLELE_FREQUENCY_KEY = "AF";
117 * delimiter that separates multiple consequence data blocks
119 private static final String COMMA = ",";
122 * the feature group assigned to a VCF variant in Jalview
124 private static final String FEATURE_GROUP_VCF = "VCF";
127 * internal delimiter used to build keys for assemblyMappings
130 private static final String EXCL = "!";
133 * the alignment we are associating VCF data with
135 private AlignmentI al;
138 * mappings between VCF and sequence reference assembly regions, as
139 * key = "species!chromosome!fromAssembly!toAssembly
140 * value = Map{fromRange, toRange}
142 private Map<String, Map<int[], int[]>> assemblyMappings;
145 * holds details of the VCF header lines (metadata)
147 private VCFHeader header;
150 * the position (0...) of field in each block of
151 * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
152 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
154 private int csqAlleleFieldIndex = -1;
155 private int csqAlleleNumberFieldIndex = -1;
156 private int csqFeatureFieldIndex = -1;
159 * a unique identifier under which to save metadata about feature
160 * attributes (selected INFO field data)
162 private String sourceId;
165 * The INFO IDs of data that is both present in the VCF file, and
166 * also matched by any filters for data of interest
168 List<String> vcfFieldsOfInterest;
171 * The field offsets and identifiers for VEP (CSQ) data that is both present
172 * in the VCF file, and also matched by any filters for data of interest
173 * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
175 Map<Integer, String> vepFieldsOfInterest;
178 * Constructor given an alignment context
182 public VCFLoader(AlignmentI alignment)
186 // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
187 assemblyMappings = new HashMap<>();
191 * Starts a new thread to query and load VCF variant data on to the alignment
193 * This method is not thread safe - concurrent threads should use separate
194 * instances of this class.
199 public void loadVCF(final String filePath,
200 final AlignViewControllerGuiI gui)
204 gui.setStatus(MessageManager.getString("label.searching_vcf"));
213 VCFLoader.this.doLoad(filePath, gui);
220 * Loads VCF on to an alignment - provided it can be related to one or more
221 * sequence's chromosomal coordinates
225 * optional callback handler for messages
227 protected void doLoad(String filePath, AlignViewControllerGuiI gui)
229 VCFReader reader = null;
232 // long start = System.currentTimeMillis();
233 reader = new VCFReader(filePath);
235 header = reader.getFileHeader();
239 saveMetadata(sourceId);
242 * get offset of CSQ ALLELE_NUM and Feature if declared
246 VCFHeaderLine ref = header
247 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
248 String vcfAssembly = ref.getValue();
254 * query for VCF overlapping each sequence in turn
256 for (SequenceI seq : al.getSequences())
258 int added = loadSequenceVCF(seq, reader, vcfAssembly);
263 transferAddedFeatures(seq);
268 // long elapsed = System.currentTimeMillis() - start;
269 String msg = MessageManager.formatMessage("label.added_vcf",
272 if (gui.getFeatureSettingsUI() != null)
274 gui.getFeatureSettingsUI().discoverAllFeatureData();
277 } catch (Throwable e)
279 System.err.println("Error processing VCF: " + e.getMessage());
283 gui.setStatus("Error occurred - see console for details");
292 } catch (IOException e)
301 * Reads metadata (such as INFO field descriptions and datatypes) and saves
302 * them for future reference
306 void saveMetadata(String theSourceId)
308 List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
310 vcfFieldsOfInterest = new ArrayList<>();
312 FeatureSource metadata = new FeatureSource(theSourceId);
314 for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
316 String attributeId = info.getID();
317 String desc = info.getDescription();
318 VCFHeaderLineType type = info.getType();
319 FeatureAttributeType attType = null;
323 attType = FeatureAttributeType.Character;
326 attType = FeatureAttributeType.Flag;
329 attType = FeatureAttributeType.Float;
332 attType = FeatureAttributeType.Integer;
335 attType = FeatureAttributeType.String;
338 metadata.setAttributeName(attributeId, desc);
339 metadata.setAttributeType(attributeId, attType);
341 if (isFieldWanted(attributeId, vcfFieldPatterns))
343 vcfFieldsOfInterest.add(attributeId);
347 FeatureSources.getInstance().addSource(theSourceId, metadata);
351 * Answers true if the field id is matched by any of the filter patterns, else
352 * false. Matching is against regular expression patterns, and is not
359 private boolean isFieldWanted(String id, List<Pattern> filters)
361 for (Pattern p : filters)
363 if (p.matcher(id.toUpperCase()).matches())
372 * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
373 * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
374 * required for processing.
376 * CSQ fields are declared in the CSQ INFO Description e.g.
378 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
380 protected void parseCsqHeader()
382 List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
384 vepFieldsOfInterest = new HashMap<>();
386 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
393 * parse out the pipe-separated list of CSQ fields; we assume here that
394 * these form the last part of the description, and contain no spaces
396 String desc = csqInfo.getDescription();
397 int spacePos = desc.lastIndexOf(" ");
398 desc = desc.substring(spacePos + 1);
402 String[] format = desc.split(PIPE_REGEX);
404 for (String field : format)
406 if (ALLELE_NUM_KEY.equals(field))
408 csqAlleleNumberFieldIndex = index;
410 if (ALLELE_KEY.equals(field))
412 csqAlleleFieldIndex = index;
414 if (FEATURE_KEY.equals(field))
416 csqFeatureFieldIndex = index;
419 if (isFieldWanted(field, vepFieldFilters))
421 vepFieldsOfInterest.put(index, field);
430 * Reads the Preference value for the given key, with default specified if no
431 * preference set. The value is interpreted as a comma-separated list of
432 * regular expressions, and converted into a list of compiled patterns ready
433 * for matching. Patterns are forced to upper-case for non-case-sensitive
436 * This supports user-defined filters for fields of interest to capture while
437 * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
438 * fields with an ID of AF, or starting with AC, would be matched.
444 private List<Pattern> getFieldMatchers(String key, String def)
446 String pref = Cache.getDefault(key, def);
447 List<Pattern> patterns = new ArrayList<>();
448 String[] tokens = pref.split(",");
449 for (String token : tokens)
453 patterns.add(Pattern.compile(token.toUpperCase()));
454 } catch (PatternSyntaxException e)
456 System.err.println("Invalid pattern ignored: " + token);
463 * Transfers VCF features to sequences to which this sequence has a mapping.
464 * If the mapping is 3:1, computes peptide variants from nucleotide variants.
468 protected void transferAddedFeatures(SequenceI seq)
470 DBRefEntry[] dbrefs = seq.getDBRefs();
475 for (DBRefEntry dbref : dbrefs)
477 Mapping mapping = dbref.getMap();
478 if (mapping == null || mapping.getTo() == null)
483 SequenceI mapTo = mapping.getTo();
484 MapList map = mapping.getMap();
485 if (map.getFromRatio() == 3)
488 * dna-to-peptide product mapping
490 AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
495 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
497 List<SequenceFeature> features = seq.getFeatures()
498 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
499 for (SequenceFeature sf : features)
501 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
503 transferFeature(sf, mapTo, map);
511 * Tries to add overlapping variants read from a VCF file to the given
512 * sequence, and returns the number of variant features added. Note that this
513 * requires the sequence to hold information as to its species, chromosomal
514 * positions and reference assembly, in order to be able to map the VCF
515 * variants to the sequence (or not)
522 protected int loadSequenceVCF(SequenceI seq, VCFReader reader,
525 VCFMap vcfMap = getVcfMap(seq, vcfAssembly);
531 return addVcfVariants(seq, reader, vcfMap, vcfAssembly);
535 * Answers a map from sequence coordinates to VCF chromosome ranges
541 private VCFMap getVcfMap(SequenceI seq, String vcfAssembly)
544 * simplest case: sequence has id and length matching a VCF contig
546 GeneLociI seqCoords = seq.getGeneLoci();
547 if (seqCoords == null)
549 VCFMap map = getContigMap(seq);
552 Cache.log.warn(String.format(
553 "Can't query VCF for %s as chromosome coordinates not known",
559 String species = seqCoords.getSpeciesId();
560 String chromosome = seqCoords.getChromosomeId();
561 String seqRef = seqCoords.getAssemblyId();
562 MapList map = seqCoords.getMap();
564 if (!vcfSpeciesMatchesSequence(vcfAssembly, species))
569 if (vcfAssemblyMatchesSequence(vcfAssembly, seqRef))
571 return new VCFMap(chromosome, map);
574 if (!"GRCh38".equalsIgnoreCase(seqRef) // Ensembl
575 || !vcfAssembly.contains("Homo_sapiens_assembly19")) // gnomAD
581 * map chromosomal coordinates from sequence to VCF if the VCF
582 * data has a different reference assembly to the sequence
584 // TODO generalise for cases other than GRCh38 -> GRCh37 !
585 // - or get the user to choose in a dialog
587 List<int[]> toVcfRanges = new ArrayList<>();
588 List<int[]> fromSequenceRanges = new ArrayList<>();
589 String toRef = "GRCh37";
591 for (int[] range : map.getToRanges())
593 int[] fromRange = map.locateInFrom(range[0], range[1]);
594 if (fromRange == null)
600 int[] newRange = mapReferenceRange(range, chromosome, "human", seqRef,
602 if (newRange == null)
605 String.format("Failed to map %s:%s:%s:%d:%d to %s", species,
606 chromosome, seqRef, range[0], range[1], toRef));
611 toVcfRanges.add(newRange);
612 fromSequenceRanges.add(fromRange);
616 return new VCFMap(chromosome,
617 new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
621 * If the sequence id matches a contig declared in the VCF file, and the
622 * sequence matches the contig length, then returns a 1:1 map of the sequence to
623 * the contig, else returns null
628 private VCFMap getContigMap(SequenceI seq)
630 String id = seq.getName();
631 for (VCFContigHeaderLine contig : header.getContigLines())
633 if (contig.getID().equals(id))
636 * have to construct a SAMSequenceRecord to
637 * read the contig 'length' field!
639 int len = seq.getLength();
640 SAMSequenceRecord ssr = contig.getSAMSequenceRecord();
641 if (len == ssr.getSequenceLength())
643 MapList map = new MapList(new int[] { 1, len },
646 return new VCFMap(id, map);
655 * Answers true if we determine that the VCF data uses the same reference
656 * assembly as the sequence, else false
662 private boolean vcfAssemblyMatchesSequence(String vcfAssembly,
665 // TODO improve on this stub, which handles gnomAD and
666 // hopes for the best for other cases
668 if ("GRCh38".equalsIgnoreCase(seqRef) // Ensembl
669 && vcfAssembly.contains("Homo_sapiens_assembly19")) // gnomAD
677 * Answers true if the species inferred from the VCF reference identifier
678 * matches that for the sequence
684 boolean vcfSpeciesMatchesSequence(String vcfAssembly, String speciesId)
687 // there are many aliases for species - how to equate one with another?
689 // VCF ##reference header is an unstructured URI - how to extract species?
690 // perhaps check if ref includes any (Ensembl) alias of speciesId??
691 // TODO ask the user to confirm this??
693 if (vcfAssembly.contains("Homo_sapiens") // gnomAD exome data example
694 && "HOMO_SAPIENS".equals(speciesId)) // Ensembl species id
699 if (vcfAssembly.contains("c_elegans") // VEP VCF response example
700 && "CAENORHABDITIS_ELEGANS".equals(speciesId)) // Ensembl
705 // this is not a sustainable solution...
711 * Queries the VCF reader for any variants that overlap the mapped chromosome
712 * ranges of the sequence, and adds as variant features. Returns the number of
713 * overlapping variants found.
718 * mapping from sequence to VCF coordinates
720 * the '##reference' identifier for the VCF reference assembly
723 protected int addVcfVariants(SequenceI seq, VCFReader reader,
724 VCFMap map, String vcfAssembly)
726 boolean forwardStrand = map.map.isToForwardStrand();
729 * query the VCF for overlaps of each contiguous chromosomal region
733 for (int[] range : map.map.getToRanges())
735 int vcfStart = Math.min(range[0], range[1]);
736 int vcfEnd = Math.max(range[0], range[1]);
737 CloseableIterator<VariantContext> variants = reader
738 .query(map.chromosome, vcfStart, vcfEnd);
739 while (variants.hasNext())
741 VariantContext variant = variants.next();
743 int[] featureRange = map.map.locateInFrom(variant.getStart(),
746 if (featureRange != null)
748 int featureStart = Math.min(featureRange[0], featureRange[1]);
749 int featureEnd = Math.max(featureRange[0], featureRange[1]);
750 count += addAlleleFeatures(seq, variant, featureStart, featureEnd,
761 * A convenience method to get the AF value for the given alternate allele
768 protected float getAlleleFrequency(VariantContext variant, int alleleIndex)
771 String attributeValue = getAttributeValue(variant,
772 ALLELE_FREQUENCY_KEY, alleleIndex);
773 if (attributeValue != null)
777 score = Float.parseFloat(attributeValue);
778 } catch (NumberFormatException e)
788 * A convenience method to get an attribute value for an alternate allele
791 * @param attributeName
795 protected String getAttributeValue(VariantContext variant,
796 String attributeName, int alleleIndex)
798 Object att = variant.getAttribute(attributeName);
800 if (att instanceof String)
804 else if (att instanceof ArrayList)
806 return ((List<String>) att).get(alleleIndex);
813 * Adds one variant feature for each allele in the VCF variant record, and
814 * returns the number of features added.
818 * @param featureStart
820 * @param forwardStrand
823 protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
824 int featureStart, int featureEnd, boolean forwardStrand)
829 * Javadoc says getAlternateAlleles() imposes no order on the list returned
830 * so we proceed defensively to get them in strict order
832 int altAlleleCount = variant.getAlternateAlleles().size();
833 for (int i = 0; i < altAlleleCount; i++)
835 added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
842 * Inspects one allele and attempts to add a variant feature for it to the
843 * sequence. We extract as much as possible of the additional data associated
844 * with this allele to store in the feature's key-value map. Answers the
845 * number of features added (0 or 1).
849 * @param altAlleleIndex
851 * @param featureStart
853 * @param forwardStrand
856 protected int addAlleleFeature(SequenceI seq, VariantContext variant,
857 int altAlleleIndex, int featureStart, int featureEnd,
858 boolean forwardStrand)
860 String reference = variant.getReference().getBaseString();
861 Allele alt = variant.getAlternateAllele(altAlleleIndex);
862 String allele = alt.getBaseString();
865 * build the ref,alt allele description e.g. "G,A", using the base
866 * complement if the sequence is on the reverse strand
868 // TODO check how structural variants are shown on reverse strand
869 StringBuilder sb = new StringBuilder();
870 sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
872 sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
873 String alleles = sb.toString(); // e.g. G,A
875 String type = SequenceOntologyI.SEQUENCE_VARIANT;
876 float score = getAlleleFrequency(variant, altAlleleIndex);
878 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
879 featureEnd, score, FEATURE_GROUP_VCF);
880 sf.setSource(sourceId);
882 sf.setValue(Gff3Helper.ALLELES, alleles);
884 addAlleleProperties(variant, seq, sf, altAlleleIndex);
886 seq.addSequenceFeature(sf);
892 * Add any allele-specific VCF key-value data to the sequence feature
897 * @param altAlelleIndex
900 protected void addAlleleProperties(VariantContext variant, SequenceI seq,
901 SequenceFeature sf, final int altAlelleIndex)
903 Map<String, Object> atts = variant.getAttributes();
905 for (Entry<String, Object> att : atts.entrySet())
907 String key = att.getKey();
910 * extract Consequence data (if present) that we are able to
911 * associated with the allele for this variant feature
913 if (CSQ_FIELD.equals(key))
915 addConsequences(variant, seq, sf, altAlelleIndex);
920 * filter out fields we don't want to capture
922 if (!vcfFieldsOfInterest.contains(key))
928 * we extract values for other data which are allele-specific;
929 * these may be per alternate allele (INFO[key].Number = 'A')
930 * or per allele including reference (INFO[key].Number = 'R')
932 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
933 if (infoHeader == null)
936 * can't be sure what data belongs to this allele, so
937 * play safe and don't take any
942 VCFHeaderLineCount number = infoHeader.getCountType();
943 int index = altAlelleIndex;
944 if (number == VCFHeaderLineCount.R)
947 * one value per allele including reference, so bump index
948 * e.g. the 3rd value is for the 2nd alternate allele
952 else if (number != VCFHeaderLineCount.A)
955 * don't save other values as not allele-related
961 * take the index'th value
963 String value = getAttributeValue(variant, key, index);
966 sf.setValue(key, value);
972 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
973 * feature for the current allele (and transcript if applicable)
975 * Allele matching: if field ALLELE_NUM is present, it must match
976 * altAlleleIndex. If not present, then field Allele value must match the VCF
979 * Transcript matching: if sequence name can be identified to at least one of
980 * the consequences' Feature values, then select only consequences that match
981 * the value (i.e. consequences for the current transcript sequence). If not,
982 * take all consequences (this is the case when adding features to the gene
988 * @param altAlelleIndex
991 protected void addConsequences(VariantContext variant, SequenceI seq,
992 SequenceFeature sf, int altAlelleIndex)
994 Object value = variant.getAttribute(CSQ_FIELD);
996 if (value == null || !(value instanceof ArrayList<?>))
1001 List<String> consequences = (List<String>) value;
1004 * if CSQ data includes 'Feature', and any value matches the sequence name,
1005 * then restrict consequence data to only the matching value (transcript)
1006 * i.e. just pick out consequences for the transcript the variant feature is on
1008 String seqName = seq.getName()== null ? "" : seq.getName().toLowerCase();
1009 String matchFeature = null;
1010 if (csqFeatureFieldIndex > -1)
1012 for (String consequence : consequences)
1014 String[] csqFields = consequence.split(PIPE_REGEX);
1015 if (csqFields.length > csqFeatureFieldIndex)
1017 String featureIdentifier = csqFields[csqFeatureFieldIndex];
1018 if (featureIdentifier.length() > 4
1019 && seqName.indexOf(featureIdentifier.toLowerCase()) > -1)
1021 matchFeature = featureIdentifier;
1028 * inspect CSQ consequences; where possible restrict to the consequence
1029 * associated with the current transcript (Feature)
1031 SortedMap<String, String> csqValues = new TreeMap<>(
1032 String.CASE_INSENSITIVE_ORDER);
1034 for (String consequence : consequences)
1036 String[] csqFields = consequence.split(PIPE_REGEX);
1038 if (includeConsequence(csqFields, matchFeature, variant,
1042 * inspect individual fields of this consequence, copying non-null
1043 * values which are 'fields of interest'
1046 for (String field : csqFields)
1048 if (field != null && field.length() > 0)
1050 String id = vepFieldsOfInterest.get(i);
1053 csqValues.put(id, field);
1061 if (!csqValues.isEmpty())
1063 sf.setValue(CSQ_FIELD, csqValues);
1068 * Answers true if we want to associate this block of consequence data with
1069 * the specified alternate allele of the VCF variant.
1071 * If consequence data includes the ALLELE_NUM field, then this has to match
1072 * altAlleleIndex. Otherwise the Allele field of the consequence data has to
1073 * match the allele value.
1075 * Optionally (if matchFeature is not null), restrict to only include
1076 * consequences whose Feature value matches. This allows us to attach
1077 * consequences to their respective transcripts.
1080 * @param matchFeature
1082 * @param altAlelleIndex
1086 protected boolean includeConsequence(String[] csqFields,
1087 String matchFeature, VariantContext variant, int altAlelleIndex)
1090 * check consequence is for the current transcript
1092 if (matchFeature != null)
1094 if (csqFields.length <= csqFeatureFieldIndex)
1098 String featureIdentifier = csqFields[csqFeatureFieldIndex];
1099 if (!featureIdentifier.equals(matchFeature))
1101 return false; // consequence is for a different transcript
1106 * if ALLELE_NUM is present, it must match altAlleleIndex
1107 * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1109 if (csqAlleleNumberFieldIndex > -1)
1111 if (csqFields.length <= csqAlleleNumberFieldIndex)
1115 String alleleNum = csqFields[csqAlleleNumberFieldIndex];
1116 return String.valueOf(altAlelleIndex + 1).equals(alleleNum);
1120 * else consequence allele must match variant allele
1122 if (csqAlleleFieldIndex > -1 && csqFields.length > csqAlleleFieldIndex)
1124 String csqAllele = csqFields[csqAlleleFieldIndex];
1125 String vcfAllele = variant.getAlternateAllele(altAlelleIndex)
1127 return csqAllele.equals(vcfAllele);
1134 * A convenience method to complement a dna base and return the string value
1140 protected String complement(byte[] reference)
1142 return String.valueOf(Dna.getComplement((char) reference[0]));
1146 * Determines the location of the query range (chromosome positions) in a
1147 * different reference assembly.
1149 * If the range is just a subregion of one for which we already have a mapping
1150 * (for example, an exon sub-region of a gene), then the mapping is just
1151 * computed arithmetically.
1153 * Otherwise, calls the Ensembl REST service that maps from one assembly
1154 * reference's coordinates to another's
1157 * start-end chromosomal range in 'fromRef' coordinates
1161 * assembly reference for the query coordinates
1163 * assembly reference we wish to translate to
1164 * @return the start-end range in 'toRef' coordinates
1166 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
1167 String species, String fromRef, String toRef)
1170 * first try shorcut of computing the mapping as a subregion of one
1171 * we already have (e.g. for an exon, if we have the gene mapping)
1173 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
1174 species, fromRef, toRef);
1175 if (mappedRange != null)
1181 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
1183 EnsemblMap mapper = new EnsemblMap();
1184 int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
1187 if (mapping == null)
1189 // mapping service failure
1194 * save mapping for possible future re-use
1196 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1197 if (!assemblyMappings.containsKey(key))
1199 assemblyMappings.put(key, new HashMap<int[], int[]>());
1202 assemblyMappings.get(key).put(queryRange, mapping);
1208 * If we already have a 1:1 contiguous mapping which subsumes the given query
1209 * range, this method just calculates and returns the subset of that mapping,
1210 * else it returns null. In practical terms, if a gene has a contiguous
1211 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
1212 * subsidiary exons occupy unchanged relative positions, and just compute
1213 * these as offsets, rather than do another lookup of the mapping.
1215 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
1216 * simply remove this method or let it always return null.
1218 * Warning: many rapid calls to the /map service map result in a 429 overload
1228 protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
1229 String species, String fromRef, String toRef)
1231 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1232 if (assemblyMappings.containsKey(key))
1234 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
1235 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
1237 int[] fromRange = mappedRange.getKey();
1238 int[] toRange = mappedRange.getValue();
1239 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
1242 * mapping is 1:1 in length, so we trust it to have no discontinuities
1244 if (MappingUtils.rangeContains(fromRange, queryRange))
1247 * fromRange subsumes our query range
1249 int offset = queryRange[0] - fromRange[0];
1250 int mappedRangeFrom = toRange[0] + offset;
1251 int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
1252 return new int[] { mappedRangeFrom, mappedRangeTo };
1261 * Transfers the sequence feature to the target sequence, locating its start
1262 * and end range based on the mapping. Features which do not overlap the
1263 * target sequence are ignored.
1266 * @param targetSequence
1268 * mapping from the feature's coordinates to the target sequence
1270 protected void transferFeature(SequenceFeature sf,
1271 SequenceI targetSequence, MapList mapping)
1273 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1275 if (mappedRange != null)
1277 String group = sf.getFeatureGroup();
1278 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1279 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1280 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1281 group, sf.getScore());
1282 targetSequence.addSequenceFeature(copy);
1287 * Formats a ranges map lookup key
1295 protected static String makeRangesKey(String chromosome, String species,
1296 String fromRef, String toRef)
1298 return species + EXCL + chromosome + EXCL + fromRef + EXCL