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 PARENT = "Parent";
35 protected static final String ID = "ID";
37 public enum EnsemblSeqType
40 * type=genomic for the full dna including introns
45 * type=cdna for transcribed dna including UTRs
50 * type=cds for coding dna excluding UTRs
55 * type=protein for the peptide product sequence
60 * the value of the 'type' parameter to fetch this version of
65 EnsemblSeqType(String t)
70 public String getType()
78 * A comparator to sort ranges into ascending start position order
80 private class RangeSorter implements Comparator<int[]>
84 RangeSorter(boolean forward)
90 public int compare(int[] o1, int[] o2)
92 return (forwards ? 1 : -1) * Integer.compare(o1[0], o2[0]);
98 * genomic sequence, with features retrieved from the REST overlap service
100 private SequenceI genomicSequence;
105 public EnsemblSeqProxy()
110 * Makes the sequence queries to Ensembl's REST service and returns an
111 * alignment consisting of the returned sequences
114 public AlignmentI getSequenceRecords(String query) throws Exception
116 long now = System.currentTimeMillis();
117 // TODO use a String... query vararg instead?
119 // danger: accession separator used as a regex here, a string elsewhere
120 // in this case it is ok (it is just a space), but (e.g.) '\' would not be
121 List<String> allIds = Arrays.asList(query.split(getAccessionSeparator()));
122 AlignmentI alignment = null;
126 * execute queries, if necessary in batches of the
127 * maximum allowed number of ids
129 int maxQueryCount = getMaximumQueryCount();
130 for (int v = 0, vSize = allIds.size(); v < vSize; v += maxQueryCount)
132 int p = Math.min(vSize, v + maxQueryCount);
133 List<String> ids = allIds.subList(v, p);
136 alignment = fetchSequences(ids, alignment);
137 } catch (Throwable r)
140 String msg = "Aborting ID retrieval after " + v
141 + " chunks. Unexpected problem (" + r.getLocalizedMessage()
143 System.err.println(msg);
144 if (alignment != null)
146 break; // return what we got
150 throw new JalviewException(msg, r);
156 * fetch and transfer genomic sequence features
158 for (String accId : allIds)
160 addFeaturesAndProduct(accId, alignment);
164 System.out.println(getClass().getName() + " took "
165 + (System.currentTimeMillis() - now) + "ms to fetch");
170 * Fetches Ensembl features using the /overlap REST endpoint, and adds them to
171 * the sequence in the alignment. Also fetches the protein product, maps it
172 * from the CDS features of the sequence, and saves it as a cross-reference of
178 protected void addFeaturesAndProduct(String accId, AlignmentI alignment)
183 * get 'dummy' genomic sequence with exon, cds and variation features
185 if (genomicSequence == null)
187 EnsemblOverlap gffFetcher = new EnsemblOverlap();
188 EnsemblFeatureType[] features = getFeaturesToFetch();
189 AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
191 if (geneFeatures.getHeight() > 0)
194 * transfer features to the query sequence
196 genomicSequence = geneFeatures.getSequenceAt(0);
199 if (genomicSequence != null)
201 SequenceI querySeq = alignment.findName(accId);
202 if (transferFeatures(accId, genomicSequence, querySeq))
206 * fetch and map protein product, and add it as a cross-reference
207 * of the retrieved sequence
209 addProteinProduct(querySeq);
212 } catch (IOException e)
214 System.err.println("Error transferring Ensembl features: "
220 * Returns those sequence feature types to fetch from Ensembl. We may want
221 * features either because they are of interest to the user, or as means to
222 * identify the locations of the sequence on the genomic sequence (CDS
223 * features identify CDS, exon features identify cDNA etc).
227 protected abstract EnsemblFeatureType[] getFeaturesToFetch();
230 * Fetches and maps the protein product, and adds it as a cross-reference of
231 * the retrieved sequence
233 protected void addProteinProduct(SequenceI querySeq)
235 String accId = querySeq.getName();
238 AlignmentI protein = new EnsemblProtein().getSequenceRecords(accId);
239 if (protein == null || protein.getHeight() == 0)
241 System.out.println("Failed to retrieve protein for " + accId);
244 SequenceI proteinSeq = protein.getSequenceAt(0);
247 * need dataset sequences (to be the subject of mappings)
249 proteinSeq.createDatasetSequence();
250 querySeq.createDatasetSequence();
252 MapList mapList = mapCdsToProtein(querySeq, proteinSeq);
255 Mapping map = new Mapping(proteinSeq.getDatasetSequence(), mapList);
256 DBRefEntry dbr = new DBRefEntry(getDbSource(), getDbVersion(),
258 querySeq.getDatasetSequence().addDBRef(dbr);
260 } catch (Exception e)
263 .println(String.format("Error retrieving protein for %s: %s",
264 accId, e.getMessage()));
269 * Returns a mapping from dna to protein by inspecting sequence features of
270 * type "CDS" on the dna.
276 protected MapList mapCdsToProtein(SequenceI dnaSeq, SequenceI proteinSeq)
278 SequenceFeature[] sfs = dnaSeq.getSequenceFeatures();
284 List<int[]> ranges = new ArrayList<int[]>(50);
285 SequenceOntology so = SequenceOntology.getInstance();
287 int mappedDnaLength = 0;
290 * Map CDS columns of dna to peptide. No need to worry about reverse strand
291 * dna here since the retrieved sequence is as transcribed (reverse
292 * complement for reverse strand), i.e in the same sense as the peptide.
294 for (SequenceFeature sf : sfs)
297 * process a CDS feature (or a sub-type of CDS)
299 if (so.isA(sf.getType(), SequenceOntology.CDS))
301 ranges.add(new int[] { sf.getBegin(), sf.getEnd() });
302 mappedDnaLength += Math.abs(sf.getEnd() - sf.getBegin()) + 1;
305 int proteinLength = proteinSeq.getLength();
306 List<int[]> proteinRange = new ArrayList<int[]>();
307 proteinRange.add(new int[] { 1, proteinLength });
310 * dna length should map to protein (or protein minus stop codon)
312 if (mappedDnaLength == 3 * proteinLength
313 || mappedDnaLength == 3 * (proteinLength + 1))
315 return new MapList(ranges, proteinRange, 3, 1);
321 * Fetches sequences for the list of accession ids and adds them to the
322 * alignment. Returns the extended (or created) alignment.
327 * @throws JalviewException
328 * @throws IOException
330 protected AlignmentI fetchSequences(List<String> ids, AlignmentI alignment)
331 throws JalviewException, IOException
333 if (!isEnsemblAvailable())
336 throw new JalviewException("ENSEMBL Rest API not available.");
338 FileParse fp = getSequenceReader(ids);
339 FastaFile fr = new FastaFile(fp);
340 if (fr.hasWarningMessage())
342 System.out.println(String.format(
343 "Warning when retrieving %d ids %s\n%s", ids.size(),
344 ids.toString(), fr.getWarningMessage()));
346 else if (fr.getSeqs().size() != ids.size())
348 System.out.println(String.format(
349 "Only retrieved %d sequences for %d query strings", fr
350 .getSeqs().size(), ids.size()));
352 if (fr.getSeqs().size() > 0)
354 AlignmentI seqal = new Alignment(
355 fr.getSeqsAsArray());
356 for (SequenceI sq:seqal.getSequences())
358 if (sq.getDescription() == null)
360 sq.setDescription(getDbName());
362 String name = sq.getName();
363 if (ids.contains(name)
364 || ids.contains(name.replace("ENSP", "ENST")))
366 DBRefUtils.parseToDbRef(sq, DBRefSource.ENSEMBL, "0", name);
369 if (alignment == null)
375 alignment.append(seqal);
382 * Returns the URL for the REST call
385 * @throws MalformedURLException
388 protected URL getUrl(List<String> ids) throws MalformedURLException
390 // ids are not used - they go in the POST body instead
391 StringBuffer urlstring = new StringBuffer(128);
392 urlstring.append(SEQUENCE_ID_URL);
394 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
395 urlstring.append("?type=").append(getSourceEnsemblType().getType());
396 urlstring.append(("&Accept=text/x-fasta"));
398 URL url = new URL(urlstring.toString());
403 * A sequence/id POST request currently allows up to 50 queries
405 * @see http://rest.ensembl.org/documentation/info/sequence_id_post
408 public int getMaximumQueryCount()
414 protected boolean useGetRequest()
420 protected String getRequestMimeType()
422 return "application/json";
426 protected String getResponseMimeType()
428 return "text/x-fasta";
433 * @return the configured sequence return type for this source
435 protected abstract EnsemblSeqType getSourceEnsemblType();
438 * Returns a list of [start, end] genomic ranges corresponding to the sequence
441 * The correspondence between the frames of reference is made by locating
442 * those features on the genomic sequence which identify the retrieved
443 * sequence. Specifically
445 * <li>genomic sequence is identified by "transcript" features with
446 * ID=transcript:transcriptId</li>
447 * <li>cdna sequence is identified by "exon" features with
448 * Parent=transcript:transcriptId</li>
449 * <li>cds sequence is identified by "CDS" features with
450 * Parent=transcript:transcriptId</li>
453 * The returned ranges are sorted to run forwards (for positive strand) or
454 * backwards (for negative strand). Aborts and returns null if both positive
455 * and negative strand are found (this should not normally happen).
457 * @param sourceSequence
460 * the start position of the sequence we are mapping to
463 protected MapList getGenomicRanges(SequenceI sourceSequence,
464 String accId, int start)
466 SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
473 * generously size for initial number of cds regions
474 * (worst case titin Q8WZ42 has c. 313 exons)
476 List<int[]> regions = new ArrayList<int[]>(100);
477 int sourceLength = sourceSequence.getLength();
478 int mappedLength = 0;
479 int direction = 1; // forward
480 boolean directionSet = false;
482 for (SequenceFeature sf : sfs)
485 * accept the target feature type or a specialisation of it
486 * (e.g. coding_exon for exon)
488 if (identifiesSequence(sf, accId))
490 int strand = sf.getStrand();
492 if (directionSet && strand != direction)
494 // abort - mix of forward and backward
495 System.err.println("Error: forward and backward strand for "
503 * add to CDS ranges, semi-sorted forwards/backwards
507 regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
511 regions.add(new int[] { sf.getBegin(), sf.getEnd() });
513 mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
515 if (mappedLength >= sourceLength)
518 * break for the case of matching gene features v gene sequence
519 * - only need to locate the 'gene' feature for accId
526 if (regions.isEmpty())
528 System.out.println("Failed to identify target sequence for " + accId
529 + " from genomic features");
534 * a final sort is needed since Ensembl returns CDS sorted within source
535 * (havana / ensembl_havana)
537 Collections.sort(regions, new RangeSorter(direction == 1));
539 List<int[]> to = new ArrayList<int[]>();
540 to.add(new int[] { start, start + mappedLength - 1 });
542 return new MapList(regions, to, 1, 1);
546 * Returns true if the sequence feature marks positions of the genomic
547 * sequence feature which are within the sequence being retrieved. For
548 * example, an 'exon' feature whose parent is the target transcript marks the
549 * cdna positions of the transcript.
555 protected abstract boolean identifiesSequence(SequenceFeature sf,
559 * Transfers the sequence feature to the target sequence, adjusting its start
560 * and end range based on the 'overlap' ranges. Features which do not overlap
561 * the target sequence are ignored, as are features with a parent other than
562 * the target sequence id.
565 * @param targetSequence
568 protected void transferFeature(SequenceFeature sf,
569 SequenceI targetSequence, MapList overlap)
571 int start = sf.getBegin();
572 int end = sf.getEnd();
573 int[] mappedRange = overlap.locateInTo(start, end);
575 if (mappedRange != null)
577 SequenceFeature copy = new SequenceFeature(sf);
578 copy.setBegin(Math.min(mappedRange[0], mappedRange[1]));
579 copy.setEnd(Math.max(mappedRange[0], mappedRange[1]));
580 targetSequence.addSequenceFeature(copy);
583 * for sequence_variant, make an additional feature with consequence
585 if (SequenceOntology.getInstance().isSequenceVariant(sf.getType()))
587 String consequence = (String) sf.getValue("consequence_type");
588 if (consequence != null)
590 SequenceFeature sf2 = new SequenceFeature("consequence",
591 consequence, copy.getBegin(), copy.getEnd(), 0f,
593 targetSequence.addSequenceFeature(sf2);
601 * Transfers features from sourceSequence to targetSequence
604 * @param sourceSequence
605 * @param targetSequence
606 * @return true if any features were transferred, else false
608 protected boolean transferFeatures(String accessionId,
609 SequenceI sourceSequence, SequenceI targetSequence)
611 if (sourceSequence == null || targetSequence == null)
616 SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
617 MapList overlap = getGenomicRanges(sourceSequence, accessionId,
618 targetSequence.getStart());
624 final boolean forwardStrand = overlap.isFromForwardStrand();
627 * sort features by start position (descending if reverse strand)
628 * before transferring (in forwards order) to the target sequence
630 Arrays.sort(sfs, new Comparator<SequenceFeature>()
633 public int compare(SequenceFeature o1, SequenceFeature o2)
635 int c = Integer.compare(o1.getBegin(), o2.getBegin());
636 return forwardStrand ? c : -c;
640 boolean transferred = false;
641 for (SequenceFeature sf : sfs)
643 if (retainFeature(sf, accessionId))
645 transferFeature(sf, targetSequence, overlap);
653 * Answers true if the feature is one to attach to the retrieved sequence
658 protected boolean retainFeature(SequenceFeature sf, String accessionId)
660 String parent = (String) sf.getValue(PARENT);
661 if (parent != null && !parent.contains(accessionId))
663 // this genomic feature belongs to a different transcript
670 public String getDescription()
672 return "Ensembl " + getSourceEnsemblType().getType()
673 + " sequence with variant features";
676 public AlignmentI getSequenceRecords(String transcriptId,
677 SequenceI geneSeq) throws Exception
679 this.genomicSequence = geneSeq;
680 return getSequenceRecords(transcriptId);