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.datamodel.features.SequenceFeatures;
34 import jalview.exceptions.JalviewException;
35 import jalview.io.FastaFile;
36 import jalview.io.FileParse;
37 import jalview.io.gff.Gff3Helper;
38 import jalview.io.gff.SequenceOntologyFactory;
39 import jalview.io.gff.SequenceOntologyI;
40 import jalview.util.Comparison;
41 import jalview.util.DBRefUtils;
42 import jalview.util.IntRangeComparator;
43 import jalview.util.MapList;
45 import java.io.IOException;
46 import java.net.MalformedURLException;
48 import java.util.ArrayList;
49 import java.util.Arrays;
50 import java.util.Collections;
51 import java.util.List;
53 import java.util.Map.Entry;
56 * Base class for Ensembl sequence fetchers
58 * @see http://rest.ensembl.org/documentation/info/sequence_id
61 public abstract class EnsemblSeqProxy extends EnsemblRestClient
63 protected static final String PARENT = "Parent";
65 protected static final String ID = "ID";
67 protected static final String NAME = "Name";
69 protected static final String DESCRIPTION = "description";
72 * enum for 'type' parameter to the /sequence REST service
74 public enum EnsemblSeqType
77 * type=genomic to fetch full dna including introns
82 * type=cdna to fetch coding dna including UTRs
87 * type=cds to fetch coding dna excluding UTRs
92 * type=protein to fetch peptide product sequence
97 * the value of the 'type' parameter to fetch this version of
102 EnsemblSeqType(String t)
107 public String getType()
115 * Default constructor (to use rest.ensembl.org)
117 public EnsemblSeqProxy()
123 * Constructor given the target domain to fetch data from
125 public EnsemblSeqProxy(String d)
131 * Makes the sequence queries to Ensembl's REST service and returns an
132 * alignment consisting of the returned sequences.
135 public AlignmentI getSequenceRecords(String query) throws Exception
137 // TODO use a String... query vararg instead?
139 // danger: accession separator used as a regex here, a string elsewhere
140 // in this case it is ok (it is just a space), but (e.g.) '\' would not be
141 List<String> allIds = Arrays
142 .asList(query.split(getAccessionSeparator()));
143 AlignmentI alignment = null;
147 * execute queries, if necessary in batches of the
148 * maximum allowed number of ids
150 int maxQueryCount = getMaximumQueryCount();
151 for (int v = 0, vSize = allIds.size(); v < vSize; v += maxQueryCount)
153 int p = Math.min(vSize, v + maxQueryCount);
154 List<String> ids = allIds.subList(v, p);
157 alignment = fetchSequences(ids, alignment);
158 } catch (Throwable r)
161 String msg = "Aborting ID retrieval after " + v
162 + " chunks. Unexpected problem (" + r.getLocalizedMessage()
164 System.err.println(msg);
170 if (alignment == null)
176 * fetch and transfer genomic sequence features,
177 * fetch protein product and add as cross-reference
179 for (String accId : allIds)
181 addFeaturesAndProduct(accId, alignment);
184 for (SequenceI seq : alignment.getSequences())
186 getCrossReferences(seq);
193 * Fetches Ensembl features using the /overlap REST endpoint, and adds them to
194 * the sequence in the alignment. Also fetches the protein product, maps it
195 * from the CDS features of the sequence, and saves it as a cross-reference of
201 protected void addFeaturesAndProduct(String accId, AlignmentI alignment)
203 if (alignment == null)
211 * get 'dummy' genomic sequence with exon, cds and variation features
213 SequenceI genomicSequence = null;
214 EnsemblFeatures gffFetcher = new EnsemblFeatures(getDomain());
215 EnsemblFeatureType[] features = getFeaturesToFetch();
216 AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
218 if (geneFeatures != null && geneFeatures.getHeight() > 0)
220 genomicSequence = geneFeatures.getSequenceAt(0);
222 if (genomicSequence != null)
225 * transfer features to the query sequence
227 SequenceI querySeq = alignment.findName(accId);
228 if (transferFeatures(accId, genomicSequence, querySeq))
232 * fetch and map protein product, and add it as a cross-reference
233 * of the retrieved sequence
235 addProteinProduct(querySeq);
238 } catch (IOException e)
241 "Error transferring Ensembl features: " + e.getMessage());
246 * Returns those sequence feature types to fetch from Ensembl. We may want
247 * features either because they are of interest to the user, or as means to
248 * identify the locations of the sequence on the genomic sequence (CDS
249 * features identify CDS, exon features identify cDNA etc).
253 protected abstract EnsemblFeatureType[] getFeaturesToFetch();
256 * Fetches and maps the protein product, and adds it as a cross-reference of
257 * the retrieved sequence
259 protected void addProteinProduct(SequenceI querySeq)
261 String accId = querySeq.getName();
264 AlignmentI protein = new EnsemblProtein(getDomain())
265 .getSequenceRecords(accId);
266 if (protein == null || protein.getHeight() == 0)
268 System.out.println("No protein product found for " + accId);
271 SequenceI proteinSeq = protein.getSequenceAt(0);
274 * need dataset sequences (to be the subject of mappings)
276 proteinSeq.createDatasetSequence();
277 querySeq.createDatasetSequence();
279 MapList mapList = AlignmentUtils.mapCdsToProtein(querySeq,
283 // clunky: ensure Uniprot xref if we have one is on mapped sequence
284 SequenceI ds = proteinSeq.getDatasetSequence();
285 // TODO: Verify ensp primary ref is on proteinSeq.getDatasetSequence()
286 Mapping map = new Mapping(ds, mapList);
287 DBRefEntry dbr = new DBRefEntry(getDbSource(),
288 getEnsemblDataVersion(), proteinSeq.getName(), map);
289 querySeq.getDatasetSequence().addDBRef(dbr);
290 DBRefEntry[] uprots = DBRefUtils.selectRefs(ds.getDBRefs(),
292 { DBRefSource.UNIPROT });
293 DBRefEntry[] upxrefs = DBRefUtils.selectRefs(querySeq.getDBRefs(),
295 { DBRefSource.UNIPROT });
298 for (DBRefEntry up : uprots)
300 // locate local uniprot ref and map
301 List<DBRefEntry> upx = DBRefUtils.searchRefs(upxrefs,
302 up.getAccessionId());
311 "Implementation issue - multiple uniprot acc on product sequence.");
316 upxref = new DBRefEntry(DBRefSource.UNIPROT,
317 getEnsemblDataVersion(), up.getAccessionId());
320 Mapping newMap = new Mapping(ds, mapList);
321 upxref.setVersion(getEnsemblDataVersion());
322 upxref.setMap(newMap);
325 // add the new uniprot ref
326 querySeq.getDatasetSequence().addDBRef(upxref);
333 * copy exon features to protein, compute peptide variants from dna
334 * variants and add as features on the protein sequence ta-da
336 AlignmentUtils.computeProteinFeatures(querySeq, proteinSeq,
339 } catch (Exception e)
342 .println(String.format("Error retrieving protein for %s: %s",
343 accId, e.getMessage()));
348 * Get database xrefs from Ensembl, and attach them to the sequence
352 protected void getCrossReferences(SequenceI seq)
354 while (seq.getDatasetSequence() != null)
356 seq = seq.getDatasetSequence();
359 EnsemblXref xrefFetcher = new EnsemblXref(getDomain(), getDbSource(),
360 getEnsemblDataVersion());
361 List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName());
362 for (DBRefEntry xref : xrefs)
368 * and add a reference to itself
370 DBRefEntry self = new DBRefEntry(getDbSource(), getEnsemblDataVersion(),
376 * Fetches sequences for the list of accession ids and adds them to the
377 * alignment. Returns the extended (or created) alignment.
382 * @throws JalviewException
383 * @throws IOException
385 protected AlignmentI fetchSequences(List<String> ids,
386 AlignmentI alignment) throws JalviewException, IOException
388 if (!isEnsemblAvailable())
391 throw new JalviewException("ENSEMBL Rest API not available.");
393 FileParse fp = getSequenceReader(ids);
399 FastaFile fr = new FastaFile(fp);
400 if (fr.hasWarningMessage())
403 String.format("Warning when retrieving %d ids %s\n%s",
404 ids.size(), ids.toString(), fr.getWarningMessage()));
406 else if (fr.getSeqs().size() != ids.size())
408 System.out.println(String.format(
409 "Only retrieved %d sequences for %d query strings",
410 fr.getSeqs().size(), ids.size()));
413 if (fr.getSeqs().size() == 1 && fr.getSeqs().get(0).getLength() == 0)
416 * POST request has returned an empty FASTA file e.g. for invalid id
418 throw new IOException("No data returned for " + ids);
421 if (fr.getSeqs().size() > 0)
423 AlignmentI seqal = new Alignment(fr.getSeqsAsArray());
424 for (SequenceI sq : seqal.getSequences())
426 if (sq.getDescription() == null)
428 sq.setDescription(getDbName());
430 String name = sq.getName();
431 if (ids.contains(name)
432 || ids.contains(name.replace("ENSP", "ENST")))
434 DBRefEntry dbref = DBRefUtils.parseToDbRef(sq, getDbSource(),
435 getEnsemblDataVersion(), name);
439 if (alignment == null)
445 alignment.append(seqal);
452 * Returns the URL for the REST call
455 * @throws MalformedURLException
458 protected URL getUrl(List<String> ids) throws MalformedURLException
461 * a single id is included in the URL path
462 * multiple ids go in the POST body instead
464 StringBuffer urlstring = new StringBuffer(128);
465 urlstring.append(getDomain() + "/sequence/id");
468 urlstring.append("/").append(ids.get(0));
470 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
471 urlstring.append("?type=").append(getSourceEnsemblType().getType());
472 urlstring.append(("&Accept=text/x-fasta"));
474 Map<String, String> params = getAdditionalParameters();
477 for (Entry<String, String> entry : params.entrySet())
479 urlstring.append("&").append(entry.getKey()).append("=")
480 .append(entry.getValue());
484 URL url = new URL(urlstring.toString());
489 * Override this method to add any additional x=y URL parameters needed
493 protected Map<String, String> getAdditionalParameters()
499 * A sequence/id POST request currently allows up to 50 queries
501 * @see http://rest.ensembl.org/documentation/info/sequence_id_post
504 public int getMaximumQueryCount()
510 protected boolean useGetRequest()
516 protected String getRequestMimeType(boolean multipleIds)
518 return multipleIds ? "application/json" : "text/x-fasta";
522 protected String getResponseMimeType()
524 return "text/x-fasta";
529 * @return the configured sequence return type for this source
531 protected abstract EnsemblSeqType getSourceEnsemblType();
534 * Returns a list of [start, end] genomic ranges corresponding to the sequence
537 * The correspondence between the frames of reference is made by locating
538 * those features on the genomic sequence which identify the retrieved
539 * sequence. Specifically
541 * <li>genomic sequence is identified by "transcript" features with
542 * ID=transcript:transcriptId</li>
543 * <li>cdna sequence is identified by "exon" features with
544 * Parent=transcript:transcriptId</li>
545 * <li>cds sequence is identified by "CDS" features with
546 * Parent=transcript:transcriptId</li>
549 * The returned ranges are sorted to run forwards (for positive strand) or
550 * backwards (for negative strand). Aborts and returns null if both positive
551 * and negative strand are found (this should not normally happen).
553 * @param sourceSequence
556 * the start position of the sequence we are mapping to
559 protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
560 String accId, int start)
562 // SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
563 List<SequenceFeature> sfs = sourceSequence.getFeatures()
564 .getPositionalFeatures();
571 * generously initial size for number of cds regions
572 * (worst case titin Q8WZ42 has c. 313 exons)
574 List<int[]> regions = new ArrayList<int[]>(100);
575 int mappedLength = 0;
576 int direction = 1; // forward
577 boolean directionSet = false;
579 for (SequenceFeature sf : sfs)
582 * accept the target feature type or a specialisation of it
583 * (e.g. coding_exon for exon)
585 if (identifiesSequence(sf, accId))
587 int strand = sf.getStrand();
588 strand = strand == 0 ? 1 : strand; // treat unknown as forward
590 if (directionSet && strand != direction)
592 // abort - mix of forward and backward
594 "Error: forward and backward strand for " + accId);
601 * add to CDS ranges, semi-sorted forwards/backwards
605 regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
609 regions.add(new int[] { sf.getBegin(), sf.getEnd() });
611 mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
616 * 'gene' sequence is contiguous so we can stop as soon as its
617 * identifying feature has been found
624 if (regions.isEmpty())
626 System.out.println("Failed to identify target sequence for " + accId
627 + " from genomic features");
632 * a final sort is needed since Ensembl returns CDS sorted within source
633 * (havana / ensembl_havana)
635 Collections.sort(regions, direction == 1 ? IntRangeComparator.ASCENDING
636 : IntRangeComparator.DESCENDING);
638 List<int[]> to = Arrays
640 { start, start + mappedLength - 1 });
642 return new MapList(regions, to, 1, 1);
646 * Answers true if the sequence being retrieved may occupy discontiguous
647 * regions on the genomic sequence.
649 protected boolean isSpliceable()
655 * Returns true if the sequence feature marks positions of the genomic
656 * sequence feature which are within the sequence being retrieved. For
657 * example, an 'exon' feature whose parent is the target transcript marks the
658 * cdna positions of the transcript.
664 protected abstract boolean identifiesSequence(SequenceFeature sf,
668 * Transfers the sequence feature to the target sequence, locating its start
669 * and end range based on the mapping. Features which do not overlap the
670 * target sequence are ignored.
673 * @param targetSequence
675 * mapping from the sequence feature's coordinates to the target
677 * @param forwardStrand
679 protected void transferFeature(SequenceFeature sf,
680 SequenceI targetSequence, MapList mapping, boolean forwardStrand)
682 int start = sf.getBegin();
683 int end = sf.getEnd();
684 int[] mappedRange = mapping.locateInTo(start, end);
686 if (mappedRange != null)
688 String group = sf.getFeatureGroup();
689 if (".".equals(group))
691 group = getDbSource();
693 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
694 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
695 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
696 group, sf.getScore());
697 targetSequence.addSequenceFeature(copy);
700 * for sequence_variant on reverse strand, have to convert the allele
701 * values to their complements
703 if (!forwardStrand && SequenceOntologyFactory.getInstance()
704 .isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
706 reverseComplementAlleles(copy);
712 * Change the 'alleles' value of a feature by converting to complementary
713 * bases, and also update the feature description to match
717 static void reverseComplementAlleles(SequenceFeature sf)
719 final String alleles = (String) sf.getValue(Gff3Helper.ALLELES);
724 StringBuilder complement = new StringBuilder(alleles.length());
725 for (String allele : alleles.split(","))
727 reverseComplementAllele(complement, allele);
729 String comp = complement.toString();
730 sf.setValue(Gff3Helper.ALLELES, comp);
731 sf.setDescription(comp);
734 * replace value of "alleles=" in sf.ATTRIBUTES as well
735 * so 'output as GFF' shows reverse complement alleles
737 String atts = sf.getAttributes();
740 atts = atts.replace(Gff3Helper.ALLELES + "=" + alleles,
741 Gff3Helper.ALLELES + "=" + comp);
742 sf.setAttributes(atts);
747 * Makes the 'reverse complement' of the given allele and appends it to the
748 * buffer, after a comma separator if not the first
753 static void reverseComplementAllele(StringBuilder complement,
756 if (complement.length() > 0)
758 complement.append(",");
762 * some 'alleles' are actually descriptive terms
763 * e.g. HGMD_MUTATION, PhenCode_variation
764 * - we don't want to 'reverse complement' these
766 if (!Comparison.isNucleotideSequence(allele, true))
768 complement.append(allele);
772 for (int i = allele.length() - 1; i >= 0; i--)
774 complement.append(Dna.getComplement(allele.charAt(i)));
780 * Transfers features from sourceSequence to targetSequence
783 * @param sourceSequence
784 * @param targetSequence
785 * @return true if any features were transferred, else false
787 protected boolean transferFeatures(String accessionId,
788 SequenceI sourceSequence, SequenceI targetSequence)
790 if (sourceSequence == null || targetSequence == null)
795 // long start = System.currentTimeMillis();
796 List<SequenceFeature> sfs = sourceSequence.getFeatures()
797 .getPositionalFeatures();
798 MapList mapping = getGenomicRangesFromFeatures(sourceSequence,
799 accessionId, targetSequence.getStart());
805 boolean result = transferFeatures(sfs, targetSequence, mapping,
807 // System.out.println("transferFeatures (" + (sfs.size()) + " --> "
808 // + targetSequence.getFeatures().getFeatureCount(true) + ") to "
809 // + targetSequence.getName() + " took "
810 // + (System.currentTimeMillis() - start) + "ms");
815 * Transfer features to the target sequence. The start/end positions are
816 * converted using the mapping. Features which do not overlap are ignored.
817 * Features whose parent is not the specified identifier are also ignored.
820 * @param targetSequence
825 protected boolean transferFeatures(List<SequenceFeature> sfs,
826 SequenceI targetSequence, MapList mapping, String parentId)
828 final boolean forwardStrand = mapping.isFromForwardStrand();
831 * sort features by start position (which corresponds to end
832 * position descending if reverse strand) so as to add them in
833 * 'forwards' order to the target sequence
835 SequenceFeatures.sortFeatures(sfs, forwardStrand);
837 boolean transferred = false;
838 for (SequenceFeature sf : sfs)
840 if (retainFeature(sf, parentId))
842 transferFeature(sf, targetSequence, mapping, forwardStrand);
850 * Answers true if the feature type is one we want to keep for the sequence.
851 * Some features are only retrieved in order to identify the sequence range,
852 * and may then be discarded as redundant information (e.g. "CDS" feature for
855 @SuppressWarnings("unused")
856 protected boolean retainFeature(SequenceFeature sf, String accessionId)
858 return true; // override as required
862 * Answers true if the feature has a Parent which refers to the given
863 * accession id, or if the feature has no parent. Answers false if the
864 * feature's Parent is for a different accession id.
870 protected boolean featureMayBelong(SequenceFeature sf, String identifier)
872 String parent = (String) sf.getValue(PARENT);
873 // using contains to allow for prefix "gene:", "transcript:" etc
874 if (parent != null && !parent.contains(identifier))
876 // this genomic feature belongs to a different transcript
883 public String getDescription()
885 return "Ensembl " + getSourceEnsemblType().getType()
886 + " sequence with variant features";
890 * Returns a (possibly empty) list of features on the sequence which have the
891 * specified sequence ontology term (or a sub-type of it), and the given
892 * identifier as parent
899 protected List<SequenceFeature> findFeatures(SequenceI sequence,
900 String term, String parentId)
902 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
904 List<SequenceFeature> sfs = sequence.getFeatures()
905 .getFeaturesByOntology(term);
906 for (SequenceFeature sf : sfs)
908 String parent = (String) sf.getValue(PARENT);
909 if (parent != null && parent.equals(parentId))
919 * Answers true if the feature type is either 'NMD_transcript_variant' or
920 * 'transcript' or one of its sub-types in the Sequence Ontology. This is
921 * needed because NMD_transcript_variant behaves like 'transcript' in Ensembl
922 * although strictly speaking it is not (it is a sub-type of
928 public static boolean isTranscript(String featureType)
930 return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
931 || SequenceOntologyFactory.getInstance().isA(featureType,
932 SequenceOntologyI.TRANSCRIPT);