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.DBRefUtils;
18 import jalview.util.MapList;
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.List;
30 * Base class for Ensembl sequence fetchers
32 * @see http://rest.ensembl.org/documentation/info/sequence_id
35 public abstract class EnsemblSeqProxy extends EnsemblRestClient
37 private static final String ALLELES = "alleles";
39 private static final List<String> CROSS_REFERENCES = Arrays
40 .asList(new String[] { "CCDS", "Uniprot/SWISSPROT",
41 "Uniprot/SPTREMBL" });
43 protected static final String CONSEQUENCE_TYPE = "consequence_type";
45 protected static final String PARENT = "Parent";
47 protected static final String ID = "ID";
49 protected static final String NAME = "Name";
51 protected static final String DESCRIPTION = "description";
54 * enum for 'type' parameter to the /sequence REST service
56 public enum EnsemblSeqType
59 * type=genomic to fetch full dna including introns
64 * type=cdna to fetch dna including UTRs
69 * type=cds to fetch coding dna excluding UTRs
74 * type=protein to fetch peptide product sequence
79 * the value of the 'type' parameter to fetch this version of
84 EnsemblSeqType(String t)
89 public String getType()
97 * A comparator to sort ranges into ascending start position order
99 private class RangeSorter implements Comparator<int[]>
103 RangeSorter(boolean forward)
109 public int compare(int[] o1, int[] o2)
111 return (forwards ? 1 : -1) * Integer.compare(o1[0], o2[0]);
117 * Default constructor (to use rest.ensembl.org)
119 public EnsemblSeqProxy()
125 * Constructor given the target domain to fetch data from
127 public EnsemblSeqProxy(String d)
133 * Makes the sequence queries to Ensembl's REST service and returns an
134 * alignment consisting of the returned sequences.
137 public AlignmentI getSequenceRecords(String query) throws Exception
139 // TODO use a String... query vararg instead?
141 // danger: accession separator used as a regex here, a string elsewhere
142 // in this case it is ok (it is just a space), but (e.g.) '\' would not be
143 List<String> allIds = Arrays.asList(query
144 .split(getAccessionSeparator()));
145 AlignmentI alignment = null;
149 * execute queries, if necessary in batches of the
150 * maximum allowed number of ids
152 int maxQueryCount = getMaximumQueryCount();
153 for (int v = 0, vSize = allIds.size(); v < vSize; v += maxQueryCount)
155 int p = Math.min(vSize, v + maxQueryCount);
156 List<String> ids = allIds.subList(v, p);
159 alignment = fetchSequences(ids, alignment);
160 } catch (Throwable r)
163 String msg = "Aborting ID retrieval after " + v
164 + " chunks. Unexpected problem (" + r.getLocalizedMessage()
166 System.err.println(msg);
171 if (alignment == null)
177 * fetch and transfer genomic sequence features,
178 * fetch protein product and add as cross-reference
180 for (String accId : allIds)
182 addFeaturesAndProduct(accId, alignment);
185 for (SequenceI seq : alignment.getSequences())
187 getCrossReferences(seq);
194 * Fetches Ensembl features using the /overlap REST endpoint, and adds them to
195 * the sequence in the alignment. Also fetches the protein product, maps it
196 * from the CDS features of the sequence, and saves it as a cross-reference of
202 protected void addFeaturesAndProduct(String accId, AlignmentI alignment)
204 if (alignment == null)
212 * get 'dummy' genomic sequence with exon, cds and variation features
214 SequenceI genomicSequence = null;
215 EnsemblFeatures gffFetcher = new EnsemblFeatures(getDomain());
216 EnsemblFeatureType[] features = getFeaturesToFetch();
217 AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
219 if (geneFeatures.getHeight() > 0)
221 genomicSequence = geneFeatures.getSequenceAt(0);
223 if (genomicSequence != null)
226 * transfer features to the query sequence
228 SequenceI querySeq = alignment.findName(accId);
229 if (transferFeatures(accId, genomicSequence, querySeq))
233 * fetch and map protein product, and add it as a cross-reference
234 * of the retrieved sequence
236 addProteinProduct(querySeq);
239 } catch (IOException e)
241 System.err.println("Error transferring Ensembl features: "
247 * Returns those sequence feature types to fetch from Ensembl. We may want
248 * features either because they are of interest to the user, or as means to
249 * identify the locations of the sequence on the genomic sequence (CDS
250 * features identify CDS, exon features identify cDNA etc).
254 protected abstract EnsemblFeatureType[] getFeaturesToFetch();
257 * Fetches and maps the protein product, and adds it as a cross-reference of
258 * the retrieved sequence
260 protected void addProteinProduct(SequenceI querySeq)
262 String accId = querySeq.getName();
265 AlignmentI protein = new EnsemblProtein(getDomain())
266 .getSequenceRecords(accId);
267 if (protein == null || protein.getHeight() == 0)
269 System.out.println("No protein product found for " + accId);
272 SequenceI proteinSeq = protein.getSequenceAt(0);
275 * need dataset sequences (to be the subject of mappings)
277 proteinSeq.createDatasetSequence();
278 querySeq.createDatasetSequence();
280 MapList mapList = AlignmentUtils.mapCdsToProtein(querySeq, proteinSeq);
283 // clunky: ensure Uniprot xref if we have one is on mapped sequence
284 SequenceI ds = proteinSeq.getDatasetSequence();
285 ds.setSourceDBRef(proteinSeq.getSourceDBRef());
286 Mapping map = new Mapping(ds, mapList);
287 DBRefEntry dbr = new DBRefEntry(getDbSource(), getDbVersion(),
289 querySeq.getDatasetSequence().addDBRef(dbr);
292 * copy exon features to protein, compute peptide variants from dna
293 * variants and add as features on the protein sequence ta-da
295 AlignmentUtils.computeProteinFeatures(querySeq, proteinSeq, mapList);
297 } catch (Exception e)
300 .println(String.format("Error retrieving protein for %s: %s",
301 accId, e.getMessage()));
306 * Get database xrefs from Ensembl, and attach them to the sequence
310 protected void getCrossReferences(SequenceI seq)
312 while (seq.getDatasetSequence() != null)
314 seq = seq.getDatasetSequence();
317 EnsemblXref xrefFetcher = new EnsemblXref(getDomain());
318 List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName(),
319 getCrossReferenceDatabases());
320 for (DBRefEntry xref : xrefs)
324 * Save any Uniprot xref to be the reference for SIFTS mapping
326 if (DBRefSource.UNIPROT.equals(xref.getSource()))
328 seq.setSourceDBRef(xref);
334 * Returns a list of database names to be used when fetching cross-references.
335 * Specifically, the names are used to filter data returned by the Ensembl
336 * xrefs REST service on the value in field 'dbname'.
340 protected List<String> getCrossReferenceDatabases()
342 return CROSS_REFERENCES;
346 * Fetches sequences for the list of accession ids and adds them to the
347 * alignment. Returns the extended (or created) alignment.
352 * @throws JalviewException
353 * @throws IOException
355 protected AlignmentI fetchSequences(List<String> ids, AlignmentI alignment)
356 throws JalviewException, IOException
358 if (!isEnsemblAvailable())
361 throw new JalviewException("ENSEMBL Rest API not available.");
363 FileParse fp = getSequenceReader(ids);
364 FastaFile fr = new FastaFile(fp);
365 if (fr.hasWarningMessage())
367 System.out.println(String.format(
368 "Warning when retrieving %d ids %s\n%s", ids.size(),
369 ids.toString(), fr.getWarningMessage()));
371 else if (fr.getSeqs().size() != ids.size())
373 System.out.println(String.format(
374 "Only retrieved %d sequences for %d query strings", fr
375 .getSeqs().size(), ids.size()));
378 if (fr.getSeqs().size() == 1 && fr.getSeqs().get(0).getLength() == 0)
381 * POST request has returned an empty FASTA file e.g. for invalid id
383 throw new IOException("No data returned for " + ids);
386 if (fr.getSeqs().size() > 0)
388 AlignmentI seqal = new Alignment(
389 fr.getSeqsAsArray());
390 for (SequenceI sq:seqal.getSequences())
392 if (sq.getDescription() == null)
394 sq.setDescription(getDbName());
396 String name = sq.getName();
397 if (ids.contains(name)
398 || ids.contains(name.replace("ENSP", "ENST")))
400 DBRefUtils.parseToDbRef(sq, DBRefSource.ENSEMBL, "0", name);
403 if (alignment == null)
409 alignment.append(seqal);
416 * Returns the URL for the REST call
419 * @throws MalformedURLException
422 protected URL getUrl(List<String> ids) throws MalformedURLException
425 * a single id is included in the URL path
426 * multiple ids go in the POST body instead
428 StringBuffer urlstring = new StringBuffer(128);
429 urlstring.append(getDomain() + "/sequence/id");
432 urlstring.append("/").append(ids.get(0));
434 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
435 urlstring.append("?type=").append(getSourceEnsemblType().getType());
436 urlstring.append(("&Accept=text/x-fasta"));
438 URL url = new URL(urlstring.toString());
443 * A sequence/id POST request currently allows up to 50 queries
445 * @see http://rest.ensembl.org/documentation/info/sequence_id_post
448 public int getMaximumQueryCount()
454 protected boolean useGetRequest()
460 protected String getRequestMimeType(boolean multipleIds)
462 return multipleIds ? "application/json" : "text/x-fasta";
466 protected String getResponseMimeType()
468 return "text/x-fasta";
473 * @return the configured sequence return type for this source
475 protected abstract EnsemblSeqType getSourceEnsemblType();
478 * Returns a list of [start, end] genomic ranges corresponding to the sequence
481 * The correspondence between the frames of reference is made by locating
482 * those features on the genomic sequence which identify the retrieved
483 * sequence. Specifically
485 * <li>genomic sequence is identified by "transcript" features with
486 * ID=transcript:transcriptId</li>
487 * <li>cdna sequence is identified by "exon" features with
488 * Parent=transcript:transcriptId</li>
489 * <li>cds sequence is identified by "CDS" features with
490 * Parent=transcript:transcriptId</li>
493 * The returned ranges are sorted to run forwards (for positive strand) or
494 * backwards (for negative strand). Aborts and returns null if both positive
495 * and negative strand are found (this should not normally happen).
497 * @param sourceSequence
500 * the start position of the sequence we are mapping to
503 protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
504 String accId, int start)
506 SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
513 * generously initial size for number of cds regions
514 * (worst case titin Q8WZ42 has c. 313 exons)
516 List<int[]> regions = new ArrayList<int[]>(100);
517 int mappedLength = 0;
518 int direction = 1; // forward
519 boolean directionSet = false;
521 for (SequenceFeature sf : sfs)
524 * accept the target feature type or a specialisation of it
525 * (e.g. coding_exon for exon)
527 if (identifiesSequence(sf, accId))
529 int strand = sf.getStrand();
530 strand = strand == 0 ? 1 : strand; // treat unknown as forward
532 if (directionSet && strand != direction)
534 // abort - mix of forward and backward
535 System.err.println("Error: forward and backward strand for "
543 * add to CDS ranges, semi-sorted forwards/backwards
547 regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
551 regions.add(new int[] { sf.getBegin(), sf.getEnd() });
553 mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
558 * 'gene' sequence is contiguous so we can stop as soon as its
559 * identifying feature has been found
566 if (regions.isEmpty())
568 System.out.println("Failed to identify target sequence for " + accId
569 + " from genomic features");
574 * a final sort is needed since Ensembl returns CDS sorted within source
575 * (havana / ensembl_havana)
577 Collections.sort(regions, new RangeSorter(direction == 1));
579 List<int[]> to = Arrays.asList(new int[] { start,
580 start + mappedLength - 1 });
582 return new MapList(regions, to, 1, 1);
586 * Answers true if the sequence being retrieved may occupy discontiguous
587 * regions on the genomic sequence.
589 protected boolean isSpliceable()
595 * Returns true if the sequence feature marks positions of the genomic
596 * sequence feature which are within the sequence being retrieved. For
597 * example, an 'exon' feature whose parent is the target transcript marks the
598 * cdna positions of the transcript.
604 protected abstract boolean identifiesSequence(SequenceFeature sf,
608 * Transfers the sequence feature to the target sequence, locating its start
609 * and end range based on the mapping. Features which do not overlap the
610 * target sequence are ignored.
613 * @param targetSequence
615 * mapping from the sequence feature's coordinates to the target
617 * @param forwardStrand
619 protected void transferFeature(SequenceFeature sf,
620 SequenceI targetSequence, MapList mapping, boolean forwardStrand)
622 int start = sf.getBegin();
623 int end = sf.getEnd();
624 int[] mappedRange = mapping.locateInTo(start, end);
626 if (mappedRange != null)
628 SequenceFeature copy = new SequenceFeature(sf);
629 copy.setBegin(Math.min(mappedRange[0], mappedRange[1]));
630 copy.setEnd(Math.max(mappedRange[0], mappedRange[1]));
631 targetSequence.addSequenceFeature(copy);
634 * for sequence_variant on reverse strand, have to convert the allele
635 * values to their complements
638 && SequenceOntologyFactory.getInstance().isA(sf.getType(),
639 SequenceOntologyI.SEQUENCE_VARIANT))
641 reverseComplementAlleles(copy);
647 * Change the 'alleles' value of a feature by converting to complementary
648 * bases, and also update the feature description to match
652 static void reverseComplementAlleles(SequenceFeature sf)
654 final String alleles = (String) sf.getValue(ALLELES);
659 StringBuilder complement = new StringBuilder(alleles.length());
660 for (String allele : alleles.split(","))
662 reverseComplementAllele(complement, allele);
664 String comp = complement.toString();
665 sf.setValue(ALLELES, comp);
666 sf.setDescription(comp);
669 * replace value of "alleles=" in sf.ATTRIBUTES as well
670 * so 'output as GFF' shows reverse complement alleles
672 String atts = sf.getAttributes();
675 atts = atts.replace(ALLELES + "=" + alleles, ALLELES + "=" + comp);
676 sf.setAttributes(atts);
681 * Makes the 'reverse complement' of the given allele and appends it to the
682 * buffer, after a comma separator if not the first
687 static void reverseComplementAllele(StringBuilder complement,
690 if (complement.length() > 0)
692 complement.append(",");
694 if ("HGMD_MUTATION".equalsIgnoreCase(allele))
696 complement.append(allele);
700 char[] alleles = allele.toCharArray();
701 for (int i = alleles.length - 1; i >= 0; i--)
703 complement.append(Dna.getComplement(alleles[i]));
709 * Transfers features from sourceSequence to targetSequence
712 * @param sourceSequence
713 * @param targetSequence
714 * @return true if any features were transferred, else false
716 protected boolean transferFeatures(String accessionId,
717 SequenceI sourceSequence, SequenceI targetSequence)
719 if (sourceSequence == null || targetSequence == null)
724 // long start = System.currentTimeMillis();
725 SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
726 MapList mapping = getGenomicRangesFromFeatures(sourceSequence, accessionId,
727 targetSequence.getStart());
733 boolean result = transferFeatures(sfs, targetSequence, mapping,
735 // System.out.println("transferFeatures (" + (sfs.length) + " --> "
736 // + targetSequence.getSequenceFeatures().length + ") to "
737 // + targetSequence.getName()
738 // + " took " + (System.currentTimeMillis() - start) + "ms");
743 * Transfer features to the target sequence. The start/end positions are
744 * converted using the mapping. Features which do not overlap are ignored.
745 * Features whose parent is not the specified identifier are also ignored.
748 * @param targetSequence
753 protected boolean transferFeatures(SequenceFeature[] features,
754 SequenceI targetSequence, MapList mapping, String parentId)
756 final boolean forwardStrand = mapping.isFromForwardStrand();
759 * sort features by start position (which corresponds to end
760 * position descending if reverse strand) so as to add them in
761 * 'forwards' order to the target sequence
763 sortFeatures(features, forwardStrand);
765 boolean transferred = false;
766 for (SequenceFeature sf : features)
768 if (retainFeature(sf, parentId))
770 transferFeature(sf, targetSequence, mapping, forwardStrand);
778 * Sort features by start position ascending (if on forward strand), or end
779 * position descending (if on reverse strand)
782 * @param forwardStrand
784 protected static void sortFeatures(SequenceFeature[] features,
785 final boolean forwardStrand)
787 Arrays.sort(features, new Comparator<SequenceFeature>()
790 public int compare(SequenceFeature o1, SequenceFeature o2)
794 return Integer.compare(o1.getBegin(), o2.getBegin());
798 return Integer.compare(o2.getEnd(), o1.getEnd());
805 * Answers true if the feature type is one we want to keep for the sequence.
806 * Some features are only retrieved in order to identify the sequence range,
807 * and may then be discarded as redundant information (e.g. "CDS" feature for
810 @SuppressWarnings("unused")
811 protected boolean retainFeature(SequenceFeature sf, String accessionId)
813 return true; // override as required
817 * Answers true if the feature has a Parent which refers to the given
818 * accession id, or if the feature has no parent. Answers false if the
819 * feature's Parent is for a different accession id.
825 protected boolean featureMayBelong(SequenceFeature sf, String identifier)
827 String parent = (String) sf.getValue(PARENT);
828 // using contains to allow for prefix "gene:", "transcript:" etc
829 if (parent != null && !parent.contains(identifier))
831 // this genomic feature belongs to a different transcript
838 public String getDescription()
840 return "Ensembl " + getSourceEnsemblType().getType()
841 + " sequence with variant features";
845 * Returns a (possibly empty) list of features on the sequence which have the
846 * specified sequence ontology type (or a sub-type of it), and the given
847 * identifier as parent
854 protected List<SequenceFeature> findFeatures(SequenceI sequence,
855 String type, String parentId)
857 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
859 SequenceFeature[] sfs = sequence.getSequenceFeatures();
861 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
862 for (SequenceFeature sf :sfs) {
863 if (so.isA(sf.getType(), type))
865 String parent = (String) sf.getValue(PARENT);
866 if (parent.equals(parentId))
877 * Answers true if the feature type is either 'NMD_transcript_variant' or
878 * 'transcript' or one of its sub-types in the Sequence Ontology. This is
879 * needed because NMD_transcript_variant behaves like 'transcript' in Ensembl
880 * although strictly speaking it is not (it is a sub-type of
886 public static boolean isTranscript(String featureType)
888 return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
889 || SequenceOntologyFactory.getInstance().isA(featureType,
890 SequenceOntologyI.TRANSCRIPT);