1 package jalview.ext.ensembl;
3 import jalview.analysis.AlignmentUtils;
4 import jalview.analysis.Dna;
5 import jalview.datamodel.Alignment;
6 import jalview.datamodel.AlignmentI;
7 import jalview.datamodel.DBRefEntry;
8 import jalview.datamodel.DBRefSource;
9 import jalview.datamodel.Mapping;
10 import jalview.datamodel.SequenceFeature;
11 import jalview.datamodel.SequenceI;
12 import jalview.exceptions.JalviewException;
13 import jalview.io.FastaFile;
14 import jalview.io.FileParse;
15 import jalview.io.gff.SequenceOntologyFactory;
16 import jalview.io.gff.SequenceOntologyI;
17 import jalview.util.Comparison;
18 import jalview.util.DBRefUtils;
19 import jalview.util.MapList;
21 import java.io.IOException;
22 import java.net.MalformedURLException;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collections;
27 import java.util.Comparator;
28 import java.util.List;
31 * Base class for Ensembl sequence fetchers
33 * @see http://rest.ensembl.org/documentation/info/sequence_id
36 public abstract class EnsemblSeqProxy extends EnsemblRestClient
38 private static final String ALLELES = "alleles";
40 protected static final String PARENT = "Parent";
42 protected static final String ID = "ID";
44 protected static final String NAME = "Name";
46 protected static final String DESCRIPTION = "description";
49 * enum for 'type' parameter to the /sequence REST service
51 public enum EnsemblSeqType
54 * type=genomic to fetch full dna including introns
59 * type=cdna to fetch coding dna including UTRs
64 * type=cds to fetch coding dna excluding UTRs
69 * type=protein to fetch peptide product sequence
74 * the value of the 'type' parameter to fetch this version of
79 EnsemblSeqType(String t)
84 public String getType()
92 * A comparator to sort ranges into ascending start position order
94 private class RangeSorter implements Comparator<int[]>
98 RangeSorter(boolean forward)
104 public int compare(int[] o1, int[] o2)
106 return (forwards ? 1 : -1) * Integer.compare(o1[0], o2[0]);
112 * Default constructor (to use rest.ensembl.org)
114 public EnsemblSeqProxy()
120 * Constructor given the target domain to fetch data from
122 public EnsemblSeqProxy(String d)
128 * Makes the sequence queries to Ensembl's REST service and returns an
129 * alignment consisting of the returned sequences.
132 public AlignmentI getSequenceRecords(String query) throws Exception
134 // TODO use a String... query vararg instead?
136 // danger: accession separator used as a regex here, a string elsewhere
137 // in this case it is ok (it is just a space), but (e.g.) '\' would not be
138 List<String> allIds = Arrays.asList(query
139 .split(getAccessionSeparator()));
140 AlignmentI alignment = null;
144 * execute queries, if necessary in batches of the
145 * maximum allowed number of ids
147 int maxQueryCount = getMaximumQueryCount();
148 for (int v = 0, vSize = allIds.size(); v < vSize; v += maxQueryCount)
150 int p = Math.min(vSize, v + maxQueryCount);
151 List<String> ids = allIds.subList(v, p);
154 alignment = fetchSequences(ids, alignment);
155 } catch (Throwable r)
158 String msg = "Aborting ID retrieval after " + v
159 + " chunks. Unexpected problem (" + r.getLocalizedMessage()
161 System.err.println(msg);
166 if (alignment == null)
172 * fetch and transfer genomic sequence features,
173 * fetch protein product and add as cross-reference
175 for (String accId : allIds)
177 addFeaturesAndProduct(accId, alignment);
180 for (SequenceI seq : alignment.getSequences())
182 getCrossReferences(seq);
189 * Fetches Ensembl features using the /overlap REST endpoint, and adds them to
190 * the sequence in the alignment. Also fetches the protein product, maps it
191 * from the CDS features of the sequence, and saves it as a cross-reference of
197 protected void addFeaturesAndProduct(String accId, AlignmentI alignment)
199 if (alignment == null)
207 * get 'dummy' genomic sequence with exon, cds and variation features
209 SequenceI genomicSequence = null;
210 EnsemblFeatures gffFetcher = new EnsemblFeatures(getDomain());
211 EnsemblFeatureType[] features = getFeaturesToFetch();
212 AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
214 if (geneFeatures.getHeight() > 0)
216 genomicSequence = geneFeatures.getSequenceAt(0);
218 if (genomicSequence != null)
221 * transfer features to the query sequence
223 SequenceI querySeq = alignment.findName(accId);
224 if (transferFeatures(accId, genomicSequence, querySeq))
228 * fetch and map protein product, and add it as a cross-reference
229 * of the retrieved sequence
231 addProteinProduct(querySeq);
234 } catch (IOException e)
236 System.err.println("Error transferring Ensembl features: "
242 * Returns those sequence feature types to fetch from Ensembl. We may want
243 * features either because they are of interest to the user, or as means to
244 * identify the locations of the sequence on the genomic sequence (CDS
245 * features identify CDS, exon features identify cDNA etc).
249 protected abstract EnsemblFeatureType[] getFeaturesToFetch();
252 * Fetches and maps the protein product, and adds it as a cross-reference of
253 * the retrieved sequence
255 protected void addProteinProduct(SequenceI querySeq)
257 String accId = querySeq.getName();
260 AlignmentI protein = new EnsemblProtein(getDomain())
261 .getSequenceRecords(accId);
262 if (protein == null || protein.getHeight() == 0)
264 System.out.println("No protein product found for " + accId);
267 SequenceI proteinSeq = protein.getSequenceAt(0);
270 * need dataset sequences (to be the subject of mappings)
272 proteinSeq.createDatasetSequence();
273 querySeq.createDatasetSequence();
275 MapList mapList = AlignmentUtils.mapCdsToProtein(querySeq, proteinSeq);
278 // clunky: ensure Uniprot xref if we have one is on mapped sequence
279 SequenceI ds = proteinSeq.getDatasetSequence();
280 ds.setSourceDBRef(proteinSeq.getSourceDBRef());
282 Mapping map = new Mapping(ds, mapList);
283 DBRefEntry dbr = new DBRefEntry(getDbSource(),
284 getEnsemblDataVersion(), proteinSeq.getName(), map);
285 querySeq.getDatasetSequence().addDBRef(dbr);
288 * copy exon features to protein, compute peptide variants from dna
289 * variants and add as features on the protein sequence ta-da
291 AlignmentUtils.computeProteinFeatures(querySeq, proteinSeq, mapList);
293 } catch (Exception e)
296 .println(String.format("Error retrieving protein for %s: %s",
297 accId, e.getMessage()));
302 * Get database xrefs from Ensembl, and attach them to the sequence
306 protected void getCrossReferences(SequenceI seq)
308 while (seq.getDatasetSequence() != null)
310 seq = seq.getDatasetSequence();
313 EnsemblXref xrefFetcher = new EnsemblXref(getDomain());
314 List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName());
315 for (DBRefEntry xref : xrefs)
319 * Save any Uniprot xref to be the reference for SIFTS mapping
321 if (DBRefSource.UNIPROT.equals(xref.getSource()))
323 seq.setSourceDBRef(xref);
328 * and add a reference to itself
330 DBRefEntry self = new DBRefEntry(getDbSource(),
331 getEnsemblDataVersion(), seq.getName());
336 * Fetches sequences for the list of accession ids and adds them to the
337 * alignment. Returns the extended (or created) alignment.
342 * @throws JalviewException
343 * @throws IOException
345 protected AlignmentI fetchSequences(List<String> ids, AlignmentI alignment)
346 throws JalviewException, IOException
348 if (!isEnsemblAvailable())
351 throw new JalviewException("ENSEMBL Rest API not available.");
353 FileParse fp = getSequenceReader(ids);
354 FastaFile fr = new FastaFile(fp);
355 if (fr.hasWarningMessage())
357 System.out.println(String.format(
358 "Warning when retrieving %d ids %s\n%s", ids.size(),
359 ids.toString(), fr.getWarningMessage()));
361 else if (fr.getSeqs().size() != ids.size())
363 System.out.println(String.format(
364 "Only retrieved %d sequences for %d query strings", fr
365 .getSeqs().size(), ids.size()));
368 if (fr.getSeqs().size() == 1 && fr.getSeqs().get(0).getLength() == 0)
371 * POST request has returned an empty FASTA file e.g. for invalid id
373 throw new IOException("No data returned for " + ids);
376 if (fr.getSeqs().size() > 0)
378 AlignmentI seqal = new Alignment(
379 fr.getSeqsAsArray());
380 for (SequenceI sq:seqal.getSequences())
382 if (sq.getDescription() == null)
384 sq.setDescription(getDbName());
386 String name = sq.getName();
387 if (ids.contains(name)
388 || ids.contains(name.replace("ENSP", "ENST")))
390 DBRefUtils.parseToDbRef(sq, getDbSource(),
391 getEnsemblDataVersion(), name);
394 if (alignment == null)
400 alignment.append(seqal);
407 * Returns the URL for the REST call
410 * @throws MalformedURLException
413 protected URL getUrl(List<String> ids) throws MalformedURLException
416 * a single id is included in the URL path
417 * multiple ids go in the POST body instead
419 StringBuffer urlstring = new StringBuffer(128);
420 urlstring.append(getDomain() + "/sequence/id");
423 urlstring.append("/").append(ids.get(0));
425 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
426 urlstring.append("?type=").append(getSourceEnsemblType().getType());
427 urlstring.append(("&Accept=text/x-fasta"));
429 URL url = new URL(urlstring.toString());
434 * A sequence/id POST request currently allows up to 50 queries
436 * @see http://rest.ensembl.org/documentation/info/sequence_id_post
439 public int getMaximumQueryCount()
445 protected boolean useGetRequest()
451 protected String getRequestMimeType(boolean multipleIds)
453 return multipleIds ? "application/json" : "text/x-fasta";
457 protected String getResponseMimeType()
459 return "text/x-fasta";
464 * @return the configured sequence return type for this source
466 protected abstract EnsemblSeqType getSourceEnsemblType();
469 * Returns a list of [start, end] genomic ranges corresponding to the sequence
472 * The correspondence between the frames of reference is made by locating
473 * those features on the genomic sequence which identify the retrieved
474 * sequence. Specifically
476 * <li>genomic sequence is identified by "transcript" features with
477 * ID=transcript:transcriptId</li>
478 * <li>cdna sequence is identified by "exon" features with
479 * Parent=transcript:transcriptId</li>
480 * <li>cds sequence is identified by "CDS" features with
481 * Parent=transcript:transcriptId</li>
484 * The returned ranges are sorted to run forwards (for positive strand) or
485 * backwards (for negative strand). Aborts and returns null if both positive
486 * and negative strand are found (this should not normally happen).
488 * @param sourceSequence
491 * the start position of the sequence we are mapping to
494 protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
495 String accId, int start)
497 SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
504 * generously initial size for number of cds regions
505 * (worst case titin Q8WZ42 has c. 313 exons)
507 List<int[]> regions = new ArrayList<int[]>(100);
508 int mappedLength = 0;
509 int direction = 1; // forward
510 boolean directionSet = false;
512 for (SequenceFeature sf : sfs)
515 * accept the target feature type or a specialisation of it
516 * (e.g. coding_exon for exon)
518 if (identifiesSequence(sf, accId))
520 int strand = sf.getStrand();
521 strand = strand == 0 ? 1 : strand; // treat unknown as forward
523 if (directionSet && strand != direction)
525 // abort - mix of forward and backward
526 System.err.println("Error: forward and backward strand for "
534 * add to CDS ranges, semi-sorted forwards/backwards
538 regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
542 regions.add(new int[] { sf.getBegin(), sf.getEnd() });
544 mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
549 * 'gene' sequence is contiguous so we can stop as soon as its
550 * identifying feature has been found
557 if (regions.isEmpty())
559 System.out.println("Failed to identify target sequence for " + accId
560 + " from genomic features");
565 * a final sort is needed since Ensembl returns CDS sorted within source
566 * (havana / ensembl_havana)
568 Collections.sort(regions, new RangeSorter(direction == 1));
570 List<int[]> to = Arrays.asList(new int[] { start,
571 start + mappedLength - 1 });
573 return new MapList(regions, to, 1, 1);
577 * Answers true if the sequence being retrieved may occupy discontiguous
578 * regions on the genomic sequence.
580 protected boolean isSpliceable()
586 * Returns true if the sequence feature marks positions of the genomic
587 * sequence feature which are within the sequence being retrieved. For
588 * example, an 'exon' feature whose parent is the target transcript marks the
589 * cdna positions of the transcript.
595 protected abstract boolean identifiesSequence(SequenceFeature sf,
599 * Transfers the sequence feature to the target sequence, locating its start
600 * and end range based on the mapping. Features which do not overlap the
601 * target sequence are ignored.
604 * @param targetSequence
606 * mapping from the sequence feature's coordinates to the target
608 * @param forwardStrand
610 protected void transferFeature(SequenceFeature sf,
611 SequenceI targetSequence, MapList mapping, boolean forwardStrand)
613 int start = sf.getBegin();
614 int end = sf.getEnd();
615 int[] mappedRange = mapping.locateInTo(start, end);
617 if (mappedRange != null)
619 SequenceFeature copy = new SequenceFeature(sf);
620 copy.setBegin(Math.min(mappedRange[0], mappedRange[1]));
621 copy.setEnd(Math.max(mappedRange[0], mappedRange[1]));
622 targetSequence.addSequenceFeature(copy);
625 * for sequence_variant on reverse strand, have to convert the allele
626 * values to their complements
629 && SequenceOntologyFactory.getInstance().isA(sf.getType(),
630 SequenceOntologyI.SEQUENCE_VARIANT))
632 reverseComplementAlleles(copy);
638 * Change the 'alleles' value of a feature by converting to complementary
639 * bases, and also update the feature description to match
643 static void reverseComplementAlleles(SequenceFeature sf)
645 final String alleles = (String) sf.getValue(ALLELES);
650 StringBuilder complement = new StringBuilder(alleles.length());
651 for (String allele : alleles.split(","))
653 reverseComplementAllele(complement, allele);
655 String comp = complement.toString();
656 sf.setValue(ALLELES, comp);
657 sf.setDescription(comp);
660 * replace value of "alleles=" in sf.ATTRIBUTES as well
661 * so 'output as GFF' shows reverse complement alleles
663 String atts = sf.getAttributes();
666 atts = atts.replace(ALLELES + "=" + alleles, ALLELES + "=" + comp);
667 sf.setAttributes(atts);
672 * Makes the 'reverse complement' of the given allele and appends it to the
673 * buffer, after a comma separator if not the first
678 static void reverseComplementAllele(StringBuilder complement,
681 if (complement.length() > 0)
683 complement.append(",");
687 * some 'alleles' are actually descriptive terms
688 * e.g. HGMD_MUTATION, PhenCode_variation
689 * - we don't want to 'reverse complement' these
691 if (!Comparison.isNucleotideSequence(allele, true))
693 complement.append(allele);
697 for (int i = allele.length() - 1; i >= 0; i--)
699 complement.append(Dna.getComplement(allele.charAt(i)));
705 * Transfers features from sourceSequence to targetSequence
708 * @param sourceSequence
709 * @param targetSequence
710 * @return true if any features were transferred, else false
712 protected boolean transferFeatures(String accessionId,
713 SequenceI sourceSequence, SequenceI targetSequence)
715 if (sourceSequence == null || targetSequence == null)
720 // long start = System.currentTimeMillis();
721 SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
722 MapList mapping = getGenomicRangesFromFeatures(sourceSequence, accessionId,
723 targetSequence.getStart());
729 boolean result = transferFeatures(sfs, targetSequence, mapping,
731 // System.out.println("transferFeatures (" + (sfs.length) + " --> "
732 // + targetSequence.getSequenceFeatures().length + ") to "
733 // + targetSequence.getName()
734 // + " took " + (System.currentTimeMillis() - start) + "ms");
739 * Transfer features to the target sequence. The start/end positions are
740 * converted using the mapping. Features which do not overlap are ignored.
741 * Features whose parent is not the specified identifier are also ignored.
744 * @param targetSequence
749 protected boolean transferFeatures(SequenceFeature[] features,
750 SequenceI targetSequence, MapList mapping, String parentId)
752 final boolean forwardStrand = mapping.isFromForwardStrand();
755 * sort features by start position (which corresponds to end
756 * position descending if reverse strand) so as to add them in
757 * 'forwards' order to the target sequence
759 sortFeatures(features, forwardStrand);
761 boolean transferred = false;
762 for (SequenceFeature sf : features)
764 if (retainFeature(sf, parentId))
766 transferFeature(sf, targetSequence, mapping, forwardStrand);
774 * Sort features by start position ascending (if on forward strand), or end
775 * position descending (if on reverse strand)
778 * @param forwardStrand
780 protected static void sortFeatures(SequenceFeature[] features,
781 final boolean forwardStrand)
783 Arrays.sort(features, new Comparator<SequenceFeature>()
786 public int compare(SequenceFeature o1, SequenceFeature o2)
790 return Integer.compare(o1.getBegin(), o2.getBegin());
794 return Integer.compare(o2.getEnd(), o1.getEnd());
801 * Answers true if the feature type is one we want to keep for the sequence.
802 * Some features are only retrieved in order to identify the sequence range,
803 * and may then be discarded as redundant information (e.g. "CDS" feature for
806 @SuppressWarnings("unused")
807 protected boolean retainFeature(SequenceFeature sf, String accessionId)
809 return true; // override as required
813 * Answers true if the feature has a Parent which refers to the given
814 * accession id, or if the feature has no parent. Answers false if the
815 * feature's Parent is for a different accession id.
821 protected boolean featureMayBelong(SequenceFeature sf, String identifier)
823 String parent = (String) sf.getValue(PARENT);
824 // using contains to allow for prefix "gene:", "transcript:" etc
825 if (parent != null && !parent.contains(identifier))
827 // this genomic feature belongs to a different transcript
834 public String getDescription()
836 return "Ensembl " + getSourceEnsemblType().getType()
837 + " sequence with variant features";
841 * Returns a (possibly empty) list of features on the sequence which have the
842 * specified sequence ontology type (or a sub-type of it), and the given
843 * identifier as parent
850 protected List<SequenceFeature> findFeatures(SequenceI sequence,
851 String type, String parentId)
853 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
855 SequenceFeature[] sfs = sequence.getSequenceFeatures();
857 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
858 for (SequenceFeature sf :sfs) {
859 if (so.isA(sf.getType(), type))
861 String parent = (String) sf.getValue(PARENT);
862 if (parent.equals(parentId))
873 * Answers true if the feature type is either 'NMD_transcript_variant' or
874 * 'transcript' or one of its sub-types in the Sequence Ontology. This is
875 * needed because NMD_transcript_variant behaves like 'transcript' in Ensembl
876 * although strictly speaking it is not (it is a sub-type of
882 public static boolean isTranscript(String featureType)
884 return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
885 || SequenceOntologyFactory.getInstance().isA(featureType,
886 SequenceOntologyI.TRANSCRIPT);