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 java.io.IOException;
24 import java.net.MalformedURLException;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Collections;
29 import java.util.List;
32 import org.json.simple.parser.ParseException;
34 import jalview.analysis.AlignmentUtils;
35 import jalview.analysis.Dna;
36 import jalview.bin.Console;
37 import jalview.datamodel.Alignment;
38 import jalview.datamodel.AlignmentI;
39 import jalview.datamodel.DBRefEntry;
40 import jalview.datamodel.DBRefSource;
41 import jalview.datamodel.Mapping;
42 import jalview.datamodel.Sequence;
43 import jalview.datamodel.SequenceFeature;
44 import jalview.datamodel.SequenceI;
45 import jalview.datamodel.features.SequenceFeatures;
46 import jalview.exceptions.JalviewException;
47 import jalview.io.gff.Gff3Helper;
48 import jalview.io.gff.SequenceOntologyFactory;
49 import jalview.io.gff.SequenceOntologyI;
50 import jalview.util.Comparison;
51 import jalview.util.DBRefUtils;
52 import jalview.util.IntRangeComparator;
53 import jalview.util.MapList;
56 * Base class for Ensembl sequence fetchers
58 * @see http://rest.ensembl.org/documentation/info/sequence_id
61 public abstract class EnsemblSeqProxy extends EnsemblRestClient
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 jalview.bin.Console.errPrintln(msg);
164 if (alignment == null)
170 * fetch and transfer genomic sequence features,
171 * fetch protein product and add as cross-reference
173 for (int i = 0, n = allIds.size(); i < n; i++)
175 addFeaturesAndProduct(allIds.get(i), alignment);
178 List<SequenceI> seqs = alignment.getSequences();
179 for (int i = 0, n = seqs.size(); i < n; i++)
181 getCrossReferences(seqs.get(i));
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);
215 AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
217 if (geneFeatures != null && geneFeatures.getHeight() > 0)
219 genomicSequence = geneFeatures.getSequenceAt(0);
222 // Platform.timeCheck("ESP.getsequencerec2", Platform.TIME_MARK);
224 if (genomicSequence != null)
227 * transfer features to the query sequence
229 SequenceI querySeq = alignment.findName(accId, true);
230 if (transferFeatures(accId, genomicSequence, querySeq))
234 * fetch and map protein product, and add it as a cross-reference
235 * of the retrieved sequence
237 // Platform.timeCheck("ESP.transferFeatures", Platform.TIME_MARK);
238 addProteinProduct(querySeq);
241 } catch (IOException e)
243 jalview.bin.Console.errPrintln(
244 "Error transferring Ensembl features: " + e.getMessage());
246 // Platform.timeCheck("ESP.addfeat done", Platform.TIME_MARK);
250 * Returns those sequence feature types to fetch from Ensembl. We may want
251 * features either because they are of interest to the user, or as means to
252 * identify the locations of the sequence on the genomic sequence (CDS
253 * features identify CDS, exon features identify cDNA etc).
257 protected abstract EnsemblFeatureType[] getFeaturesToFetch();
260 * Fetches and maps the protein product, and adds it as a cross-reference of
261 * the retrieved sequence
263 protected void addProteinProduct(SequenceI querySeq)
265 String accId = querySeq.getName();
268 jalview.bin.Console.outPrintln("Adding protein product for " + accId);
269 AlignmentI protein = new EnsemblProtein(getDomain())
270 .getSequenceRecords(accId);
271 if (protein == null || protein.getHeight() == 0)
273 jalview.bin.Console.outPrintln("No protein product found for " + accId);
276 SequenceI proteinSeq = protein.getSequenceAt(0);
279 * need dataset sequences (to be the subject of mappings)
281 proteinSeq.createDatasetSequence();
282 querySeq.createDatasetSequence();
284 MapList mapList = AlignmentUtils.mapCdsToProtein(querySeq,
288 // clunky: ensure Uniprot xref if we have one is on mapped sequence
289 SequenceI ds = proteinSeq.getDatasetSequence();
290 // TODO: Verify ensp primary ref is on proteinSeq.getDatasetSequence()
291 Mapping map = new Mapping(ds, mapList);
292 DBRefEntry dbr = new DBRefEntry(getDbSource(),
293 getEnsemblDataVersion(), proteinSeq.getName(), map);
294 querySeq.getDatasetSequence().addDBRef(dbr);
295 List<DBRefEntry> uprots = DBRefUtils.selectRefs(ds.getDBRefs(),
297 { DBRefSource.UNIPROT });
298 List<DBRefEntry> upxrefs = DBRefUtils
299 .selectRefs(querySeq.getDBRefs(), new String[]
300 { DBRefSource.UNIPROT });
303 for (DBRefEntry up : uprots)
305 // locate local uniprot ref and map
306 List<DBRefEntry> upx = DBRefUtils.searchRefs(upxrefs,
307 up.getAccessionId());
316 "Implementation issue - multiple uniprot acc on product sequence.");
321 upxref = new DBRefEntry(DBRefSource.UNIPROT,
322 getEnsemblDataVersion(), up.getAccessionId());
325 Mapping newMap = new Mapping(ds, mapList);
326 upxref.setVersion(getEnsemblDataVersion());
327 upxref.setMap(newMap);
330 // add the new uniprot ref
331 querySeq.getDatasetSequence().addDBRef(upxref);
338 * copy exon features to protein, compute peptide variants from dna
339 * variants and add as features on the protein sequence ta-da
341 // JAL-3187 render on the fly instead
342 // AlignmentUtils.computeProteinFeatures(querySeq, proteinSeq, mapList);
344 } catch (Exception e)
347 .println(String.format("Error retrieving protein for %s: %s",
348 accId, e.getMessage()));
353 * Get database xrefs from Ensembl, and attach them to the sequence
357 protected void getCrossReferences(SequenceI seq)
360 // Platform.timeCheck("ESP. getdataseq ", Platform.TIME_MARK);
362 while (seq.getDatasetSequence() != null)
364 seq = seq.getDatasetSequence();
367 // Platform.timeCheck("ESP. getxref ", Platform.TIME_MARK);
369 EnsemblXref xrefFetcher = new EnsemblXref(getDomain(), getDbSource(),
370 getEnsemblDataVersion());
371 List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName());
373 for (int i = 0, n = xrefs.size(); i < n; i++)
375 // Platform.timeCheck("ESP. getxref + " + (i) + "/" + n,
376 // Platform.TIME_MARK);
377 // BH 2019.01.25 this next method was taking 174 ms PER addition for a
378 // 266-reference example.
379 // DBRefUtils.ensurePrimaries(seq)
380 // was at the end of seq.addDBRef, so executed after ever addition!
381 // This method was moved to seq.getPrimaryDBRefs()
382 seq.addDBRef(xrefs.get(i));
385 // jalview.bin.Console.outPrintln("primaries are " + seq.getPrimaryDBRefs().toString());
387 * and add a reference to itself
390 // Platform.timeCheck("ESP. getxref self ", Platform.TIME_MARK);
392 DBRefEntry self = new DBRefEntry(getDbSource(), getEnsemblDataVersion(),
395 // Platform.timeCheck("ESP. getxref self add ", Platform.TIME_MARK);
399 // Platform.timeCheck("ESP. seqprox done ", Platform.TIME_MARK);
403 * Fetches sequences for the list of accession ids and adds them to the
404 * alignment. Returns the extended (or created) alignment.
409 * @throws JalviewException
410 * @throws IOException
412 protected AlignmentI fetchSequences(List<String> ids,
413 AlignmentI alignment) throws JalviewException, IOException
415 if (!isEnsemblAvailable())
418 throw new JalviewException("ENSEMBL Rest API not available.");
420 // Platform.timeCheck("EnsemblSeqProx.fetchSeq ", Platform.TIME_MARK);
422 List<SequenceI> seqs = parseSequenceJson(ids);
428 throw new IOException("No data returned for " + ids);
431 if (seqs.size() != ids.size())
433 jalview.bin.Console.outPrintln(String.format(
434 "Only retrieved %d sequences for %d query strings",
435 seqs.size(), ids.size()));
440 AlignmentI seqal = new Alignment(
441 seqs.toArray(new SequenceI[seqs.size()]));
442 for (SequenceI seq : seqs)
444 if (seq.getDescription() == null)
446 seq.setDescription(getDbName());
448 String name = seq.getName();
449 if (ids.contains(name)
450 || ids.contains(name.replace("ENSP", "ENST")))
452 // TODO JAL-3077 use true accession version in dbref
453 DBRefEntry dbref = DBRefUtils.parseToDbRef(seq, getDbSource(),
454 getEnsemblDataVersion(), name);
458 if (alignment == null)
464 alignment.append(seqal);
471 * Parses a JSON response for a single sequence ID query
474 * @return a single jalview.datamodel.Sequence
475 * @see http://rest.ensembl.org/documentation/info/sequence_id
477 @SuppressWarnings("unchecked")
478 protected List<SequenceI> parseSequenceJson(List<String> ids)
480 List<SequenceI> result = new ArrayList<>();
484 * for now, assumes only one sequence returned; refactor if needed
485 * in future to handle a JSONArray with more than one
487 // Platform.timeCheck("ENS seqproxy", Platform.TIME_MARK);
488 Map<String, Object> val = (Map<String, Object>) getJSON(null, ids, -1,
492 Object s = val.get("desc");
493 String desc = s == null ? null : s.toString();
495 String id = s == null ? null : s.toString();
497 String seq = s == null ? null : s.toString();
498 Sequence sequence = new Sequence(id, seq);
501 sequence.setDescription(desc);
503 // todo JAL-3077 make a DBRefEntry with true accession version
504 // s = val.get("version");
505 // String version = s == null ? "0" : s.toString();
506 // DBRefEntry dbref = new DBRefEntry(getDbSource(), version, id);
507 // sequence.addDBRef(dbref);
508 result.add(sequence);
509 } catch (ParseException | IOException e)
511 jalview.bin.Console.errPrintln("Error processing JSON response: " + e.toString());
514 // Platform.timeCheck("ENS seqproxy2", Platform.TIME_MARK);
519 * Returns the URL for the REST call
522 * @throws MalformedURLException
525 protected URL getUrl(List<String> ids) throws MalformedURLException
528 * a single id is included in the URL path
529 * multiple ids go in the POST body instead
531 StringBuffer urlstring = new StringBuffer(128);
532 urlstring.append(getDomain() + "/sequence/id");
535 urlstring.append("/").append(ids.get(0));
537 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
538 urlstring.append("?type=").append(getSourceEnsemblType().getType());
539 urlstring.append(("&Accept=application/json"));
540 urlstring.append(("&content-type=application/json"));
542 String objectType = getObjectType();
543 if (objectType != null)
545 urlstring.append("&").append(OBJECT_TYPE).append("=")
549 URL url = new URL(urlstring.toString());
554 * Override this method to specify object_type request parameter
558 protected String getObjectType()
564 * A sequence/id POST request currently allows up to 50 queries
566 * @see http://rest.ensembl.org/documentation/info/sequence_id_post
569 public int getMaximumQueryCount()
575 protected boolean useGetRequest()
582 * @return the configured sequence return type for this source
584 protected abstract EnsemblSeqType getSourceEnsemblType();
587 * Returns a list of [start, end] genomic ranges corresponding to the sequence
590 * The correspondence between the frames of reference is made by locating
591 * those features on the genomic sequence which identify the retrieved
592 * sequence. Specifically
594 * <li>genomic sequence is identified by "transcript" features with
595 * ID=transcript:transcriptId</li>
596 * <li>cdna sequence is identified by "exon" features with
597 * Parent=transcript:transcriptId</li>
598 * <li>cds sequence is identified by "CDS" features with
599 * Parent=transcript:transcriptId</li>
602 * The returned ranges are sorted to run forwards (for positive strand) or
603 * backwards (for negative strand). Aborts and returns null if both positive
604 * and negative strand are found (this should not normally happen).
606 * @param sourceSequence
609 * the start position of the sequence we are mapping to
612 protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
613 String accId, int start)
615 List<SequenceFeature> sfs = getIdentifyingFeatures(sourceSequence,
623 * generously initial size for number of cds regions
624 * (worst case titin Q8WZ42 has c. 313 exons)
626 List<int[]> regions = new ArrayList<>(100);
627 int mappedLength = 0;
628 int direction = 1; // forward
629 boolean directionSet = false;
631 for (SequenceFeature sf : sfs)
633 int strand = sf.getStrand();
634 strand = strand == 0 ? 1 : strand; // treat unknown as forward
636 if (directionSet && strand != direction)
638 // abort - mix of forward and backward
640 .println("Error: forward and backward strand for " + accId);
647 * add to CDS ranges, semi-sorted forwards/backwards
651 regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
655 regions.add(new int[] { sf.getBegin(), sf.getEnd() });
657 mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
660 if (regions.isEmpty())
662 jalview.bin.Console.outPrintln("Failed to identify target sequence for " + accId
663 + " from genomic features");
668 * a final sort is needed since Ensembl returns CDS sorted within source
669 * (havana / ensembl_havana)
671 Collections.sort(regions, direction == 1 ? IntRangeComparator.ASCENDING
672 : IntRangeComparator.DESCENDING);
674 List<int[]> to = Arrays
676 { start, start + mappedLength - 1 });
678 return new MapList(regions, to, 1, 1);
682 * Answers a list of sequence features that mark positions of the genomic
683 * sequence feature which are within the sequence being retrieved. For
684 * example, an 'exon' feature whose parent is the target transcript marks the
685 * cdna positions of the transcript. For a gene sequence, this is trivially
686 * just the 'gene' feature with matching gene id.
692 protected abstract List<SequenceFeature> getIdentifyingFeatures(
693 SequenceI seq, String accId);
698 * Transfers the sequence feature to the target sequence, locating its start
699 * and end range based on the mapping. Features which do not overlap the
700 * target sequence are ignored.
703 * @param targetSequence
705 * mapping from the sequence feature's coordinates to the target
707 * @param forwardStrand
709 protected void transferFeature(SequenceFeature sf,
710 SequenceI targetSequence, MapList mapping, boolean forwardStrand)
712 int start = sf.getBegin();
713 int end = sf.getEnd();
714 int[] mappedRange = mapping.locateInTo(start, end);
716 if (mappedRange != null)
718 // Platform.timeCheck(null, Platform.TIME_SET);
719 String group = sf.getFeatureGroup();
720 if (".".equals(group))
722 group = getDbSource();
724 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
725 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
726 // Platform.timeCheck(null, Platform.TIME_MARK);
729 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
730 group, sf.getScore());
732 targetSequence.addSequenceFeature(copy);
735 * for sequence_variant on reverse strand, have to convert the allele
736 * values to their complements
738 if (!forwardStrand && SequenceOntologyFactory.getInstance()
739 .isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
741 reverseComplementAlleles(copy);
747 * Change the 'alleles' value of a feature by converting to complementary
748 * bases, and also update the feature description to match
752 static void reverseComplementAlleles(SequenceFeature sf)
754 final String alleles = (String) sf.getValue(Gff3Helper.ALLELES);
759 StringBuilder complement = new StringBuilder(alleles.length());
760 for (String allele : alleles.split(","))
762 reverseComplementAllele(complement, allele);
764 String comp = complement.toString();
765 sf.setValue(Gff3Helper.ALLELES, comp);
766 sf.setDescription(comp);
770 * Makes the 'reverse complement' of the given allele and appends it to the
771 * buffer, after a comma separator if not the first
776 static void reverseComplementAllele(StringBuilder complement,
779 if (complement.length() > 0)
781 complement.append(",");
785 * some 'alleles' are actually descriptive terms
786 * e.g. HGMD_MUTATION, PhenCode_variation
787 * - we don't want to 'reverse complement' these
789 if (!Comparison.isNucleotideSequence(allele, true))
791 complement.append(allele);
795 for (int i = allele.length() - 1; i >= 0; i--)
797 complement.append(Dna.getComplement(allele.charAt(i)));
803 * Transfers features from sourceSequence to targetSequence
806 * @param sourceSequence
807 * @param targetSequence
808 * @return true if any features were transferred, else false
810 protected boolean transferFeatures(String accessionId,
811 SequenceI sourceSequence, SequenceI targetSequence)
813 if (sourceSequence == null || targetSequence == null)
818 // long start = System.currentTimeMillis();
819 List<SequenceFeature> sfs = sourceSequence.getFeatures()
820 .getPositionalFeatures();
821 MapList mapping = getGenomicRangesFromFeatures(sourceSequence,
822 accessionId, targetSequence.getStart());
828 // Platform.timeCheck("ESP. xfer " + sfs.size(), Platform.TIME_MARK);
830 boolean result = transferFeatures(sfs, targetSequence, mapping,
832 // jalview.bin.Console.outPrintln("transferFeatures (" + (sfs.size()) + " --> "
833 // + targetSequence.getFeatures().getFeatureCount(true) + ") to "
834 // + targetSequence.getName() + " took "
835 // + (System.currentTimeMillis() - start) + "ms");
840 * Transfer features to the target sequence. The start/end positions are
841 * converted using the mapping. Features which do not overlap are ignored.
842 * Features whose parent is not the specified identifier are also ignored.
845 * @param targetSequence
850 protected boolean transferFeatures(List<SequenceFeature> sfs,
851 SequenceI targetSequence, MapList mapping, String parentId)
853 final boolean forwardStrand = mapping.isFromForwardStrand();
856 * sort features by start position (which corresponds to end
857 * position descending if reverse strand) so as to add them in
858 * 'forwards' order to the target sequence
860 SequenceFeatures.sortFeatures(sfs, forwardStrand);
862 boolean transferred = false;
864 for (int i = 0, n = sfs.size(); i < n; i++)
867 // if ((i%1000) == 0) {
868 //// Platform.timeCheck("Feature " + bhtest, Platform.TIME_GET);
869 // Platform.timeCheck("ESP. xferFeature + " + (i) + "/" + n,
870 // Platform.TIME_MARK);
873 SequenceFeature sf = sfs.get(i);
874 if (retainFeature(sf, parentId))
876 transferFeature(sf, targetSequence, mapping, forwardStrand);
885 * Answers true if the feature type is one we want to keep for the sequence.
886 * Some features are only retrieved in order to identify the sequence range,
887 * and may then be discarded as redundant information (e.g. "CDS" feature for
890 @SuppressWarnings("unused")
891 protected boolean retainFeature(SequenceFeature sf, String accessionId)
893 return true; // override as required
897 * Answers true if the feature has a Parent which refers to the given
898 * accession id, or if the feature has no parent. Answers false if the
899 * feature's Parent is for a different accession id.
905 protected boolean featureMayBelong(SequenceFeature sf, String identifier)
907 String parent = (String) sf.getValue(PARENT);
908 if (parent != null && !parent.equalsIgnoreCase(identifier))
910 // this genomic feature belongs to a different transcript
917 * Answers a short description of the sequence fetcher
920 public String getDescription()
922 return "Ensembl " + getSourceEnsemblType().getType()
923 + " sequence with variant features";
927 * Returns a (possibly empty) list of features on the sequence which have the
928 * specified sequence ontology term (or a sub-type of it), and the given
929 * identifier as parent
936 protected List<SequenceFeature> findFeatures(SequenceI sequence,
937 String term, String parentId)
939 List<SequenceFeature> result = new ArrayList<>();
941 List<SequenceFeature> sfs = sequence.getFeatures()
942 .getFeaturesByOntology(term);
943 for (SequenceFeature sf : sfs)
945 String parent = (String) sf.getValue(PARENT);
946 if (parent != null && parent.equalsIgnoreCase(parentId))
956 * Answers true if the feature type is either 'NMD_transcript_variant' or
957 * 'transcript' (or one of its sub-types in the Sequence Ontology). This is
958 * because NMD_transcript_variant behaves like 'transcript' in Ensembl
959 * although strictly speaking it is not (it is a sub-type of
962 * (This test was needed when fetching transcript features as GFF. As we are
963 * now fetching as JSON, all features have type 'transcript' so the check for
964 * NMD_transcript_variant is redundant. Left in for any future case arising.)
969 public static boolean isTranscript(String featureType)
971 return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
972 || SequenceOntologyFactory.getInstance().isA(featureType,
973 SequenceOntologyI.TRANSCRIPT);