1 package jalview.ext.ensembl;
3 import jalview.analysis.AlignmentUtils;
4 import jalview.analysis.Dna;
5 import jalview.datamodel.Alignment;
6 import jalview.datamodel.AlignmentI;
7 import jalview.datamodel.DBRefEntry;
8 import jalview.datamodel.Mapping;
9 import jalview.datamodel.SequenceFeature;
10 import jalview.datamodel.SequenceI;
11 import jalview.exceptions.JalviewException;
12 import jalview.io.FastaFile;
13 import jalview.io.FileParse;
14 import jalview.io.gff.SequenceOntologyFactory;
15 import jalview.io.gff.SequenceOntologyI;
16 import jalview.util.Comparison;
17 import jalview.util.DBRefUtils;
18 import jalview.util.MapList;
20 import java.io.IOException;
21 import java.net.MalformedURLException;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collections;
26 import java.util.Comparator;
27 import java.util.List;
30 * Base class for Ensembl sequence fetchers
32 * @see http://rest.ensembl.org/documentation/info/sequence_id
35 public abstract class EnsemblSeqProxy extends EnsemblRestClient
37 private static final String ALLELES = "alleles";
39 protected static final String PARENT = "Parent";
41 protected static final String ID = "ID";
43 protected static final String NAME = "Name";
45 protected static final String DESCRIPTION = "description";
48 * enum for 'type' parameter to the /sequence REST service
50 public enum EnsemblSeqType
53 * type=genomic to fetch full dna including introns
58 * type=cdna to fetch coding dna including UTRs
63 * type=cds to fetch coding dna excluding UTRs
68 * type=protein to fetch peptide product sequence
73 * the value of the 'type' parameter to fetch this version of
78 EnsemblSeqType(String t)
83 public String getType()
91 * A comparator to sort ranges into ascending start position order
93 private class RangeSorter implements Comparator<int[]>
97 RangeSorter(boolean forward)
103 public int compare(int[] o1, int[] o2)
105 return (forwards ? 1 : -1) * Integer.compare(o1[0], o2[0]);
111 * Default constructor (to use rest.ensembl.org)
113 public EnsemblSeqProxy()
119 * Constructor given the target domain to fetch data from
121 public EnsemblSeqProxy(String d)
127 * Makes the sequence queries to Ensembl's REST service and returns an
128 * alignment consisting of the returned sequences.
131 public AlignmentI getSequenceRecords(String query) throws Exception
133 // TODO use a String... query vararg instead?
135 // danger: accession separator used as a regex here, a string elsewhere
136 // in this case it is ok (it is just a space), but (e.g.) '\' would not be
137 List<String> allIds = Arrays.asList(query
138 .split(getAccessionSeparator()));
139 AlignmentI alignment = null;
143 * execute queries, if necessary in batches of the
144 * maximum allowed number of ids
146 int maxQueryCount = getMaximumQueryCount();
147 for (int v = 0, vSize = allIds.size(); v < vSize; v += maxQueryCount)
149 int p = Math.min(vSize, v + maxQueryCount);
150 List<String> ids = allIds.subList(v, p);
153 alignment = fetchSequences(ids, alignment);
154 } catch (Throwable r)
157 String msg = "Aborting ID retrieval after " + v
158 + " chunks. Unexpected problem (" + r.getLocalizedMessage()
160 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 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.getHeight() > 0)
215 genomicSequence = geneFeatures.getSequenceAt(0);
217 if (genomicSequence != null)
220 * transfer features to the query sequence
222 SequenceI querySeq = alignment.findName(accId);
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)
235 System.err.println("Error transferring Ensembl features: "
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, proteinSeq);
277 // clunky: ensure Uniprot xref if we have one is on mapped sequence
278 SequenceI ds = proteinSeq.getDatasetSequence();
279 // TODO: Verify ensp primary ref is on proteinSeq.getDatasetSequence()
280 Mapping map = new Mapping(ds, mapList);
281 DBRefEntry dbr = new DBRefEntry(getDbSource(),
282 getEnsemblDataVersion(), proteinSeq.getName(), map);
283 querySeq.getDatasetSequence().addDBRef(dbr);
286 * copy exon features to protein, compute peptide variants from dna
287 * variants and add as features on the protein sequence ta-da
289 AlignmentUtils.computeProteinFeatures(querySeq, proteinSeq, mapList);
291 } catch (Exception e)
294 .println(String.format("Error retrieving protein for %s: %s",
295 accId, e.getMessage()));
300 * Get database xrefs from Ensembl, and attach them to the sequence
304 protected void getCrossReferences(SequenceI seq)
306 while (seq.getDatasetSequence() != null)
308 seq = seq.getDatasetSequence();
311 EnsemblXref xrefFetcher = new EnsemblXref(getDomain(), getDbSource(),
312 getEnsemblDataVersion());
313 List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName());
314 for (DBRefEntry xref : xrefs)
320 * and add a reference to itself
322 DBRefEntry self = new DBRefEntry(getDbSource(),
323 getEnsemblDataVersion(), seq.getName());
328 * Fetches sequences for the list of accession ids and adds them to the
329 * alignment. Returns the extended (or created) alignment.
334 * @throws JalviewException
335 * @throws IOException
337 protected AlignmentI fetchSequences(List<String> ids, AlignmentI alignment)
338 throws JalviewException, IOException
340 if (!isEnsemblAvailable())
343 throw new JalviewException("ENSEMBL Rest API not available.");
345 FileParse fp = getSequenceReader(ids);
346 FastaFile fr = new FastaFile(fp);
347 if (fr.hasWarningMessage())
349 System.out.println(String.format(
350 "Warning when retrieving %d ids %s\n%s", ids.size(),
351 ids.toString(), fr.getWarningMessage()));
353 else if (fr.getSeqs().size() != ids.size())
355 System.out.println(String.format(
356 "Only retrieved %d sequences for %d query strings", fr
357 .getSeqs().size(), ids.size()));
360 if (fr.getSeqs().size() == 1 && fr.getSeqs().get(0).getLength() == 0)
363 * POST request has returned an empty FASTA file e.g. for invalid id
365 throw new IOException("No data returned for " + ids);
368 if (fr.getSeqs().size() > 0)
370 AlignmentI seqal = new Alignment(
371 fr.getSeqsAsArray());
372 for (SequenceI sq:seqal.getSequences())
374 if (sq.getDescription() == null)
376 sq.setDescription(getDbName());
378 String name = sq.getName();
379 if (ids.contains(name)
380 || ids.contains(name.replace("ENSP", "ENST")))
382 DBRefEntry dbref = DBRefUtils.parseToDbRef(sq, getDbSource(),
383 getEnsemblDataVersion(), name);
387 if (alignment == null)
393 alignment.append(seqal);
400 * Returns the URL for the REST call
403 * @throws MalformedURLException
406 protected URL getUrl(List<String> ids) throws MalformedURLException
409 * a single id is included in the URL path
410 * multiple ids go in the POST body instead
412 StringBuffer urlstring = new StringBuffer(128);
413 urlstring.append(getDomain() + "/sequence/id");
416 urlstring.append("/").append(ids.get(0));
418 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
419 urlstring.append("?type=").append(getSourceEnsemblType().getType());
420 urlstring.append(("&Accept=text/x-fasta"));
422 URL url = new URL(urlstring.toString());
427 * A sequence/id POST request currently allows up to 50 queries
429 * @see http://rest.ensembl.org/documentation/info/sequence_id_post
432 public int getMaximumQueryCount()
438 protected boolean useGetRequest()
444 protected String getRequestMimeType(boolean multipleIds)
446 return multipleIds ? "application/json" : "text/x-fasta";
450 protected String getResponseMimeType()
452 return "text/x-fasta";
457 * @return the configured sequence return type for this source
459 protected abstract EnsemblSeqType getSourceEnsemblType();
462 * Returns a list of [start, end] genomic ranges corresponding to the sequence
465 * The correspondence between the frames of reference is made by locating
466 * those features on the genomic sequence which identify the retrieved
467 * sequence. Specifically
469 * <li>genomic sequence is identified by "transcript" features with
470 * ID=transcript:transcriptId</li>
471 * <li>cdna sequence is identified by "exon" features with
472 * Parent=transcript:transcriptId</li>
473 * <li>cds sequence is identified by "CDS" features with
474 * Parent=transcript:transcriptId</li>
477 * The returned ranges are sorted to run forwards (for positive strand) or
478 * backwards (for negative strand). Aborts and returns null if both positive
479 * and negative strand are found (this should not normally happen).
481 * @param sourceSequence
484 * the start position of the sequence we are mapping to
487 protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
488 String accId, int start)
490 SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
497 * generously initial size for number of cds regions
498 * (worst case titin Q8WZ42 has c. 313 exons)
500 List<int[]> regions = new ArrayList<int[]>(100);
501 int mappedLength = 0;
502 int direction = 1; // forward
503 boolean directionSet = false;
505 for (SequenceFeature sf : sfs)
508 * accept the target feature type or a specialisation of it
509 * (e.g. coding_exon for exon)
511 if (identifiesSequence(sf, accId))
513 int strand = sf.getStrand();
514 strand = strand == 0 ? 1 : strand; // treat unknown as forward
516 if (directionSet && strand != direction)
518 // abort - mix of forward and backward
519 System.err.println("Error: forward and backward strand for "
527 * add to CDS ranges, semi-sorted forwards/backwards
531 regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
535 regions.add(new int[] { sf.getBegin(), sf.getEnd() });
537 mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
542 * 'gene' sequence is contiguous so we can stop as soon as its
543 * identifying feature has been found
550 if (regions.isEmpty())
552 System.out.println("Failed to identify target sequence for " + accId
553 + " from genomic features");
558 * a final sort is needed since Ensembl returns CDS sorted within source
559 * (havana / ensembl_havana)
561 Collections.sort(regions, new RangeSorter(direction == 1));
563 List<int[]> to = Arrays.asList(new int[] { start,
564 start + mappedLength - 1 });
566 return new MapList(regions, to, 1, 1);
570 * Answers true if the sequence being retrieved may occupy discontiguous
571 * regions on the genomic sequence.
573 protected boolean isSpliceable()
579 * Returns true if the sequence feature marks positions of the genomic
580 * sequence feature which are within the sequence being retrieved. For
581 * example, an 'exon' feature whose parent is the target transcript marks the
582 * cdna positions of the transcript.
588 protected abstract boolean identifiesSequence(SequenceFeature sf,
592 * Transfers the sequence feature to the target sequence, locating its start
593 * and end range based on the mapping. Features which do not overlap the
594 * target sequence are ignored.
597 * @param targetSequence
599 * mapping from the sequence feature's coordinates to the target
601 * @param forwardStrand
603 protected void transferFeature(SequenceFeature sf,
604 SequenceI targetSequence, MapList mapping, boolean forwardStrand)
606 int start = sf.getBegin();
607 int end = sf.getEnd();
608 int[] mappedRange = mapping.locateInTo(start, end);
610 if (mappedRange != null)
612 SequenceFeature copy = new SequenceFeature(sf);
613 copy.setBegin(Math.min(mappedRange[0], mappedRange[1]));
614 copy.setEnd(Math.max(mappedRange[0], mappedRange[1]));
615 if (".".equals(copy.getFeatureGroup()))
617 copy.setFeatureGroup(getDbSource());
619 targetSequence.addSequenceFeature(copy);
622 * for sequence_variant on reverse strand, have to convert the allele
623 * values to their complements
626 && SequenceOntologyFactory.getInstance().isA(sf.getType(),
627 SequenceOntologyI.SEQUENCE_VARIANT))
629 reverseComplementAlleles(copy);
635 * Change the 'alleles' value of a feature by converting to complementary
636 * bases, and also update the feature description to match
640 static void reverseComplementAlleles(SequenceFeature sf)
642 final String alleles = (String) sf.getValue(ALLELES);
647 StringBuilder complement = new StringBuilder(alleles.length());
648 for (String allele : alleles.split(","))
650 reverseComplementAllele(complement, allele);
652 String comp = complement.toString();
653 sf.setValue(ALLELES, comp);
654 sf.setDescription(comp);
657 * replace value of "alleles=" in sf.ATTRIBUTES as well
658 * so 'output as GFF' shows reverse complement alleles
660 String atts = sf.getAttributes();
663 atts = atts.replace(ALLELES + "=" + alleles, ALLELES + "=" + comp);
664 sf.setAttributes(atts);
669 * Makes the 'reverse complement' of the given allele and appends it to the
670 * buffer, after a comma separator if not the first
675 static void reverseComplementAllele(StringBuilder complement,
678 if (complement.length() > 0)
680 complement.append(",");
684 * some 'alleles' are actually descriptive terms
685 * e.g. HGMD_MUTATION, PhenCode_variation
686 * - we don't want to 'reverse complement' these
688 if (!Comparison.isNucleotideSequence(allele, true))
690 complement.append(allele);
694 for (int i = allele.length() - 1; i >= 0; i--)
696 complement.append(Dna.getComplement(allele.charAt(i)));
702 * Transfers features from sourceSequence to targetSequence
705 * @param sourceSequence
706 * @param targetSequence
707 * @return true if any features were transferred, else false
709 protected boolean transferFeatures(String accessionId,
710 SequenceI sourceSequence, SequenceI targetSequence)
712 if (sourceSequence == null || targetSequence == null)
717 // long start = System.currentTimeMillis();
718 SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
719 MapList mapping = getGenomicRangesFromFeatures(sourceSequence, accessionId,
720 targetSequence.getStart());
726 boolean result = transferFeatures(sfs, targetSequence, mapping,
728 // System.out.println("transferFeatures (" + (sfs.length) + " --> "
729 // + targetSequence.getSequenceFeatures().length + ") to "
730 // + targetSequence.getName()
731 // + " took " + (System.currentTimeMillis() - start) + "ms");
736 * Transfer features to the target sequence. The start/end positions are
737 * converted using the mapping. Features which do not overlap are ignored.
738 * Features whose parent is not the specified identifier are also ignored.
741 * @param targetSequence
746 protected boolean transferFeatures(SequenceFeature[] features,
747 SequenceI targetSequence, MapList mapping, String parentId)
749 final boolean forwardStrand = mapping.isFromForwardStrand();
752 * sort features by start position (which corresponds to end
753 * position descending if reverse strand) so as to add them in
754 * 'forwards' order to the target sequence
756 sortFeatures(features, forwardStrand);
758 boolean transferred = false;
759 for (SequenceFeature sf : features)
761 if (retainFeature(sf, parentId))
763 transferFeature(sf, targetSequence, mapping, forwardStrand);
771 * Sort features by start position ascending (if on forward strand), or end
772 * position descending (if on reverse strand)
775 * @param forwardStrand
777 protected static void sortFeatures(SequenceFeature[] features,
778 final boolean forwardStrand)
780 Arrays.sort(features, new Comparator<SequenceFeature>()
783 public int compare(SequenceFeature o1, SequenceFeature o2)
787 return Integer.compare(o1.getBegin(), o2.getBegin());
791 return Integer.compare(o2.getEnd(), o1.getEnd());
798 * Answers true if the feature type is one we want to keep for the sequence.
799 * Some features are only retrieved in order to identify the sequence range,
800 * and may then be discarded as redundant information (e.g. "CDS" feature for
803 @SuppressWarnings("unused")
804 protected boolean retainFeature(SequenceFeature sf, String accessionId)
806 return true; // override as required
810 * Answers true if the feature has a Parent which refers to the given
811 * accession id, or if the feature has no parent. Answers false if the
812 * feature's Parent is for a different accession id.
818 protected boolean featureMayBelong(SequenceFeature sf, String identifier)
820 String parent = (String) sf.getValue(PARENT);
821 // using contains to allow for prefix "gene:", "transcript:" etc
822 if (parent != null && !parent.contains(identifier))
824 // this genomic feature belongs to a different transcript
831 public String getDescription()
833 return "Ensembl " + getSourceEnsemblType().getType()
834 + " sequence with variant features";
838 * Returns a (possibly empty) list of features on the sequence which have the
839 * specified sequence ontology type (or a sub-type of it), and the given
840 * identifier as parent
847 protected List<SequenceFeature> findFeatures(SequenceI sequence,
848 String type, String parentId)
850 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
852 SequenceFeature[] sfs = sequence.getSequenceFeatures();
854 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
855 for (SequenceFeature sf :sfs) {
856 if (so.isA(sf.getType(), type))
858 String parent = (String) sf.getValue(PARENT);
859 if (parent.equals(parentId))
870 * Answers true if the feature type is either 'NMD_transcript_variant' or
871 * 'transcript' or one of its sub-types in the Sequence Ontology. This is
872 * needed because NMD_transcript_variant behaves like 'transcript' in Ensembl
873 * although strictly speaking it is not (it is a sub-type of
879 public static boolean isTranscript(String featureType)
881 return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
882 || SequenceOntologyFactory.getInstance().isA(featureType,
883 SequenceOntologyI.TRANSCRIPT);