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.SequenceOntologyFactory;
37 import jalview.io.gff.SequenceOntologyI;
38 import jalview.util.Comparison;
39 import jalview.util.DBRefUtils;
40 import jalview.util.IntRangeComparator;
41 import jalview.util.MapList;
43 import java.io.BufferedReader;
44 import java.io.IOException;
45 import java.net.MalformedURLException;
47 import java.util.ArrayList;
48 import java.util.Arrays;
49 import java.util.Collections;
50 import java.util.List;
52 import org.json.simple.JSONObject;
53 import org.json.simple.parser.JSONParser;
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 private static final String ALLELES = "alleles";
66 protected static final String NAME = "Name";
68 protected static final String DESCRIPTION = "description";
71 * enum for 'type' parameter to the /sequence REST service
73 public enum EnsemblSeqType
76 * type=genomic to fetch full dna including introns
81 * type=cdna to fetch coding dna including UTRs
86 * type=cds to fetch coding dna excluding UTRs
91 * type=protein to fetch peptide product sequence
96 * the value of the 'type' parameter to fetch this version of
101 EnsemblSeqType(String t)
106 public String getType()
114 * Default constructor (to use rest.ensembl.org)
116 public EnsemblSeqProxy()
122 * Constructor given the target domain to fetch data from
124 public EnsemblSeqProxy(String d)
130 * Makes the sequence queries to Ensembl's REST service and returns an
131 * alignment consisting of the returned sequences.
134 public AlignmentI getSequenceRecords(String query) throws Exception
136 // TODO use a String... query vararg instead?
138 // danger: accession separator used as a regex here, a string elsewhere
139 // in this case it is ok (it is just a space), but (e.g.) '\' would not be
140 List<String> allIds = Arrays
141 .asList(query.split(getAccessionSeparator()));
142 AlignmentI alignment = null;
146 * execute queries, if necessary in batches of the
147 * maximum allowed number of ids
149 int maxQueryCount = getMaximumQueryCount();
150 for (int v = 0, vSize = allIds.size(); v < vSize; v += maxQueryCount)
152 int p = Math.min(vSize, v + maxQueryCount);
153 List<String> ids = allIds.subList(v, p);
156 alignment = fetchSequences(ids, alignment);
157 } catch (Throwable r)
160 String msg = "Aborting ID retrieval after " + v
161 + " chunks. Unexpected problem (" + r.getLocalizedMessage()
163 System.err.println(msg);
169 if (alignment == null)
175 * fetch and transfer genomic sequence features,
176 * fetch protein product and add as cross-reference
178 for (String accId : allIds)
180 addFeaturesAndProduct(accId, alignment);
183 for (SequenceI seq : alignment.getSequences())
185 getCrossReferences(seq);
192 * Fetches Ensembl features using the /overlap REST endpoint, and adds them to
193 * the sequence in the alignment. Also fetches the protein product, maps it
194 * from the CDS features of the sequence, and saves it as a cross-reference of
200 protected void addFeaturesAndProduct(String accId, AlignmentI alignment)
202 if (alignment == null)
210 * get 'dummy' genomic sequence with gene, transcript,
211 * exon, cds and variation features
213 SequenceI genomicSequence = null;
214 EnsemblFeatures gffFetcher = new EnsemblFeatures(getDomain());
215 EnsemblFeatureType[] features = getFeaturesToFetch();
216 AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
218 if (geneFeatures != null && geneFeatures.getHeight() > 0)
220 genomicSequence = geneFeatures.getSequenceAt(0);
222 if (genomicSequence != null)
225 * transfer features to the query sequence
227 SequenceI querySeq = alignment.findName(accId, true);
228 if (transferFeatures(accId, genomicSequence, querySeq))
232 * fetch and map protein product, and add it as a cross-reference
233 * of the retrieved sequence
235 addProteinProduct(querySeq);
238 } catch (IOException e)
241 "Error transferring Ensembl features: " + e.getMessage());
246 * Returns those sequence feature types to fetch from Ensembl. We may want
247 * features either because they are of interest to the user, or as means to
248 * identify the locations of the sequence on the genomic sequence (CDS
249 * features identify CDS, exon features identify cDNA etc).
253 protected abstract EnsemblFeatureType[] getFeaturesToFetch();
256 * Fetches and maps the protein product, and adds it as a cross-reference of
257 * the retrieved sequence
259 protected void addProteinProduct(SequenceI querySeq)
261 String accId = querySeq.getName();
264 AlignmentI protein = new EnsemblProtein(getDomain())
265 .getSequenceRecords(accId);
266 if (protein == null || protein.getHeight() == 0)
268 System.out.println("No protein product found for " + accId);
271 SequenceI proteinSeq = protein.getSequenceAt(0);
274 * need dataset sequences (to be the subject of mappings)
276 proteinSeq.createDatasetSequence();
277 querySeq.createDatasetSequence();
279 MapList mapList = AlignmentUtils.mapCdsToProtein(querySeq,
283 // clunky: ensure Uniprot xref if we have one is on mapped sequence
284 SequenceI ds = proteinSeq.getDatasetSequence();
285 // TODO: Verify ensp primary ref is on proteinSeq.getDatasetSequence()
286 Mapping map = new Mapping(ds, mapList);
287 DBRefEntry dbr = new DBRefEntry(getDbSource(),
288 getEnsemblDataVersion(), proteinSeq.getName(), map);
289 querySeq.getDatasetSequence().addDBRef(dbr);
290 DBRefEntry[] uprots = DBRefUtils.selectRefs(ds.getDBRefs(),
292 { DBRefSource.UNIPROT });
293 DBRefEntry[] upxrefs = DBRefUtils.selectRefs(querySeq.getDBRefs(),
295 { DBRefSource.UNIPROT });
298 for (DBRefEntry up : uprots)
300 // locate local uniprot ref and map
301 List<DBRefEntry> upx = DBRefUtils.searchRefs(upxrefs,
302 up.getAccessionId());
311 "Implementation issue - multiple uniprot acc on product sequence.");
316 upxref = new DBRefEntry(DBRefSource.UNIPROT,
317 getEnsemblDataVersion(), up.getAccessionId());
320 Mapping newMap = new Mapping(ds, mapList);
321 upxref.setVersion(getEnsemblDataVersion());
322 upxref.setMap(newMap);
325 // add the new uniprot ref
326 querySeq.getDatasetSequence().addDBRef(upxref);
333 * copy exon features to protein, compute peptide variants from dna
334 * variants and add as features on the protein sequence ta-da
336 AlignmentUtils.computeProteinFeatures(querySeq, proteinSeq,
339 } catch (Exception e)
342 .println(String.format("Error retrieving protein for %s: %s",
343 accId, e.getMessage()));
348 * Get database xrefs from Ensembl, and attach them to the sequence
352 protected void getCrossReferences(SequenceI seq)
354 while (seq.getDatasetSequence() != null)
356 seq = seq.getDatasetSequence();
359 EnsemblXref xrefFetcher = new EnsemblXref(getDomain(), getDbSource(),
360 getEnsemblDataVersion());
361 List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName());
362 for (DBRefEntry xref : xrefs)
368 * and add a reference to itself
370 DBRefEntry self = new DBRefEntry(getDbSource(), getEnsemblDataVersion(),
376 * Fetches sequences for the list of accession ids and adds them to the
377 * alignment. Returns the extended (or created) alignment.
382 * @throws JalviewException
383 * @throws IOException
385 protected AlignmentI fetchSequences(List<String> ids,
386 AlignmentI alignment) throws JalviewException, IOException
388 if (!isEnsemblAvailable())
391 throw new JalviewException("ENSEMBL Rest API not available.");
393 BufferedReader br = getSequenceReader(ids);
399 List<SequenceI> seqs = parseSequenceJson(br);
403 throw new IOException("No data returned for " + ids);
406 if (seqs.size() != ids.size())
408 System.out.println(String.format(
409 "Only retrieved %d sequences for %d query strings",
410 seqs.size(), ids.size()));
415 AlignmentI seqal = new Alignment(
416 seqs.toArray(new SequenceI[seqs.size()]));
417 for (SequenceI seq : seqs)
419 if (seq.getDescription() == null)
421 seq.setDescription(getDbName());
423 String name = seq.getName();
424 if (ids.contains(name)
425 || ids.contains(name.replace("ENSP", "ENST")))
427 // TODO JAL-3077 use true accession version in dbref
428 DBRefEntry dbref = DBRefUtils.parseToDbRef(seq, getDbSource(),
429 getEnsemblDataVersion(), name);
433 if (alignment == null)
439 alignment.append(seqal);
446 * Parses a JSON response into a list of sequences
450 * @see http://rest.ensembl.org/documentation/info/sequence_id
452 protected List<SequenceI> parseSequenceJson(BufferedReader br)
454 JSONParser jp = new JSONParser();
455 List<SequenceI> result = new ArrayList<>();
459 * for now, assumes only one sequence returned; refactor if needed
460 * in future to handle a JSONArray with more than one
462 final JSONObject val = (JSONObject) jp.parse(br);
463 Object s = val.get("desc");
464 String desc = s == null ? null : s.toString();
466 String id = s == null ? null : s.toString();
468 String seq = s == null ? null : s.toString();
469 Sequence sequence = new Sequence(id, seq);
472 sequence.setDescription(desc);
474 // todo JAL-3077 make a DBRefEntry with true accession version
475 // s = val.get("version");
476 // String version = s == null ? "0" : s.toString();
477 // DBRefEntry dbref = new DBRefEntry(getDbSource(), version, id);
478 // sequence.addDBRef(dbref);
479 result.add(sequence);
480 } catch (ParseException | IOException e)
482 System.err.println("Error processing JSON response: " + e.toString());
489 * Returns the URL for the REST call
492 * @throws MalformedURLException
495 protected URL getUrl(List<String> ids) throws MalformedURLException
498 * a single id is included in the URL path
499 * multiple ids go in the POST body instead
501 StringBuffer urlstring = new StringBuffer(128);
502 urlstring.append(getDomain() + "/sequence/id");
505 urlstring.append("/").append(ids.get(0));
507 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
508 urlstring.append("?type=").append(getSourceEnsemblType().getType());
509 urlstring.append(("&Accept=application/json"));
510 urlstring.append(("&Content-Type=application/json"));
512 String objectType = getObjectType();
513 if (objectType != null)
515 urlstring.append("&").append(OBJECT_TYPE).append("=")
519 URL url = new URL(urlstring.toString());
524 * Override this method to specify object_type request parameter
528 protected String getObjectType()
534 * A sequence/id POST request currently allows up to 50 queries
536 * @see http://rest.ensembl.org/documentation/info/sequence_id_post
539 public int getMaximumQueryCount()
545 protected boolean useGetRequest()
552 * @return the configured sequence return type for this source
554 protected abstract EnsemblSeqType getSourceEnsemblType();
557 * Returns a list of [start, end] genomic ranges corresponding to the sequence
560 * The correspondence between the frames of reference is made by locating
561 * those features on the genomic sequence which identify the retrieved
562 * sequence. Specifically
564 * <li>genomic sequence is identified by "transcript" features with
565 * ID=transcript:transcriptId</li>
566 * <li>cdna sequence is identified by "exon" features with
567 * Parent=transcript:transcriptId</li>
568 * <li>cds sequence is identified by "CDS" features with
569 * Parent=transcript:transcriptId</li>
572 * The returned ranges are sorted to run forwards (for positive strand) or
573 * backwards (for negative strand). Aborts and returns null if both positive
574 * and negative strand are found (this should not normally happen).
576 * @param sourceSequence
579 * the start position of the sequence we are mapping to
582 protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
583 String accId, int start)
585 List<SequenceFeature> sfs = sourceSequence.getFeatures()
586 .getPositionalFeatures();
593 * generously initial size for number of cds regions
594 * (worst case titin Q8WZ42 has c. 313 exons)
596 List<int[]> regions = new ArrayList<>(100);
597 int mappedLength = 0;
598 int direction = 1; // forward
599 boolean directionSet = false;
601 for (SequenceFeature sf : sfs)
604 * accept the target feature type or a specialisation of it
605 * (e.g. coding_exon for exon)
607 if (identifiesSequence(sf, accId))
609 int strand = sf.getStrand();
610 strand = strand == 0 ? 1 : strand; // treat unknown as forward
612 if (directionSet && strand != direction)
614 // abort - mix of forward and backward
616 "Error: forward and backward strand for " + accId);
623 * add to CDS ranges, semi-sorted forwards/backwards
627 regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
631 regions.add(new int[] { sf.getBegin(), sf.getEnd() });
633 mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
638 * 'gene' sequence is contiguous so we can stop as soon as its
639 * identifying feature has been found
646 if (regions.isEmpty())
648 System.out.println("Failed to identify target sequence for " + accId
649 + " from genomic features");
654 * a final sort is needed since Ensembl returns CDS sorted within source
655 * (havana / ensembl_havana)
657 Collections.sort(regions, direction == 1 ? IntRangeComparator.ASCENDING
658 : IntRangeComparator.DESCENDING);
660 List<int[]> to = Arrays
662 { start, start + mappedLength - 1 });
664 return new MapList(regions, to, 1, 1);
668 * Answers true if the sequence being retrieved may occupy discontiguous
669 * regions on the genomic sequence.
671 protected boolean isSpliceable()
677 * Returns true if the sequence feature marks positions of the genomic
678 * sequence feature which are within the sequence being retrieved. For
679 * example, an 'exon' feature whose parent is the target transcript marks the
680 * cdna positions of the transcript.
686 protected abstract boolean identifiesSequence(SequenceFeature sf,
690 * Transfers the sequence feature to the target sequence, locating its start
691 * and end range based on the mapping. Features which do not overlap the
692 * target sequence are ignored.
695 * @param targetSequence
697 * mapping from the sequence feature's coordinates to the target
699 * @param forwardStrand
701 protected void transferFeature(SequenceFeature sf,
702 SequenceI targetSequence, MapList mapping, boolean forwardStrand)
704 int start = sf.getBegin();
705 int end = sf.getEnd();
706 int[] mappedRange = mapping.locateInTo(start, end);
708 if (mappedRange != null)
710 String group = sf.getFeatureGroup();
711 if (".".equals(group))
713 group = getDbSource();
715 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
716 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
717 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
718 group, sf.getScore());
719 targetSequence.addSequenceFeature(copy);
722 * for sequence_variant on reverse strand, have to convert the allele
723 * values to their complements
725 if (!forwardStrand && SequenceOntologyFactory.getInstance()
726 .isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
728 reverseComplementAlleles(copy);
734 * Change the 'alleles' value of a feature by converting to complementary
735 * bases, and also update the feature description to match
739 static void reverseComplementAlleles(SequenceFeature sf)
741 final String alleles = (String) sf.getValue(ALLELES);
746 StringBuilder complement = new StringBuilder(alleles.length());
747 for (String allele : alleles.split(","))
749 reverseComplementAllele(complement, allele);
751 String comp = complement.toString();
752 sf.setValue(ALLELES, comp);
753 sf.setDescription(comp);
756 * replace value of "alleles=" in sf.ATTRIBUTES as well
757 * so 'output as GFF' shows reverse complement alleles
759 String atts = sf.getAttributes();
762 atts = atts.replace(ALLELES + "=" + alleles, ALLELES + "=" + comp);
763 sf.setAttributes(atts);
768 * Makes the 'reverse complement' of the given allele and appends it to the
769 * buffer, after a comma separator if not the first
774 static void reverseComplementAllele(StringBuilder complement,
777 if (complement.length() > 0)
779 complement.append(",");
783 * some 'alleles' are actually descriptive terms
784 * e.g. HGMD_MUTATION, PhenCode_variation
785 * - we don't want to 'reverse complement' these
787 if (!Comparison.isNucleotideSequence(allele, true))
789 complement.append(allele);
793 for (int i = allele.length() - 1; i >= 0; i--)
795 complement.append(Dna.getComplement(allele.charAt(i)));
801 * Transfers features from sourceSequence to targetSequence
804 * @param sourceSequence
805 * @param targetSequence
806 * @return true if any features were transferred, else false
808 protected boolean transferFeatures(String accessionId,
809 SequenceI sourceSequence, SequenceI targetSequence)
811 if (sourceSequence == null || targetSequence == null)
816 // long start = System.currentTimeMillis();
817 List<SequenceFeature> sfs = sourceSequence.getFeatures()
818 .getPositionalFeatures();
819 MapList mapping = getGenomicRangesFromFeatures(sourceSequence,
820 accessionId, targetSequence.getStart());
826 boolean result = transferFeatures(sfs, targetSequence, mapping,
828 // System.out.println("transferFeatures (" + (sfs.size()) + " --> "
829 // + targetSequence.getFeatures().getFeatureCount(true) + ") to "
830 // + targetSequence.getName() + " took "
831 // + (System.currentTimeMillis() - start) + "ms");
836 * Transfer features to the target sequence. The start/end positions are
837 * converted using the mapping. Features which do not overlap are ignored.
838 * Features whose parent is not the specified identifier are also ignored.
841 * @param targetSequence
846 protected boolean transferFeatures(List<SequenceFeature> sfs,
847 SequenceI targetSequence, MapList mapping, String parentId)
849 final boolean forwardStrand = mapping.isFromForwardStrand();
852 * sort features by start position (which corresponds to end
853 * position descending if reverse strand) so as to add them in
854 * 'forwards' order to the target sequence
856 SequenceFeatures.sortFeatures(sfs, forwardStrand);
858 boolean transferred = false;
859 for (SequenceFeature sf : sfs)
861 if (retainFeature(sf, parentId))
863 transferFeature(sf, targetSequence, mapping, forwardStrand);
871 * Answers true if the feature type is one we want to keep for the sequence.
872 * Some features are only retrieved in order to identify the sequence range,
873 * and may then be discarded as redundant information (e.g. "CDS" feature for
876 @SuppressWarnings("unused")
877 protected boolean retainFeature(SequenceFeature sf, String accessionId)
879 return true; // override as required
883 * Answers true if the feature has a Parent which refers to the given
884 * accession id, or if the feature has no parent. Answers false if the
885 * feature's Parent is for a different accession id.
891 protected boolean featureMayBelong(SequenceFeature sf, String identifier)
893 String parent = (String) sf.getValue(PARENT);
894 // using contains to allow for prefix "gene:", "transcript:" etc
896 && !parent.toUpperCase().contains(identifier.toUpperCase()))
898 // this genomic feature belongs to a different transcript
905 public String getDescription()
907 return "Ensembl " + getSourceEnsemblType().getType()
908 + " sequence with variant features";
912 * Returns a (possibly empty) list of features on the sequence which have the
913 * specified sequence ontology term (or a sub-type of it), and the given
914 * identifier as parent
921 protected List<SequenceFeature> findFeatures(SequenceI sequence,
922 String term, String parentId)
924 List<SequenceFeature> result = new ArrayList<>();
926 List<SequenceFeature> sfs = sequence.getFeatures()
927 .getFeaturesByOntology(term);
928 for (SequenceFeature sf : sfs)
930 String parent = (String) sf.getValue(PARENT);
931 if (parent != null && parent.equalsIgnoreCase(parentId))
941 * Answers true if the feature type is either 'NMD_transcript_variant' or
942 * 'transcript' or one of its sub-types in the Sequence Ontology. This is
943 * needed because NMD_transcript_variant behaves like 'transcript' in Ensembl
944 * although strictly speaking it is not (it is a sub-type of
950 public static boolean isTranscript(String featureType)
952 return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
953 || SequenceOntologyFactory.getInstance().isA(featureType,
954 SequenceOntologyI.TRANSCRIPT);