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 protected static final String CONSEQUENCE_TYPE = "consequence_type";
41 protected static final String PARENT = "Parent";
43 protected static final String ID = "ID";
45 protected static final String NAME = "Name";
47 protected static final String DESCRIPTION = "description";
50 * enum for 'type' parameter to the /sequence REST service
52 public enum EnsemblSeqType
55 * type=genomic to fetch full dna including introns
60 * type=cdna to fetch dna including UTRs
65 * type=cds to fetch coding dna excluding UTRs
70 * type=protein to fetch 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]);
113 * Default constructor (to use rest.ensembl.org)
115 public EnsemblSeqProxy()
121 * Constructor given the target domain to fetch data from
123 public EnsemblSeqProxy(String d)
129 * Makes the sequence queries to Ensembl's REST service and returns an
130 * alignment consisting of the returned sequences.
133 public AlignmentI getSequenceRecords(String query) throws Exception
135 // TODO use a String... query vararg instead?
137 // danger: accession separator used as a regex here, a string elsewhere
138 // in this case it is ok (it is just a space), but (e.g.) '\' would not be
139 List<String> allIds = Arrays.asList(query
140 .split(getAccessionSeparator()));
141 AlignmentI alignment = null;
145 * execute queries, if necessary in batches of the
146 * maximum allowed number of ids
148 int maxQueryCount = getMaximumQueryCount();
149 for (int v = 0, vSize = allIds.size(); v < vSize; v += maxQueryCount)
151 int p = Math.min(vSize, v + maxQueryCount);
152 List<String> ids = allIds.subList(v, p);
155 alignment = fetchSequences(ids, alignment);
156 } catch (Throwable r)
159 String msg = "Aborting ID retrieval after " + v
160 + " chunks. Unexpected problem (" + r.getLocalizedMessage()
162 System.err.println(msg);
167 if (alignment == null)
173 * fetch and transfer genomic sequence features,
174 * fetch protein product and add as cross-reference
176 for (String accId : allIds)
178 addFeaturesAndProduct(accId, alignment);
181 for (SequenceI seq : alignment.getSequences())
183 getCrossReferences(seq);
190 * Fetches Ensembl features using the /overlap REST endpoint, and adds them to
191 * the sequence in the alignment. Also fetches the protein product, maps it
192 * from the CDS features of the sequence, and saves it as a cross-reference of
198 protected void addFeaturesAndProduct(String accId, AlignmentI alignment)
200 if (alignment == null)
208 * get 'dummy' genomic sequence with exon, cds and variation features
210 SequenceI genomicSequence = null;
211 EnsemblFeatures gffFetcher = new EnsemblFeatures(getDomain());
212 EnsemblFeatureType[] features = getFeaturesToFetch();
213 AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
215 if (geneFeatures.getHeight() > 0)
217 genomicSequence = geneFeatures.getSequenceAt(0);
219 if (genomicSequence != null)
222 * transfer features to the query sequence
224 SequenceI querySeq = alignment.findName(accId);
225 if (transferFeatures(accId, genomicSequence, querySeq))
229 * fetch and map protein product, and add it as a cross-reference
230 * of the retrieved sequence
232 addProteinProduct(querySeq);
235 } catch (IOException e)
237 System.err.println("Error transferring Ensembl features: "
243 * Returns those sequence feature types to fetch from Ensembl. We may want
244 * features either because they are of interest to the user, or as means to
245 * identify the locations of the sequence on the genomic sequence (CDS
246 * features identify CDS, exon features identify cDNA etc).
250 protected abstract EnsemblFeatureType[] getFeaturesToFetch();
253 * Fetches and maps the protein product, and adds it as a cross-reference of
254 * the retrieved sequence
256 protected void addProteinProduct(SequenceI querySeq)
258 String accId = querySeq.getName();
261 AlignmentI protein = new EnsemblProtein(getDomain())
262 .getSequenceRecords(accId);
263 if (protein == null || protein.getHeight() == 0)
265 System.out.println("No protein product found for " + accId);
268 SequenceI proteinSeq = protein.getSequenceAt(0);
271 * need dataset sequences (to be the subject of mappings)
273 proteinSeq.createDatasetSequence();
274 querySeq.createDatasetSequence();
276 MapList mapList = AlignmentUtils.mapCdsToProtein(querySeq, proteinSeq);
279 // clunky: ensure Uniprot xref if we have one is on mapped sequence
280 SequenceI ds = proteinSeq.getDatasetSequence();
281 ds.setSourceDBRef(proteinSeq.getSourceDBRef());
283 Mapping map = new Mapping(ds, mapList);
284 DBRefEntry dbr = new DBRefEntry(getDbSource(), getDbVersion(),
285 proteinSeq.getName(), map);
286 querySeq.getDatasetSequence().addDBRef(dbr);
289 * copy exon features to protein, compute peptide variants from dna
290 * variants and add as features on the protein sequence ta-da
292 AlignmentUtils.computeProteinFeatures(querySeq, proteinSeq, mapList);
294 } catch (Exception e)
297 .println(String.format("Error retrieving protein for %s: %s",
298 accId, e.getMessage()));
303 * Get database xrefs from Ensembl, and attach them to the sequence
307 protected void getCrossReferences(SequenceI seq)
309 while (seq.getDatasetSequence() != null)
311 seq = seq.getDatasetSequence();
314 EnsemblXref xrefFetcher = new EnsemblXref(getDomain());
315 List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName());
316 for (DBRefEntry xref : xrefs)
320 * Save any Uniprot xref to be the reference for SIFTS mapping
322 if (DBRefSource.UNIPROT.equals(xref.getSource()))
324 seq.setSourceDBRef(xref);
329 * and add a reference to itself
331 DBRefEntry self = new DBRefEntry(getDbSource(), "0", 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, DBRefSource.ENSEMBL, "0", name);
393 if (alignment == null)
399 alignment.append(seqal);
406 * Returns the URL for the REST call
409 * @throws MalformedURLException
412 protected URL getUrl(List<String> ids) throws MalformedURLException
415 * a single id is included in the URL path
416 * multiple ids go in the POST body instead
418 StringBuffer urlstring = new StringBuffer(128);
419 urlstring.append(getDomain() + "/sequence/id");
422 urlstring.append("/").append(ids.get(0));
424 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
425 urlstring.append("?type=").append(getSourceEnsemblType().getType());
426 urlstring.append(("&Accept=text/x-fasta"));
428 URL url = new URL(urlstring.toString());
433 * A sequence/id POST request currently allows up to 50 queries
435 * @see http://rest.ensembl.org/documentation/info/sequence_id_post
438 public int getMaximumQueryCount()
444 protected boolean useGetRequest()
450 protected String getRequestMimeType(boolean multipleIds)
452 return multipleIds ? "application/json" : "text/x-fasta";
456 protected String getResponseMimeType()
458 return "text/x-fasta";
463 * @return the configured sequence return type for this source
465 protected abstract EnsemblSeqType getSourceEnsemblType();
468 * Returns a list of [start, end] genomic ranges corresponding to the sequence
471 * The correspondence between the frames of reference is made by locating
472 * those features on the genomic sequence which identify the retrieved
473 * sequence. Specifically
475 * <li>genomic sequence is identified by "transcript" features with
476 * ID=transcript:transcriptId</li>
477 * <li>cdna sequence is identified by "exon" features with
478 * Parent=transcript:transcriptId</li>
479 * <li>cds sequence is identified by "CDS" features with
480 * Parent=transcript:transcriptId</li>
483 * The returned ranges are sorted to run forwards (for positive strand) or
484 * backwards (for negative strand). Aborts and returns null if both positive
485 * and negative strand are found (this should not normally happen).
487 * @param sourceSequence
490 * the start position of the sequence we are mapping to
493 protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
494 String accId, int start)
496 SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
503 * generously initial size for number of cds regions
504 * (worst case titin Q8WZ42 has c. 313 exons)
506 List<int[]> regions = new ArrayList<int[]>(100);
507 int mappedLength = 0;
508 int direction = 1; // forward
509 boolean directionSet = false;
511 for (SequenceFeature sf : sfs)
514 * accept the target feature type or a specialisation of it
515 * (e.g. coding_exon for exon)
517 if (identifiesSequence(sf, accId))
519 int strand = sf.getStrand();
520 strand = strand == 0 ? 1 : strand; // treat unknown as forward
522 if (directionSet && strand != direction)
524 // abort - mix of forward and backward
525 System.err.println("Error: forward and backward strand for "
533 * add to CDS ranges, semi-sorted forwards/backwards
537 regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
541 regions.add(new int[] { sf.getBegin(), sf.getEnd() });
543 mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
548 * 'gene' sequence is contiguous so we can stop as soon as its
549 * identifying feature has been found
556 if (regions.isEmpty())
558 System.out.println("Failed to identify target sequence for " + accId
559 + " from genomic features");
564 * a final sort is needed since Ensembl returns CDS sorted within source
565 * (havana / ensembl_havana)
567 Collections.sort(regions, new RangeSorter(direction == 1));
569 List<int[]> to = Arrays.asList(new int[] { start,
570 start + mappedLength - 1 });
572 return new MapList(regions, to, 1, 1);
576 * Answers true if the sequence being retrieved may occupy discontiguous
577 * regions on the genomic sequence.
579 protected boolean isSpliceable()
585 * Returns true if the sequence feature marks positions of the genomic
586 * sequence feature which are within the sequence being retrieved. For
587 * example, an 'exon' feature whose parent is the target transcript marks the
588 * cdna positions of the transcript.
594 protected abstract boolean identifiesSequence(SequenceFeature sf,
598 * Transfers the sequence feature to the target sequence, locating its start
599 * and end range based on the mapping. Features which do not overlap the
600 * target sequence are ignored.
603 * @param targetSequence
605 * mapping from the sequence feature's coordinates to the target
607 * @param forwardStrand
609 protected void transferFeature(SequenceFeature sf,
610 SequenceI targetSequence, MapList mapping, boolean forwardStrand)
612 int start = sf.getBegin();
613 int end = sf.getEnd();
614 int[] mappedRange = mapping.locateInTo(start, end);
616 if (mappedRange != null)
618 SequenceFeature copy = new SequenceFeature(sf);
619 copy.setBegin(Math.min(mappedRange[0], mappedRange[1]));
620 copy.setEnd(Math.max(mappedRange[0], mappedRange[1]));
621 targetSequence.addSequenceFeature(copy);
624 * for sequence_variant on reverse strand, have to convert the allele
625 * values to their complements
628 && SequenceOntologyFactory.getInstance().isA(sf.getType(),
629 SequenceOntologyI.SEQUENCE_VARIANT))
631 reverseComplementAlleles(copy);
637 * Change the 'alleles' value of a feature by converting to complementary
638 * bases, and also update the feature description to match
642 static void reverseComplementAlleles(SequenceFeature sf)
644 final String alleles = (String) sf.getValue(ALLELES);
649 StringBuilder complement = new StringBuilder(alleles.length());
650 for (String allele : alleles.split(","))
652 reverseComplementAllele(complement, allele);
654 String comp = complement.toString();
655 sf.setValue(ALLELES, comp);
656 sf.setDescription(comp);
659 * replace value of "alleles=" in sf.ATTRIBUTES as well
660 * so 'output as GFF' shows reverse complement alleles
662 String atts = sf.getAttributes();
665 atts = atts.replace(ALLELES + "=" + alleles, ALLELES + "=" + comp);
666 sf.setAttributes(atts);
671 * Makes the 'reverse complement' of the given allele and appends it to the
672 * buffer, after a comma separator if not the first
677 static void reverseComplementAllele(StringBuilder complement,
680 if (complement.length() > 0)
682 complement.append(",");
684 if ("HGMD_MUTATION".equalsIgnoreCase(allele))
686 complement.append(allele);
690 char[] alleles = allele.toCharArray();
691 for (int i = alleles.length - 1; i >= 0; i--)
693 complement.append(Dna.getComplement(alleles[i]));
699 * Transfers features from sourceSequence to targetSequence
702 * @param sourceSequence
703 * @param targetSequence
704 * @return true if any features were transferred, else false
706 protected boolean transferFeatures(String accessionId,
707 SequenceI sourceSequence, SequenceI targetSequence)
709 if (sourceSequence == null || targetSequence == null)
714 // long start = System.currentTimeMillis();
715 SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
716 MapList mapping = getGenomicRangesFromFeatures(sourceSequence, accessionId,
717 targetSequence.getStart());
723 boolean result = transferFeatures(sfs, targetSequence, mapping,
725 // System.out.println("transferFeatures (" + (sfs.length) + " --> "
726 // + targetSequence.getSequenceFeatures().length + ") to "
727 // + targetSequence.getName()
728 // + " took " + (System.currentTimeMillis() - start) + "ms");
733 * Transfer features to the target sequence. The start/end positions are
734 * converted using the mapping. Features which do not overlap are ignored.
735 * Features whose parent is not the specified identifier are also ignored.
738 * @param targetSequence
743 protected boolean transferFeatures(SequenceFeature[] features,
744 SequenceI targetSequence, MapList mapping, String parentId)
746 final boolean forwardStrand = mapping.isFromForwardStrand();
749 * sort features by start position (which corresponds to end
750 * position descending if reverse strand) so as to add them in
751 * 'forwards' order to the target sequence
753 sortFeatures(features, forwardStrand);
755 boolean transferred = false;
756 for (SequenceFeature sf : features)
758 if (retainFeature(sf, parentId))
760 transferFeature(sf, targetSequence, mapping, forwardStrand);
768 * Sort features by start position ascending (if on forward strand), or end
769 * position descending (if on reverse strand)
772 * @param forwardStrand
774 protected static void sortFeatures(SequenceFeature[] features,
775 final boolean forwardStrand)
777 Arrays.sort(features, new Comparator<SequenceFeature>()
780 public int compare(SequenceFeature o1, SequenceFeature o2)
784 return Integer.compare(o1.getBegin(), o2.getBegin());
788 return Integer.compare(o2.getEnd(), o1.getEnd());
795 * Answers true if the feature type is one we want to keep for the sequence.
796 * Some features are only retrieved in order to identify the sequence range,
797 * and may then be discarded as redundant information (e.g. "CDS" feature for
800 @SuppressWarnings("unused")
801 protected boolean retainFeature(SequenceFeature sf, String accessionId)
803 return true; // override as required
807 * Answers true if the feature has a Parent which refers to the given
808 * accession id, or if the feature has no parent. Answers false if the
809 * feature's Parent is for a different accession id.
815 protected boolean featureMayBelong(SequenceFeature sf, String identifier)
817 String parent = (String) sf.getValue(PARENT);
818 // using contains to allow for prefix "gene:", "transcript:" etc
819 if (parent != null && !parent.contains(identifier))
821 // this genomic feature belongs to a different transcript
828 public String getDescription()
830 return "Ensembl " + getSourceEnsemblType().getType()
831 + " sequence with variant features";
835 * Returns a (possibly empty) list of features on the sequence which have the
836 * specified sequence ontology type (or a sub-type of it), and the given
837 * identifier as parent
844 protected List<SequenceFeature> findFeatures(SequenceI sequence,
845 String type, String parentId)
847 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
849 SequenceFeature[] sfs = sequence.getSequenceFeatures();
851 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
852 for (SequenceFeature sf :sfs) {
853 if (so.isA(sf.getType(), type))
855 String parent = (String) sf.getValue(PARENT);
856 if (parent.equals(parentId))
867 * Answers true if the feature type is either 'NMD_transcript_variant' or
868 * 'transcript' or one of its sub-types in the Sequence Ontology. This is
869 * needed because NMD_transcript_variant behaves like 'transcript' in Ensembl
870 * although strictly speaking it is not (it is a sub-type of
876 public static boolean isTranscript(String featureType)
878 return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
879 || SequenceOntologyFactory.getInstance().isA(featureType,
880 SequenceOntologyI.TRANSCRIPT);