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;
53 * Base class for Ensembl sequence fetchers
55 * @see http://rest.ensembl.org/documentation/info/sequence_id
58 public abstract class EnsemblSeqProxy extends EnsemblRestClient
60 private static final String ALLELES = "alleles";
62 protected static final String NAME = "Name";
64 protected static final String DESCRIPTION = "description";
67 * enum for 'type' parameter to the /sequence REST service
69 public enum EnsemblSeqType
72 * type=genomic to fetch full dna including introns
77 * type=cdna to fetch coding dna including UTRs
82 * type=cds to fetch coding dna excluding UTRs
87 * type=protein to fetch peptide product sequence
92 * the value of the 'type' parameter to fetch this version of
97 EnsemblSeqType(String t)
102 public String getType()
110 * Default constructor (to use rest.ensembl.org)
112 public EnsemblSeqProxy()
118 * Constructor given the target domain to fetch data from
120 public EnsemblSeqProxy(String d)
126 * Makes the sequence queries to Ensembl's REST service and returns an
127 * alignment consisting of the returned sequences.
130 public AlignmentI getSequenceRecords(String query) throws Exception
132 // TODO use a String... query vararg instead?
134 // danger: accession separator used as a regex here, a string elsewhere
135 // in this case it is ok (it is just a space), but (e.g.) '\' would not be
136 List<String> allIds = Arrays
137 .asList(query.split(getAccessionSeparator()));
138 AlignmentI alignment = null;
142 * execute queries, if necessary in batches of the
143 * maximum allowed number of ids
145 int maxQueryCount = getMaximumQueryCount();
146 for (int v = 0, vSize = allIds.size(); v < vSize; v += maxQueryCount)
148 int p = Math.min(vSize, v + maxQueryCount);
149 List<String> ids = allIds.subList(v, p);
152 alignment = fetchSequences(ids, alignment);
153 } catch (Throwable r)
156 String msg = "Aborting ID retrieval after " + v
157 + " chunks. Unexpected problem (" + r.getLocalizedMessage()
159 System.err.println(msg);
165 if (alignment == null)
171 * fetch and transfer genomic sequence features,
172 * fetch protein product and add as cross-reference
174 for (String accId : allIds)
176 addFeaturesAndProduct(accId, alignment);
179 for (SequenceI seq : alignment.getSequences())
181 getCrossReferences(seq);
188 * Fetches Ensembl features using the /overlap REST endpoint, and adds them to
189 * the sequence in the alignment. Also fetches the protein product, maps it
190 * from the CDS features of the sequence, and saves it as a cross-reference of
196 protected void addFeaturesAndProduct(String accId, AlignmentI alignment)
198 if (alignment == null)
206 * get 'dummy' genomic sequence with gene, transcript,
207 * exon, cds and variation features
209 SequenceI genomicSequence = null;
210 EnsemblFeatures gffFetcher = new EnsemblFeatures(getDomain());
211 EnsemblFeatureType[] features = getFeaturesToFetch();
212 AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
214 if (geneFeatures != null && geneFeatures.getHeight() > 0)
216 genomicSequence = geneFeatures.getSequenceAt(0);
218 if (genomicSequence != null)
221 * transfer features to the query sequence
223 SequenceI querySeq = alignment.findName(accId, true);
224 if (transferFeatures(accId, genomicSequence, querySeq))
228 * fetch and map protein product, and add it as a cross-reference
229 * of the retrieved sequence
231 addProteinProduct(querySeq);
234 } catch (IOException e)
237 "Error transferring Ensembl features: " + e.getMessage());
242 * Returns those sequence feature types to fetch from Ensembl. We may want
243 * features either because they are of interest to the user, or as means to
244 * identify the locations of the sequence on the genomic sequence (CDS
245 * features identify CDS, exon features identify cDNA etc).
249 protected abstract EnsemblFeatureType[] getFeaturesToFetch();
252 * Fetches and maps the protein product, and adds it as a cross-reference of
253 * the retrieved sequence
255 protected void addProteinProduct(SequenceI querySeq)
257 String accId = querySeq.getName();
260 AlignmentI protein = new EnsemblProtein(getDomain())
261 .getSequenceRecords(accId);
262 if (protein == null || protein.getHeight() == 0)
264 System.out.println("No protein product found for " + accId);
267 SequenceI proteinSeq = protein.getSequenceAt(0);
270 * need dataset sequences (to be the subject of mappings)
272 proteinSeq.createDatasetSequence();
273 querySeq.createDatasetSequence();
275 MapList mapList = AlignmentUtils.mapCdsToProtein(querySeq,
279 // clunky: ensure Uniprot xref if we have one is on mapped sequence
280 SequenceI ds = proteinSeq.getDatasetSequence();
281 // TODO: Verify ensp primary ref is on proteinSeq.getDatasetSequence()
282 Mapping map = new Mapping(ds, mapList);
283 DBRefEntry dbr = new DBRefEntry(getDbSource(),
284 getEnsemblDataVersion(), proteinSeq.getName(), map);
285 querySeq.getDatasetSequence().addDBRef(dbr);
286 DBRefEntry[] uprots = DBRefUtils.selectRefs(ds.getDBRefs(),
288 { DBRefSource.UNIPROT });
289 DBRefEntry[] upxrefs = DBRefUtils.selectRefs(querySeq.getDBRefs(),
291 { DBRefSource.UNIPROT });
294 for (DBRefEntry up : uprots)
296 // locate local uniprot ref and map
297 List<DBRefEntry> upx = DBRefUtils.searchRefs(upxrefs,
298 up.getAccessionId());
307 "Implementation issue - multiple uniprot acc on product sequence.");
312 upxref = new DBRefEntry(DBRefSource.UNIPROT,
313 getEnsemblDataVersion(), up.getAccessionId());
316 Mapping newMap = new Mapping(ds, mapList);
317 upxref.setVersion(getEnsemblDataVersion());
318 upxref.setMap(newMap);
321 // add the new uniprot ref
322 querySeq.getDatasetSequence().addDBRef(upxref);
329 * copy exon features to protein, compute peptide variants from dna
330 * variants and add as features on the protein sequence ta-da
332 AlignmentUtils.computeProteinFeatures(querySeq, proteinSeq,
335 } catch (Exception e)
338 .println(String.format("Error retrieving protein for %s: %s",
339 accId, e.getMessage()));
344 * Get database xrefs from Ensembl, and attach them to the sequence
348 protected void getCrossReferences(SequenceI seq)
350 while (seq.getDatasetSequence() != null)
352 seq = seq.getDatasetSequence();
355 EnsemblXref xrefFetcher = new EnsemblXref(getDomain(), getDbSource(),
356 getEnsemblDataVersion());
357 List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName());
358 for (DBRefEntry xref : xrefs)
364 * and add a reference to itself
366 DBRefEntry self = new DBRefEntry(getDbSource(), getEnsemblDataVersion(),
372 * Fetches sequences for the list of accession ids and adds them to the
373 * alignment. Returns the extended (or created) alignment.
378 * @throws JalviewException
379 * @throws IOException
381 protected AlignmentI fetchSequences(List<String> ids,
382 AlignmentI alignment) throws JalviewException, IOException
384 if (!isEnsemblAvailable())
387 throw new JalviewException("ENSEMBL Rest API not available.");
389 FileParse fp = getSequenceReader(ids);
395 FastaFile fr = new FastaFile(fp);
396 if (fr.hasWarningMessage())
399 String.format("Warning when retrieving %d ids %s\n%s",
400 ids.size(), ids.toString(), fr.getWarningMessage()));
402 else if (fr.getSeqs().size() != ids.size())
404 System.out.println(String.format(
405 "Only retrieved %d sequences for %d query strings",
406 fr.getSeqs().size(), ids.size()));
409 if (fr.getSeqs().size() == 1 && fr.getSeqs().get(0).getLength() == 0)
412 * POST request has returned an empty FASTA file e.g. for invalid id
414 throw new IOException("No data returned for " + ids);
417 if (fr.getSeqs().size() > 0)
419 AlignmentI seqal = new Alignment(fr.getSeqsAsArray());
420 for (SequenceI sq : seqal.getSequences())
422 if (sq.getDescription() == null)
424 sq.setDescription(getDbName());
426 String name = sq.getName();
427 if (ids.contains(name)
428 || ids.contains(name.replace("ENSP", "ENST")))
430 DBRefEntry dbref = DBRefUtils.parseToDbRef(sq, getDbSource(),
431 getEnsemblDataVersion(), name);
435 if (alignment == null)
441 alignment.append(seqal);
448 * Returns the URL for the REST call
451 * @throws MalformedURLException
454 protected URL getUrl(List<String> ids) throws MalformedURLException
457 * a single id is included in the URL path
458 * multiple ids go in the POST body instead
460 StringBuffer urlstring = new StringBuffer(128);
461 urlstring.append(getDomain() + "/sequence/id");
464 urlstring.append("/").append(ids.get(0));
466 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
467 urlstring.append("?type=").append(getSourceEnsemblType().getType());
468 urlstring.append(("&Accept=text/x-fasta"));
470 String objectType = getObjectType();
471 if (objectType != null)
473 urlstring.append("&").append(OBJECT_TYPE).append("=")
477 URL url = new URL(urlstring.toString());
482 * Override this method to specify object_type request parameter
486 protected String getObjectType()
492 * A sequence/id POST request currently allows up to 50 queries
494 * @see http://rest.ensembl.org/documentation/info/sequence_id_post
497 public int getMaximumQueryCount()
503 protected boolean useGetRequest()
509 protected String getRequestMimeType(boolean multipleIds)
511 return multipleIds ? "application/json" : "text/x-fasta";
515 protected String getResponseMimeType()
517 return "text/x-fasta";
522 * @return the configured sequence return type for this source
524 protected abstract EnsemblSeqType getSourceEnsemblType();
527 * Returns a list of [start, end] genomic ranges corresponding to the sequence
530 * The correspondence between the frames of reference is made by locating
531 * those features on the genomic sequence which identify the retrieved
532 * sequence. Specifically
534 * <li>genomic sequence is identified by "transcript" features with
535 * ID=transcript:transcriptId</li>
536 * <li>cdna sequence is identified by "exon" features with
537 * Parent=transcript:transcriptId</li>
538 * <li>cds sequence is identified by "CDS" features with
539 * Parent=transcript:transcriptId</li>
542 * The returned ranges are sorted to run forwards (for positive strand) or
543 * backwards (for negative strand). Aborts and returns null if both positive
544 * and negative strand are found (this should not normally happen).
546 * @param sourceSequence
549 * the start position of the sequence we are mapping to
552 protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
553 String accId, int start)
555 List<SequenceFeature> sfs = sourceSequence.getFeatures()
556 .getPositionalFeatures();
563 * generously initial size for number of cds regions
564 * (worst case titin Q8WZ42 has c. 313 exons)
566 List<int[]> regions = new ArrayList<>(100);
567 int mappedLength = 0;
568 int direction = 1; // forward
569 boolean directionSet = false;
571 for (SequenceFeature sf : sfs)
574 * accept the target feature type or a specialisation of it
575 * (e.g. coding_exon for exon)
577 if (identifiesSequence(sf, accId))
579 int strand = sf.getStrand();
580 strand = strand == 0 ? 1 : strand; // treat unknown as forward
582 if (directionSet && strand != direction)
584 // abort - mix of forward and backward
586 "Error: forward and backward strand for " + accId);
593 * add to CDS ranges, semi-sorted forwards/backwards
597 regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
601 regions.add(new int[] { sf.getBegin(), sf.getEnd() });
603 mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
608 * 'gene' sequence is contiguous so we can stop as soon as its
609 * identifying feature has been found
616 if (regions.isEmpty())
618 System.out.println("Failed to identify target sequence for " + accId
619 + " from genomic features");
624 * a final sort is needed since Ensembl returns CDS sorted within source
625 * (havana / ensembl_havana)
627 Collections.sort(regions, direction == 1 ? IntRangeComparator.ASCENDING
628 : IntRangeComparator.DESCENDING);
630 List<int[]> to = Arrays
632 { start, 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 String group = sf.getFeatureGroup();
681 if (".".equals(group))
683 group = getDbSource();
685 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
686 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
687 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
688 group, sf.getScore());
689 targetSequence.addSequenceFeature(copy);
692 * for sequence_variant on reverse strand, have to convert the allele
693 * values to their complements
695 if (!forwardStrand && SequenceOntologyFactory.getInstance()
696 .isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
698 reverseComplementAlleles(copy);
704 * Change the 'alleles' value of a feature by converting to complementary
705 * bases, and also update the feature description to match
709 static void reverseComplementAlleles(SequenceFeature sf)
711 final String alleles = (String) sf.getValue(ALLELES);
716 StringBuilder complement = new StringBuilder(alleles.length());
717 for (String allele : alleles.split(","))
719 reverseComplementAllele(complement, allele);
721 String comp = complement.toString();
722 sf.setValue(ALLELES, comp);
723 sf.setDescription(comp);
726 * replace value of "alleles=" in sf.ATTRIBUTES as well
727 * so 'output as GFF' shows reverse complement alleles
729 String atts = sf.getAttributes();
732 atts = atts.replace(ALLELES + "=" + alleles, 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);