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.util.DBRefUtils;
15 import jalview.util.MapList;
17 import java.io.IOException;
18 import java.net.MalformedURLException;
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.List;
27 * Base class for Ensembl sequence fetchers
31 public abstract class EnsemblSeqProxy extends EnsemblRestClient
33 protected static final String CONSEQUENCE_TYPE = "consequence_type";
35 protected static final String PARENT = "Parent";
37 protected static final String ID = "ID";
40 * this needs special handling, as it isA sequence_variant in the
41 * Sequence Ontology, but behaves in Ensembl as if it isA transcript
43 protected static final String NMD_VARIANT = "NMD_transcript_variant";
45 protected static final String NAME = "Name";
47 public enum EnsemblSeqType
50 * type=genomic for the full dna including introns
55 * type=cdna for transcribed dna including UTRs
60 * type=cds for coding dna excluding UTRs
65 * type=protein for the peptide product sequence
70 * the value of the 'type' parameter to fetch this version of
75 EnsemblSeqType(String t)
80 public String getType()
88 * A comparator to sort ranges into ascending start position order
90 private class RangeSorter implements Comparator<int[]>
94 RangeSorter(boolean forward)
100 public int compare(int[] o1, int[] o2)
102 return (forwards ? 1 : -1) * Integer.compare(o1[0], o2[0]);
110 public EnsemblSeqProxy()
115 * Makes the sequence queries to Ensembl's REST service and returns an
116 * alignment consisting of the returned sequences.
119 public AlignmentI getSequenceRecords(String query) throws Exception
121 long now = System.currentTimeMillis();
122 // TODO use a String... query vararg instead?
124 // danger: accession separator used as a regex here, a string elsewhere
125 // in this case it is ok (it is just a space), but (e.g.) '\' would not be
126 List<String> allIds = Arrays.asList(query
127 .split(getAccessionSeparator()));
128 AlignmentI alignment = null;
132 * execute queries, if necessary in batches of the
133 * maximum allowed number of ids
135 int maxQueryCount = getMaximumQueryCount();
136 for (int v = 0, vSize = allIds.size(); v < vSize; v += maxQueryCount)
138 int p = Math.min(vSize, v + maxQueryCount);
139 List<String> ids = allIds.subList(v, p);
142 alignment = fetchSequences(ids, alignment);
143 } catch (Throwable r)
146 String msg = "Aborting ID retrieval after " + v
147 + " chunks. Unexpected problem (" + r.getLocalizedMessage()
149 System.err.println(msg);
150 if (alignment != null)
152 break; // return what we got
156 throw new JalviewException(msg, r);
162 * fetch and transfer genomic sequence features,
163 * fetch protein product and add as cross-reference
165 for (String accId : allIds)
167 addFeaturesAndProduct(accId, alignment);
171 System.out.println(getClass().getName() + " took "
172 + (System.currentTimeMillis() - now) + "ms to fetch");
177 * Fetches Ensembl features using the /overlap REST endpoint, and adds them to
178 * the sequence in the alignment. Also fetches the protein product, maps it
179 * from the CDS features of the sequence, and saves it as a cross-reference of
185 protected void addFeaturesAndProduct(String accId, AlignmentI alignment)
187 if (alignment == null)
195 * get 'dummy' genomic sequence with exon, cds and variation features
197 SequenceI genomicSequence = null;
198 EnsemblOverlap gffFetcher = new EnsemblOverlap();
199 EnsemblFeatureType[] features = getFeaturesToFetch();
200 AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
202 if (geneFeatures.getHeight() > 0)
204 genomicSequence = geneFeatures.getSequenceAt(0);
206 if (genomicSequence != null)
209 * transfer features to the query sequence
211 SequenceI querySeq = alignment.findName(accId);
212 if (transferFeatures(accId, genomicSequence, querySeq))
216 * fetch and map protein product, and add it as a cross-reference
217 * of the retrieved sequence
219 addProteinProduct(querySeq);
222 } catch (IOException e)
224 System.err.println("Error transferring Ensembl features: "
230 * Returns those sequence feature types to fetch from Ensembl. We may want
231 * features either because they are of interest to the user, or as means to
232 * identify the locations of the sequence on the genomic sequence (CDS
233 * features identify CDS, exon features identify cDNA etc).
237 protected abstract EnsemblFeatureType[] getFeaturesToFetch();
240 * Fetches and maps the protein product, and adds it as a cross-reference of
241 * the retrieved sequence
243 protected void addProteinProduct(SequenceI querySeq)
245 String accId = querySeq.getName();
248 AlignmentI protein = new EnsemblProtein().getSequenceRecords(accId);
249 if (protein == null || protein.getHeight() == 0)
251 System.out.println("Failed to retrieve protein for " + accId);
254 SequenceI proteinSeq = protein.getSequenceAt(0);
257 * need dataset sequences (to be the subject of mappings)
259 proteinSeq.createDatasetSequence();
260 querySeq.createDatasetSequence();
262 MapList mapList = mapCdsToProtein(querySeq, proteinSeq);
265 Mapping map = new Mapping(proteinSeq.getDatasetSequence(), mapList);
266 DBRefEntry dbr = new DBRefEntry(getDbSource(), getDbVersion(),
268 querySeq.getDatasetSequence().addDBRef(dbr);
270 } catch (Exception e)
273 .println(String.format("Error retrieving protein for %s: %s",
274 accId, e.getMessage()));
279 * Returns a mapping from dna to protein by inspecting sequence features of
280 * type "CDS" on the dna.
286 protected MapList mapCdsToProtein(SequenceI dnaSeq, SequenceI proteinSeq)
288 SequenceFeature[] sfs = dnaSeq.getSequenceFeatures();
294 List<int[]> ranges = new ArrayList<int[]>(50);
295 SequenceOntology so = SequenceOntology.getInstance();
297 int mappedDnaLength = 0;
300 * Map CDS columns of dna to peptide. No need to worry about reverse strand
301 * dna here since the retrieved sequence is as transcribed (reverse
302 * complement for reverse strand), i.e in the same sense as the peptide.
304 boolean fivePrimeIncomplete = false;
305 for (SequenceFeature sf : sfs)
308 * process a CDS feature (or a sub-type of CDS)
310 if (so.isA(sf.getType(), SequenceOntology.CDS))
314 phase = Integer.parseInt(sf.getPhase());
315 } catch (NumberFormatException e)
320 * phase > 0 on first codon means 5' incomplete - skip to the start
321 * of the next codon; example ENST00000496384
323 int begin = sf.getBegin();
324 int end = sf.getEnd();
325 if (ranges.isEmpty() && phase > 0)
327 fivePrimeIncomplete = true;
331 continue; // shouldn't happen?
334 ranges.add(new int[] { begin, end });
335 mappedDnaLength += Math.abs(end - begin) + 1;
338 int proteinLength = proteinSeq.getLength();
339 List<int[]> proteinRange = new ArrayList<int[]>();
340 int proteinStart = 1;
341 if (fivePrimeIncomplete && proteinSeq.getCharAt(0) == 'X')
346 proteinRange.add(new int[] { proteinStart, proteinLength });
349 * dna length should map to protein (or protein plus stop codon)
351 int codesForResidues = mappedDnaLength / 3;
352 if (codesForResidues == proteinLength
353 || codesForResidues == (proteinLength + 1))
355 return new MapList(ranges, proteinRange, 3, 1);
361 * Fetches sequences for the list of accession ids and adds them to the
362 * alignment. Returns the extended (or created) alignment.
367 * @throws JalviewException
368 * @throws IOException
370 protected AlignmentI fetchSequences(List<String> ids, AlignmentI alignment)
371 throws JalviewException, IOException
373 if (!isEnsemblAvailable())
376 throw new JalviewException("ENSEMBL Rest API not available.");
378 FileParse fp = getSequenceReader(ids);
379 FastaFile fr = new FastaFile(fp);
380 if (fr.hasWarningMessage())
382 System.out.println(String.format(
383 "Warning when retrieving %d ids %s\n%s", ids.size(),
384 ids.toString(), fr.getWarningMessage()));
386 else if (fr.getSeqs().size() != ids.size())
388 System.out.println(String.format(
389 "Only retrieved %d sequences for %d query strings", fr
390 .getSeqs().size(), ids.size()));
393 if (fr.getSeqs().size() == 1 && fr.getSeqs().get(0).getLength() == 0)
396 * POST request has returned an empty FASTA file e.g. for invalid id
398 throw new IOException("No data returned for " + ids);
401 if (fr.getSeqs().size() > 0)
403 AlignmentI seqal = new Alignment(
404 fr.getSeqsAsArray());
405 for (SequenceI sq:seqal.getSequences())
407 if (sq.getDescription() == null)
409 sq.setDescription(getDbName());
411 String name = sq.getName();
412 if (ids.contains(name)
413 || ids.contains(name.replace("ENSP", "ENST")))
415 DBRefUtils.parseToDbRef(sq, DBRefSource.ENSEMBL, "0", name);
418 if (alignment == null)
424 alignment.append(seqal);
431 * Returns the URL for the REST call
434 * @throws MalformedURLException
437 protected URL getUrl(List<String> ids) throws MalformedURLException
440 * a single id is included in the URL path
441 * multiple ids go in the POST body instead
443 StringBuffer urlstring = new StringBuffer(128);
444 urlstring.append(SEQUENCE_ID_URL);
447 urlstring.append("/").append(ids.get(0));
449 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
450 urlstring.append("?type=").append(getSourceEnsemblType().getType());
451 urlstring.append(("&Accept=text/x-fasta"));
453 URL url = new URL(urlstring.toString());
458 * A sequence/id POST request currently allows up to 50 queries
460 * @see http://rest.ensembl.org/documentation/info/sequence_id_post
463 public int getMaximumQueryCount()
469 protected boolean useGetRequest()
475 protected String getRequestMimeType(boolean multipleIds)
477 return multipleIds ? "application/json" : "text/x-fasta";
481 protected String getResponseMimeType()
483 return "text/x-fasta";
488 * @return the configured sequence return type for this source
490 protected abstract EnsemblSeqType getSourceEnsemblType();
493 * Returns a list of [start, end] genomic ranges corresponding to the sequence
496 * The correspondence between the frames of reference is made by locating
497 * those features on the genomic sequence which identify the retrieved
498 * sequence. Specifically
500 * <li>genomic sequence is identified by "transcript" features with
501 * ID=transcript:transcriptId</li>
502 * <li>cdna sequence is identified by "exon" features with
503 * Parent=transcript:transcriptId</li>
504 * <li>cds sequence is identified by "CDS" features with
505 * Parent=transcript:transcriptId</li>
508 * The returned ranges are sorted to run forwards (for positive strand) or
509 * backwards (for negative strand). Aborts and returns null if both positive
510 * and negative strand are found (this should not normally happen).
512 * @param sourceSequence
515 * the start position of the sequence we are mapping to
518 protected MapList getGenomicRanges(SequenceI sourceSequence,
519 String accId, int start)
521 SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
528 * generously initial size for number of cds regions
529 * (worst case titin Q8WZ42 has c. 313 exons)
531 List<int[]> regions = new ArrayList<int[]>(100);
532 int mappedLength = 0;
533 int direction = 1; // forward
534 boolean directionSet = false;
536 for (SequenceFeature sf : sfs)
539 * accept the target feature type or a specialisation of it
540 * (e.g. coding_exon for exon)
542 if (identifiesSequence(sf, accId))
544 int strand = sf.getStrand();
546 if (directionSet && strand != direction)
548 // abort - mix of forward and backward
549 System.err.println("Error: forward and backward strand for "
557 * add to CDS ranges, semi-sorted forwards/backwards
561 regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
565 regions.add(new int[] { sf.getBegin(), sf.getEnd() });
567 mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
572 * 'gene' sequence is contiguous so we can stop as soon as its
573 * identifying feature has been found
580 if (regions.isEmpty())
582 System.out.println("Failed to identify target sequence for " + accId
583 + " from genomic features");
588 * a final sort is needed since Ensembl returns CDS sorted within source
589 * (havana / ensembl_havana)
591 Collections.sort(regions, new RangeSorter(direction == 1));
593 List<int[]> to = new ArrayList<int[]>();
594 to.add(new int[] { start, start + mappedLength - 1 });
596 return new MapList(regions, to, 1, 1);
600 * Answers true if the sequence being retrieved may occupy discontiguous
601 * regions on the genomic sequence.
603 protected boolean isSpliceable()
609 * Returns true if the sequence feature marks positions of the genomic
610 * sequence feature which are within the sequence being retrieved. For
611 * example, an 'exon' feature whose parent is the target transcript marks the
612 * cdna positions of the transcript.
618 protected abstract boolean identifiesSequence(SequenceFeature sf,
622 * Transfers the sequence feature to the target sequence, locating its start
623 * and end range based on the mapping. Features which do not overlap the
624 * target sequence are ignored.
627 * @param targetSequence
629 * mapping from the sequence feature's coordinates to the target
632 protected void transferFeature(SequenceFeature sf,
633 SequenceI targetSequence, MapList mapping)
635 int start = sf.getBegin();
636 int end = sf.getEnd();
637 int[] mappedRange = mapping.locateInTo(start, end);
639 if (mappedRange != null)
641 SequenceFeature copy = new SequenceFeature(sf);
642 copy.setBegin(Math.min(mappedRange[0], mappedRange[1]));
643 copy.setEnd(Math.max(mappedRange[0], mappedRange[1]));
644 targetSequence.addSequenceFeature(copy);
647 * for sequence_variant, make an additional feature with consequence
649 if (SequenceOntology.getInstance().isSequenceVariant(sf.getType()))
651 String consequence = (String) sf.getValue(CONSEQUENCE_TYPE);
652 if (consequence != null)
654 SequenceFeature sf2 = new SequenceFeature("consequence",
655 consequence, copy.getBegin(), copy.getEnd(), 0f,
657 targetSequence.addSequenceFeature(sf2);
664 * Transfers features from sourceSequence to targetSequence
667 * @param sourceSequence
668 * @param targetSequence
669 * @return true if any features were transferred, else false
671 protected boolean transferFeatures(String accessionId,
672 SequenceI sourceSequence, SequenceI targetSequence)
674 if (sourceSequence == null || targetSequence == null)
679 SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
680 MapList mapping = getGenomicRanges(sourceSequence, accessionId,
681 targetSequence.getStart());
687 return transferFeatures(sfs, targetSequence, mapping, accessionId);
691 * Transfer features to the target sequence. The start/end positions are
692 * converted using the mapping. Features which do not overlap are ignored.
693 * Features whose parent is not the specified identifier are also ignored.
696 * @param targetSequence
701 protected boolean transferFeatures(SequenceFeature[] features,
702 SequenceI targetSequence, MapList mapping, String parentId)
704 final boolean forwardStrand = mapping.isFromForwardStrand();
707 * sort features by start position (descending if reverse strand)
708 * before transferring (in forwards order) to the target sequence
710 Arrays.sort(features, new Comparator<SequenceFeature>()
713 public int compare(SequenceFeature o1, SequenceFeature o2)
715 int c = Integer.compare(o1.getBegin(), o2.getBegin());
716 return forwardStrand ? c : -c;
720 boolean transferred = false;
721 for (SequenceFeature sf : features)
723 if (retainFeature(sf, parentId))
725 transferFeature(sf, targetSequence, mapping);
733 * Answers true if the feature type is one we want to keep for the sequence.
734 * Some features are only retrieved in order to identify the sequence range,
735 * and may then be discarded as redundant information (e.g. "CDS" feature for
738 @SuppressWarnings("unused")
739 protected boolean retainFeature(SequenceFeature sf, String accessionId)
741 return true; // override as required
745 * Answers true if the feature has a Parent which refers to the given
746 * accession id, or if the feature has no parent. Answers false if the
747 * feature's Parent is for a different accession id.
753 protected boolean featureMayBelong(SequenceFeature sf, String identifier)
755 String parent = (String) sf.getValue(PARENT);
756 // using contains to allow for prefix "gene:", "transcript:" etc
757 if (parent != null && !parent.contains(identifier))
759 // this genomic feature belongs to a different transcript
766 public String getDescription()
768 return "Ensembl " + getSourceEnsemblType().getType()
769 + " sequence with variant features";
773 * Returns a (possibly empty) list of features on the sequence which have the
774 * specified sequence ontology type (or a sub-type of it), and the given
775 * identifier as parent
782 protected List<SequenceFeature> findFeatures(SequenceI sequence,
783 String type, String parentId)
785 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
787 SequenceFeature[] sfs = sequence.getSequenceFeatures();
789 SequenceOntology so = SequenceOntology.getInstance();
790 for (SequenceFeature sf :sfs) {
791 if (so.isA(sf.getType(), type))
793 String parent = (String) sf.getValue(PARENT);
794 if (parent.equals(parentId))
805 * Answers true if the feature type is either 'NMD_transcript_variant' or
806 * 'transcript' or one of its sub-types in the Sequence Ontology. This is
807 * needed because NMD_transcript_variant behaves like 'transcript' in Ensembl
808 * although strictly speaking it is not (it is a sub-type of
814 public static boolean isTranscript(String featureType)
816 return NMD_VARIANT.equals(featureType)
817 || SequenceOntology.getInstance().isA(featureType, SequenceOntology.TRANSCRIPT);