2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.ext.ensembl;
23 import jalview.analysis.AlignmentUtils;
24 import jalview.analysis.Dna;
25 import jalview.bin.Cache;
26 import jalview.datamodel.Alignment;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.DBRefEntry;
29 import jalview.datamodel.DBRefSource;
30 import jalview.datamodel.Mapping;
31 import jalview.datamodel.SequenceFeature;
32 import jalview.datamodel.SequenceI;
33 import jalview.exceptions.JalviewException;
34 import jalview.io.FastaFile;
35 import jalview.io.FileParse;
36 import jalview.io.gff.SequenceOntologyFactory;
37 import jalview.io.gff.SequenceOntologyI;
38 import jalview.util.Comparison;
39 import jalview.util.DBRefUtils;
40 import jalview.util.MapList;
42 import java.io.IOException;
43 import java.net.MalformedURLException;
45 import java.util.ArrayList;
46 import java.util.Arrays;
47 import java.util.Collections;
48 import java.util.Comparator;
49 import java.util.List;
52 * Base class for Ensembl sequence fetchers
54 * @see http://rest.ensembl.org/documentation/info/sequence_id
57 public abstract class EnsemblSeqProxy extends EnsemblRestClient
59 private static final String ALLELES = "alleles";
61 protected static final String PARENT = "Parent";
63 protected static final String ID = "ID";
65 protected static final String NAME = "Name";
67 protected static final String DESCRIPTION = "description";
70 * enum for 'type' parameter to the /sequence REST service
72 public enum EnsemblSeqType
75 * type=genomic to fetch full dna including introns
80 * type=cdna to fetch coding dna including UTRs
85 * type=cds to fetch coding dna excluding UTRs
90 * type=protein to fetch peptide product sequence
95 * the value of the 'type' parameter to fetch this version of
100 EnsemblSeqType(String t)
105 public String getType()
113 * A comparator to sort ranges into ascending start position order
115 private class RangeSorter implements Comparator<int[]>
119 RangeSorter(boolean forward)
125 public int compare(int[] o1, int[] o2)
127 return (forwards ? 1 : -1) * Integer.compare(o1[0], o2[0]);
133 * Default constructor (to use rest.ensembl.org)
135 public EnsemblSeqProxy()
141 * Constructor given the target domain to fetch data from
143 public EnsemblSeqProxy(String d)
149 * Makes the sequence queries to Ensembl's REST service and returns an
150 * alignment consisting of the returned sequences.
153 public AlignmentI getSequenceRecords(String query) throws Exception
155 // TODO use a String... query vararg instead?
157 // danger: accession separator used as a regex here, a string elsewhere
158 // in this case it is ok (it is just a space), but (e.g.) '\' would not be
159 List<String> allIds = Arrays.asList(query
160 .split(getAccessionSeparator()));
161 AlignmentI alignment = null;
165 * execute queries, if necessary in batches of the
166 * maximum allowed number of ids
168 int maxQueryCount = getMaximumQueryCount();
169 for (int v = 0, vSize = allIds.size(); v < vSize; v += maxQueryCount)
171 int p = Math.min(vSize, v + maxQueryCount);
172 List<String> ids = allIds.subList(v, p);
175 alignment = fetchSequences(ids, alignment);
176 } catch (Throwable r)
179 String msg = "Aborting ID retrieval after " + v
180 + " chunks. Unexpected problem (" + r.getLocalizedMessage()
182 System.err.println(msg);
188 if (alignment == null)
194 * fetch and transfer genomic sequence features,
195 * fetch protein product and add as cross-reference
197 for (String accId : allIds)
199 addFeaturesAndProduct(accId, alignment);
202 for (SequenceI seq : alignment.getSequences())
204 getCrossReferences(seq);
211 * Fetches Ensembl features using the /overlap REST endpoint, and adds them to
212 * the sequence in the alignment. Also fetches the protein product, maps it
213 * from the CDS features of the sequence, and saves it as a cross-reference of
219 protected void addFeaturesAndProduct(String accId, AlignmentI alignment)
221 if (alignment == null)
229 * get 'dummy' genomic sequence with exon, cds and variation features
231 SequenceI genomicSequence = null;
232 EnsemblFeatures gffFetcher = new EnsemblFeatures(getDomain());
233 EnsemblFeatureType[] features = getFeaturesToFetch();
234 AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
236 if (geneFeatures != null && geneFeatures.getHeight() > 0)
238 genomicSequence = geneFeatures.getSequenceAt(0);
240 if (genomicSequence != null)
243 * transfer features to the query sequence
245 SequenceI querySeq = alignment.findName(accId);
246 if (transferFeatures(accId, genomicSequence, querySeq))
250 * fetch and map protein product, and add it as a cross-reference
251 * of the retrieved sequence
253 addProteinProduct(querySeq);
256 } catch (IOException e)
258 System.err.println("Error transferring Ensembl features: "
264 * Returns those sequence feature types to fetch from Ensembl. We may want
265 * features either because they are of interest to the user, or as means to
266 * identify the locations of the sequence on the genomic sequence (CDS
267 * features identify CDS, exon features identify cDNA etc).
271 protected abstract EnsemblFeatureType[] getFeaturesToFetch();
274 * Fetches and maps the protein product, and adds it as a cross-reference of
275 * the retrieved sequence
277 protected void addProteinProduct(SequenceI querySeq)
279 String accId = querySeq.getName();
282 AlignmentI protein = new EnsemblProtein(getDomain())
283 .getSequenceRecords(accId);
284 if (protein == null || protein.getHeight() == 0)
286 System.out.println("No protein product found for " + accId);
289 SequenceI proteinSeq = protein.getSequenceAt(0);
292 * need dataset sequences (to be the subject of mappings)
294 proteinSeq.createDatasetSequence();
295 querySeq.createDatasetSequence();
297 MapList mapList = AlignmentUtils
298 .mapCdsToProtein(querySeq, proteinSeq);
301 // clunky: ensure Uniprot xref if we have one is on mapped sequence
302 SequenceI ds = proteinSeq.getDatasetSequence();
303 // TODO: Verify ensp primary ref is on proteinSeq.getDatasetSequence()
304 Mapping map = new Mapping(ds, mapList);
305 DBRefEntry dbr = new DBRefEntry(getDbSource(),
306 getEnsemblDataVersion(), proteinSeq.getName(), map);
307 querySeq.getDatasetSequence().addDBRef(dbr);
308 DBRefEntry[] uprots = DBRefUtils.selectRefs(ds.getDBRefs(),
309 new String[] { DBRefSource.UNIPROT });
310 DBRefEntry[] upxrefs = DBRefUtils.selectRefs(querySeq.getDBRefs(),
311 new String[] { DBRefSource.UNIPROT });
314 for (DBRefEntry up : uprots)
316 // locate local uniprot ref and map
317 List<DBRefEntry> upx = DBRefUtils.searchRefs(upxrefs,
318 up.getAccessionId());
327 .warn("Implementation issue - multiple uniprot acc on product sequence.");
332 upxref = new DBRefEntry(DBRefSource.UNIPROT,
333 getEnsemblDataVersion(), up.getAccessionId());
336 Mapping newMap = new Mapping(ds, mapList);
337 upxref.setVersion(getEnsemblDataVersion());
338 upxref.setMap(newMap);
341 // add the new uniprot ref
342 querySeq.getDatasetSequence().addDBRef(upxref);
349 * copy exon features to protein, compute peptide variants from dna
350 * variants and add as features on the protein sequence ta-da
353 .computeProteinFeatures(querySeq, proteinSeq, mapList);
355 } catch (Exception e)
358 .println(String.format("Error retrieving protein for %s: %s",
359 accId, e.getMessage()));
364 * Get database xrefs from Ensembl, and attach them to the sequence
368 protected void getCrossReferences(SequenceI seq)
370 while (seq.getDatasetSequence() != null)
372 seq = seq.getDatasetSequence();
375 EnsemblXref xrefFetcher = new EnsemblXref(getDomain(), getDbSource(),
376 getEnsemblDataVersion());
377 List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName());
378 for (DBRefEntry xref : xrefs)
384 * and add a reference to itself
386 DBRefEntry self = new DBRefEntry(getDbSource(),
387 getEnsemblDataVersion(), seq.getName());
392 * Fetches sequences for the list of accession ids and adds them to the
393 * alignment. Returns the extended (or created) alignment.
398 * @throws JalviewException
399 * @throws IOException
401 protected AlignmentI fetchSequences(List<String> ids, AlignmentI alignment)
402 throws JalviewException, IOException
404 if (!isEnsemblAvailable())
407 throw new JalviewException("ENSEMBL Rest API not available.");
409 FileParse fp = getSequenceReader(ids);
415 FastaFile fr = new FastaFile(fp);
416 if (fr.hasWarningMessage())
418 System.out.println(String.format(
419 "Warning when retrieving %d ids %s\n%s", ids.size(),
420 ids.toString(), fr.getWarningMessage()));
422 else if (fr.getSeqs().size() != ids.size())
424 System.out.println(String.format(
425 "Only retrieved %d sequences for %d query strings", fr
426 .getSeqs().size(), ids.size()));
429 if (fr.getSeqs().size() == 1 && fr.getSeqs().get(0).getLength() == 0)
432 * POST request has returned an empty FASTA file e.g. for invalid id
434 throw new IOException("No data returned for " + ids);
437 if (fr.getSeqs().size() > 0)
439 AlignmentI seqal = new Alignment(fr.getSeqsAsArray());
440 for (SequenceI sq : seqal.getSequences())
442 if (sq.getDescription() == null)
444 sq.setDescription(getDbName());
446 String name = sq.getName();
447 if (ids.contains(name)
448 || ids.contains(name.replace("ENSP", "ENST")))
450 DBRefEntry dbref = DBRefUtils.parseToDbRef(sq, getDbSource(),
451 getEnsemblDataVersion(), name);
455 if (alignment == null)
461 alignment.append(seqal);
468 * Returns the URL for the REST call
471 * @throws MalformedURLException
474 protected URL getUrl(List<String> ids) throws MalformedURLException
477 * a single id is included in the URL path
478 * multiple ids go in the POST body instead
480 StringBuffer urlstring = new StringBuffer(128);
481 urlstring.append(getDomain() + "/sequence/id");
484 urlstring.append("/").append(ids.get(0));
486 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
487 urlstring.append("?type=").append(getSourceEnsemblType().getType());
488 urlstring.append(("&Accept=text/x-fasta"));
490 URL url = new URL(urlstring.toString());
495 * A sequence/id POST request currently allows up to 50 queries
497 * @see http://rest.ensembl.org/documentation/info/sequence_id_post
500 public int getMaximumQueryCount()
506 protected boolean useGetRequest()
512 protected String getRequestMimeType(boolean multipleIds)
514 return multipleIds ? "application/json" : "text/x-fasta";
518 protected String getResponseMimeType()
520 return "text/x-fasta";
525 * @return the configured sequence return type for this source
527 protected abstract EnsemblSeqType getSourceEnsemblType();
530 * Returns a list of [start, end] genomic ranges corresponding to the sequence
533 * The correspondence between the frames of reference is made by locating
534 * those features on the genomic sequence which identify the retrieved
535 * sequence. Specifically
537 * <li>genomic sequence is identified by "transcript" features with
538 * ID=transcript:transcriptId</li>
539 * <li>cdna sequence is identified by "exon" features with
540 * Parent=transcript:transcriptId</li>
541 * <li>cds sequence is identified by "CDS" features with
542 * Parent=transcript:transcriptId</li>
545 * The returned ranges are sorted to run forwards (for positive strand) or
546 * backwards (for negative strand). Aborts and returns null if both positive
547 * and negative strand are found (this should not normally happen).
549 * @param sourceSequence
552 * the start position of the sequence we are mapping to
555 protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
556 String accId, int start)
558 SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
565 * generously initial size for number of cds regions
566 * (worst case titin Q8WZ42 has c. 313 exons)
568 List<int[]> regions = new ArrayList<int[]>(100);
569 int mappedLength = 0;
570 int direction = 1; // forward
571 boolean directionSet = false;
573 for (SequenceFeature sf : sfs)
576 * accept the target feature type or a specialisation of it
577 * (e.g. coding_exon for exon)
579 if (identifiesSequence(sf, accId))
581 int strand = sf.getStrand();
582 strand = strand == 0 ? 1 : strand; // treat unknown as forward
584 if (directionSet && strand != direction)
586 // abort - mix of forward and backward
587 System.err.println("Error: forward and backward strand for "
595 * add to CDS ranges, semi-sorted forwards/backwards
599 regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
603 regions.add(new int[] { sf.getBegin(), sf.getEnd() });
605 mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
610 * 'gene' sequence is contiguous so we can stop as soon as its
611 * identifying feature has been found
618 if (regions.isEmpty())
620 System.out.println("Failed to identify target sequence for " + accId
621 + " from genomic features");
626 * a final sort is needed since Ensembl returns CDS sorted within source
627 * (havana / ensembl_havana)
629 Collections.sort(regions, new RangeSorter(direction == 1));
631 List<int[]> to = Arrays.asList(new int[] { start,
632 start + mappedLength - 1 });
634 return new MapList(regions, to, 1, 1);
638 * Answers true if the sequence being retrieved may occupy discontiguous
639 * regions on the genomic sequence.
641 protected boolean isSpliceable()
647 * Returns true if the sequence feature marks positions of the genomic
648 * sequence feature which are within the sequence being retrieved. For
649 * example, an 'exon' feature whose parent is the target transcript marks the
650 * cdna positions of the transcript.
656 protected abstract boolean identifiesSequence(SequenceFeature sf,
660 * Transfers the sequence feature to the target sequence, locating its start
661 * and end range based on the mapping. Features which do not overlap the
662 * target sequence are ignored.
665 * @param targetSequence
667 * mapping from the sequence feature's coordinates to the target
669 * @param forwardStrand
671 protected void transferFeature(SequenceFeature sf,
672 SequenceI targetSequence, MapList mapping, boolean forwardStrand)
674 int start = sf.getBegin();
675 int end = sf.getEnd();
676 int[] mappedRange = mapping.locateInTo(start, end);
678 if (mappedRange != null)
680 SequenceFeature copy = new SequenceFeature(sf);
681 copy.setBegin(Math.min(mappedRange[0], mappedRange[1]));
682 copy.setEnd(Math.max(mappedRange[0], mappedRange[1]));
683 if (".".equals(copy.getFeatureGroup()))
685 copy.setFeatureGroup(getDbSource());
687 targetSequence.addSequenceFeature(copy);
690 * for sequence_variant on reverse strand, have to convert the allele
691 * values to their complements
694 && SequenceOntologyFactory.getInstance().isA(sf.getType(),
695 SequenceOntologyI.SEQUENCE_VARIANT))
697 reverseComplementAlleles(copy);
703 * Change the 'alleles' value of a feature by converting to complementary
704 * bases, and also update the feature description to match
708 static void reverseComplementAlleles(SequenceFeature sf)
710 final String alleles = (String) sf.getValue(ALLELES);
715 StringBuilder complement = new StringBuilder(alleles.length());
716 for (String allele : alleles.split(","))
718 reverseComplementAllele(complement, allele);
720 String comp = complement.toString();
721 sf.setValue(ALLELES, comp);
722 sf.setDescription(comp);
725 * replace value of "alleles=" in sf.ATTRIBUTES as well
726 * so 'output as GFF' shows reverse complement alleles
728 String atts = sf.getAttributes();
731 atts = atts.replace(ALLELES + "=" + alleles, ALLELES + "=" + comp);
732 sf.setAttributes(atts);
737 * Makes the 'reverse complement' of the given allele and appends it to the
738 * buffer, after a comma separator if not the first
743 static void reverseComplementAllele(StringBuilder complement,
746 if (complement.length() > 0)
748 complement.append(",");
752 * some 'alleles' are actually descriptive terms
753 * e.g. HGMD_MUTATION, PhenCode_variation
754 * - we don't want to 'reverse complement' these
756 if (!Comparison.isNucleotideSequence(allele, true))
758 complement.append(allele);
762 for (int i = allele.length() - 1; i >= 0; i--)
764 complement.append(Dna.getComplement(allele.charAt(i)));
770 * Transfers features from sourceSequence to targetSequence
773 * @param sourceSequence
774 * @param targetSequence
775 * @return true if any features were transferred, else false
777 protected boolean transferFeatures(String accessionId,
778 SequenceI sourceSequence, SequenceI targetSequence)
780 if (sourceSequence == null || targetSequence == null)
785 // long start = System.currentTimeMillis();
786 SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
787 MapList mapping = getGenomicRangesFromFeatures(sourceSequence,
788 accessionId, targetSequence.getStart());
794 boolean result = transferFeatures(sfs, targetSequence, mapping,
796 // System.out.println("transferFeatures (" + (sfs.length) + " --> "
797 // + targetSequence.getSequenceFeatures().length + ") to "
798 // + targetSequence.getName()
799 // + " took " + (System.currentTimeMillis() - start) + "ms");
804 * Transfer features to the target sequence. The start/end positions are
805 * converted using the mapping. Features which do not overlap are ignored.
806 * Features whose parent is not the specified identifier are also ignored.
809 * @param targetSequence
814 protected boolean transferFeatures(SequenceFeature[] features,
815 SequenceI targetSequence, MapList mapping, String parentId)
817 final boolean forwardStrand = mapping.isFromForwardStrand();
820 * sort features by start position (which corresponds to end
821 * position descending if reverse strand) so as to add them in
822 * 'forwards' order to the target sequence
824 sortFeatures(features, forwardStrand);
826 boolean transferred = false;
827 for (SequenceFeature sf : features)
829 if (retainFeature(sf, parentId))
831 transferFeature(sf, targetSequence, mapping, forwardStrand);
839 * Sort features by start position ascending (if on forward strand), or end
840 * position descending (if on reverse strand)
843 * @param forwardStrand
845 protected static void sortFeatures(SequenceFeature[] features,
846 final boolean forwardStrand)
848 Arrays.sort(features, new Comparator<SequenceFeature>()
851 public int compare(SequenceFeature o1, SequenceFeature o2)
855 return Integer.compare(o1.getBegin(), o2.getBegin());
859 return Integer.compare(o2.getEnd(), o1.getEnd());
866 * Answers true if the feature type is one we want to keep for the sequence.
867 * Some features are only retrieved in order to identify the sequence range,
868 * and may then be discarded as redundant information (e.g. "CDS" feature for
871 @SuppressWarnings("unused")
872 protected boolean retainFeature(SequenceFeature sf, String accessionId)
874 return true; // override as required
878 * Answers true if the feature has a Parent which refers to the given
879 * accession id, or if the feature has no parent. Answers false if the
880 * feature's Parent is for a different accession id.
886 protected boolean featureMayBelong(SequenceFeature sf, String identifier)
888 String parent = (String) sf.getValue(PARENT);
889 // using contains to allow for prefix "gene:", "transcript:" etc
890 if (parent != null && !parent.contains(identifier))
892 // this genomic feature belongs to a different transcript
899 public String getDescription()
901 return "Ensembl " + getSourceEnsemblType().getType()
902 + " sequence with variant features";
906 * Returns a (possibly empty) list of features on the sequence which have the
907 * specified sequence ontology type (or a sub-type of it), and the given
908 * identifier as parent
915 protected List<SequenceFeature> findFeatures(SequenceI sequence,
916 String type, String parentId)
918 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
920 SequenceFeature[] sfs = sequence.getSequenceFeatures();
923 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
924 for (SequenceFeature sf : sfs)
926 if (so.isA(sf.getType(), type))
928 String parent = (String) sf.getValue(PARENT);
929 if (parent.equals(parentId))
940 * Answers true if the feature type is either 'NMD_transcript_variant' or
941 * 'transcript' or one of its sub-types in the Sequence Ontology. This is
942 * needed because NMD_transcript_variant behaves like 'transcript' in Ensembl
943 * although strictly speaking it is not (it is a sub-type of
949 public static boolean isTranscript(String featureType)
951 return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
952 || SequenceOntologyFactory.getInstance().isA(featureType,
953 SequenceOntologyI.TRANSCRIPT);