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;
54 * Base class for Ensembl sequence fetchers
56 * @see http://rest.ensembl.org/documentation/info/sequence_id
59 public abstract class EnsemblSeqProxy extends EnsemblRestClient
61 protected static final String NAME = "Name";
63 protected static final String DESCRIPTION = "description";
66 * enum for 'type' parameter to the /sequence REST service
68 public enum EnsemblSeqType
71 * type=genomic to fetch full dna including introns
76 * type=cdna to fetch coding dna including UTRs
81 * type=cds to fetch coding dna excluding UTRs
86 * type=protein to fetch peptide product sequence
91 * the value of the 'type' parameter to fetch this version of
96 EnsemblSeqType(String t)
101 public String getType()
109 * Default constructor (to use rest.ensembl.org)
111 public EnsemblSeqProxy()
117 * Constructor given the target domain to fetch data from
119 public EnsemblSeqProxy(String d)
125 * Makes the sequence queries to Ensembl's REST service and returns an
126 * alignment consisting of the returned sequences.
129 public AlignmentI getSequenceRecords(String query) throws Exception
131 // TODO use a String... query vararg instead?
133 // danger: accession separator used as a regex here, a string elsewhere
134 // in this case it is ok (it is just a space), but (e.g.) '\' would not be
135 List<String> allIds = Arrays
136 .asList(query.split(getAccessionSeparator()));
137 AlignmentI alignment = null;
141 * execute queries, if necessary in batches of the
142 * maximum allowed number of ids
144 int maxQueryCount = getMaximumQueryCount();
145 for (int v = 0, vSize = allIds.size(); v < vSize; v += maxQueryCount)
147 int p = Math.min(vSize, v + maxQueryCount);
148 List<String> ids = allIds.subList(v, p);
151 alignment = fetchSequences(ids, alignment);
152 } catch (Throwable r)
155 String msg = "Aborting ID retrieval after " + v
156 + " chunks. Unexpected problem (" + r.getLocalizedMessage()
158 System.err.println(msg);
164 if (alignment == null)
170 * fetch and transfer genomic sequence features,
171 * fetch protein product and add as cross-reference
173 for (String accId : allIds)
175 addFeaturesAndProduct(accId, alignment);
178 for (SequenceI seq : alignment.getSequences())
180 getCrossReferences(seq);
187 * Fetches Ensembl features using the /overlap REST endpoint, and adds them to
188 * the sequence in the alignment. Also fetches the protein product, maps it
189 * from the CDS features of the sequence, and saves it as a cross-reference of
195 protected void addFeaturesAndProduct(String accId, AlignmentI alignment)
197 if (alignment == null)
205 * get 'dummy' genomic sequence with gene, transcript,
206 * exon, cds and variation features
208 SequenceI genomicSequence = null;
209 EnsemblFeatures gffFetcher = new EnsemblFeatures(getDomain());
210 EnsemblFeatureType[] features = getFeaturesToFetch();
211 AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
213 if (geneFeatures != null && geneFeatures.getHeight() > 0)
215 genomicSequence = geneFeatures.getSequenceAt(0);
217 if (genomicSequence != null)
220 * transfer features to the query sequence
222 SequenceI querySeq = alignment.findName(accId, true);
223 if (transferFeatures(accId, genomicSequence, querySeq))
227 * fetch and map protein product, and add it as a cross-reference
228 * of the retrieved sequence
230 addProteinProduct(querySeq);
233 } catch (IOException e)
236 "Error transferring Ensembl features: " + e.getMessage());
241 * Returns those sequence feature types to fetch from Ensembl. We may want
242 * features either because they are of interest to the user, or as means to
243 * identify the locations of the sequence on the genomic sequence (CDS
244 * features identify CDS, exon features identify cDNA etc).
248 protected abstract EnsemblFeatureType[] getFeaturesToFetch();
251 * Fetches and maps the protein product, and adds it as a cross-reference of
252 * the retrieved sequence
254 protected void addProteinProduct(SequenceI querySeq)
256 String accId = querySeq.getName();
259 AlignmentI protein = new EnsemblProtein(getDomain())
260 .getSequenceRecords(accId);
261 if (protein == null || protein.getHeight() == 0)
263 System.out.println("No protein product found for " + accId);
266 SequenceI proteinSeq = protein.getSequenceAt(0);
269 * need dataset sequences (to be the subject of mappings)
271 proteinSeq.createDatasetSequence();
272 querySeq.createDatasetSequence();
274 MapList mapList = AlignmentUtils.mapCdsToProtein(querySeq,
278 // clunky: ensure Uniprot xref if we have one is on mapped sequence
279 SequenceI ds = proteinSeq.getDatasetSequence();
280 // TODO: Verify ensp primary ref is on proteinSeq.getDatasetSequence()
281 Mapping map = new Mapping(ds, mapList);
282 DBRefEntry dbr = new DBRefEntry(getDbSource(),
283 getEnsemblDataVersion(), proteinSeq.getName(), map);
284 querySeq.getDatasetSequence().addDBRef(dbr);
285 DBRefEntry[] uprots = DBRefUtils.selectRefs(ds.getDBRefs(),
287 { DBRefSource.UNIPROT });
288 DBRefEntry[] upxrefs = DBRefUtils.selectRefs(querySeq.getDBRefs(),
290 { DBRefSource.UNIPROT });
293 for (DBRefEntry up : uprots)
295 // locate local uniprot ref and map
296 List<DBRefEntry> upx = DBRefUtils.searchRefs(upxrefs,
297 up.getAccessionId());
306 "Implementation issue - multiple uniprot acc on product sequence.");
311 upxref = new DBRefEntry(DBRefSource.UNIPROT,
312 getEnsemblDataVersion(), up.getAccessionId());
315 Mapping newMap = new Mapping(ds, mapList);
316 upxref.setVersion(getEnsemblDataVersion());
317 upxref.setMap(newMap);
320 // add the new uniprot ref
321 querySeq.getDatasetSequence().addDBRef(upxref);
328 * copy exon features to protein, compute peptide variants from dna
329 * variants and add as features on the protein sequence ta-da
331 AlignmentUtils.computeProteinFeatures(querySeq, proteinSeq,
334 } catch (Exception e)
337 .println(String.format("Error retrieving protein for %s: %s",
338 accId, e.getMessage()));
343 * Get database xrefs from Ensembl, and attach them to the sequence
347 protected void getCrossReferences(SequenceI seq)
349 while (seq.getDatasetSequence() != null)
351 seq = seq.getDatasetSequence();
354 EnsemblXref xrefFetcher = new EnsemblXref(getDomain(), getDbSource(),
355 getEnsemblDataVersion());
356 List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName());
357 for (DBRefEntry xref : xrefs)
363 * and add a reference to itself
365 DBRefEntry self = new DBRefEntry(getDbSource(), getEnsemblDataVersion(),
371 * Fetches sequences for the list of accession ids and adds them to the
372 * alignment. Returns the extended (or created) alignment.
377 * @throws JalviewException
378 * @throws IOException
380 protected AlignmentI fetchSequences(List<String> ids,
381 AlignmentI alignment) throws JalviewException, IOException
383 if (!isEnsemblAvailable())
386 throw new JalviewException("ENSEMBL Rest API not available.");
388 FileParse fp = getSequenceReader(ids);
394 FastaFile fr = new FastaFile(fp);
395 if (fr.hasWarningMessage())
398 String.format("Warning when retrieving %d ids %s\n%s",
399 ids.size(), ids.toString(), fr.getWarningMessage()));
401 else if (fr.getSeqs().size() != ids.size())
403 System.out.println(String.format(
404 "Only retrieved %d sequences for %d query strings",
405 fr.getSeqs().size(), ids.size()));
408 if (fr.getSeqs().size() == 1 && fr.getSeqs().get(0).getLength() == 0)
411 * POST request has returned an empty FASTA file e.g. for invalid id
413 throw new IOException("No data returned for " + ids);
416 if (fr.getSeqs().size() > 0)
418 AlignmentI seqal = new Alignment(fr.getSeqsAsArray());
419 for (SequenceI sq : seqal.getSequences())
421 if (sq.getDescription() == null)
423 sq.setDescription(getDbName());
425 String name = sq.getName();
426 if (ids.contains(name)
427 || ids.contains(name.replace("ENSP", "ENST")))
429 DBRefEntry dbref = DBRefUtils.parseToDbRef(sq, getDbSource(),
430 getEnsemblDataVersion(), name);
434 if (alignment == null)
440 alignment.append(seqal);
447 * Returns the URL for the REST call
450 * @throws MalformedURLException
453 protected URL getUrl(List<String> ids) throws MalformedURLException
456 * a single id is included in the URL path
457 * multiple ids go in the POST body instead
459 StringBuffer urlstring = new StringBuffer(128);
460 urlstring.append(getDomain() + "/sequence/id");
463 urlstring.append("/").append(ids.get(0));
465 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
466 urlstring.append("?type=").append(getSourceEnsemblType().getType());
467 urlstring.append(("&Accept=text/x-fasta"));
469 String objectType = getObjectType();
470 if (objectType != null)
472 urlstring.append("&").append(OBJECT_TYPE).append("=")
476 URL url = new URL(urlstring.toString());
481 * Override this method to specify object_type request parameter
485 protected String getObjectType()
491 * A sequence/id POST request currently allows up to 50 queries
493 * @see http://rest.ensembl.org/documentation/info/sequence_id_post
496 public int getMaximumQueryCount()
502 protected boolean useGetRequest()
508 protected String getRequestMimeType(boolean multipleIds)
510 return multipleIds ? "application/json" : "text/x-fasta";
514 protected String getResponseMimeType()
516 return "text/x-fasta";
521 * @return the configured sequence return type for this source
523 protected abstract EnsemblSeqType getSourceEnsemblType();
526 * Returns a list of [start, end] genomic ranges corresponding to the sequence
529 * The correspondence between the frames of reference is made by locating
530 * those features on the genomic sequence which identify the retrieved
531 * sequence. Specifically
533 * <li>genomic sequence is identified by "transcript" features with
534 * ID=transcript:transcriptId</li>
535 * <li>cdna sequence is identified by "exon" features with
536 * Parent=transcript:transcriptId</li>
537 * <li>cds sequence is identified by "CDS" features with
538 * Parent=transcript:transcriptId</li>
541 * The returned ranges are sorted to run forwards (for positive strand) or
542 * backwards (for negative strand). Aborts and returns null if both positive
543 * and negative strand are found (this should not normally happen).
545 * @param sourceSequence
548 * the start position of the sequence we are mapping to
551 protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
552 String accId, int start)
554 List<SequenceFeature> sfs = sourceSequence.getFeatures()
555 .getPositionalFeatures();
562 * generously initial size for number of cds regions
563 * (worst case titin Q8WZ42 has c. 313 exons)
565 List<int[]> regions = new ArrayList<>(100);
566 int mappedLength = 0;
567 int direction = 1; // forward
568 boolean directionSet = false;
570 for (SequenceFeature sf : sfs)
573 * accept the target feature type or a specialisation of it
574 * (e.g. coding_exon for exon)
576 if (identifiesSequence(sf, accId))
578 int strand = sf.getStrand();
579 strand = strand == 0 ? 1 : strand; // treat unknown as forward
581 if (directionSet && strand != direction)
583 // abort - mix of forward and backward
585 "Error: forward and backward strand for " + accId);
592 * add to CDS ranges, semi-sorted forwards/backwards
596 regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
600 regions.add(new int[] { sf.getBegin(), sf.getEnd() });
602 mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
607 * 'gene' sequence is contiguous so we can stop as soon as its
608 * identifying feature has been found
615 if (regions.isEmpty())
617 System.out.println("Failed to identify target sequence for " + accId
618 + " from genomic features");
623 * a final sort is needed since Ensembl returns CDS sorted within source
624 * (havana / ensembl_havana)
626 Collections.sort(regions, direction == 1 ? IntRangeComparator.ASCENDING
627 : IntRangeComparator.DESCENDING);
629 List<int[]> to = Arrays
631 { start, start + mappedLength - 1 });
633 return new MapList(regions, to, 1, 1);
637 * Answers true if the sequence being retrieved may occupy discontiguous
638 * regions on the genomic sequence.
640 protected boolean isSpliceable()
646 * Returns true if the sequence feature marks positions of the genomic
647 * sequence feature which are within the sequence being retrieved. For
648 * example, an 'exon' feature whose parent is the target transcript marks the
649 * cdna positions of the transcript.
655 protected abstract boolean identifiesSequence(SequenceFeature sf,
659 * Transfers the sequence feature to the target sequence, locating its start
660 * and end range based on the mapping. Features which do not overlap the
661 * target sequence are ignored.
664 * @param targetSequence
666 * mapping from the sequence feature's coordinates to the target
668 * @param forwardStrand
670 protected void transferFeature(SequenceFeature sf,
671 SequenceI targetSequence, MapList mapping, boolean forwardStrand)
673 int start = sf.getBegin();
674 int end = sf.getEnd();
675 int[] mappedRange = mapping.locateInTo(start, end);
677 if (mappedRange != null)
679 String group = sf.getFeatureGroup();
680 if (".".equals(group))
682 group = getDbSource();
684 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
685 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
686 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
687 group, sf.getScore());
688 targetSequence.addSequenceFeature(copy);
691 * for sequence_variant on reverse strand, have to convert the allele
692 * values to their complements
694 if (!forwardStrand && SequenceOntologyFactory.getInstance()
695 .isA(sf.getType(), 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(Gff3Helper.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(Gff3Helper.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(Gff3Helper.ALLELES + "=" + alleles,
732 Gff3Helper.ALLELES + "=" + comp);
733 sf.setAttributes(atts);
738 * Makes the 'reverse complement' of the given allele and appends it to the
739 * buffer, after a comma separator if not the first
744 static void reverseComplementAllele(StringBuilder complement,
747 if (complement.length() > 0)
749 complement.append(",");
753 * some 'alleles' are actually descriptive terms
754 * e.g. HGMD_MUTATION, PhenCode_variation
755 * - we don't want to 'reverse complement' these
757 if (!Comparison.isNucleotideSequence(allele, true))
759 complement.append(allele);
763 for (int i = allele.length() - 1; i >= 0; i--)
765 complement.append(Dna.getComplement(allele.charAt(i)));
771 * Transfers features from sourceSequence to targetSequence
774 * @param sourceSequence
775 * @param targetSequence
776 * @return true if any features were transferred, else false
778 protected boolean transferFeatures(String accessionId,
779 SequenceI sourceSequence, SequenceI targetSequence)
781 if (sourceSequence == null || targetSequence == null)
786 // long start = System.currentTimeMillis();
787 List<SequenceFeature> sfs = sourceSequence.getFeatures()
788 .getPositionalFeatures();
789 MapList mapping = getGenomicRangesFromFeatures(sourceSequence,
790 accessionId, targetSequence.getStart());
796 boolean result = transferFeatures(sfs, targetSequence, mapping,
798 // System.out.println("transferFeatures (" + (sfs.size()) + " --> "
799 // + targetSequence.getFeatures().getFeatureCount(true) + ") to "
800 // + targetSequence.getName() + " took "
801 // + (System.currentTimeMillis() - start) + "ms");
806 * Transfer features to the target sequence. The start/end positions are
807 * converted using the mapping. Features which do not overlap are ignored.
808 * Features whose parent is not the specified identifier are also ignored.
811 * @param targetSequence
816 protected boolean transferFeatures(List<SequenceFeature> sfs,
817 SequenceI targetSequence, MapList mapping, String parentId)
819 final boolean forwardStrand = mapping.isFromForwardStrand();
822 * sort features by start position (which corresponds to end
823 * position descending if reverse strand) so as to add them in
824 * 'forwards' order to the target sequence
826 SequenceFeatures.sortFeatures(sfs, forwardStrand);
828 boolean transferred = false;
829 for (SequenceFeature sf : sfs)
831 if (retainFeature(sf, parentId))
833 transferFeature(sf, targetSequence, mapping, forwardStrand);
841 * Answers true if the feature type is one we want to keep for the sequence.
842 * Some features are only retrieved in order to identify the sequence range,
843 * and may then be discarded as redundant information (e.g. "CDS" feature for
846 @SuppressWarnings("unused")
847 protected boolean retainFeature(SequenceFeature sf, String accessionId)
849 return true; // override as required
853 * Answers true if the feature has a Parent which refers to the given
854 * accession id, or if the feature has no parent. Answers false if the
855 * feature's Parent is for a different accession id.
861 protected boolean featureMayBelong(SequenceFeature sf, String identifier)
863 String parent = (String) sf.getValue(PARENT);
864 // using contains to allow for prefix "gene:", "transcript:" etc
866 && !parent.toUpperCase().contains(identifier.toUpperCase()))
868 // this genomic feature belongs to a different transcript
875 public String getDescription()
877 return "Ensembl " + getSourceEnsemblType().getType()
878 + " sequence with variant features";
882 * Returns a (possibly empty) list of features on the sequence which have the
883 * specified sequence ontology term (or a sub-type of it), and the given
884 * identifier as parent
891 protected List<SequenceFeature> findFeatures(SequenceI sequence,
892 String term, String parentId)
894 List<SequenceFeature> result = new ArrayList<>();
896 List<SequenceFeature> sfs = sequence.getFeatures()
897 .getFeaturesByOntology(term);
898 for (SequenceFeature sf : sfs)
900 String parent = (String) sf.getValue(PARENT);
901 if (parent != null && parent.equalsIgnoreCase(parentId))
911 * Answers true if the feature type is either 'NMD_transcript_variant' or
912 * 'transcript' or one of its sub-types in the Sequence Ontology. This is
913 * needed because NMD_transcript_variant behaves like 'transcript' in Ensembl
914 * although strictly speaking it is not (it is a sub-type of
920 public static boolean isTranscript(String featureType)
922 return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
923 || SequenceOntologyFactory.getInstance().isA(featureType,
924 SequenceOntologyI.TRANSCRIPT);