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.DBRefEntry;
8 import jalview.datamodel.GeneLociI;
9 import jalview.datamodel.Mapping;
10 import jalview.datamodel.SequenceFeature;
11 import jalview.datamodel.SequenceI;
12 import jalview.datamodel.features.FeatureAttributeType;
13 import jalview.datamodel.features.FeatureSource;
14 import jalview.datamodel.features.FeatureSources;
15 import jalview.ext.ensembl.EnsemblMap;
16 import jalview.ext.htsjdk.HtsContigDb;
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;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
30 import java.util.Map.Entry;
31 import java.util.regex.Pattern;
32 import java.util.regex.PatternSyntaxException;
34 import htsjdk.samtools.SAMException;
35 import htsjdk.samtools.SAMSequenceDictionary;
36 import htsjdk.samtools.SAMSequenceRecord;
37 import htsjdk.samtools.util.CloseableIterator;
38 import htsjdk.variant.variantcontext.Allele;
39 import htsjdk.variant.variantcontext.VariantContext;
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)
77 public String toString()
79 return chromosome + ":" + map.toString();
84 * Lookup keys, and default values, for Preference entries that describe
85 * patterns for VCF and VEP fields to capture
87 private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
89 private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
91 private static final String DEFAULT_VCF_FIELDS = ".*";
93 private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
96 * keys to fields of VEP CSQ consequence data
97 * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
99 private static final String CSQ_CONSEQUENCE_KEY = "Consequence";
100 private static final String CSQ_ALLELE_KEY = "Allele";
101 private static final String CSQ_ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref), 1...
102 private static final String CSQ_FEATURE_KEY = "Feature"; // Ensembl stable id
105 * default VCF INFO key for VEP consequence data
106 * NB this can be overridden running VEP with --vcf_info_field
107 * - we don't handle this case (require identifier to be CSQ)
109 private static final String CSQ_FIELD = "CSQ";
112 * separator for fields in consequence data is '|'
114 private static final String PIPE_REGEX = "\\|";
117 * key for Allele Frequency output by VEP
118 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
120 private static final String ALLELE_FREQUENCY_KEY = "AF";
123 * delimiter that separates multiple consequence data blocks
125 private static final String COMMA = ",";
128 * the feature group assigned to a VCF variant in Jalview
130 private static final String FEATURE_GROUP_VCF = "VCF";
133 * internal delimiter used to build keys for assemblyMappings
136 private static final String EXCL = "!";
139 * the VCF file we are processing
141 protected String vcfFilePath;
144 * mappings between VCF and sequence reference assembly regions, as
145 * key = "species!chromosome!fromAssembly!toAssembly
146 * value = Map{fromRange, toRange}
148 private Map<String, Map<int[], int[]>> assemblyMappings;
150 private VCFReader reader;
153 * holds details of the VCF header lines (metadata)
155 private VCFHeader header;
158 * a Dictionary of contigs (if present) referenced in the VCF file
160 private SAMSequenceDictionary dictionary;
163 * the position (0...) of field in each block of
164 * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
165 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
167 private int csqConsequenceFieldIndex = -1;
168 private int csqAlleleFieldIndex = -1;
169 private int csqAlleleNumberFieldIndex = -1;
170 private int csqFeatureFieldIndex = -1;
172 // todo the same fields for SnpEff ANN data if wanted
173 // see http://snpeff.sourceforge.net/SnpEff_manual.html#input
176 * a unique identifier under which to save metadata about feature
177 * attributes (selected INFO field data)
179 private String sourceId;
182 * The INFO IDs of data that is both present in the VCF file, and
183 * also matched by any filters for data of interest
185 List<String> vcfFieldsOfInterest;
188 * The field offsets and identifiers for VEP (CSQ) data that is both present
189 * in the VCF file, and also matched by any filters for data of interest
190 * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
192 Map<Integer, String> vepFieldsOfInterest;
195 * Constructor given a VCF file
199 public VCFLoader(String vcfFile)
204 } catch (IOException e)
206 System.err.println("Error opening VCF file: " + e.getMessage());
209 // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
210 assemblyMappings = new HashMap<>();
214 * Starts a new thread to query and load VCF variant data on to the given
217 * This method is not thread safe - concurrent threads should use separate
218 * instances of this class.
223 public void loadVCF(SequenceI[] seqs, final AlignViewControllerGuiI gui)
227 gui.setStatus(MessageManager.getString("label.searching_vcf"));
235 VCFLoader.this.doLoad(seqs, gui);
241 * Reads the specified contig sequence and adds its VCF variants to it
244 * the id of a single sequence (contig) to load
247 public SequenceI loadVCFContig(String contig)
249 String ref = header.getOtherHeaderLine(VCFHeader.REFERENCE_KEY)
251 if (ref.startsWith("file://"))
253 ref = ref.substring(7);
256 SequenceI seq = null;
257 File dbFile = new File(ref);
261 HtsContigDb db = new HtsContigDb("", dbFile);
262 seq = db.getSequenceProxy(contig);
263 loadSequenceVCF(seq, ref);
268 System.err.println("VCF reference not found: " + ref);
275 * Loads VCF on to one or more sequences
279 * optional callback handler for messages
281 protected void doLoad(SequenceI[] seqs, AlignViewControllerGuiI gui)
285 VCFHeaderLine ref = header
286 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
287 String vcfAssembly = ref.getValue();
293 * query for VCF overlapping each sequence in turn
295 for (SequenceI seq : seqs)
297 int added = loadSequenceVCF(seq, vcfAssembly);
302 transferAddedFeatures(seq);
307 String msg = MessageManager.formatMessage("label.added_vcf",
310 if (gui.getFeatureSettingsUI() != null)
312 gui.getFeatureSettingsUI().discoverAllFeatureData();
315 } catch (Throwable e)
317 System.err.println("Error processing VCF: " + e.getMessage());
321 gui.setStatus("Error occurred - see console for details");
330 } catch (IOException e)
341 * Opens the VCF file and parses header data
344 * @throws IOException
346 private void initialise(String filePath) throws IOException
348 vcfFilePath = filePath;
350 reader = new VCFReader(filePath);
352 header = reader.getFileHeader();
356 dictionary = header.getSequenceDictionary();
357 } catch (SAMException e)
359 // ignore - thrown if any contig line lacks length info
364 saveMetadata(sourceId);
367 * get offset of CSQ ALLELE_NUM and Feature if declared
373 * Reads metadata (such as INFO field descriptions and datatypes) and saves
374 * them for future reference
378 void saveMetadata(String theSourceId)
380 List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
382 vcfFieldsOfInterest = new ArrayList<>();
384 FeatureSource metadata = new FeatureSource(theSourceId);
386 for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
388 String attributeId = info.getID();
389 String desc = info.getDescription();
390 VCFHeaderLineType type = info.getType();
391 FeatureAttributeType attType = null;
395 attType = FeatureAttributeType.Character;
398 attType = FeatureAttributeType.Flag;
401 attType = FeatureAttributeType.Float;
404 attType = FeatureAttributeType.Integer;
407 attType = FeatureAttributeType.String;
410 metadata.setAttributeName(attributeId, desc);
411 metadata.setAttributeType(attributeId, attType);
413 if (isFieldWanted(attributeId, vcfFieldPatterns))
415 vcfFieldsOfInterest.add(attributeId);
419 FeatureSources.getInstance().addSource(theSourceId, metadata);
423 * Answers true if the field id is matched by any of the filter patterns, else
424 * false. Matching is against non-case-sensitive regular expression patterns.
430 private boolean isFieldWanted(String id, List<Pattern> filters)
432 for (Pattern p : filters)
434 if (p.matcher(id).matches())
443 * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
444 * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
445 * required for processing.
447 * CSQ fields are declared in the CSQ INFO Description e.g.
449 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
451 protected void parseCsqHeader()
453 List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
455 vepFieldsOfInterest = new HashMap<>();
457 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
464 * parse out the pipe-separated list of CSQ fields; we assume here that
465 * these form the last part of the description, and contain no spaces
467 String desc = csqInfo.getDescription();
468 int spacePos = desc.lastIndexOf(" ");
469 desc = desc.substring(spacePos + 1);
473 String[] format = desc.split(PIPE_REGEX);
475 for (String field : format)
477 if (CSQ_CONSEQUENCE_KEY.equals(field))
479 csqConsequenceFieldIndex = index;
481 if (CSQ_ALLELE_NUM_KEY.equals(field))
483 csqAlleleNumberFieldIndex = index;
485 if (CSQ_ALLELE_KEY.equals(field))
487 csqAlleleFieldIndex = index;
489 if (CSQ_FEATURE_KEY.equals(field))
491 csqFeatureFieldIndex = index;
494 if (isFieldWanted(field, vepFieldFilters))
496 vepFieldsOfInterest.put(index, field);
505 * Reads the Preference value for the given key, with default specified if no
506 * preference set. The value is interpreted as a comma-separated list of
507 * regular expressions, and converted into a list of compiled patterns ready
508 * for matching. Patterns are set to non-case-sensitive matching.
510 * This supports user-defined filters for fields of interest to capture while
511 * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
512 * fields with an ID of AF, or starting with AC, would be matched.
518 private List<Pattern> getFieldMatchers(String key, String def)
520 String pref = Cache.getDefault(key, def);
521 List<Pattern> patterns = new ArrayList<>();
522 String[] tokens = pref.split(",");
523 for (String token : tokens)
527 patterns.add(Pattern.compile(token, Pattern.CASE_INSENSITIVE));
528 } catch (PatternSyntaxException e)
530 System.err.println("Invalid pattern ignored: " + token);
537 * Transfers VCF features to sequences to which this sequence has a mapping.
538 * If the mapping is 3:1, computes peptide variants from nucleotide variants.
542 protected void transferAddedFeatures(SequenceI seq)
544 DBRefEntry[] dbrefs = seq.getDBRefs();
549 for (DBRefEntry dbref : dbrefs)
551 Mapping mapping = dbref.getMap();
552 if (mapping == null || mapping.getTo() == null)
557 SequenceI mapTo = mapping.getTo();
558 MapList map = mapping.getMap();
559 if (map.getFromRatio() == 3)
562 * dna-to-peptide product mapping
564 AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
569 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
571 List<SequenceFeature> features = seq.getFeatures()
572 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
573 for (SequenceFeature sf : features)
575 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
577 transferFeature(sf, mapTo, map);
585 * Tries to add overlapping variants read from a VCF file to the given sequence,
586 * and returns the number of variant features added
592 protected int loadSequenceVCF(SequenceI seq, String vcfAssembly)
594 VCFMap vcfMap = getVcfMap(seq, vcfAssembly);
601 * work with the dataset sequence here
603 SequenceI dss = seq.getDatasetSequence();
608 return addVcfVariants(dss, vcfMap);
612 * Answers a map from sequence coordinates to VCF chromosome ranges
618 private VCFMap getVcfMap(SequenceI seq, String vcfAssembly)
621 * simplest case: sequence has id and length matching a VCF contig
623 VCFMap vcfMap = null;
624 if (dictionary != null)
626 vcfMap = getContigMap(seq);
634 * otherwise, map to VCF from chromosomal coordinates
635 * of the sequence (if known)
637 GeneLociI seqCoords = seq.getGeneLoci();
638 if (seqCoords == null)
640 Cache.log.warn(String.format(
641 "Can't query VCF for %s as chromosome coordinates not known",
646 String species = seqCoords.getSpeciesId();
647 String chromosome = seqCoords.getChromosomeId();
648 String seqRef = seqCoords.getAssemblyId();
649 MapList map = seqCoords.getMap();
651 if (!vcfSpeciesMatchesSequence(vcfAssembly, species))
656 if (vcfAssemblyMatchesSequence(vcfAssembly, seqRef))
658 return new VCFMap(chromosome, map);
661 if (!"GRCh38".equalsIgnoreCase(seqRef) // Ensembl
662 || !vcfAssembly.contains("Homo_sapiens_assembly19")) // gnomAD
668 * map chromosomal coordinates from sequence to VCF if the VCF
669 * data has a different reference assembly to the sequence
671 // TODO generalise for cases other than GRCh38 -> GRCh37 !
672 // - or get the user to choose in a dialog
674 List<int[]> toVcfRanges = new ArrayList<>();
675 List<int[]> fromSequenceRanges = new ArrayList<>();
676 String toRef = "GRCh37";
678 for (int[] range : map.getToRanges())
680 int[] fromRange = map.locateInFrom(range[0], range[1]);
681 if (fromRange == null)
687 int[] newRange = mapReferenceRange(range, chromosome, "human", seqRef,
689 if (newRange == null)
692 String.format("Failed to map %s:%s:%s:%d:%d to %s", species,
693 chromosome, seqRef, range[0], range[1], toRef));
698 toVcfRanges.add(newRange);
699 fromSequenceRanges.add(fromRange);
703 return new VCFMap(chromosome,
704 new MapList(fromSequenceRanges, toVcfRanges, 1, 1));
708 * If the sequence id matches a contig declared in the VCF file, and the
709 * sequence length matches the contig length, then returns a 1:1 map of the
710 * sequence to the contig, else returns null
715 private VCFMap getContigMap(SequenceI seq)
717 String id = seq.getName();
718 SAMSequenceRecord contig = dictionary.getSequence(id);
721 int len = seq.getLength();
722 if (len == contig.getSequenceLength())
724 MapList map = new MapList(new int[] { 1, len },
727 return new VCFMap(id, map);
734 * Answers true if we determine that the VCF data uses the same reference
735 * assembly as the sequence, else false
741 private boolean vcfAssemblyMatchesSequence(String vcfAssembly,
744 // TODO improve on this stub, which handles gnomAD and
745 // hopes for the best for other cases
747 if ("GRCh38".equalsIgnoreCase(seqRef) // Ensembl
748 && vcfAssembly.contains("Homo_sapiens_assembly19")) // gnomAD
756 * Answers true if the species inferred from the VCF reference identifier
757 * matches that for the sequence
763 boolean vcfSpeciesMatchesSequence(String vcfAssembly, String speciesId)
766 // there are many aliases for species - how to equate one with another?
768 // VCF ##reference header is an unstructured URI - how to extract species?
769 // perhaps check if ref includes any (Ensembl) alias of speciesId??
770 // TODO ask the user to confirm this??
772 if (vcfAssembly.contains("Homo_sapiens") // gnomAD exome data example
773 && "HOMO_SAPIENS".equals(speciesId)) // Ensembl species id
778 if (vcfAssembly.contains("c_elegans") // VEP VCF response example
779 && "CAENORHABDITIS_ELEGANS".equals(speciesId)) // Ensembl
784 // this is not a sustainable solution...
790 * Queries the VCF reader for any variants that overlap the mapped chromosome
791 * ranges of the sequence, and adds as variant features. Returns the number of
792 * overlapping variants found.
796 * mapping from sequence to VCF coordinates
799 protected int addVcfVariants(SequenceI seq, VCFMap map)
801 boolean forwardStrand = map.map.isToForwardStrand();
804 * query the VCF for overlaps of each contiguous chromosomal region
808 for (int[] range : map.map.getToRanges())
810 int vcfStart = Math.min(range[0], range[1]);
811 int vcfEnd = Math.max(range[0], range[1]);
812 CloseableIterator<VariantContext> variants = reader
813 .query(map.chromosome, vcfStart, vcfEnd);
814 while (variants.hasNext())
816 VariantContext variant = variants.next();
818 int[] featureRange = map.map.locateInFrom(variant.getStart(),
821 if (featureRange != null)
823 int featureStart = Math.min(featureRange[0], featureRange[1]);
824 int featureEnd = Math.max(featureRange[0], featureRange[1]);
825 count += addAlleleFeatures(seq, variant, featureStart, featureEnd,
836 * A convenience method to get the AF value for the given alternate allele
843 protected float getAlleleFrequency(VariantContext variant, int alleleIndex)
846 String attributeValue = getAttributeValue(variant,
847 ALLELE_FREQUENCY_KEY, alleleIndex);
848 if (attributeValue != null)
852 score = Float.parseFloat(attributeValue);
853 } catch (NumberFormatException e)
863 * A convenience method to get an attribute value for an alternate allele
866 * @param attributeName
870 protected String getAttributeValue(VariantContext variant,
871 String attributeName, int alleleIndex)
873 Object att = variant.getAttribute(attributeName);
875 if (att instanceof String)
879 else if (att instanceof ArrayList)
881 return ((List<String>) att).get(alleleIndex);
888 * Adds one variant feature for each allele in the VCF variant record, and
889 * returns the number of features added.
893 * @param featureStart
895 * @param forwardStrand
898 protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
899 int featureStart, int featureEnd, boolean forwardStrand)
904 * Javadoc says getAlternateAlleles() imposes no order on the list returned
905 * so we proceed defensively to get them in strict order
907 int altAlleleCount = variant.getAlternateAlleles().size();
908 for (int i = 0; i < altAlleleCount; i++)
910 added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
917 * Inspects one allele and attempts to add a variant feature for it to the
918 * sequence. The additional data associated with this allele is extracted to
919 * store in the feature's key-value map. Answers the number of features added (0
924 * @param altAlleleIndex
926 * @param featureStart
928 * @param forwardStrand
931 protected int addAlleleFeature(SequenceI seq, VariantContext variant,
932 int altAlleleIndex, int featureStart, int featureEnd,
933 boolean forwardStrand)
935 String reference = variant.getReference().getBaseString();
936 Allele alt = variant.getAlternateAllele(altAlleleIndex);
937 String allele = alt.getBaseString();
940 * insertion after a genomic base, if on reverse strand, has to be
941 * converted to insertion of complement after the preceding position
943 int referenceLength = reference.length();
944 if (!forwardStrand && allele.length() > referenceLength
945 && allele.startsWith(reference))
947 featureStart -= referenceLength;
948 featureEnd = featureStart;
949 char insertAfter = seq.getCharAt(featureStart - seq.getStart());
950 reference = Dna.reverseComplement(String.valueOf(insertAfter));
951 allele = allele.substring(referenceLength) + reference;
955 * build the ref,alt allele description e.g. "G,A", using the base
956 * complement if the sequence is on the reverse strand
958 StringBuilder sb = new StringBuilder();
959 sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
961 sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
962 String alleles = sb.toString(); // e.g. G,A
965 * pick out the consequence data (if any) that is for the current allele
966 * and feature (transcript) that matches the current sequence
968 String consequence = getConsequenceForAlleleAndFeature(variant, CSQ_FIELD,
969 altAlleleIndex, csqAlleleFieldIndex,
970 csqAlleleNumberFieldIndex, seq.getName().toLowerCase(),
971 csqFeatureFieldIndex);
974 * pick out the ontology term for the consequence type
976 String type = SequenceOntologyI.SEQUENCE_VARIANT;
977 if (consequence != null)
979 type = getOntologyTerm(consequence);
982 float score = getAlleleFrequency(variant, altAlleleIndex);
984 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
985 featureEnd, score, FEATURE_GROUP_VCF);
986 sf.setSource(sourceId);
988 sf.setValue(Gff3Helper.ALLELES, alleles);
990 addAlleleProperties(variant, sf, altAlleleIndex, consequence);
992 seq.addSequenceFeature(sf);
998 * Determines the Sequence Ontology term to use for the variant feature type in
999 * Jalview. The default is 'sequence_variant', but a more specific term is used
1002 * <li>VEP (or SnpEff) Consequence annotation is included in the VCF</li>
1003 * <li>sequence id can be matched to VEP Feature (or SnpEff Feature_ID)</li>
1006 * @param consequence
1008 * @see http://www.sequenceontology.org/browser/current_svn/term/SO:0001060
1010 String getOntologyTerm(String consequence)
1012 String type = SequenceOntologyI.SEQUENCE_VARIANT;
1015 * could we associate Consequence data with this allele and feature (transcript)?
1016 * if so, prefer the consequence term from that data
1018 if (csqAlleleFieldIndex == -1) // && snpEffAlleleFieldIndex == -1
1021 * no Consequence data so we can't refine the ontology term
1026 if (consequence != null)
1028 String[] csqFields = consequence.split(PIPE_REGEX);
1029 if (csqFields.length > csqConsequenceFieldIndex)
1031 type = csqFields[csqConsequenceFieldIndex];
1036 // todo the same for SnpEff consequence data matching if wanted
1040 * if of the form (e.g.) missense_variant&splice_region_variant,
1041 * just take the first ('most severe') consequence
1045 int pos = type.indexOf('&');
1048 type = type.substring(0, pos);
1055 * Returns matched consequence data if it can be found, else null.
1057 * <li>inspects the VCF data for key 'vcfInfoId'</li>
1058 * <li>splits this on comma (to distinct consequences)</li>
1059 * <li>returns the first consequence (if any) where</li>
1061 * <li>the allele matches the altAlleleIndex'th allele of variant</li>
1062 * <li>the feature matches the sequence name (e.g. transcript id)</li>
1065 * If matched, the consequence is returned (as pipe-delimited fields).
1069 * @param altAlleleIndex
1070 * @param alleleFieldIndex
1071 * @param alleleNumberFieldIndex
1073 * @param featureFieldIndex
1076 private String getConsequenceForAlleleAndFeature(VariantContext variant,
1077 String vcfInfoId, int altAlleleIndex, int alleleFieldIndex,
1078 int alleleNumberFieldIndex,
1079 String seqName, int featureFieldIndex)
1081 if (alleleFieldIndex == -1 || featureFieldIndex == -1)
1085 Object value = variant.getAttribute(vcfInfoId);
1087 if (value == null || !(value instanceof List<?>))
1093 * inspect each consequence in turn (comma-separated blocks
1094 * extracted by htsjdk)
1096 List<String> consequences = (List<String>) value;
1098 for (String consequence : consequences)
1100 String[] csqFields = consequence.split(PIPE_REGEX);
1101 if (csqFields.length > featureFieldIndex)
1103 String featureIdentifier = csqFields[featureFieldIndex];
1104 if (featureIdentifier.length() > 4
1105 && seqName.indexOf(featureIdentifier.toLowerCase()) > -1)
1108 * feature (transcript) matched - now check for allele match
1110 if (matchAllele(variant, altAlleleIndex, csqFields,
1111 alleleFieldIndex, alleleNumberFieldIndex))
1121 private boolean matchAllele(VariantContext variant, int altAlleleIndex,
1122 String[] csqFields, int alleleFieldIndex,
1123 int alleleNumberFieldIndex)
1126 * if ALLELE_NUM is present, it must match altAlleleIndex
1127 * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
1129 if (alleleNumberFieldIndex > -1)
1131 if (csqFields.length <= alleleNumberFieldIndex)
1135 String alleleNum = csqFields[alleleNumberFieldIndex];
1136 return String.valueOf(altAlleleIndex + 1).equals(alleleNum);
1140 * else consequence allele must match variant allele
1142 if (alleleFieldIndex > -1 && csqFields.length > alleleFieldIndex)
1144 String csqAllele = csqFields[alleleFieldIndex];
1145 String vcfAllele = variant.getAlternateAllele(altAlleleIndex)
1147 return csqAllele.equals(vcfAllele);
1153 * Add any allele-specific VCF key-value data to the sequence feature
1157 * @param altAlelleIndex
1159 * @param consequence
1160 * if not null, the consequence specific to this sequence (transcript
1161 * feature) and allele
1163 protected void addAlleleProperties(VariantContext variant,
1164 SequenceFeature sf, final int altAlelleIndex, String consequence)
1166 Map<String, Object> atts = variant.getAttributes();
1168 for (Entry<String, Object> att : atts.entrySet())
1170 String key = att.getKey();
1173 * extract Consequence data (if present) that we are able to
1174 * associated with the allele for this variant feature
1176 if (CSQ_FIELD.equals(key))
1178 addConsequences(variant, sf, consequence);
1183 * filter out fields we don't want to capture
1185 if (!vcfFieldsOfInterest.contains(key))
1191 * we extract values for other data which are allele-specific;
1192 * these may be per alternate allele (INFO[key].Number = 'A')
1193 * or per allele including reference (INFO[key].Number = 'R')
1195 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
1196 if (infoHeader == null)
1199 * can't be sure what data belongs to this allele, so
1200 * play safe and don't take any
1205 VCFHeaderLineCount number = infoHeader.getCountType();
1206 int index = altAlelleIndex;
1207 if (number == VCFHeaderLineCount.R)
1210 * one value per allele including reference, so bump index
1211 * e.g. the 3rd value is for the 2nd alternate allele
1215 else if (number != VCFHeaderLineCount.A)
1218 * don't save other values as not allele-related
1224 * take the index'th value
1226 String value = getAttributeValue(variant, key, index);
1229 sf.setValue(key, value);
1235 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
1238 * If <code>myConsequence</code> is not null, then this is the specific
1239 * consequence data (pipe-delimited fields) that is for the current allele and
1240 * transcript (sequence) being processed)
1244 * @param myConsequence
1246 protected void addConsequences(VariantContext variant, SequenceFeature sf,
1247 String myConsequence)
1249 Object value = variant.getAttribute(CSQ_FIELD);
1251 if (value == null || !(value instanceof List<?>))
1256 List<String> consequences = (List<String>) value;
1259 * inspect CSQ consequences; restrict to the consequence
1260 * associated with the current transcript (Feature)
1262 Map<String, String> csqValues = new HashMap<>();
1264 for (String consequence : consequences)
1266 if (myConsequence == null || myConsequence.equals(consequence))
1268 String[] csqFields = consequence.split(PIPE_REGEX);
1271 * inspect individual fields of this consequence, copying non-null
1272 * values which are 'fields of interest'
1275 for (String field : csqFields)
1277 if (field != null && field.length() > 0)
1279 String id = vepFieldsOfInterest.get(i);
1282 csqValues.put(id, field);
1290 if (!csqValues.isEmpty())
1292 sf.setValue(CSQ_FIELD, csqValues);
1297 * A convenience method to complement a dna base and return the string value
1303 protected String complement(byte[] reference)
1305 return String.valueOf(Dna.getComplement((char) reference[0]));
1309 * Determines the location of the query range (chromosome positions) in a
1310 * different reference assembly.
1312 * If the range is just a subregion of one for which we already have a mapping
1313 * (for example, an exon sub-region of a gene), then the mapping is just
1314 * computed arithmetically.
1316 * Otherwise, calls the Ensembl REST service that maps from one assembly
1317 * reference's coordinates to another's
1320 * start-end chromosomal range in 'fromRef' coordinates
1324 * assembly reference for the query coordinates
1326 * assembly reference we wish to translate to
1327 * @return the start-end range in 'toRef' coordinates
1329 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
1330 String species, String fromRef, String toRef)
1333 * first try shorcut of computing the mapping as a subregion of one
1334 * we already have (e.g. for an exon, if we have the gene mapping)
1336 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
1337 species, fromRef, toRef);
1338 if (mappedRange != null)
1344 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
1346 EnsemblMap mapper = new EnsemblMap();
1347 int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
1350 if (mapping == null)
1352 // mapping service failure
1357 * save mapping for possible future re-use
1359 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1360 if (!assemblyMappings.containsKey(key))
1362 assemblyMappings.put(key, new HashMap<int[], int[]>());
1365 assemblyMappings.get(key).put(queryRange, mapping);
1371 * If we already have a 1:1 contiguous mapping which subsumes the given query
1372 * range, this method just calculates and returns the subset of that mapping,
1373 * else it returns null. In practical terms, if a gene has a contiguous
1374 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
1375 * subsidiary exons occupy unchanged relative positions, and just compute
1376 * these as offsets, rather than do another lookup of the mapping.
1378 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
1379 * simply remove this method or let it always return null.
1381 * Warning: many rapid calls to the /map service map result in a 429 overload
1391 protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
1392 String species, String fromRef, String toRef)
1394 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1395 if (assemblyMappings.containsKey(key))
1397 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
1398 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
1400 int[] fromRange = mappedRange.getKey();
1401 int[] toRange = mappedRange.getValue();
1402 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
1405 * mapping is 1:1 in length, so we trust it to have no discontinuities
1407 if (MappingUtils.rangeContains(fromRange, queryRange))
1410 * fromRange subsumes our query range
1412 int offset = queryRange[0] - fromRange[0];
1413 int mappedRangeFrom = toRange[0] + offset;
1414 int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
1415 return new int[] { mappedRangeFrom, mappedRangeTo };
1424 * Transfers the sequence feature to the target sequence, locating its start
1425 * and end range based on the mapping. Features which do not overlap the
1426 * target sequence are ignored.
1429 * @param targetSequence
1431 * mapping from the feature's coordinates to the target sequence
1433 protected void transferFeature(SequenceFeature sf,
1434 SequenceI targetSequence, MapList mapping)
1436 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1438 if (mappedRange != null)
1440 String group = sf.getFeatureGroup();
1441 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1442 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1443 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1444 group, sf.getScore());
1445 targetSequence.addSequenceFeature(copy);
1450 * Formats a ranges map lookup key
1458 protected static String makeRangesKey(String chromosome, String species,
1459 String fromRef, String toRef)
1461 return species + EXCL + chromosome + EXCL + fromRef + EXCL