1 package jalview.ext.ensembl;
3 import jalview.analysis.AlignmentUtils;
4 import jalview.analysis.Dna;
5 import jalview.bin.Cache;
6 import jalview.datamodel.Alignment;
7 import jalview.datamodel.AlignmentI;
8 import jalview.datamodel.DBRefEntry;
9 import jalview.datamodel.DBRefSource;
10 import jalview.datamodel.Mapping;
11 import jalview.datamodel.SequenceFeature;
12 import jalview.datamodel.SequenceI;
13 import jalview.exceptions.JalviewException;
14 import jalview.io.FastaFile;
15 import jalview.io.FileParse;
16 import jalview.io.gff.SequenceOntologyFactory;
17 import jalview.io.gff.SequenceOntologyI;
18 import jalview.util.Comparison;
19 import jalview.util.DBRefUtils;
20 import jalview.util.MapList;
22 import java.io.IOException;
23 import java.net.MalformedURLException;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collections;
28 import java.util.Comparator;
29 import java.util.List;
32 * Base class for Ensembl sequence fetchers
34 * @see http://rest.ensembl.org/documentation/info/sequence_id
37 public abstract class EnsemblSeqProxy extends EnsemblRestClient
39 private static final String ALLELES = "alleles";
41 protected static final String PARENT = "Parent";
43 protected static final String ID = "ID";
45 protected static final String NAME = "Name";
47 protected static final String DESCRIPTION = "description";
50 * enum for 'type' parameter to the /sequence REST service
52 public enum EnsemblSeqType
55 * type=genomic to fetch full dna including introns
60 * type=cdna to fetch coding dna including UTRs
65 * type=cds to fetch coding dna excluding UTRs
70 * type=protein to fetch peptide product sequence
75 * the value of the 'type' parameter to fetch this version of
80 EnsemblSeqType(String t)
85 public String getType()
93 * A comparator to sort ranges into ascending start position order
95 private class RangeSorter implements Comparator<int[]>
99 RangeSorter(boolean forward)
105 public int compare(int[] o1, int[] o2)
107 return (forwards ? 1 : -1) * Integer.compare(o1[0], o2[0]);
113 * Default constructor (to use rest.ensembl.org)
115 public EnsemblSeqProxy()
121 * Constructor given the target domain to fetch data from
123 public EnsemblSeqProxy(String d)
129 * Makes the sequence queries to Ensembl's REST service and returns an
130 * alignment consisting of the returned sequences.
133 public AlignmentI getSequenceRecords(String query) throws Exception
135 // TODO use a String... query vararg instead?
137 // danger: accession separator used as a regex here, a string elsewhere
138 // in this case it is ok (it is just a space), but (e.g.) '\' would not be
139 List<String> allIds = Arrays.asList(query
140 .split(getAccessionSeparator()));
141 AlignmentI alignment = null;
145 * execute queries, if necessary in batches of the
146 * maximum allowed number of ids
148 int maxQueryCount = getMaximumQueryCount();
149 for (int v = 0, vSize = allIds.size(); v < vSize; v += maxQueryCount)
151 int p = Math.min(vSize, v + maxQueryCount);
152 List<String> ids = allIds.subList(v, p);
155 alignment = fetchSequences(ids, alignment);
156 } catch (Throwable r)
159 String msg = "Aborting ID retrieval after " + v
160 + " chunks. Unexpected problem (" + r.getLocalizedMessage()
162 System.err.println(msg);
168 if (alignment == null)
174 * fetch and transfer genomic sequence features,
175 * fetch protein product and add as cross-reference
177 for (String accId : allIds)
179 addFeaturesAndProduct(accId, alignment);
182 for (SequenceI seq : alignment.getSequences())
184 getCrossReferences(seq);
191 * Fetches Ensembl features using the /overlap REST endpoint, and adds them to
192 * the sequence in the alignment. Also fetches the protein product, maps it
193 * from the CDS features of the sequence, and saves it as a cross-reference of
199 protected void addFeaturesAndProduct(String accId, AlignmentI alignment)
201 if (alignment == null)
209 * get 'dummy' genomic sequence with exon, cds and variation features
211 SequenceI genomicSequence = null;
212 EnsemblFeatures gffFetcher = new EnsemblFeatures(getDomain());
213 EnsemblFeatureType[] features = getFeaturesToFetch();
214 AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
216 if (geneFeatures.getHeight() > 0)
218 genomicSequence = geneFeatures.getSequenceAt(0);
220 if (genomicSequence != null)
223 * transfer features to the query sequence
225 SequenceI querySeq = alignment.findName(accId);
226 if (transferFeatures(accId, genomicSequence, querySeq))
230 * fetch and map protein product, and add it as a cross-reference
231 * of the retrieved sequence
233 addProteinProduct(querySeq);
236 } catch (IOException e)
238 System.err.println("Error transferring Ensembl features: "
244 * Returns those sequence feature types to fetch from Ensembl. We may want
245 * features either because they are of interest to the user, or as means to
246 * identify the locations of the sequence on the genomic sequence (CDS
247 * features identify CDS, exon features identify cDNA etc).
251 protected abstract EnsemblFeatureType[] getFeaturesToFetch();
254 * Fetches and maps the protein product, and adds it as a cross-reference of
255 * the retrieved sequence
257 protected void addProteinProduct(SequenceI querySeq)
259 String accId = querySeq.getName();
262 AlignmentI protein = new EnsemblProtein(getDomain())
263 .getSequenceRecords(accId);
264 if (protein == null || protein.getHeight() == 0)
266 System.out.println("No protein product found for " + accId);
269 SequenceI proteinSeq = protein.getSequenceAt(0);
272 * need dataset sequences (to be the subject of mappings)
274 proteinSeq.createDatasetSequence();
275 querySeq.createDatasetSequence();
277 MapList mapList = AlignmentUtils.mapCdsToProtein(querySeq, proteinSeq);
280 // clunky: ensure Uniprot xref if we have one is on mapped sequence
281 SequenceI ds = proteinSeq.getDatasetSequence();
282 // TODO: Verify ensp primary ref is on proteinSeq.getDatasetSequence()
283 Mapping map = new Mapping(ds, mapList);
284 DBRefEntry dbr = new DBRefEntry(getDbSource(),
285 getEnsemblDataVersion(), proteinSeq.getName(), map);
286 querySeq.getDatasetSequence().addDBRef(dbr);
287 DBRefEntry[] uprots = DBRefUtils.selectRefs(ds.getDBRefs(),
288 new String[] { DBRefSource.UNIPROT });
289 DBRefEntry[] upxrefs = DBRefUtils.selectRefs(querySeq.getDBRefs(),
290 new String[] { DBRefSource.UNIPROT });
293 for (DBRefEntry up : uprots)
295 // locate local uniprot ref and map
296 List<DBRefEntry> upx = DBRefUtils.searchRefs(upxrefs, up.getAccessionId());
305 .warn("Implementation issue - multiple uniprot acc on product sequence.");
310 upxref = new DBRefEntry(DBRefSource.UNIPROT,
311 getEnsemblDataVersion(), up.getAccessionId());
314 Mapping newMap = new Mapping(ds, mapList);
315 upxref.setVersion(getEnsemblDataVersion());
316 upxref.setMap(newMap);
319 // add the new uniprot ref
320 querySeq.getDatasetSequence().addDBRef(upxref);
327 * copy exon features to protein, compute peptide variants from dna
328 * variants and add as features on the protein sequence ta-da
330 AlignmentUtils.computeProteinFeatures(querySeq, proteinSeq, mapList);
332 } catch (Exception e)
335 .println(String.format("Error retrieving protein for %s: %s",
336 accId, e.getMessage()));
341 * Get database xrefs from Ensembl, and attach them to the sequence
345 protected void getCrossReferences(SequenceI seq)
347 while (seq.getDatasetSequence() != null)
349 seq = seq.getDatasetSequence();
352 EnsemblXref xrefFetcher = new EnsemblXref(getDomain(), getDbSource(),
353 getEnsemblDataVersion());
354 List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName());
355 for (DBRefEntry xref : xrefs)
361 * and add a reference to itself
363 DBRefEntry self = new DBRefEntry(getDbSource(),
364 getEnsemblDataVersion(), seq.getName());
369 * Fetches sequences for the list of accession ids and adds them to the
370 * alignment. Returns the extended (or created) alignment.
375 * @throws JalviewException
376 * @throws IOException
378 protected AlignmentI fetchSequences(List<String> ids, AlignmentI alignment)
379 throws JalviewException, IOException
381 if (!isEnsemblAvailable())
384 throw new JalviewException("ENSEMBL Rest API not available.");
386 FileParse fp = getSequenceReader(ids);
387 FastaFile fr = new FastaFile(fp);
388 if (fr.hasWarningMessage())
390 System.out.println(String.format(
391 "Warning when retrieving %d ids %s\n%s", ids.size(),
392 ids.toString(), fr.getWarningMessage()));
394 else if (fr.getSeqs().size() != ids.size())
396 System.out.println(String.format(
397 "Only retrieved %d sequences for %d query strings", fr
398 .getSeqs().size(), ids.size()));
401 if (fr.getSeqs().size() == 1 && fr.getSeqs().get(0).getLength() == 0)
404 * POST request has returned an empty FASTA file e.g. for invalid id
406 throw new IOException("No data returned for " + ids);
409 if (fr.getSeqs().size() > 0)
411 AlignmentI seqal = new Alignment(
412 fr.getSeqsAsArray());
413 for (SequenceI sq:seqal.getSequences())
415 if (sq.getDescription() == null)
417 sq.setDescription(getDbName());
419 String name = sq.getName();
420 if (ids.contains(name)
421 || ids.contains(name.replace("ENSP", "ENST")))
423 DBRefEntry dbref = DBRefUtils.parseToDbRef(sq, getDbSource(),
424 getEnsemblDataVersion(), name);
428 if (alignment == null)
434 alignment.append(seqal);
441 * Returns the URL for the REST call
444 * @throws MalformedURLException
447 protected URL getUrl(List<String> ids) throws MalformedURLException
450 * a single id is included in the URL path
451 * multiple ids go in the POST body instead
453 StringBuffer urlstring = new StringBuffer(128);
454 urlstring.append(getDomain() + "/sequence/id");
457 urlstring.append("/").append(ids.get(0));
459 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
460 urlstring.append("?type=").append(getSourceEnsemblType().getType());
461 urlstring.append(("&Accept=text/x-fasta"));
463 URL url = new URL(urlstring.toString());
468 * A sequence/id POST request currently allows up to 50 queries
470 * @see http://rest.ensembl.org/documentation/info/sequence_id_post
473 public int getMaximumQueryCount()
479 protected boolean useGetRequest()
485 protected String getRequestMimeType(boolean multipleIds)
487 return multipleIds ? "application/json" : "text/x-fasta";
491 protected String getResponseMimeType()
493 return "text/x-fasta";
498 * @return the configured sequence return type for this source
500 protected abstract EnsemblSeqType getSourceEnsemblType();
503 * Returns a list of [start, end] genomic ranges corresponding to the sequence
506 * The correspondence between the frames of reference is made by locating
507 * those features on the genomic sequence which identify the retrieved
508 * sequence. Specifically
510 * <li>genomic sequence is identified by "transcript" features with
511 * ID=transcript:transcriptId</li>
512 * <li>cdna sequence is identified by "exon" features with
513 * Parent=transcript:transcriptId</li>
514 * <li>cds sequence is identified by "CDS" features with
515 * Parent=transcript:transcriptId</li>
518 * The returned ranges are sorted to run forwards (for positive strand) or
519 * backwards (for negative strand). Aborts and returns null if both positive
520 * and negative strand are found (this should not normally happen).
522 * @param sourceSequence
525 * the start position of the sequence we are mapping to
528 protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
529 String accId, int start)
531 SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
538 * generously initial size for number of cds regions
539 * (worst case titin Q8WZ42 has c. 313 exons)
541 List<int[]> regions = new ArrayList<int[]>(100);
542 int mappedLength = 0;
543 int direction = 1; // forward
544 boolean directionSet = false;
546 for (SequenceFeature sf : sfs)
549 * accept the target feature type or a specialisation of it
550 * (e.g. coding_exon for exon)
552 if (identifiesSequence(sf, accId))
554 int strand = sf.getStrand();
555 strand = strand == 0 ? 1 : strand; // treat unknown as forward
557 if (directionSet && strand != direction)
559 // abort - mix of forward and backward
560 System.err.println("Error: forward and backward strand for "
568 * add to CDS ranges, semi-sorted forwards/backwards
572 regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
576 regions.add(new int[] { sf.getBegin(), sf.getEnd() });
578 mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
583 * 'gene' sequence is contiguous so we can stop as soon as its
584 * identifying feature has been found
591 if (regions.isEmpty())
593 System.out.println("Failed to identify target sequence for " + accId
594 + " from genomic features");
599 * a final sort is needed since Ensembl returns CDS sorted within source
600 * (havana / ensembl_havana)
602 Collections.sort(regions, new RangeSorter(direction == 1));
604 List<int[]> to = Arrays.asList(new int[] { start,
605 start + mappedLength - 1 });
607 return new MapList(regions, to, 1, 1);
611 * Answers true if the sequence being retrieved may occupy discontiguous
612 * regions on the genomic sequence.
614 protected boolean isSpliceable()
620 * Returns true if the sequence feature marks positions of the genomic
621 * sequence feature which are within the sequence being retrieved. For
622 * example, an 'exon' feature whose parent is the target transcript marks the
623 * cdna positions of the transcript.
629 protected abstract boolean identifiesSequence(SequenceFeature sf,
633 * Transfers the sequence feature to the target sequence, locating its start
634 * and end range based on the mapping. Features which do not overlap the
635 * target sequence are ignored.
638 * @param targetSequence
640 * mapping from the sequence feature's coordinates to the target
642 * @param forwardStrand
644 protected void transferFeature(SequenceFeature sf,
645 SequenceI targetSequence, MapList mapping, boolean forwardStrand)
647 int start = sf.getBegin();
648 int end = sf.getEnd();
649 int[] mappedRange = mapping.locateInTo(start, end);
651 if (mappedRange != null)
653 SequenceFeature copy = new SequenceFeature(sf);
654 copy.setBegin(Math.min(mappedRange[0], mappedRange[1]));
655 copy.setEnd(Math.max(mappedRange[0], mappedRange[1]));
656 if (".".equals(copy.getFeatureGroup()))
658 copy.setFeatureGroup(getDbSource());
660 targetSequence.addSequenceFeature(copy);
663 * for sequence_variant on reverse strand, have to convert the allele
664 * values to their complements
667 && SequenceOntologyFactory.getInstance().isA(sf.getType(),
668 SequenceOntologyI.SEQUENCE_VARIANT))
670 reverseComplementAlleles(copy);
676 * Change the 'alleles' value of a feature by converting to complementary
677 * bases, and also update the feature description to match
681 static void reverseComplementAlleles(SequenceFeature sf)
683 final String alleles = (String) sf.getValue(ALLELES);
688 StringBuilder complement = new StringBuilder(alleles.length());
689 for (String allele : alleles.split(","))
691 reverseComplementAllele(complement, allele);
693 String comp = complement.toString();
694 sf.setValue(ALLELES, comp);
695 sf.setDescription(comp);
698 * replace value of "alleles=" in sf.ATTRIBUTES as well
699 * so 'output as GFF' shows reverse complement alleles
701 String atts = sf.getAttributes();
704 atts = atts.replace(ALLELES + "=" + alleles, ALLELES + "=" + comp);
705 sf.setAttributes(atts);
710 * Makes the 'reverse complement' of the given allele and appends it to the
711 * buffer, after a comma separator if not the first
716 static void reverseComplementAllele(StringBuilder complement,
719 if (complement.length() > 0)
721 complement.append(",");
725 * some 'alleles' are actually descriptive terms
726 * e.g. HGMD_MUTATION, PhenCode_variation
727 * - we don't want to 'reverse complement' these
729 if (!Comparison.isNucleotideSequence(allele, true))
731 complement.append(allele);
735 for (int i = allele.length() - 1; i >= 0; i--)
737 complement.append(Dna.getComplement(allele.charAt(i)));
743 * Transfers features from sourceSequence to targetSequence
746 * @param sourceSequence
747 * @param targetSequence
748 * @return true if any features were transferred, else false
750 protected boolean transferFeatures(String accessionId,
751 SequenceI sourceSequence, SequenceI targetSequence)
753 if (sourceSequence == null || targetSequence == null)
758 // long start = System.currentTimeMillis();
759 SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
760 MapList mapping = getGenomicRangesFromFeatures(sourceSequence, accessionId,
761 targetSequence.getStart());
767 boolean result = transferFeatures(sfs, targetSequence, mapping,
769 // System.out.println("transferFeatures (" + (sfs.length) + " --> "
770 // + targetSequence.getSequenceFeatures().length + ") to "
771 // + targetSequence.getName()
772 // + " took " + (System.currentTimeMillis() - start) + "ms");
777 * Transfer features to the target sequence. The start/end positions are
778 * converted using the mapping. Features which do not overlap are ignored.
779 * Features whose parent is not the specified identifier are also ignored.
782 * @param targetSequence
787 protected boolean transferFeatures(SequenceFeature[] features,
788 SequenceI targetSequence, MapList mapping, String parentId)
790 final boolean forwardStrand = mapping.isFromForwardStrand();
793 * sort features by start position (which corresponds to end
794 * position descending if reverse strand) so as to add them in
795 * 'forwards' order to the target sequence
797 sortFeatures(features, forwardStrand);
799 boolean transferred = false;
800 for (SequenceFeature sf : features)
802 if (retainFeature(sf, parentId))
804 transferFeature(sf, targetSequence, mapping, forwardStrand);
812 * Sort features by start position ascending (if on forward strand), or end
813 * position descending (if on reverse strand)
816 * @param forwardStrand
818 protected static void sortFeatures(SequenceFeature[] features,
819 final boolean forwardStrand)
821 Arrays.sort(features, new Comparator<SequenceFeature>()
824 public int compare(SequenceFeature o1, SequenceFeature o2)
828 return Integer.compare(o1.getBegin(), o2.getBegin());
832 return Integer.compare(o2.getEnd(), o1.getEnd());
839 * Answers true if the feature type is one we want to keep for the sequence.
840 * Some features are only retrieved in order to identify the sequence range,
841 * and may then be discarded as redundant information (e.g. "CDS" feature for
844 @SuppressWarnings("unused")
845 protected boolean retainFeature(SequenceFeature sf, String accessionId)
847 return true; // override as required
851 * Answers true if the feature has a Parent which refers to the given
852 * accession id, or if the feature has no parent. Answers false if the
853 * feature's Parent is for a different accession id.
859 protected boolean featureMayBelong(SequenceFeature sf, String identifier)
861 String parent = (String) sf.getValue(PARENT);
862 // using contains to allow for prefix "gene:", "transcript:" etc
863 if (parent != null && !parent.contains(identifier))
865 // this genomic feature belongs to a different transcript
872 public String getDescription()
874 return "Ensembl " + getSourceEnsemblType().getType()
875 + " sequence with variant features";
879 * Returns a (possibly empty) list of features on the sequence which have the
880 * specified sequence ontology type (or a sub-type of it), and the given
881 * identifier as parent
888 protected List<SequenceFeature> findFeatures(SequenceI sequence,
889 String type, String parentId)
891 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
893 SequenceFeature[] sfs = sequence.getSequenceFeatures();
895 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
896 for (SequenceFeature sf :sfs) {
897 if (so.isA(sf.getType(), type))
899 String parent = (String) sf.getValue(PARENT);
900 if (parent.equals(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);