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.util.CloseableIterator;
34 import htsjdk.variant.variantcontext.Allele;
35 import htsjdk.variant.variantcontext.VariantContext;
36 import htsjdk.variant.vcf.VCFHeader;
37 import htsjdk.variant.vcf.VCFHeaderLine;
38 import htsjdk.variant.vcf.VCFHeaderLineCount;
39 import htsjdk.variant.vcf.VCFHeaderLineType;
40 import htsjdk.variant.vcf.VCFInfoHeaderLine;
43 * A class to read VCF data (using the htsjdk) and add variants as sequence
44 * features on dna and any related protein product sequences
48 public class VCFLoader
51 * Lookup keys, and default values, for Preference entries that describe
52 * patterns for VCF and VEP fields to capture
54 private static final String VEP_FIELDS_PREF = "VEP_FIELDS";
56 private static final String VCF_FIELDS_PREF = "VCF_FIELDS";
58 private static final String DEFAULT_VCF_FIELDS = "AF,AC*";
60 private static final String DEFAULT_VEP_FIELDS = ".*";// "Allele,Consequence,IMPACT,SWISSPROT,SIFT,PolyPhen,CLIN_SIG";
63 * keys to fields of VEP CSQ consequence data
64 * see https://www.ensembl.org/info/docs/tools/vep/vep_formats.html
66 private static final String ALLELE_KEY = "Allele";
68 private static final String ALLELE_NUM_KEY = "ALLELE_NUM"; // 0 (ref), 1...
69 private static final String FEATURE_KEY = "Feature"; // Ensembl stable id
72 * default VCF INFO key for VEP consequence data
73 * NB this can be overridden running VEP with --vcf_info_field
74 * - we don't handle this case (require identifier to be CSQ)
76 private static final String CSQ_FIELD = "CSQ";
79 * separator for fields in consequence data is '|'
81 private static final String PIPE_REGEX = "\\|";
84 * key for Allele Frequency output by VEP
85 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
87 private static final String ALLELE_FREQUENCY_KEY = "AF";
90 * delimiter that separates multiple consequence data blocks
92 private static final String COMMA = ",";
95 * the feature group assigned to a VCF variant in Jalview
97 private static final String FEATURE_GROUP_VCF = "VCF";
100 * internal delimiter used to build keys for assemblyMappings
103 private static final String EXCL = "!";
106 * the alignment we are associating VCF data with
108 private AlignmentI al;
111 * mappings between VCF and sequence reference assembly regions, as
112 * key = "species!chromosome!fromAssembly!toAssembly
113 * value = Map{fromRange, toRange}
115 private Map<String, Map<int[], int[]>> assemblyMappings;
118 * holds details of the VCF header lines (metadata)
120 private VCFHeader header;
123 * the position (0...) of field in each block of
124 * CSQ (consequence) data (if declared in the VCF INFO header for CSQ)
125 * see http://www.ensembl.org/info/docs/tools/vep/vep_formats.html
127 private int csqAlleleFieldIndex = -1;
128 private int csqAlleleNumberFieldIndex = -1;
129 private int csqFeatureFieldIndex = -1;
132 * a unique identifier under which to save metadata about feature
133 * attributes (selected INFO field data)
135 private String sourceId;
138 * The INFO IDs of data that is both present in the VCF file, and
139 * also matched by any filters for data of interest
141 List<String> vcfFieldsOfInterest;
144 * The field offsets and identifiers for VEP (CSQ) data that is both present
145 * in the VCF file, and also matched by any filters for data of interest
146 * for example 0 -> Allele, 1 -> Consequence, ..., 36 -> SIFT, ...
148 Map<Integer, String> vepFieldsOfInterest;
151 * Constructor given an alignment context
155 public VCFLoader(AlignmentI alignment)
159 // map of species!chromosome!fromAssembly!toAssembly to {fromRange, toRange}
160 assemblyMappings = new HashMap<>();
164 * Starts a new thread to query and load VCF variant data on to the alignment
166 * This method is not thread safe - concurrent threads should use separate
167 * instances of this class.
172 public void loadVCF(final String filePath,
173 final AlignViewControllerGuiI gui)
177 gui.setStatus(MessageManager.getString("label.searching_vcf"));
186 VCFLoader.this.doLoad(filePath, gui);
193 * Loads VCF on to an alignment - provided it can be related to one or more
194 * sequence's chromosomal coordinates
198 * optional callback handler for messages
200 protected void doLoad(String filePath, AlignViewControllerGuiI gui)
202 VCFReader reader = null;
205 // long start = System.currentTimeMillis();
206 reader = new VCFReader(filePath);
208 header = reader.getFileHeader();
212 saveMetadata(sourceId);
215 * get offset of CSQ ALLELE_NUM and Feature if declared
219 VCFHeaderLine ref = header
220 .getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
221 String vcfAssembly = ref.getValue();
227 * query for VCF overlapping each sequence in turn
229 for (SequenceI seq : al.getSequences())
231 int added = loadSequenceVCF(seq, reader, vcfAssembly);
236 transferAddedFeatures(seq);
241 // long elapsed = System.currentTimeMillis() - start;
242 String msg = MessageManager.formatMessage("label.added_vcf",
245 if (gui.getFeatureSettingsUI() != null)
247 gui.getFeatureSettingsUI().discoverAllFeatureData();
250 } catch (Throwable e)
252 System.err.println("Error processing VCF: " + e.getMessage());
256 gui.setStatus("Error occurred - see console for details");
265 } catch (IOException e)
274 * Reads metadata (such as INFO field descriptions and datatypes) and saves
275 * them for future reference
279 void saveMetadata(String theSourceId)
281 List<Pattern> vcfFieldPatterns = getFieldMatchers(VCF_FIELDS_PREF,
283 vcfFieldsOfInterest = new ArrayList<>();
285 FeatureSource metadata = new FeatureSource(theSourceId);
287 for (VCFInfoHeaderLine info : header.getInfoHeaderLines())
289 String attributeId = info.getID();
290 String desc = info.getDescription();
291 VCFHeaderLineType type = info.getType();
292 FeatureAttributeType attType = null;
296 attType = FeatureAttributeType.Character;
299 attType = FeatureAttributeType.Flag;
302 attType = FeatureAttributeType.Float;
305 attType = FeatureAttributeType.Integer;
308 attType = FeatureAttributeType.String;
311 metadata.setAttributeName(attributeId, desc);
312 metadata.setAttributeType(attributeId, attType);
314 if (isFieldWanted(attributeId, vcfFieldPatterns))
316 vcfFieldsOfInterest.add(attributeId);
320 FeatureSources.getInstance().addSource(theSourceId, metadata);
324 * Answers true if the field id is matched by any of the filter patterns, else
325 * false. Matching is against regular expression patterns, and is not
332 private boolean isFieldWanted(String id, List<Pattern> filters)
334 for (Pattern p : filters)
336 if (p.matcher(id.toUpperCase()).matches())
345 * Records 'wanted' fields defined in the CSQ INFO header (if there is one).
346 * Also records the position of selected fields (Allele, ALLELE_NUM, Feature)
347 * required for processing.
349 * CSQ fields are declared in the CSQ INFO Description e.g.
351 * Description="Consequence ...from ... VEP. Format: Allele|Consequence|...
353 protected void parseCsqHeader()
355 List<Pattern> vepFieldFilters = getFieldMatchers(VEP_FIELDS_PREF,
357 vepFieldsOfInterest = new HashMap<>();
359 VCFInfoHeaderLine csqInfo = header.getInfoHeaderLine(CSQ_FIELD);
366 * parse out the pipe-separated list of CSQ fields; we assume here that
367 * these form the last part of the description, and contain no spaces
369 String desc = csqInfo.getDescription();
370 int spacePos = desc.lastIndexOf(" ");
371 desc = desc.substring(spacePos + 1);
375 String[] format = desc.split(PIPE_REGEX);
377 for (String field : format)
379 if (ALLELE_NUM_KEY.equals(field))
381 csqAlleleNumberFieldIndex = index;
383 if (ALLELE_KEY.equals(field))
385 csqAlleleFieldIndex = index;
387 if (FEATURE_KEY.equals(field))
389 csqFeatureFieldIndex = index;
392 if (isFieldWanted(field, vepFieldFilters))
394 vepFieldsOfInterest.put(index, field);
403 * Reads the Preference value for the given key, with default specified if no
404 * preference set. The value is interpreted as a comma-separated list of
405 * regular expressions, and converted into a list of compiled patterns ready
406 * for matching. Patterns are forced to upper-case for non-case-sensitive
409 * This supports user-defined filters for fields of interest to capture while
410 * processing data. For example, VCF_FIELDS = AF,AC* would mean that VCF INFO
411 * fields with an ID of AF, or starting with AC, would be matched.
417 private List<Pattern> getFieldMatchers(String key, String def)
419 String pref = Cache.getDefault(key, def);
420 List<Pattern> patterns = new ArrayList<>();
421 String[] tokens = pref.split(",");
422 for (String token : tokens)
426 patterns.add(Pattern.compile(token.toUpperCase()));
427 } catch (PatternSyntaxException e)
429 System.err.println("Invalid pattern ignored: " + token);
436 * Transfers VCF features to sequences to which this sequence has a mapping.
437 * If the mapping is 3:1, computes peptide variants from nucleotide variants.
441 protected void transferAddedFeatures(SequenceI seq)
443 DBRefEntry[] dbrefs = seq.getDBRefs();
448 for (DBRefEntry dbref : dbrefs)
450 Mapping mapping = dbref.getMap();
451 if (mapping == null || mapping.getTo() == null)
456 SequenceI mapTo = mapping.getTo();
457 MapList map = mapping.getMap();
458 if (map.getFromRatio() == 3)
461 * dna-to-peptide product mapping
463 AlignmentUtils.computeProteinFeatures(seq, mapTo, map);
468 * nucleotide-to-nucleotide mapping e.g. transcript to CDS
470 List<SequenceFeature> features = seq.getFeatures()
471 .getPositionalFeatures(SequenceOntologyI.SEQUENCE_VARIANT);
472 for (SequenceFeature sf : features)
474 if (FEATURE_GROUP_VCF.equals(sf.getFeatureGroup()))
476 transferFeature(sf, mapTo, map);
484 * Tries to add overlapping variants read from a VCF file to the given
485 * sequence, and returns the number of variant features added. Note that this
486 * requires the sequence to hold information as to its species, chromosomal
487 * positions and reference assembly, in order to be able to map the VCF
488 * variants to the sequence (or not)
495 protected int loadSequenceVCF(SequenceI seq, VCFReader reader,
499 GeneLociI seqCoords = seq.getGeneLoci();
500 if (seqCoords == null)
502 System.out.println(String.format(
503 "Can't query VCF for %s as chromosome coordinates not known",
508 if (!vcfSpeciesMatchesSequence(vcfAssembly, seqCoords.getSpeciesId()))
513 List<int[]> seqChromosomalContigs = seqCoords.getMap().getToRanges();
514 for (int[] range : seqChromosomalContigs)
516 count += addVcfVariants(seq, reader, range, vcfAssembly);
523 * Answers true if the species inferred from the VCF reference identifier
524 * matches that for the sequence
530 boolean vcfSpeciesMatchesSequence(String vcfAssembly, String speciesId)
533 // there are many aliases for species - how to equate one with another?
535 // VCF ##reference header is an unstructured URI - how to extract species?
536 // perhaps check if ref includes any (Ensembl) alias of speciesId??
537 // TODO ask the user to confirm this??
539 if (vcfAssembly.contains("Homo_sapiens") // gnomAD exome data example
540 && "HOMO_SAPIENS".equals(speciesId)) // Ensembl species id
545 if (vcfAssembly.contains("c_elegans") // VEP VCF response example
546 && "CAENORHABDITIS_ELEGANS".equals(speciesId)) // Ensembl
551 // this is not a sustainable solution...
557 * Queries the VCF reader for any variants that overlap the given chromosome
558 * region of the sequence, and adds as variant features. Returns the number of
559 * overlapping variants found.
564 * start-end range of a sequence region in its chromosomal
567 * the '##reference' identifier for the VCF reference assembly
570 protected int addVcfVariants(SequenceI seq, VCFReader reader,
571 int[] range, String vcfAssembly)
573 GeneLociI seqCoords = seq.getGeneLoci();
575 String chromosome = seqCoords.getChromosomeId();
576 String seqRef = seqCoords.getAssemblyId();
577 String species = seqCoords.getSpeciesId();
580 * map chromosomal coordinates from sequence to VCF if the VCF
581 * data has a different reference assembly to the sequence
583 // TODO generalise for non-human species
584 // - or get the user to choose in a dialog
587 if ("GRCh38".equalsIgnoreCase(seqRef) // Ensembl
588 && vcfAssembly.contains("Homo_sapiens_assembly19")) // gnomAD
590 String toRef = "GRCh37";
591 int[] newRange = mapReferenceRange(range, chromosome, "human",
593 if (newRange == null)
595 System.err.println(String.format(
596 "Failed to map %s:%s:%s:%d:%d to %s", species, chromosome,
597 seqRef, range[0], range[1], toRef));
600 offset = newRange[0] - range[0];
604 boolean forwardStrand = range[0] <= range[1];
607 * query the VCF for overlaps
608 * (convert a reverse strand range to forwards)
611 MapList mapping = seqCoords.getMap();
613 int fromLocus = Math.min(range[0], range[1]);
614 int toLocus = Math.max(range[0], range[1]);
615 CloseableIterator<VariantContext> variants = reader.query(chromosome,
617 while (variants.hasNext())
620 * get variant location in sequence chromosomal coordinates
622 VariantContext variant = variants.next();
624 int start = variant.getStart() - offset;
625 int end = variant.getEnd() - offset;
628 * convert chromosomal location to sequence coordinates
629 * - may be reverse strand (convert to forward for sequence feature)
630 * - null if a partially overlapping feature
632 int[] seqLocation = mapping.locateInFrom(start, end);
633 if (seqLocation != null)
635 int featureStart = Math.min(seqLocation[0], seqLocation[1]);
636 int featureEnd = Math.max(seqLocation[0], seqLocation[1]);
637 count += addAlleleFeatures(seq, variant, featureStart, featureEnd,
648 * A convenience method to get the AF value for the given alternate allele
655 protected float getAlleleFrequency(VariantContext variant, int alleleIndex)
658 String attributeValue = getAttributeValue(variant,
659 ALLELE_FREQUENCY_KEY, alleleIndex);
660 if (attributeValue != null)
664 score = Float.parseFloat(attributeValue);
665 } catch (NumberFormatException e)
675 * A convenience method to get an attribute value for an alternate allele
678 * @param attributeName
682 protected String getAttributeValue(VariantContext variant,
683 String attributeName, int alleleIndex)
685 Object att = variant.getAttribute(attributeName);
687 if (att instanceof String)
691 else if (att instanceof ArrayList)
693 return ((List<String>) att).get(alleleIndex);
700 * Adds one variant feature for each allele in the VCF variant record, and
701 * returns the number of features added.
705 * @param featureStart
707 * @param forwardStrand
710 protected int addAlleleFeatures(SequenceI seq, VariantContext variant,
711 int featureStart, int featureEnd, boolean forwardStrand)
716 * Javadoc says getAlternateAlleles() imposes no order on the list returned
717 * so we proceed defensively to get them in strict order
719 int altAlleleCount = variant.getAlternateAlleles().size();
720 for (int i = 0; i < altAlleleCount; i++)
722 added += addAlleleFeature(seq, variant, i, featureStart, featureEnd,
729 * Inspects one allele and attempts to add a variant feature for it to the
730 * sequence. We extract as much as possible of the additional data associated
731 * with this allele to store in the feature's key-value map. Answers the
732 * number of features added (0 or 1).
736 * @param altAlleleIndex
738 * @param featureStart
740 * @param forwardStrand
743 protected int addAlleleFeature(SequenceI seq, VariantContext variant,
744 int altAlleleIndex, int featureStart, int featureEnd,
745 boolean forwardStrand)
747 String reference = variant.getReference().getBaseString();
748 Allele alt = variant.getAlternateAllele(altAlleleIndex);
749 String allele = alt.getBaseString();
752 * build the ref,alt allele description e.g. "G,A", using the base
753 * complement if the sequence is on the reverse strand
755 // TODO check how structural variants are shown on reverse strand
756 StringBuilder sb = new StringBuilder();
757 sb.append(forwardStrand ? reference : Dna.reverseComplement(reference));
759 sb.append(forwardStrand ? allele : Dna.reverseComplement(allele));
760 String alleles = sb.toString(); // e.g. G,A
762 String type = SequenceOntologyI.SEQUENCE_VARIANT;
763 float score = getAlleleFrequency(variant, altAlleleIndex);
765 SequenceFeature sf = new SequenceFeature(type, alleles, featureStart,
766 featureEnd, score, FEATURE_GROUP_VCF);
767 sf.setSource(sourceId);
769 sf.setValue(Gff3Helper.ALLELES, alleles);
771 addAlleleProperties(variant, seq, sf, altAlleleIndex);
773 seq.addSequenceFeature(sf);
779 * Add any allele-specific VCF key-value data to the sequence feature
784 * @param altAlelleIndex
787 protected void addAlleleProperties(VariantContext variant, SequenceI seq,
788 SequenceFeature sf, final int altAlelleIndex)
790 Map<String, Object> atts = variant.getAttributes();
792 for (Entry<String, Object> att : atts.entrySet())
794 String key = att.getKey();
797 * extract Consequence data (if present) that we are able to
798 * associated with the allele for this variant feature
800 if (CSQ_FIELD.equals(key))
802 addConsequences(variant, seq, sf, altAlelleIndex);
807 * filter out fields we don't want to capture
809 if (!vcfFieldsOfInterest.contains(key))
815 * we extract values for other data which are allele-specific;
816 * these may be per alternate allele (INFO[key].Number = 'A')
817 * or per allele including reference (INFO[key].Number = 'R')
819 VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(key);
820 if (infoHeader == null)
823 * can't be sure what data belongs to this allele, so
824 * play safe and don't take any
829 VCFHeaderLineCount number = infoHeader.getCountType();
830 int index = altAlelleIndex;
831 if (number == VCFHeaderLineCount.R)
834 * one value per allele including reference, so bump index
835 * e.g. the 3rd value is for the 2nd alternate allele
839 else if (number != VCFHeaderLineCount.A)
842 * don't save other values as not allele-related
848 * take the index'th value
850 String value = getAttributeValue(variant, key, index);
853 sf.setValue(key, value);
859 * Inspects CSQ data blocks (consequences) and adds attributes on the sequence
860 * feature for the current allele (and transcript if applicable)
862 * Allele matching: if field ALLELE_NUM is present, it must match
863 * altAlleleIndex. If not present, then field Allele value must match the VCF
866 * Transcript matching: if sequence name can be identified to at least one of
867 * the consequences' Feature values, then select only consequences that match
868 * the value (i.e. consequences for the current transcript sequence). If not,
869 * take all consequences (this is the case when adding features to the gene
875 * @param altAlelleIndex
878 protected void addConsequences(VariantContext variant, SequenceI seq,
879 SequenceFeature sf, int altAlelleIndex)
881 Object value = variant.getAttribute(CSQ_FIELD);
883 if (value == null || !(value instanceof ArrayList<?>))
888 List<String> consequences = (List<String>) value;
891 * if CSQ data includes 'Feature', and any value matches the sequence name,
892 * then restrict consequence data to only the matching value (transcript)
893 * i.e. just pick out consequences for the transcript the variant feature is on
895 String seqName = seq.getName()== null ? "" : seq.getName().toLowerCase();
896 String matchFeature = null;
897 if (csqFeatureFieldIndex > -1)
899 for (String consequence : consequences)
901 String[] csqFields = consequence.split(PIPE_REGEX);
902 if (csqFields.length > csqFeatureFieldIndex)
904 String featureIdentifier = csqFields[csqFeatureFieldIndex];
905 if (featureIdentifier.length() > 4
906 && seqName.indexOf(featureIdentifier.toLowerCase()) > -1)
908 matchFeature = featureIdentifier;
915 * inspect CSQ consequences; where possible restrict to the consequence
916 * associated with the current transcript (Feature)
918 Map<String, String> csqValues = new HashMap<>();
920 for (String consequence : consequences)
922 String[] csqFields = consequence.split(PIPE_REGEX);
924 if (includeConsequence(csqFields, matchFeature, variant,
928 * inspect individual fields of this consequence, copying non-null
929 * values which are 'fields of interest'
932 for (String field : csqFields)
934 if (field != null && field.length() > 0)
936 String id = vepFieldsOfInterest.get(i);
939 csqValues.put(id, field);
947 if (!csqValues.isEmpty())
949 sf.setValue(CSQ_FIELD, csqValues);
954 * Answers true if we want to associate this block of consequence data with
955 * the specified alternate allele of the VCF variant.
957 * If consequence data includes the ALLELE_NUM field, then this has to match
958 * altAlleleIndex. Otherwise the Allele field of the consequence data has to
959 * match the allele value.
961 * Optionally (if matchFeature is not null), restrict to only include
962 * consequences whose Feature value matches. This allows us to attach
963 * consequences to their respective transcripts.
966 * @param matchFeature
968 * @param altAlelleIndex
972 protected boolean includeConsequence(String[] csqFields,
973 String matchFeature, VariantContext variant, int altAlelleIndex)
976 * check consequence is for the current transcript
978 if (matchFeature != null)
980 if (csqFields.length <= csqFeatureFieldIndex)
984 String featureIdentifier = csqFields[csqFeatureFieldIndex];
985 if (!featureIdentifier.equals(matchFeature))
987 return false; // consequence is for a different transcript
992 * if ALLELE_NUM is present, it must match altAlleleIndex
993 * NB first alternate allele is 1 for ALLELE_NUM, 0 for altAlleleIndex
995 if (csqAlleleNumberFieldIndex > -1)
997 if (csqFields.length <= csqAlleleNumberFieldIndex)
1001 String alleleNum = csqFields[csqAlleleNumberFieldIndex];
1002 return String.valueOf(altAlelleIndex + 1).equals(alleleNum);
1006 * else consequence allele must match variant allele
1008 if (csqAlleleFieldIndex > -1 && csqFields.length > csqAlleleFieldIndex)
1010 String csqAllele = csqFields[csqAlleleFieldIndex];
1011 String vcfAllele = variant.getAlternateAllele(altAlelleIndex)
1013 return csqAllele.equals(vcfAllele);
1020 * A convenience method to complement a dna base and return the string value
1026 protected String complement(byte[] reference)
1028 return String.valueOf(Dna.getComplement((char) reference[0]));
1032 * Determines the location of the query range (chromosome positions) in a
1033 * different reference assembly.
1035 * If the range is just a subregion of one for which we already have a mapping
1036 * (for example, an exon sub-region of a gene), then the mapping is just
1037 * computed arithmetically.
1039 * Otherwise, calls the Ensembl REST service that maps from one assembly
1040 * reference's coordinates to another's
1043 * start-end chromosomal range in 'fromRef' coordinates
1047 * assembly reference for the query coordinates
1049 * assembly reference we wish to translate to
1050 * @return the start-end range in 'toRef' coordinates
1052 protected int[] mapReferenceRange(int[] queryRange, String chromosome,
1053 String species, String fromRef, String toRef)
1056 * first try shorcut of computing the mapping as a subregion of one
1057 * we already have (e.g. for an exon, if we have the gene mapping)
1059 int[] mappedRange = findSubsumedRangeMapping(queryRange, chromosome,
1060 species, fromRef, toRef);
1061 if (mappedRange != null)
1067 * call (e.g.) http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37
1069 EnsemblMap mapper = new EnsemblMap();
1070 int[] mapping = mapper.getAssemblyMapping(species, chromosome, fromRef,
1073 if (mapping == null)
1075 // mapping service failure
1080 * save mapping for possible future re-use
1082 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1083 if (!assemblyMappings.containsKey(key))
1085 assemblyMappings.put(key, new HashMap<int[], int[]>());
1088 assemblyMappings.get(key).put(queryRange, mapping);
1094 * If we already have a 1:1 contiguous mapping which subsumes the given query
1095 * range, this method just calculates and returns the subset of that mapping,
1096 * else it returns null. In practical terms, if a gene has a contiguous
1097 * mapping between (for example) GRCh37 and GRCh38, then we assume that its
1098 * subsidiary exons occupy unchanged relative positions, and just compute
1099 * these as offsets, rather than do another lookup of the mapping.
1101 * If in future these assumptions prove invalid (e.g. for bacterial dna?!),
1102 * simply remove this method or let it always return null.
1104 * Warning: many rapid calls to the /map service map result in a 429 overload
1114 protected int[] findSubsumedRangeMapping(int[] queryRange, String chromosome,
1115 String species, String fromRef, String toRef)
1117 String key = makeRangesKey(chromosome, species, fromRef, toRef);
1118 if (assemblyMappings.containsKey(key))
1120 Map<int[], int[]> mappedRanges = assemblyMappings.get(key);
1121 for (Entry<int[], int[]> mappedRange : mappedRanges.entrySet())
1123 int[] fromRange = mappedRange.getKey();
1124 int[] toRange = mappedRange.getValue();
1125 if (fromRange[1] - fromRange[0] == toRange[1] - toRange[0])
1128 * mapping is 1:1 in length, so we trust it to have no discontinuities
1130 if (MappingUtils.rangeContains(fromRange, queryRange))
1133 * fromRange subsumes our query range
1135 int offset = queryRange[0] - fromRange[0];
1136 int mappedRangeFrom = toRange[0] + offset;
1137 int mappedRangeTo = mappedRangeFrom + (queryRange[1] - queryRange[0]);
1138 return new int[] { mappedRangeFrom, mappedRangeTo };
1147 * Transfers the sequence feature to the target sequence, locating its start
1148 * and end range based on the mapping. Features which do not overlap the
1149 * target sequence are ignored.
1152 * @param targetSequence
1154 * mapping from the feature's coordinates to the target sequence
1156 protected void transferFeature(SequenceFeature sf,
1157 SequenceI targetSequence, MapList mapping)
1159 int[] mappedRange = mapping.locateInTo(sf.getBegin(), sf.getEnd());
1161 if (mappedRange != null)
1163 String group = sf.getFeatureGroup();
1164 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
1165 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
1166 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1167 group, sf.getScore());
1168 targetSequence.addSequenceFeature(copy);
1173 * Formats a ranges map lookup key
1181 protected static String makeRangesKey(String chromosome, String species,
1182 String fromRef, String toRef)
1184 return species + EXCL + chromosome + EXCL + fromRef + EXCL