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 (int i = 0, n = allIds.size(); i < n; i++)
176 addFeaturesAndProduct(allIds.get(i), alignment);
179 List<SequenceI> seqs = alignment.getSequences();
180 for (int i = 0, n = seqs.size(); i < n; i++)
182 getCrossReferences(seqs.get(i));
189 * Fetches Ensembl features using the /overlap REST endpoint, and adds them to
190 * the sequence in the alignment. Also fetches the protein product, maps it
191 * from the CDS features of the sequence, and saves it as a cross-reference of
197 protected void addFeaturesAndProduct(String accId, AlignmentI alignment)
199 if (alignment == null)
207 * get 'dummy' genomic sequence with gene, transcript,
208 * exon, cds and variation features
210 SequenceI genomicSequence = null;
211 EnsemblFeatures gffFetcher = new EnsemblFeatures(getDomain());
212 EnsemblFeatureType[] features = getFeaturesToFetch();
214 Platform.timeCheck("ESP.getsequencerec1", Platform.TIME_MARK);
217 AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
219 if (geneFeatures != null && geneFeatures.getHeight() > 0)
221 genomicSequence = geneFeatures.getSequenceAt(0);
224 Platform.timeCheck("ESP.getsequencerec2", Platform.TIME_MARK);
226 if (genomicSequence != null)
229 * transfer features to the query sequence
231 SequenceI querySeq = alignment.findName(accId, true);
232 if (transferFeatures(accId, genomicSequence, querySeq))
236 * fetch and map protein product, and add it as a cross-reference
237 * of the retrieved sequence
239 Platform.timeCheck("ESP.transferFeatures", Platform.TIME_MARK);
240 addProteinProduct(querySeq);
243 } catch (IOException e)
246 "Error transferring Ensembl features: " + e.getMessage());
248 Platform.timeCheck("ESP.addfeat done", Platform.TIME_MARK);
252 * Returns those sequence feature types to fetch from Ensembl. We may want
253 * features either because they are of interest to the user, or as means to
254 * identify the locations of the sequence on the genomic sequence (CDS
255 * features identify CDS, exon features identify cDNA etc).
259 protected abstract EnsemblFeatureType[] getFeaturesToFetch();
262 * Fetches and maps the protein product, and adds it as a cross-reference of
263 * the retrieved sequence
265 protected void addProteinProduct(SequenceI querySeq)
267 String accId = querySeq.getName();
270 System.out.println("Adding protein product for " + accId);
271 AlignmentI protein = new EnsemblProtein(getDomain())
272 .getSequenceRecords(accId);
273 if (protein == null || protein.getHeight() == 0)
275 System.out.println("No protein product found for " + accId);
278 SequenceI proteinSeq = protein.getSequenceAt(0);
281 * need dataset sequences (to be the subject of mappings)
283 proteinSeq.createDatasetSequence();
284 querySeq.createDatasetSequence();
286 MapList mapList = AlignmentUtils.mapCdsToProtein(querySeq,
290 // clunky: ensure Uniprot xref if we have one is on mapped sequence
291 SequenceI ds = proteinSeq.getDatasetSequence();
292 // TODO: Verify ensp primary ref is on proteinSeq.getDatasetSequence()
293 Mapping map = new Mapping(ds, mapList);
294 DBRefEntry dbr = new DBRefEntry(getDbSource(),
295 getEnsemblDataVersion(), proteinSeq.getName(), map);
296 querySeq.getDatasetSequence().addDBRef(dbr);
297 List<DBRefEntry> uprots = DBRefUtils.selectRefs(ds.getDBRefs(),
299 { DBRefSource.UNIPROT });
300 List<DBRefEntry> upxrefs = DBRefUtils.selectRefs(querySeq.getDBRefs(),
302 { DBRefSource.UNIPROT });
305 for (DBRefEntry up : uprots)
307 // locate local uniprot ref and map
308 List<DBRefEntry> upx = DBRefUtils.searchRefs(upxrefs,
309 up.getAccessionId());
318 "Implementation issue - multiple uniprot acc on product sequence.");
323 upxref = new DBRefEntry(DBRefSource.UNIPROT,
324 getEnsemblDataVersion(), up.getAccessionId());
327 Mapping newMap = new Mapping(ds, mapList);
328 upxref.setVersion(getEnsemblDataVersion());
329 upxref.setMap(newMap);
332 // add the new uniprot ref
333 querySeq.getDatasetSequence().addDBRef(upxref);
340 * copy exon features to protein, compute peptide variants from dna
341 * variants and add as features on the protein sequence ta-da
343 AlignmentUtils.computeProteinFeatures(querySeq, proteinSeq,
346 } catch (Exception e)
349 .println(String.format("Error retrieving protein for %s: %s",
350 accId, e.getMessage()));
355 * Get database xrefs from Ensembl, and attach them to the sequence
359 protected void getCrossReferences(SequenceI seq)
362 Platform.timeCheck("ESP. getdataseq ", Platform.TIME_MARK);
365 while (seq.getDatasetSequence() != null)
367 seq = seq.getDatasetSequence();
370 Platform.timeCheck("ESP. getxref ", Platform.TIME_MARK);
372 EnsemblXref xrefFetcher = new EnsemblXref(getDomain(), getDbSource(),
373 getEnsemblDataVersion());
374 List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName());
376 for (int i = 0, n = xrefs.size(); i < n; i++)
378 // Platform.timeCheck("ESP. getxref + " + (i) + "/" + n, Platform.TIME_MARK);
379 // BH 2019.01.25 this next method was taking 174 ms PER addition for a 266-reference example.
380 // DBRefUtils.ensurePrimaries(seq)
381 // was at the end of seq.addDBRef, so executed after ever addition!
382 // This method was moved to seq.getPrimaryDBRefs()
383 seq.addDBRef(xrefs.get(i));
386 // System.out.println("primaries are " + seq.getPrimaryDBRefs().toString());
388 * and add a reference to itself
391 // Platform.timeCheck("ESP. getxref self ", Platform.TIME_MARK);
393 DBRefEntry self = new DBRefEntry(getDbSource(), getEnsemblDataVersion(),
396 // Platform.timeCheck("ESP. getxref self add ", Platform.TIME_MARK);
400 Platform.timeCheck("ESP. seqprox done ", Platform.TIME_MARK);
405 * Fetches sequences for the list of accession ids and adds them to the
406 * alignment. Returns the extended (or created) alignment.
411 * @throws JalviewException
412 * @throws IOException
414 protected AlignmentI fetchSequences(List<String> ids,
415 AlignmentI alignment) throws JalviewException, IOException
417 if (!isEnsemblAvailable())
420 throw new JalviewException("ENSEMBL Rest API not available.");
422 Platform.timeCheck("EnsemblSeqProx.fetchSeq ", Platform.TIME_MARK);
424 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);
498 Object s = val.get("desc");
499 String desc = s == null ? null : s.toString();
501 String id = s == null ? null : s.toString();
503 String seq = s == null ? null : s.toString();
504 Sequence sequence = new Sequence(id, seq);
507 sequence.setDescription(desc);
509 // todo JAL-3077 make a DBRefEntry with true accession version
510 // s = val.get("version");
511 // String version = s == null ? "0" : s.toString();
512 // DBRefEntry dbref = new DBRefEntry(getDbSource(), version, id);
513 // sequence.addDBRef(dbref);
514 result.add(sequence);
515 } catch (ParseException | IOException e)
517 System.err.println("Error processing JSON response: " + e.toString());
520 Platform.timeCheck("ENS seqproxy2", Platform.TIME_MARK);
525 * Returns the URL for the REST call
528 * @throws MalformedURLException
531 protected URL getUrl(List<String> ids) throws MalformedURLException
534 * a single id is included in the URL path
535 * multiple ids go in the POST body instead
537 StringBuffer urlstring = new StringBuffer(128);
538 urlstring.append(getDomain() + "/sequence/id");
541 urlstring.append("/").append(ids.get(0));
543 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
544 urlstring.append("?type=").append(getSourceEnsemblType().getType());
545 urlstring.append(("&Accept=application/json"));
546 urlstring.append(("&content-type=application/json"));
548 String objectType = getObjectType();
549 if (objectType != null)
551 urlstring.append("&").append(OBJECT_TYPE).append("=")
555 URL url = new URL(urlstring.toString());
560 * Override this method to specify object_type request parameter
564 protected String getObjectType()
570 * A sequence/id POST request currently allows up to 50 queries
572 * @see http://rest.ensembl.org/documentation/info/sequence_id_post
575 public int getMaximumQueryCount()
581 protected boolean useGetRequest()
588 * @return the configured sequence return type for this source
590 protected abstract EnsemblSeqType getSourceEnsemblType();
593 * Returns a list of [start, end] genomic ranges corresponding to the sequence
596 * The correspondence between the frames of reference is made by locating
597 * those features on the genomic sequence which identify the retrieved
598 * sequence. Specifically
600 * <li>genomic sequence is identified by "transcript" features with
601 * ID=transcript:transcriptId</li>
602 * <li>cdna sequence is identified by "exon" features with
603 * Parent=transcript:transcriptId</li>
604 * <li>cds sequence is identified by "CDS" features with
605 * Parent=transcript:transcriptId</li>
608 * The returned ranges are sorted to run forwards (for positive strand) or
609 * backwards (for negative strand). Aborts and returns null if both positive
610 * and negative strand are found (this should not normally happen).
612 * @param sourceSequence
615 * the start position of the sequence we are mapping to
618 protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
619 String accId, int start)
621 List<SequenceFeature> sfs = getIdentifyingFeatures(sourceSequence,
629 * generously initial size for number of cds regions
630 * (worst case titin Q8WZ42 has c. 313 exons)
632 List<int[]> regions = new ArrayList<>(100);
633 int mappedLength = 0;
634 int direction = 1; // forward
635 boolean directionSet = false;
637 for (SequenceFeature sf : sfs)
639 int strand = sf.getStrand();
640 strand = strand == 0 ? 1 : strand; // treat unknown as forward
642 if (directionSet && strand != direction)
644 // abort - mix of forward and backward
646 .println("Error: forward and backward strand for " + accId);
653 * add to CDS ranges, semi-sorted forwards/backwards
657 regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
661 regions.add(new int[] { sf.getBegin(), sf.getEnd() });
663 mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
666 if (regions.isEmpty())
668 System.out.println("Failed to identify target sequence for " + accId
669 + " from genomic features");
674 * a final sort is needed since Ensembl returns CDS sorted within source
675 * (havana / ensembl_havana)
677 Collections.sort(regions, direction == 1 ? IntRangeComparator.ASCENDING
678 : IntRangeComparator.DESCENDING);
680 List<int[]> to = Arrays
682 { start, start + mappedLength - 1 });
684 return new MapList(regions, to, 1, 1);
688 * Answers a list of sequence features that mark positions of the genomic
689 * sequence feature which are within the sequence being retrieved. For
690 * example, an 'exon' feature whose parent is the target transcript marks the
691 * cdna positions of the transcript. For a gene sequence, this is trivially
692 * just the 'gene' feature with matching gene id.
698 protected abstract List<SequenceFeature> getIdentifyingFeatures(
699 SequenceI seq, String accId);
704 * Transfers the sequence feature to the target sequence, locating its start
705 * and end range based on the mapping. Features which do not overlap the
706 * target sequence are ignored.
709 * @param targetSequence
711 * mapping from the sequence feature's coordinates to the target
713 * @param forwardStrand
715 protected void transferFeature(SequenceFeature sf,
716 SequenceI targetSequence, MapList mapping, boolean forwardStrand)
718 int start = sf.getBegin();
719 int end = sf.getEnd();
720 int[] mappedRange = mapping.locateInTo(start, end);
722 if (mappedRange != null)
724 // Platform.timeCheck(null, Platform.TIME_SET);
725 String group = sf.getFeatureGroup();
726 if (".".equals(group))
728 group = getDbSource();
730 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
731 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
732 // Platform.timeCheck(null, Platform.TIME_MARK);
735 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd, group, sf.getScore());
737 targetSequence.addSequenceFeature(copy);
740 * for sequence_variant on reverse strand, have to convert the allele
741 * values to their complements
743 if (!forwardStrand && SequenceOntologyFactory.getSequenceOntology()
744 .isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
746 reverseComplementAlleles(copy);
752 * Change the 'alleles' value of a feature by converting to complementary
753 * bases, and also update the feature description to match
757 static void reverseComplementAlleles(SequenceFeature sf)
759 final String alleles = (String) sf.getValue(Gff3Helper.ALLELES);
764 StringBuilder complement = new StringBuilder(alleles.length());
765 for (String allele : alleles.split(","))
767 reverseComplementAllele(complement, allele);
769 String comp = complement.toString();
770 sf.setValue(Gff3Helper.ALLELES, comp);
771 sf.setDescription(comp);
774 * replace value of "alleles=" in sf.ATTRIBUTES as well
775 * so 'output as GFF' shows reverse complement alleles
777 String atts = sf.getAttributes();
780 atts = atts.replace(Gff3Helper.ALLELES + "=" + alleles,
781 Gff3Helper.ALLELES + "=" + comp);
782 sf.setAttributes(atts);
787 * Makes the 'reverse complement' of the given allele and appends it to the
788 * buffer, after a comma separator if not the first
793 static void reverseComplementAllele(StringBuilder complement,
796 if (complement.length() > 0)
798 complement.append(",");
802 * some 'alleles' are actually descriptive terms
803 * e.g. HGMD_MUTATION, PhenCode_variation
804 * - we don't want to 'reverse complement' these
806 if (!Comparison.isNucleotideSequence(allele, true))
808 complement.append(allele);
812 for (int i = allele.length() - 1; i >= 0; i--)
814 complement.append(Dna.getComplement(allele.charAt(i)));
820 * Transfers features from sourceSequence to targetSequence
823 * @param sourceSequence
824 * @param targetSequence
825 * @return true if any features were transferred, else false
827 protected boolean transferFeatures(String accessionId,
828 SequenceI sourceSequence, SequenceI targetSequence)
830 if (sourceSequence == null || targetSequence == null)
835 // long start = System.currentTimeMillis();
836 List<SequenceFeature> sfs = sourceSequence.getFeatures()
837 .getPositionalFeatures();
838 MapList mapping = getGenomicRangesFromFeatures(sourceSequence,
839 accessionId, targetSequence.getStart());
846 Platform.timeCheck("ESP. xfer " + sfs.size(), Platform.TIME_MARK);
849 boolean result = transferFeatures(sfs, targetSequence, mapping,
851 // System.out.println("transferFeatures (" + (sfs.size()) + " --> "
852 // + targetSequence.getFeatures().getFeatureCount(true) + ") to "
853 // + targetSequence.getName() + " took "
854 // + (System.currentTimeMillis() - start) + "ms");
859 * Transfer features to the target sequence. The start/end positions are
860 * converted using the mapping. Features which do not overlap are ignored.
861 * Features whose parent is not the specified identifier are also ignored.
864 * @param targetSequence
869 protected boolean transferFeatures(List<SequenceFeature> sfs,
870 SequenceI targetSequence, MapList mapping, String parentId)
872 final boolean forwardStrand = mapping.isFromForwardStrand();
875 * sort features by start position (which corresponds to end
876 * position descending if reverse strand) so as to add them in
877 * 'forwards' order to the target sequence
879 SequenceFeatures.sortFeatures(sfs, forwardStrand);
881 boolean transferred = false;
883 for (int i = 0, n = sfs.size(); i < n; i++)
886 // if ((i%1000) == 0) {
887 //// Platform.timeCheck("Feature " + bhtest, Platform.TIME_GET);
888 // Platform.timeCheck("ESP. xferFeature + " + (i) + "/" + n, Platform.TIME_MARK);
891 SequenceFeature sf = sfs.get(i);
892 if (retainFeature(sf, parentId))
894 transferFeature(sf, targetSequence, mapping, forwardStrand);
903 * Answers true if the feature type is one we want to keep for the sequence.
904 * Some features are only retrieved in order to identify the sequence range,
905 * and may then be discarded as redundant information (e.g. "CDS" feature for
908 @SuppressWarnings("unused")
909 protected boolean retainFeature(SequenceFeature sf, String accessionId)
911 return true; // override as required
915 * Answers true if the feature has a Parent which refers to the given
916 * accession id, or if the feature has no parent. Answers false if the
917 * feature's Parent is for a different accession id.
923 protected boolean featureMayBelong(SequenceFeature sf, String identifier)
925 String parent = (String) sf.getValue(PARENT);
927 && !parent.equalsIgnoreCase(identifier))
929 // this genomic feature belongs to a different transcript
936 * Answers a short description of the sequence fetcher
939 public String getDescription()
941 return "Ensembl " + getSourceEnsemblType().getType()
942 + " sequence with variant features";
946 * Returns a (possibly empty) list of features on the sequence which have the
947 * specified sequence ontology term (or a sub-type of it), and the given
948 * identifier as parent
955 protected List<SequenceFeature> findFeatures(SequenceI sequence,
956 String term, String parentId)
958 List<SequenceFeature> result = new ArrayList<>();
960 List<SequenceFeature> sfs = sequence.getFeatures()
961 .getFeaturesByOntology(term);
962 for (SequenceFeature sf : sfs)
964 String parent = (String) sf.getValue(PARENT);
965 if (parent != null && parent.equalsIgnoreCase(parentId))
975 * Answers true if the feature type is either 'NMD_transcript_variant' or
976 * 'transcript' (or one of its sub-types in the Sequence Ontology). This is
977 * because NMD_transcript_variant behaves like 'transcript' in Ensembl
978 * although strictly speaking it is not (it is a sub-type of
981 * (This test was needed when fetching transcript features as GFF. As we are
982 * now fetching as JSON, all features have type 'transcript' so the check for
983 * NMD_transcript_variant is redundant. Left in for any future case arising.)
988 public static boolean isTranscript(String featureType)
990 return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
991 || SequenceOntologyFactory.getSequenceOntology().isA(featureType,
992 SequenceOntologyI.TRANSCRIPT);