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.Sequence;
32 import jalview.datamodel.SequenceFeature;
33 import jalview.datamodel.SequenceI;
34 import jalview.datamodel.features.SequenceFeatures;
35 import jalview.exceptions.JalviewException;
36 import jalview.io.gff.Gff3Helper;
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;
43 import jalview.util.Platform;
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 import org.json.simple.parser.ParseException;
57 * Base class for Ensembl sequence fetchers
59 * @see http://rest.ensembl.org/documentation/info/sequence_id
62 public abstract class EnsemblSeqProxy extends EnsemblRestClient
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();
213 Platform.timeCheck("ESP.getsequencerec1", Platform.TIME_MARK);
216 AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
218 if (geneFeatures != null && geneFeatures.getHeight() > 0)
220 genomicSequence = geneFeatures.getSequenceAt(0);
223 Platform.timeCheck("ESP.getsequencerec2", Platform.TIME_MARK);
225 if (genomicSequence != null)
228 * transfer features to the query sequence
230 SequenceI querySeq = alignment.findName(accId, true);
232 Platform.timeCheck("ESP.transferfeat", Platform.TIME_MARK);
234 if (transferFeatures(accId, genomicSequence, querySeq))
238 * fetch and map protein product, and add it as a cross-reference
239 * of the retrieved sequence
241 Platform.timeCheck("ESP.addprotein", Platform.TIME_MARK);
242 addProteinProduct(querySeq);
245 } catch (IOException e)
248 "Error transferring Ensembl features: " + e.getMessage());
250 Platform.timeCheck("ESP.addfeat done", Platform.TIME_MARK);
254 * Returns those sequence feature types to fetch from Ensembl. We may want
255 * features either because they are of interest to the user, or as means to
256 * identify the locations of the sequence on the genomic sequence (CDS
257 * features identify CDS, exon features identify cDNA etc).
261 protected abstract EnsemblFeatureType[] getFeaturesToFetch();
264 * Fetches and maps the protein product, and adds it as a cross-reference of
265 * the retrieved sequence
267 protected void addProteinProduct(SequenceI querySeq)
269 String accId = querySeq.getName();
272 System.out.println("Adding protein product for " + accId);
273 AlignmentI protein = new EnsemblProtein(getDomain())
274 .getSequenceRecords(accId);
275 if (protein == null || protein.getHeight() == 0)
277 System.out.println("No protein product found for " + accId);
280 SequenceI proteinSeq = protein.getSequenceAt(0);
283 * need dataset sequences (to be the subject of mappings)
285 proteinSeq.createDatasetSequence();
286 querySeq.createDatasetSequence();
288 MapList mapList = AlignmentUtils.mapCdsToProtein(querySeq,
292 // clunky: ensure Uniprot xref if we have one is on mapped sequence
293 SequenceI ds = proteinSeq.getDatasetSequence();
294 // TODO: Verify ensp primary ref is on proteinSeq.getDatasetSequence()
295 Mapping map = new Mapping(ds, mapList);
296 DBRefEntry dbr = new DBRefEntry(getDbSource(),
297 getEnsemblDataVersion(), proteinSeq.getName(), map);
298 querySeq.getDatasetSequence().addDBRef(dbr);
299 List<DBRefEntry> uprots = DBRefUtils.selectRefs(ds.getDBRefs(),
301 { DBRefSource.UNIPROT });
302 List<DBRefEntry> upxrefs = DBRefUtils.selectRefs(querySeq.getDBRefs(),
304 { DBRefSource.UNIPROT });
307 for (DBRefEntry up : uprots)
309 // locate local uniprot ref and map
310 List<DBRefEntry> upx = DBRefUtils.searchRefs(upxrefs,
311 up.getAccessionId());
320 "Implementation issue - multiple uniprot acc on product sequence.");
325 upxref = new DBRefEntry(DBRefSource.UNIPROT,
326 getEnsemblDataVersion(), up.getAccessionId());
329 Mapping newMap = new Mapping(ds, mapList);
330 upxref.setVersion(getEnsemblDataVersion());
331 upxref.setMap(newMap);
334 // add the new uniprot ref
335 querySeq.getDatasetSequence().addDBRef(upxref);
342 * copy exon features to protein, compute peptide variants from dna
343 * variants and add as features on the protein sequence ta-da
345 AlignmentUtils.computeProteinFeatures(querySeq, proteinSeq,
348 } catch (Exception e)
351 .println(String.format("Error retrieving protein for %s: %s",
352 accId, e.getMessage()));
357 * Get database xrefs from Ensembl, and attach them to the sequence
361 protected void getCrossReferences(SequenceI seq)
364 Platform.timeCheck("ESP. getdataseq ", Platform.TIME_MARK);
367 while (seq.getDatasetSequence() != null)
369 seq = seq.getDatasetSequence();
372 Platform.timeCheck("ESP. getxref ", Platform.TIME_MARK);
374 EnsemblXref xrefFetcher = new EnsemblXref(getDomain(), getDbSource(),
375 getEnsemblDataVersion());
376 List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName());
378 for (int i = 0, n = xrefs.size(); i < n; i++)
380 Platform.timeCheck("ESP. getxref + " + (i) + "/" + n, Platform.TIME_MARK);
381 // BH 2019.01.25 this next method was taking 174 ms PER addition for a 266-reference example.
382 // DBRefUtils.ensurePrimaries(seq)
383 // was at the end of seq.addDBRef, so executed after ever addition!
384 // This method was moved to seq.getPrimaryDBRefs()
385 seq.addDBRef(xrefs.get(i));
388 System.out.println("primaries are " + seq.getPrimaryDBRefs().toString());
390 * and add a reference to itself
393 Platform.timeCheck("ESP. getxref self ", Platform.TIME_MARK);
395 DBRefEntry self = new DBRefEntry(getDbSource(), getEnsemblDataVersion(),
398 Platform.timeCheck("ESP. getxref self add ", Platform.TIME_MARK);
402 Platform.timeCheck("ESP. seqprox done ", Platform.TIME_MARK);
407 * Fetches sequences for the list of accession ids and adds them to the
408 * alignment. Returns the extended (or created) alignment.
413 * @throws JalviewException
414 * @throws IOException
416 protected AlignmentI fetchSequences(List<String> ids,
417 AlignmentI alignment) throws JalviewException, IOException
419 if (!isEnsemblAvailable())
422 throw new JalviewException("ENSEMBL Rest API not available.");
424 Platform.timeCheck("EnsemblSeqProx.fetchSeq ", Platform.TIME_MARK);
426 List<SequenceI> seqs = parseSequenceJson(ids);
432 throw new IOException("No data returned for " + ids);
435 if (seqs.size() != ids.size())
437 System.out.println(String.format(
438 "Only retrieved %d sequences for %d query strings",
439 seqs.size(), ids.size()));
444 AlignmentI seqal = new Alignment(
445 seqs.toArray(new SequenceI[seqs.size()]));
446 for (SequenceI seq : seqs)
448 if (seq.getDescription() == null)
450 seq.setDescription(getDbName());
452 String name = seq.getName();
453 if (ids.contains(name)
454 || ids.contains(name.replace("ENSP", "ENST")))
456 // TODO JAL-3077 use true accession version in dbref
457 DBRefEntry dbref = DBRefUtils.parseToDbRef(seq, getDbSource(),
458 getEnsemblDataVersion(), name);
462 if (alignment == null)
468 alignment.append(seqal);
475 * Parses a JSON response for a single sequence ID query
478 * @return a single jalview.datamodel.Sequence
479 * @see http://rest.ensembl.org/documentation/info/sequence_id
481 @SuppressWarnings("unchecked")
482 protected List<SequenceI> parseSequenceJson(List<String> ids)
484 List<SequenceI> result = new ArrayList<>();
488 * for now, assumes only one sequence returned; refactor if needed
489 * in future to handle a JSONArray with more than one
492 Platform.timeCheck("ENS seqproxy", Platform.TIME_MARK);
493 Map<String, Object> val = (Map<String, Object>) getJSON(null, ids, -1, MODE_MAP, null);
496 Object s = val.get("desc");
497 String desc = s == null ? null : s.toString();
499 String id = s == null ? null : s.toString();
501 String seq = s == null ? null : s.toString();
502 Sequence sequence = new Sequence(id, seq);
505 sequence.setDescription(desc);
507 // todo JAL-3077 make a DBRefEntry with true accession version
508 // s = val.get("version");
509 // String version = s == null ? "0" : s.toString();
510 // DBRefEntry dbref = new DBRefEntry(getDbSource(), version, id);
511 // sequence.addDBRef(dbref);
512 result.add(sequence);
513 } catch (ParseException | IOException e)
515 System.err.println("Error processing JSON response: " + e.toString());
518 Platform.timeCheck("ENS seqproxy2", Platform.TIME_MARK);
523 * Returns the URL for the REST call
526 * @throws MalformedURLException
529 protected URL getUrl(List<String> ids) throws MalformedURLException
532 * a single id is included in the URL path
533 * multiple ids go in the POST body instead
535 StringBuffer urlstring = new StringBuffer(128);
536 urlstring.append(getDomain() + "/sequence/id");
539 urlstring.append("/").append(ids.get(0));
541 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
542 urlstring.append("?type=").append(getSourceEnsemblType().getType());
543 urlstring.append(("&Accept=application/json"));
544 urlstring.append(("&content-type=application/json"));
546 String objectType = getObjectType();
547 if (objectType != null)
549 urlstring.append("&").append(OBJECT_TYPE).append("=")
553 URL url = new URL(urlstring.toString());
558 * Override this method to specify object_type request parameter
562 protected String getObjectType()
568 * A sequence/id POST request currently allows up to 50 queries
570 * @see http://rest.ensembl.org/documentation/info/sequence_id_post
573 public int getMaximumQueryCount()
579 protected boolean useGetRequest()
586 * @return the configured sequence return type for this source
588 protected abstract EnsemblSeqType getSourceEnsemblType();
591 * Returns a list of [start, end] genomic ranges corresponding to the sequence
594 * The correspondence between the frames of reference is made by locating
595 * those features on the genomic sequence which identify the retrieved
596 * sequence. Specifically
598 * <li>genomic sequence is identified by "transcript" features with
599 * ID=transcript:transcriptId</li>
600 * <li>cdna sequence is identified by "exon" features with
601 * Parent=transcript:transcriptId</li>
602 * <li>cds sequence is identified by "CDS" features with
603 * Parent=transcript:transcriptId</li>
606 * The returned ranges are sorted to run forwards (for positive strand) or
607 * backwards (for negative strand). Aborts and returns null if both positive
608 * and negative strand are found (this should not normally happen).
610 * @param sourceSequence
613 * the start position of the sequence we are mapping to
616 protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
617 String accId, int start)
619 List<SequenceFeature> sfs = getIdentifyingFeatures(sourceSequence,
627 * generously initial size for number of cds regions
628 * (worst case titin Q8WZ42 has c. 313 exons)
630 List<int[]> regions = new ArrayList<>(100);
631 int mappedLength = 0;
632 int direction = 1; // forward
633 boolean directionSet = false;
635 for (SequenceFeature sf : sfs)
637 int strand = sf.getStrand();
638 strand = strand == 0 ? 1 : strand; // treat unknown as forward
640 if (directionSet && strand != direction)
642 // abort - mix of forward and backward
644 .println("Error: forward and backward strand for " + accId);
651 * add to CDS ranges, semi-sorted forwards/backwards
655 regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
659 regions.add(new int[] { sf.getBegin(), sf.getEnd() });
661 mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
664 if (regions.isEmpty())
666 System.out.println("Failed to identify target sequence for " + accId
667 + " from genomic features");
672 * a final sort is needed since Ensembl returns CDS sorted within source
673 * (havana / ensembl_havana)
675 Collections.sort(regions, direction == 1 ? IntRangeComparator.ASCENDING
676 : IntRangeComparator.DESCENDING);
678 List<int[]> to = Arrays
680 { start, start + mappedLength - 1 });
682 return new MapList(regions, to, 1, 1);
686 * Answers a list of sequence features that mark positions of the genomic
687 * sequence feature which are within the sequence being retrieved. For
688 * example, an 'exon' feature whose parent is the target transcript marks the
689 * cdna positions of the transcript. For a gene sequence, this is trivially
690 * just the 'gene' feature with matching gene id.
696 protected abstract List<SequenceFeature> getIdentifyingFeatures(
697 SequenceI seq, String accId);
700 * Transfers the sequence feature to the target sequence, locating its start
701 * and end range based on the mapping. Features which do not overlap the
702 * target sequence are ignored.
705 * @param targetSequence
707 * mapping from the sequence feature's coordinates to the target
709 * @param forwardStrand
711 protected void transferFeature(SequenceFeature sf,
712 SequenceI targetSequence, MapList mapping, boolean forwardStrand)
714 int start = sf.getBegin();
715 int end = sf.getEnd();
716 int[] mappedRange = mapping.locateInTo(start, end);
718 if (mappedRange != null)
720 String group = sf.getFeatureGroup();
721 if (".".equals(group))
723 group = getDbSource();
725 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
726 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
727 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
728 group, sf.getScore());
729 targetSequence.addSequenceFeature(copy);
732 * for sequence_variant on reverse strand, have to convert the allele
733 * values to their complements
735 if (!forwardStrand && SequenceOntologyFactory.getInstance()
736 .isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
738 reverseComplementAlleles(copy);
744 * Change the 'alleles' value of a feature by converting to complementary
745 * bases, and also update the feature description to match
749 static void reverseComplementAlleles(SequenceFeature sf)
751 final String alleles = (String) sf.getValue(Gff3Helper.ALLELES);
756 StringBuilder complement = new StringBuilder(alleles.length());
757 for (String allele : alleles.split(","))
759 reverseComplementAllele(complement, allele);
761 String comp = complement.toString();
762 sf.setValue(Gff3Helper.ALLELES, comp);
763 sf.setDescription(comp);
766 * replace value of "alleles=" in sf.ATTRIBUTES as well
767 * so 'output as GFF' shows reverse complement alleles
769 String atts = sf.getAttributes();
772 atts = atts.replace(Gff3Helper.ALLELES + "=" + alleles,
773 Gff3Helper.ALLELES + "=" + comp);
774 sf.setAttributes(atts);
779 * Makes the 'reverse complement' of the given allele and appends it to the
780 * buffer, after a comma separator if not the first
785 static void reverseComplementAllele(StringBuilder complement,
788 if (complement.length() > 0)
790 complement.append(",");
794 * some 'alleles' are actually descriptive terms
795 * e.g. HGMD_MUTATION, PhenCode_variation
796 * - we don't want to 'reverse complement' these
798 if (!Comparison.isNucleotideSequence(allele, true))
800 complement.append(allele);
804 for (int i = allele.length() - 1; i >= 0; i--)
806 complement.append(Dna.getComplement(allele.charAt(i)));
812 * Transfers features from sourceSequence to targetSequence
815 * @param sourceSequence
816 * @param targetSequence
817 * @return true if any features were transferred, else false
819 protected boolean transferFeatures(String accessionId,
820 SequenceI sourceSequence, SequenceI targetSequence)
822 if (sourceSequence == null || targetSequence == null)
827 // long start = System.currentTimeMillis();
828 List<SequenceFeature> sfs = sourceSequence.getFeatures()
829 .getPositionalFeatures();
830 MapList mapping = getGenomicRangesFromFeatures(sourceSequence,
831 accessionId, targetSequence.getStart());
837 boolean result = transferFeatures(sfs, targetSequence, mapping,
839 // System.out.println("transferFeatures (" + (sfs.size()) + " --> "
840 // + targetSequence.getFeatures().getFeatureCount(true) + ") to "
841 // + targetSequence.getName() + " took "
842 // + (System.currentTimeMillis() - start) + "ms");
847 * Transfer features to the target sequence. The start/end positions are
848 * converted using the mapping. Features which do not overlap are ignored.
849 * Features whose parent is not the specified identifier are also ignored.
852 * @param targetSequence
857 protected boolean transferFeatures(List<SequenceFeature> sfs,
858 SequenceI targetSequence, MapList mapping, String parentId)
860 final boolean forwardStrand = mapping.isFromForwardStrand();
863 * sort features by start position (which corresponds to end
864 * position descending if reverse strand) so as to add them in
865 * 'forwards' order to the target sequence
867 SequenceFeatures.sortFeatures(sfs, forwardStrand);
869 boolean transferred = false;
870 for (SequenceFeature sf : sfs)
872 if (retainFeature(sf, parentId))
874 transferFeature(sf, targetSequence, mapping, forwardStrand);
882 * Answers true if the feature type is one we want to keep for the sequence.
883 * Some features are only retrieved in order to identify the sequence range,
884 * and may then be discarded as redundant information (e.g. "CDS" feature for
887 @SuppressWarnings("unused")
888 protected boolean retainFeature(SequenceFeature sf, String accessionId)
890 return true; // override as required
894 * Answers true if the feature has a Parent which refers to the given
895 * accession id, or if the feature has no parent. Answers false if the
896 * feature's Parent is for a different accession id.
902 protected boolean featureMayBelong(SequenceFeature sf, String identifier)
904 String parent = (String) sf.getValue(PARENT);
906 && !parent.equalsIgnoreCase(identifier))
908 // this genomic feature belongs to a different transcript
915 * Answers a short description of the sequence fetcher
918 public String getDescription()
920 return "Ensembl " + getSourceEnsemblType().getType()
921 + " sequence with variant features";
925 * Returns a (possibly empty) list of features on the sequence which have the
926 * specified sequence ontology term (or a sub-type of it), and the given
927 * identifier as parent
934 protected List<SequenceFeature> findFeatures(SequenceI sequence,
935 String term, String parentId)
937 List<SequenceFeature> result = new ArrayList<>();
939 List<SequenceFeature> sfs = sequence.getFeatures()
940 .getFeaturesByOntology(term);
941 for (SequenceFeature sf : sfs)
943 String parent = (String) sf.getValue(PARENT);
944 if (parent != null && parent.equalsIgnoreCase(parentId))
954 * Answers true if the feature type is either 'NMD_transcript_variant' or
955 * 'transcript' (or one of its sub-types in the Sequence Ontology). This is
956 * because NMD_transcript_variant behaves like 'transcript' in Ensembl
957 * although strictly speaking it is not (it is a sub-type of
960 * (This test was needed when fetching transcript features as GFF. As we are
961 * now fetching as JSON, all features have type 'transcript' so the check for
962 * NMD_transcript_variant is redundant. Left in for any future case arising.)
967 public static boolean isTranscript(String featureType)
969 return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
970 || SequenceOntologyFactory.getInstance().isA(featureType,
971 SequenceOntologyI.TRANSCRIPT);