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.SequenceOntologyFactory;
38 import jalview.io.gff.SequenceOntologyI;
39 import jalview.util.Comparison;
40 import jalview.util.DBRefUtils;
41 import jalview.util.IntRangeComparator;
42 import jalview.util.MapList;
44 import java.io.IOException;
45 import java.net.MalformedURLException;
47 import java.util.ArrayList;
48 import java.util.Arrays;
49 import java.util.Collections;
50 import java.util.List;
52 import java.util.Map.Entry;
55 * Base class for Ensembl sequence fetchers
57 * @see http://rest.ensembl.org/documentation/info/sequence_id
60 public abstract class EnsemblSeqProxy extends EnsemblRestClient
62 private static final String ALLELES = "alleles";
64 protected static final String PARENT = "Parent";
66 protected static final String ID = "ID";
68 protected static final String NAME = "Name";
70 protected static final String DESCRIPTION = "description";
73 * enum for 'type' parameter to the /sequence REST service
75 public enum EnsemblSeqType
78 * type=genomic to fetch full dna including introns
83 * type=cdna to fetch coding dna including UTRs
88 * type=cds to fetch coding dna excluding UTRs
93 * type=protein to fetch peptide product sequence
98 * the value of the 'type' parameter to fetch this version of
103 EnsemblSeqType(String t)
108 public String getType()
116 * Default constructor (to use rest.ensembl.org)
118 public EnsemblSeqProxy()
124 * Constructor given the target domain to fetch data from
126 public EnsemblSeqProxy(String d)
132 * Makes the sequence queries to Ensembl's REST service and returns an
133 * alignment consisting of the returned sequences.
136 public AlignmentI getSequenceRecords(String query) throws Exception
138 // TODO use a String... query vararg instead?
140 // danger: accession separator used as a regex here, a string elsewhere
141 // in this case it is ok (it is just a space), but (e.g.) '\' would not be
142 List<String> allIds = Arrays
143 .asList(query.split(getAccessionSeparator()));
144 AlignmentI alignment = null;
148 * execute queries, if necessary in batches of the
149 * maximum allowed number of ids
151 int maxQueryCount = getMaximumQueryCount();
152 for (int v = 0, vSize = allIds.size(); v < vSize; v += maxQueryCount)
154 int p = Math.min(vSize, v + maxQueryCount);
155 List<String> ids = allIds.subList(v, p);
158 alignment = fetchSequences(ids, alignment);
159 } catch (Throwable r)
162 String msg = "Aborting ID retrieval after " + v
163 + " chunks. Unexpected problem (" + r.getLocalizedMessage()
165 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 != null && 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)
242 "Error transferring Ensembl features: " + e.getMessage());
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,
284 // clunky: ensure Uniprot xref if we have one is on mapped sequence
285 SequenceI ds = proteinSeq.getDatasetSequence();
286 // TODO: Verify ensp primary ref is on proteinSeq.getDatasetSequence()
287 Mapping map = new Mapping(ds, mapList);
288 DBRefEntry dbr = new DBRefEntry(getDbSource(),
289 getEnsemblDataVersion(), proteinSeq.getName(), map);
290 querySeq.getDatasetSequence().addDBRef(dbr);
291 DBRefEntry[] uprots = DBRefUtils.selectRefs(ds.getDBRefs(),
293 { DBRefSource.UNIPROT });
294 DBRefEntry[] upxrefs = DBRefUtils.selectRefs(querySeq.getDBRefs(),
296 { DBRefSource.UNIPROT });
299 for (DBRefEntry up : uprots)
301 // locate local uniprot ref and map
302 List<DBRefEntry> upx = DBRefUtils.searchRefs(upxrefs,
303 up.getAccessionId());
312 "Implementation issue - multiple uniprot acc on product sequence.");
317 upxref = new DBRefEntry(DBRefSource.UNIPROT,
318 getEnsemblDataVersion(), up.getAccessionId());
321 Mapping newMap = new Mapping(ds, mapList);
322 upxref.setVersion(getEnsemblDataVersion());
323 upxref.setMap(newMap);
326 // add the new uniprot ref
327 querySeq.getDatasetSequence().addDBRef(upxref);
334 * copy exon features to protein, compute peptide variants from dna
335 * variants and add as features on the protein sequence ta-da
337 AlignmentUtils.computeProteinFeatures(querySeq, proteinSeq,
340 } catch (Exception e)
343 .println(String.format("Error retrieving protein for %s: %s",
344 accId, e.getMessage()));
349 * Get database xrefs from Ensembl, and attach them to the sequence
353 protected void getCrossReferences(SequenceI seq)
355 while (seq.getDatasetSequence() != null)
357 seq = seq.getDatasetSequence();
360 EnsemblXref xrefFetcher = new EnsemblXref(getDomain(), getDbSource(),
361 getEnsemblDataVersion());
362 List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName());
363 for (DBRefEntry xref : xrefs)
369 * and add a reference to itself
371 DBRefEntry self = new DBRefEntry(getDbSource(), getEnsemblDataVersion(),
377 * Fetches sequences for the list of accession ids and adds them to the
378 * alignment. Returns the extended (or created) alignment.
383 * @throws JalviewException
384 * @throws IOException
386 protected AlignmentI fetchSequences(List<String> ids,
387 AlignmentI alignment) throws JalviewException, IOException
389 if (!isEnsemblAvailable())
392 throw new JalviewException("ENSEMBL Rest API not available.");
394 FileParse fp = getSequenceReader(ids);
400 FastaFile fr = new FastaFile(fp);
401 if (fr.hasWarningMessage())
404 String.format("Warning when retrieving %d ids %s\n%s",
405 ids.size(), ids.toString(), fr.getWarningMessage()));
407 else if (fr.getSeqs().size() != ids.size())
409 System.out.println(String.format(
410 "Only retrieved %d sequences for %d query strings",
411 fr.getSeqs().size(), ids.size()));
414 if (fr.getSeqs().size() == 1 && fr.getSeqs().get(0).getLength() == 0)
417 * POST request has returned an empty FASTA file e.g. for invalid id
419 throw new IOException("No data returned for " + ids);
422 if (fr.getSeqs().size() > 0)
424 AlignmentI seqal = new Alignment(fr.getSeqsAsArray());
425 for (SequenceI sq : seqal.getSequences())
427 if (sq.getDescription() == null)
429 sq.setDescription(getDbName());
431 String name = sq.getName();
432 if (ids.contains(name)
433 || ids.contains(name.replace("ENSP", "ENST")))
435 DBRefEntry dbref = DBRefUtils.parseToDbRef(sq, getDbSource(),
436 getEnsemblDataVersion(), name);
440 if (alignment == null)
446 alignment.append(seqal);
453 * Returns the URL for the REST call
456 * @throws MalformedURLException
459 protected URL getUrl(List<String> ids) throws MalformedURLException
462 * a single id is included in the URL path
463 * multiple ids go in the POST body instead
465 StringBuffer urlstring = new StringBuffer(128);
466 urlstring.append(getDomain() + "/sequence/id");
469 urlstring.append("/").append(ids.get(0));
471 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
472 urlstring.append("?type=").append(getSourceEnsemblType().getType());
473 urlstring.append(("&Accept=text/x-fasta"));
475 Map<String, String> params = getAdditionalParameters();
478 for (Entry<String, String> entry : params.entrySet())
480 urlstring.append("&").append(entry.getKey()).append("=")
481 .append(entry.getValue());
485 URL url = new URL(urlstring.toString());
490 * Override this method to add any additional x=y URL parameters needed
494 protected Map<String, String> getAdditionalParameters()
500 * A sequence/id POST request currently allows up to 50 queries
502 * @see http://rest.ensembl.org/documentation/info/sequence_id_post
505 public int getMaximumQueryCount()
511 protected boolean useGetRequest()
517 protected String getRequestMimeType(boolean multipleIds)
519 return multipleIds ? "application/json" : "text/x-fasta";
523 protected String getResponseMimeType()
525 return "text/x-fasta";
530 * @return the configured sequence return type for this source
532 protected abstract EnsemblSeqType getSourceEnsemblType();
535 * Returns a list of [start, end] genomic ranges corresponding to the sequence
538 * The correspondence between the frames of reference is made by locating
539 * those features on the genomic sequence which identify the retrieved
540 * sequence. Specifically
542 * <li>genomic sequence is identified by "transcript" features with
543 * ID=transcript:transcriptId</li>
544 * <li>cdna sequence is identified by "exon" features with
545 * Parent=transcript:transcriptId</li>
546 * <li>cds sequence is identified by "CDS" features with
547 * Parent=transcript:transcriptId</li>
550 * The returned ranges are sorted to run forwards (for positive strand) or
551 * backwards (for negative strand). Aborts and returns null if both positive
552 * and negative strand are found (this should not normally happen).
554 * @param sourceSequence
557 * the start position of the sequence we are mapping to
560 protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
561 String accId, int start)
563 // SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
564 List<SequenceFeature> sfs = sourceSequence.getFeatures()
565 .getPositionalFeatures();
572 * generously initial size for number of cds regions
573 * (worst case titin Q8WZ42 has c. 313 exons)
575 List<int[]> regions = new ArrayList<int[]>(100);
576 int mappedLength = 0;
577 int direction = 1; // forward
578 boolean directionSet = false;
580 for (SequenceFeature sf : sfs)
583 * accept the target feature type or a specialisation of it
584 * (e.g. coding_exon for exon)
586 if (identifiesSequence(sf, accId))
588 int strand = sf.getStrand();
589 strand = strand == 0 ? 1 : strand; // treat unknown as forward
591 if (directionSet && strand != direction)
593 // abort - mix of forward and backward
595 "Error: forward and backward strand for " + accId);
602 * add to CDS ranges, semi-sorted forwards/backwards
606 regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
610 regions.add(new int[] { sf.getBegin(), sf.getEnd() });
612 mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
617 * 'gene' sequence is contiguous so we can stop as soon as its
618 * identifying feature has been found
625 if (regions.isEmpty())
627 System.out.println("Failed to identify target sequence for " + accId
628 + " from genomic features");
633 * a final sort is needed since Ensembl returns CDS sorted within source
634 * (havana / ensembl_havana)
636 Collections.sort(regions, direction == 1 ? IntRangeComparator.ASCENDING
637 : IntRangeComparator.DESCENDING);
639 List<int[]> to = Arrays
641 { start, start + mappedLength - 1 });
643 return new MapList(regions, to, 1, 1);
647 * Answers true if the sequence being retrieved may occupy discontiguous
648 * regions on the genomic sequence.
650 protected boolean isSpliceable()
656 * Returns true if the sequence feature marks positions of the genomic
657 * sequence feature which are within the sequence being retrieved. For
658 * example, an 'exon' feature whose parent is the target transcript marks the
659 * cdna positions of the transcript.
665 protected abstract boolean identifiesSequence(SequenceFeature sf,
669 * Transfers the sequence feature to the target sequence, locating its start
670 * and end range based on the mapping. Features which do not overlap the
671 * target sequence are ignored.
674 * @param targetSequence
676 * mapping from the sequence feature's coordinates to the target
678 * @param forwardStrand
680 protected void transferFeature(SequenceFeature sf,
681 SequenceI targetSequence, MapList mapping, boolean forwardStrand)
683 int start = sf.getBegin();
684 int end = sf.getEnd();
685 int[] mappedRange = mapping.locateInTo(start, end);
687 if (mappedRange != null)
689 String group = sf.getFeatureGroup();
690 if (".".equals(group))
692 group = getDbSource();
694 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
695 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
696 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
697 group, sf.getScore());
698 targetSequence.addSequenceFeature(copy);
701 * for sequence_variant on reverse strand, have to convert the allele
702 * values to their complements
704 if (!forwardStrand && SequenceOntologyFactory.getInstance()
705 .isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
707 reverseComplementAlleles(copy);
713 * Change the 'alleles' value of a feature by converting to complementary
714 * bases, and also update the feature description to match
718 static void reverseComplementAlleles(SequenceFeature sf)
720 final String alleles = (String) sf.getValue(ALLELES);
725 StringBuilder complement = new StringBuilder(alleles.length());
726 for (String allele : alleles.split(","))
728 reverseComplementAllele(complement, allele);
730 String comp = complement.toString();
731 sf.setValue(ALLELES, comp);
732 sf.setDescription(comp);
735 * replace value of "alleles=" in sf.ATTRIBUTES as well
736 * so 'output as GFF' shows reverse complement alleles
738 String atts = sf.getAttributes();
741 atts = atts.replace(ALLELES + "=" + alleles, 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 // SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
797 List<SequenceFeature> sfs = sourceSequence.getFeatures()
798 .getPositionalFeatures();
799 MapList mapping = getGenomicRangesFromFeatures(sourceSequence,
800 accessionId, targetSequence.getStart());
806 boolean result = transferFeatures(sfs, targetSequence, mapping,
808 System.out.println("transferFeatures (" + (sfs.size()) + " --> "
809 + targetSequence.getFeatures().getFeatureCount(true) + ") to "
810 + targetSequence.getName() + " took "
811 + (System.currentTimeMillis() - start) + "ms");
816 * Transfer features to the target sequence. The start/end positions are
817 * converted using the mapping. Features which do not overlap are ignored.
818 * Features whose parent is not the specified identifier are also ignored.
821 * @param targetSequence
826 protected boolean transferFeatures(List<SequenceFeature> sfs,
827 SequenceI targetSequence, MapList mapping, String parentId)
829 final boolean forwardStrand = mapping.isFromForwardStrand();
832 * sort features by start position (which corresponds to end
833 * position descending if reverse strand) so as to add them in
834 * 'forwards' order to the target sequence
836 SequenceFeatures.sortFeatures(sfs, forwardStrand);
838 boolean transferred = false;
839 for (SequenceFeature sf : sfs)
841 if (retainFeature(sf, parentId))
843 transferFeature(sf, targetSequence, mapping, forwardStrand);
851 * Answers true if the feature type is one we want to keep for the sequence.
852 * Some features are only retrieved in order to identify the sequence range,
853 * and may then be discarded as redundant information (e.g. "CDS" feature for
856 @SuppressWarnings("unused")
857 protected boolean retainFeature(SequenceFeature sf, String accessionId)
859 return true; // override as required
863 * Answers true if the feature has a Parent which refers to the given
864 * accession id, or if the feature has no parent. Answers false if the
865 * feature's Parent is for a different accession id.
871 protected boolean featureMayBelong(SequenceFeature sf, String identifier)
873 String parent = (String) sf.getValue(PARENT);
874 // using contains to allow for prefix "gene:", "transcript:" etc
875 if (parent != null && !parent.contains(identifier))
877 // this genomic feature belongs to a different transcript
884 public String getDescription()
886 return "Ensembl " + getSourceEnsemblType().getType()
887 + " sequence with variant features";
891 * Returns a (possibly empty) list of features on the sequence which have the
892 * specified sequence ontology term (or a sub-type of it), and the given
893 * identifier as parent
900 protected List<SequenceFeature> findFeatures(SequenceI sequence,
901 String term, String parentId)
903 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
905 List<SequenceFeature> sfs = sequence.getFeatures()
906 .getFeaturesByOntology(term);
907 for (SequenceFeature sf : sfs)
909 String parent = (String) sf.getValue(PARENT);
910 if (parent != null && parent.equals(parentId))
920 * Answers true if the feature type is either 'NMD_transcript_variant' or
921 * 'transcript' or one of its sub-types in the Sequence Ontology. This is
922 * needed because NMD_transcript_variant behaves like 'transcript' in Ensembl
923 * although strictly speaking it is not (it is a sub-type of
929 public static boolean isTranscript(String featureType)
931 return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
932 || SequenceOntologyFactory.getInstance().isA(featureType,
933 SequenceOntologyI.TRANSCRIPT);