1 package jalview.ext.ensembl;
3 import jalview.datamodel.Alignment;
4 import jalview.datamodel.AlignmentI;
5 import jalview.datamodel.DBRefEntry;
6 import jalview.datamodel.DBRefSource;
7 import jalview.datamodel.Mapping;
8 import jalview.datamodel.SequenceFeature;
9 import jalview.datamodel.SequenceI;
10 import jalview.exceptions.JalviewException;
11 import jalview.io.FastaFile;
12 import jalview.io.FileParse;
13 import jalview.io.gff.SequenceOntology;
14 import jalview.schemes.ResidueProperties;
15 import jalview.util.DBRefUtils;
16 import jalview.util.MapList;
17 import jalview.util.MappingUtils;
18 import jalview.util.StringUtils;
20 import java.io.IOException;
21 import java.net.MalformedURLException;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collections;
26 import java.util.Comparator;
27 import java.util.LinkedHashMap;
28 import java.util.List;
29 import java.util.Map.Entry;
32 * Base class for Ensembl sequence fetchers
36 public abstract class EnsemblSeqProxy extends EnsemblRestClient
38 protected static final String CONSEQUENCE_TYPE = "consequence_type";
40 protected static final String PARENT = "Parent";
42 protected static final String ID = "ID";
45 * this needs special handling, as it isA sequence_variant in the
46 * Sequence Ontology, but behaves in Ensembl as if it isA transcript
48 protected static final String NMD_VARIANT = "NMD_transcript_variant";
50 protected static final String NAME = "Name";
52 public enum EnsemblSeqType
55 * type=genomic for the full dna including introns
60 * type=cdna for transcribed dna including UTRs
65 * type=cds for coding dna excluding UTRs
70 * type=protein for the peptide product sequence
75 * the value of the 'type' parameter to fetch this version of
80 EnsemblSeqType(String t)
85 public String getType()
93 * A comparator to sort ranges into ascending start position order
95 private class RangeSorter implements Comparator<int[]>
99 RangeSorter(boolean forward)
105 public int compare(int[] o1, int[] o2)
107 return (forwards ? 1 : -1) * Integer.compare(o1[0], o2[0]);
115 public EnsemblSeqProxy()
120 * Makes the sequence queries to Ensembl's REST service and returns an
121 * alignment consisting of the returned sequences.
124 public AlignmentI getSequenceRecords(String query) throws Exception
126 long now = System.currentTimeMillis();
127 // TODO use a String... query vararg instead?
129 // danger: accession separator used as a regex here, a string elsewhere
130 // in this case it is ok (it is just a space), but (e.g.) '\' would not be
131 List<String> allIds = Arrays.asList(query
132 .split(getAccessionSeparator()));
133 AlignmentI alignment = null;
137 * execute queries, if necessary in batches of the
138 * maximum allowed number of ids
140 int maxQueryCount = getMaximumQueryCount();
141 for (int v = 0, vSize = allIds.size(); v < vSize; v += maxQueryCount)
143 int p = Math.min(vSize, v + maxQueryCount);
144 List<String> ids = allIds.subList(v, p);
147 alignment = fetchSequences(ids, alignment);
148 } catch (Throwable r)
151 String msg = "Aborting ID retrieval after " + v
152 + " chunks. Unexpected problem (" + r.getLocalizedMessage()
154 System.err.println(msg);
155 if (alignment != null)
157 break; // return what we got
161 throw new JalviewException(msg, r);
167 * fetch and transfer genomic sequence features,
168 * fetch protein product and add as cross-reference
170 for (String accId : allIds)
172 addFeaturesAndProduct(accId, alignment);
176 System.out.println(getClass().getName() + " took "
177 + (System.currentTimeMillis() - now) + "ms to fetch");
182 * Fetches Ensembl features using the /overlap REST endpoint, and adds them to
183 * the sequence in the alignment. Also fetches the protein product, maps it
184 * from the CDS features of the sequence, and saves it as a cross-reference of
190 protected void addFeaturesAndProduct(String accId, AlignmentI alignment)
192 if (alignment == null)
200 * get 'dummy' genomic sequence with exon, cds and variation features
202 SequenceI genomicSequence = null;
203 EnsemblOverlap gffFetcher = new EnsemblOverlap();
204 EnsemblFeatureType[] features = getFeaturesToFetch();
205 AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
207 if (geneFeatures.getHeight() > 0)
209 genomicSequence = geneFeatures.getSequenceAt(0);
211 if (genomicSequence != null)
214 * transfer features to the query sequence
216 SequenceI querySeq = alignment.findName(accId);
217 if (transferFeatures(accId, genomicSequence, querySeq))
221 * fetch and map protein product, and add it as a cross-reference
222 * of the retrieved sequence
224 addProteinProduct(querySeq);
227 } catch (IOException e)
229 System.err.println("Error transferring Ensembl features: "
235 * Returns those sequence feature types to fetch from Ensembl. We may want
236 * features either because they are of interest to the user, or as means to
237 * identify the locations of the sequence on the genomic sequence (CDS
238 * features identify CDS, exon features identify cDNA etc).
242 protected abstract EnsemblFeatureType[] getFeaturesToFetch();
245 * Fetches and maps the protein product, and adds it as a cross-reference of
246 * the retrieved sequence
248 protected void addProteinProduct(SequenceI querySeq)
250 String accId = querySeq.getName();
253 AlignmentI protein = new EnsemblProtein().getSequenceRecords(accId);
254 if (protein == null || protein.getHeight() == 0)
256 System.out.println("Failed to retrieve protein for " + accId);
259 SequenceI proteinSeq = protein.getSequenceAt(0);
262 * need dataset sequences (to be the subject of mappings)
264 proteinSeq.createDatasetSequence();
265 querySeq.createDatasetSequence();
267 MapList mapList = mapCdsToProtein(querySeq, proteinSeq);
270 Mapping map = new Mapping(proteinSeq.getDatasetSequence(), mapList);
271 DBRefEntry dbr = new DBRefEntry(getDbSource(), getDbVersion(),
273 querySeq.getDatasetSequence().addDBRef(dbr);
276 * compute peptide variants from dna variants and add as
277 * sequence features on the protein sequence ta-da
279 computeProteinFeatures(querySeq, proteinSeq, mapList);
281 } catch (Exception e)
284 .println(String.format("Error retrieving protein for %s: %s",
285 accId, e.getMessage()));
290 * Returns a mapping from dna to protein by inspecting sequence features of
291 * type "CDS" on the dna.
297 protected MapList mapCdsToProtein(SequenceI dnaSeq, SequenceI proteinSeq)
299 SequenceFeature[] sfs = dnaSeq.getSequenceFeatures();
305 List<int[]> ranges = new ArrayList<int[]>(50);
306 SequenceOntology so = SequenceOntology.getInstance();
308 int mappedDnaLength = 0;
311 * Map CDS columns of dna to peptide. No need to worry about reverse strand
312 * dna here since the retrieved sequence is as transcribed (reverse
313 * complement for reverse strand), i.e in the same sense as the peptide.
315 boolean fivePrimeIncomplete = false;
316 for (SequenceFeature sf : sfs)
319 * process a CDS feature (or a sub-type of CDS)
321 if (so.isA(sf.getType(), SequenceOntology.CDS))
325 phase = Integer.parseInt(sf.getPhase());
326 } catch (NumberFormatException e)
331 * phase > 0 on first codon means 5' incomplete - skip to the start
332 * of the next codon; example ENST00000496384
334 int begin = sf.getBegin();
335 int end = sf.getEnd();
336 if (ranges.isEmpty() && phase > 0)
338 fivePrimeIncomplete = true;
342 continue; // shouldn't happen?
345 ranges.add(new int[] { begin, end });
346 mappedDnaLength += Math.abs(end - begin) + 1;
349 int proteinLength = proteinSeq.getLength();
350 List<int[]> proteinRange = new ArrayList<int[]>();
351 int proteinStart = 1;
352 if (fivePrimeIncomplete && proteinSeq.getCharAt(0) == 'X')
357 proteinRange.add(new int[] { proteinStart, proteinLength });
360 * dna length should map to protein (or protein plus stop codon)
362 int codesForResidues = mappedDnaLength / 3;
363 if (codesForResidues == proteinLength
364 || codesForResidues == (proteinLength + 1))
366 return new MapList(ranges, proteinRange, 3, 1);
372 * Fetches sequences for the list of accession ids and adds them to the
373 * alignment. Returns the extended (or created) alignment.
378 * @throws JalviewException
379 * @throws IOException
381 protected AlignmentI fetchSequences(List<String> ids, AlignmentI alignment)
382 throws JalviewException, IOException
384 if (!isEnsemblAvailable())
387 throw new JalviewException("ENSEMBL Rest API not available.");
389 FileParse fp = getSequenceReader(ids);
390 FastaFile fr = new FastaFile(fp);
391 if (fr.hasWarningMessage())
393 System.out.println(String.format(
394 "Warning when retrieving %d ids %s\n%s", ids.size(),
395 ids.toString(), fr.getWarningMessage()));
397 else if (fr.getSeqs().size() != ids.size())
399 System.out.println(String.format(
400 "Only retrieved %d sequences for %d query strings", fr
401 .getSeqs().size(), ids.size()));
404 if (fr.getSeqs().size() == 1 && fr.getSeqs().get(0).getLength() == 0)
407 * POST request has returned an empty FASTA file e.g. for invalid id
409 throw new IOException("No data returned for " + ids);
412 if (fr.getSeqs().size() > 0)
414 AlignmentI seqal = new Alignment(
415 fr.getSeqsAsArray());
416 for (SequenceI sq:seqal.getSequences())
418 if (sq.getDescription() == null)
420 sq.setDescription(getDbName());
422 String name = sq.getName();
423 if (ids.contains(name)
424 || ids.contains(name.replace("ENSP", "ENST")))
426 DBRefUtils.parseToDbRef(sq, DBRefSource.ENSEMBL, "0", name);
429 if (alignment == null)
435 alignment.append(seqal);
442 * Returns the URL for the REST call
445 * @throws MalformedURLException
448 protected URL getUrl(List<String> ids) throws MalformedURLException
451 * a single id is included in the URL path
452 * multiple ids go in the POST body instead
454 StringBuffer urlstring = new StringBuffer(128);
455 urlstring.append(SEQUENCE_ID_URL);
458 urlstring.append("/").append(ids.get(0));
460 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
461 urlstring.append("?type=").append(getSourceEnsemblType().getType());
462 urlstring.append(("&Accept=text/x-fasta"));
464 URL url = new URL(urlstring.toString());
469 * A sequence/id POST request currently allows up to 50 queries
471 * @see http://rest.ensembl.org/documentation/info/sequence_id_post
474 public int getMaximumQueryCount()
480 protected boolean useGetRequest()
486 protected String getRequestMimeType(boolean multipleIds)
488 return multipleIds ? "application/json" : "text/x-fasta";
492 protected String getResponseMimeType()
494 return "text/x-fasta";
499 * @return the configured sequence return type for this source
501 protected abstract EnsemblSeqType getSourceEnsemblType();
504 * Returns a list of [start, end] genomic ranges corresponding to the sequence
507 * The correspondence between the frames of reference is made by locating
508 * those features on the genomic sequence which identify the retrieved
509 * sequence. Specifically
511 * <li>genomic sequence is identified by "transcript" features with
512 * ID=transcript:transcriptId</li>
513 * <li>cdna sequence is identified by "exon" features with
514 * Parent=transcript:transcriptId</li>
515 * <li>cds sequence is identified by "CDS" features with
516 * Parent=transcript:transcriptId</li>
519 * The returned ranges are sorted to run forwards (for positive strand) or
520 * backwards (for negative strand). Aborts and returns null if both positive
521 * and negative strand are found (this should not normally happen).
523 * @param sourceSequence
526 * the start position of the sequence we are mapping to
529 protected MapList getGenomicRanges(SequenceI sourceSequence,
530 String accId, int start)
532 SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
539 * generously initial size for number of cds regions
540 * (worst case titin Q8WZ42 has c. 313 exons)
542 List<int[]> regions = new ArrayList<int[]>(100);
543 int mappedLength = 0;
544 int direction = 1; // forward
545 boolean directionSet = false;
547 for (SequenceFeature sf : sfs)
550 * accept the target feature type or a specialisation of it
551 * (e.g. coding_exon for exon)
553 if (identifiesSequence(sf, accId))
555 int strand = sf.getStrand();
557 if (directionSet && strand != direction)
559 // abort - mix of forward and backward
560 System.err.println("Error: forward and backward strand for "
568 * add to CDS ranges, semi-sorted forwards/backwards
572 regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
576 regions.add(new int[] { sf.getBegin(), sf.getEnd() });
578 mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
583 * 'gene' sequence is contiguous so we can stop as soon as its
584 * identifying feature has been found
591 if (regions.isEmpty())
593 System.out.println("Failed to identify target sequence for " + accId
594 + " from genomic features");
599 * a final sort is needed since Ensembl returns CDS sorted within source
600 * (havana / ensembl_havana)
602 Collections.sort(regions, new RangeSorter(direction == 1));
604 List<int[]> to = new ArrayList<int[]>();
605 to.add(new int[] { start, start + mappedLength - 1 });
607 return new MapList(regions, to, 1, 1);
611 * Answers true if the sequence being retrieved may occupy discontiguous
612 * regions on the genomic sequence.
614 protected boolean isSpliceable()
620 * Returns true if the sequence feature marks positions of the genomic
621 * sequence feature which are within the sequence being retrieved. For
622 * example, an 'exon' feature whose parent is the target transcript marks the
623 * cdna positions of the transcript.
629 protected abstract boolean identifiesSequence(SequenceFeature sf,
633 * Transfers the sequence feature to the target sequence, locating its start
634 * and end range based on the mapping. Features which do not overlap the
635 * target sequence are ignored.
638 * @param targetSequence
640 * mapping from the sequence feature's coordinates to the target
643 protected void transferFeature(SequenceFeature sf,
644 SequenceI targetSequence, MapList mapping)
646 int start = sf.getBegin();
647 int end = sf.getEnd();
648 int[] mappedRange = mapping.locateInTo(start, end);
650 if (mappedRange != null)
652 SequenceFeature copy = new SequenceFeature(sf);
653 copy.setBegin(Math.min(mappedRange[0], mappedRange[1]));
654 copy.setEnd(Math.max(mappedRange[0], mappedRange[1]));
655 targetSequence.addSequenceFeature(copy);
658 * for sequence_variant, make an additional feature with consequence
660 if (SequenceOntology.getInstance().isSequenceVariant(sf.getType()))
662 String consequence = (String) sf.getValue(CONSEQUENCE_TYPE);
663 if (consequence != null)
665 SequenceFeature sf2 = new SequenceFeature("consequence",
666 consequence, copy.getBegin(), copy.getEnd(), 0f,
668 targetSequence.addSequenceFeature(sf2);
675 * Transfers features from sourceSequence to targetSequence
678 * @param sourceSequence
679 * @param targetSequence
680 * @return true if any features were transferred, else false
682 protected boolean transferFeatures(String accessionId,
683 SequenceI sourceSequence, SequenceI targetSequence)
685 if (sourceSequence == null || targetSequence == null)
690 SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
691 MapList mapping = getGenomicRanges(sourceSequence, accessionId,
692 targetSequence.getStart());
698 return transferFeatures(sfs, targetSequence, mapping, accessionId);
702 * Transfer features to the target sequence. The start/end positions are
703 * converted using the mapping. Features which do not overlap are ignored.
704 * Features whose parent is not the specified identifier are also ignored.
707 * @param targetSequence
712 protected boolean transferFeatures(SequenceFeature[] features,
713 SequenceI targetSequence, MapList mapping, String parentId)
715 final boolean forwardStrand = mapping.isFromForwardStrand();
718 * sort features by start position (descending if reverse strand)
719 * before transferring (in forwards order) to the target sequence
721 Arrays.sort(features, new Comparator<SequenceFeature>()
724 public int compare(SequenceFeature o1, SequenceFeature o2)
726 int c = Integer.compare(o1.getBegin(), o2.getBegin());
727 return forwardStrand ? c : -c;
731 boolean transferred = false;
732 for (SequenceFeature sf : features)
734 if (retainFeature(sf, parentId))
736 transferFeature(sf, targetSequence, mapping);
744 * Answers true if the feature type is one we want to keep for the sequence.
745 * Some features are only retrieved in order to identify the sequence range,
746 * and may then be discarded as redundant information (e.g. "CDS" feature for
749 @SuppressWarnings("unused")
750 protected boolean retainFeature(SequenceFeature sf, String accessionId)
752 return true; // override as required
756 * Answers true if the feature has a Parent which refers to the given
757 * accession id, or if the feature has no parent. Answers false if the
758 * feature's Parent is for a different accession id.
764 protected boolean featureMayBelong(SequenceFeature sf, String identifier)
766 String parent = (String) sf.getValue(PARENT);
767 // using contains to allow for prefix "gene:", "transcript:" etc
768 if (parent != null && !parent.contains(identifier))
770 // this genomic feature belongs to a different transcript
777 public String getDescription()
779 return "Ensembl " + getSourceEnsemblType().getType()
780 + " sequence with variant features";
784 * Returns a (possibly empty) list of features on the sequence which have the
785 * specified sequence ontology type (or a sub-type of it), and the given
786 * identifier as parent
793 protected List<SequenceFeature> findFeatures(SequenceI sequence,
794 String type, String parentId)
796 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
798 SequenceFeature[] sfs = sequence.getSequenceFeatures();
800 SequenceOntology so = SequenceOntology.getInstance();
801 for (SequenceFeature sf :sfs) {
802 if (so.isA(sf.getType(), type))
804 String parent = (String) sf.getValue(PARENT);
805 if (parent.equals(parentId))
816 * Maps exon features from dna to protein, and computes variants in peptide
817 * product generated by variants in dna, and adds them as sequence_variant
818 * features on the protein sequence. Returns the number of variant features
823 * @param dnaToProtein
825 static int computeProteinFeatures(SequenceI dnaSeq,
826 SequenceI peptide, MapList dnaToProtein)
828 while (dnaSeq.getDatasetSequence() != null)
830 dnaSeq = dnaSeq.getDatasetSequence();
832 while (peptide.getDatasetSequence() != null)
834 peptide = peptide.getDatasetSequence();
837 mapExonsToProtein(dnaSeq, peptide, dnaToProtein);
839 LinkedHashMap<Integer, String[][]> variants = buildDnaVariantsMap(
840 dnaSeq, dnaToProtein);
843 * scan codon variations, compute peptide variants and add to peptide sequence
846 for (Entry<Integer, String[][]> variant : variants.entrySet())
848 int peptidePos = variant.getKey();
849 String[][] codonVariants = variant.getValue();
850 String residue = String.valueOf(peptide.getCharAt(peptidePos - 1)); // 0-based
851 List<String> peptideVariants = computePeptideVariants(codonVariants,
853 if (!peptideVariants.isEmpty())
855 Collections.sort(peptideVariants);
856 String desc = StringUtils.listToDelimitedString(peptideVariants,
858 SequenceFeature sf = new SequenceFeature(
859 SequenceOntology.SEQUENCE_VARIANT, desc, peptidePos,
860 peptidePos, 0f, null);
861 peptide.addSequenceFeature(sf);
869 * Transfers exon features to the corresponding mapped regions of the protein
870 * sequence. This is useful because it allows visualisation of exon boundaries
871 * on the peptide (using 'colour by label' for the exon name). Returns the
872 * number of features written.
876 * @param dnaToProtein
878 static int mapExonsToProtein(SequenceI dnaSeq, SequenceI peptide,
879 MapList dnaToProtein)
881 SequenceFeature[] sfs = dnaSeq.getSequenceFeatures();
887 SequenceOntology so = SequenceOntology.getInstance();
890 for (SequenceFeature sf : sfs)
892 if (so.isA(sf.getType(), SequenceOntology.EXON))
894 int start = sf.getBegin();
895 int end = sf.getEnd();
896 int[] mapsTo = dnaToProtein.locateInTo(start, end);
899 SequenceFeature copy = new SequenceFeature(SequenceOntology.EXON,
900 sf.getDescription(), mapsTo[0], mapsTo[1], 0f, null);
901 peptide.addSequenceFeature(copy);
910 * Builds a map whose key is position in the protein sequence, and value is an
911 * array of all variants for the coding codon positions
914 * @param dnaToProtein
917 static LinkedHashMap<Integer, String[][]> buildDnaVariantsMap(
918 SequenceI dnaSeq, MapList dnaToProtein)
921 * map from peptide position to all variant features of the codon for it
922 * LinkedHashMap ensures we add the peptide features in sequence order
924 LinkedHashMap<Integer, String[][]> variants = new LinkedHashMap<Integer, String[][]>();
925 SequenceOntology so = SequenceOntology.getInstance();
927 SequenceFeature[] dnaFeatures = dnaSeq.getSequenceFeatures();
928 if (dnaFeatures == null)
933 int[] lastCodon = null;
934 int lastPeptidePostion = 0;
937 * build a map of codon variations for peptides
939 for (SequenceFeature sf : dnaFeatures)
941 int dnaCol = sf.getBegin();
942 if (dnaCol != sf.getEnd())
944 // not handling multi-locus variant features
947 if (so.isSequenceVariant(sf.getType()))
949 int[] mapsTo = dnaToProtein.locateInTo(dnaCol, dnaCol);
952 // feature doesn't lie within coding region
955 int peptidePosition = mapsTo[0];
956 String[][] codonVariants = variants.get(peptidePosition);
957 if (codonVariants == null)
959 codonVariants = new String[3][];
960 variants.put(peptidePosition, codonVariants);
964 * extract dna variants to a string array
966 String alls = (String) sf.getValue("alleles");
971 String[] alleles = alls.split(",");
974 * get this peptides codon positions e.g. [3, 4, 5] or [4, 7, 10]
976 int[] codon = peptidePosition == lastPeptidePostion ? lastCodon
977 : MappingUtils.flattenRanges(dnaToProtein.locateInFrom(
978 peptidePosition, peptidePosition));
979 lastPeptidePostion = peptidePosition;
983 * save nucleotide (and this variant) for each codon position
985 for (int codonPos = 0; codonPos < 3; codonPos++)
987 String nucleotide = String.valueOf(dnaSeq
988 .getCharAt(codon[codonPos] - 1));
989 if (codon[codonPos] == dnaCol)
992 * record current dna base and its alleles
994 String[] dnaVariants = new String[alleles.length + 1];
995 dnaVariants[0] = nucleotide;
996 System.arraycopy(alleles, 0, dnaVariants, 1, alleles.length);
997 codonVariants[codonPos] = dnaVariants;
999 else if (codonVariants[codonPos] == null)
1002 * record current dna base only
1003 * (at least until we find any variation and overwrite it)
1005 codonVariants[codonPos] = new String[] { nucleotide };
1014 * Returns a non-redundant list of all peptide translations generated by the
1015 * given dna variants, excluding the current residue value
1017 * @param codonVariants
1018 * an array of base values for codon positions 1, 2, 3
1020 * the current residue translation
1023 static List<String> computePeptideVariants(
1024 String[][] codonVariants, String residue)
1026 List<String> result = new ArrayList<String>();
1027 for (String base1 : codonVariants[0])
1029 for (String base2 : codonVariants[1])
1031 for (String base3 : codonVariants[2])
1033 String codon = base1 + base2 + base3;
1034 // TODO: report frameshift/insertion/deletion
1035 // and multiple-base variants?!
1036 String peptide = codon.contains("-") ? "-" : ResidueProperties
1037 .codonTranslate(codon);
1038 if (peptide != null && !result.contains(peptide)
1039 && !peptide.equals(residue))
1041 result.add(peptide);
1050 * Answers true if the feature type is either 'NMD_transcript_variant' or
1051 * 'transcript' or one of its sub-types in the Sequence Ontology. This is
1052 * needed because NMD_transcript_variant behaves like 'transcript' in Ensembl
1053 * although strictly speaking it is not (it is a sub-type of
1054 * sequence_variant).
1056 * @param featureType
1059 public static boolean isTranscript(String featureType)
1061 return NMD_VARIANT.equals(featureType)
1062 || SequenceOntology.getInstance().isA(featureType, SequenceOntology.TRANSCRIPT);