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.api.FeatureColourI;
24 import jalview.api.FeatureSettingsModelI;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.GeneLoci;
27 import jalview.datamodel.Sequence;
28 import jalview.datamodel.SequenceFeature;
29 import jalview.datamodel.SequenceI;
30 import jalview.datamodel.features.SequenceFeatures;
31 import jalview.io.gff.SequenceOntologyFactory;
32 import jalview.io.gff.SequenceOntologyI;
33 import jalview.schemes.FeatureColour;
34 import jalview.schemes.FeatureSettingsAdapter;
35 import jalview.util.MapList;
37 import java.awt.Color;
38 import java.io.UnsupportedEncodingException;
39 import java.net.URLDecoder;
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.List;
44 import com.stevesoft.pat.Regex;
47 * A class that fetches genomic sequence and all transcripts for an Ensembl gene
51 public class EnsemblGene extends EnsemblSeqProxy
53 private static final String GENE_PREFIX = "gene:";
56 * accepts anything as we will attempt lookup of gene or
57 * transcript id or gene name
59 private static final Regex ACCESSION_REGEX = new Regex(".*");
61 private static final EnsemblFeatureType[] FEATURES_TO_FETCH = {
62 EnsemblFeatureType.gene, EnsemblFeatureType.transcript,
63 EnsemblFeatureType.exon, EnsemblFeatureType.cds,
64 EnsemblFeatureType.variation };
67 * Default constructor (to use rest.ensembl.org)
75 * Constructor given the target domain to fetch data from
79 public EnsemblGene(String d)
85 public String getDbName()
91 protected EnsemblFeatureType[] getFeaturesToFetch()
93 return FEATURES_TO_FETCH;
97 protected EnsemblSeqType getSourceEnsemblType()
99 return EnsemblSeqType.GENOMIC;
103 * Returns an alignment containing the gene(s) for the given gene or
104 * transcript identifier, or external identifier (e.g. Uniprot id). If given a
105 * gene name or external identifier, returns any related gene sequences found
106 * for model organisms. If only a single gene is queried for, then its
107 * transcripts are also retrieved and added to the alignment. <br>
110 * <li>resolves a transcript identifier by looking up its parent gene id</li>
111 * <li>resolves an external identifier by looking up xref-ed gene ids</li>
112 * <li>fetches the gene sequence</li>
113 * <li>fetches features on the sequence</li>
114 * <li>identifies "transcript" features whose Parent is the requested
116 * <li>fetches the transcript sequence for each transcript</li>
117 * <li>makes a mapping from the gene to each transcript</li>
118 * <li>copies features from gene to transcript sequences</li>
119 * <li>fetches the protein sequence for each transcript, maps and saves it as
120 * a cross-reference</li>
121 * <li>aligns each transcript against the gene sequence based on the position
126 * a single gene or transcript identifier or gene name
127 * @return an alignment containing a gene, and possibly transcripts, or null
130 public AlignmentI getSequenceRecords(String query) throws Exception
133 * convert to a non-duplicated list of gene identifiers
135 List<String> geneIds = getGeneIds(query);
137 AlignmentI al = null;
138 for (String geneId : geneIds)
141 * fetch the gene sequence(s) with features and xrefs
143 AlignmentI geneAlignment = super.getSequenceRecords(geneId);
144 if (geneAlignment == null)
148 if (geneAlignment.getHeight() == 1)
150 getTranscripts(geneAlignment, geneId);
158 al.append(geneAlignment);
165 * Converts a query, which may contain one or more gene or transcript
166 * identifiers, into a non-redundant list of gene identifiers.
171 List<String> getGeneIds(String accessions)
173 List<String> geneIds = new ArrayList<String>();
175 for (String acc : accessions.split(getAccessionSeparator()))
177 if (isGeneIdentifier(acc))
179 if (!geneIds.contains(acc))
186 * if given a transcript id, look up its gene parent
188 else if (isTranscriptIdentifier(acc))
190 String geneId = new EnsemblLookup(getDomain()).getParent(acc);
191 if (geneId != null && !geneIds.contains(geneId))
196 else if (isProteinIdentifier(acc))
198 String tscriptId = new EnsemblLookup(getDomain()).getParent(acc);
199 if (tscriptId != null)
201 String geneId = new EnsemblLookup(getDomain())
202 .getParent(tscriptId);
204 if (geneId != null && !geneIds.contains(geneId))
209 // NOTE - acc is lost if it resembles an ENS.+ ID but isn't actually
210 // resolving to one... e.g. ENSMICP00000009241
213 * if given a gene or other external name, lookup and fetch
214 * the corresponding gene for all model organisms
218 List<String> ids = new EnsemblSymbol(getDomain(), getDbSource(),
219 getDbVersion()).getIds(acc);
220 for (String geneId : ids)
222 if (!geneIds.contains(geneId))
233 * Attempts to get Ensembl stable identifiers for model organisms for a gene
234 * name by calling the xrefs symbol REST service to resolve the gene name.
239 protected String getGeneIdentifiersForName(String query)
241 List<String> ids = new EnsemblSymbol(getDomain(), getDbSource(),
242 getDbVersion()).getIds(query);
245 for (String id : ids)
247 if (isGeneIdentifier(id))
257 * Constructs all transcripts for the gene, as identified by "transcript"
258 * features whose Parent is the requested gene. The coding transcript
259 * sequences (i.e. with introns omitted) are added to the alignment.
265 protected void getTranscripts(AlignmentI al, String accId)
268 SequenceI gene = al.getSequenceAt(0);
269 List<SequenceFeature> transcriptFeatures = getTranscriptFeatures(accId,
272 for (SequenceFeature transcriptFeature : transcriptFeatures)
274 makeTranscript(transcriptFeature, al, gene);
277 clearGeneFeatures(gene);
281 * Remove unwanted features (transcript, exon, CDS) from the gene sequence
282 * after we have used them to derive transcripts and transfer features
286 protected void clearGeneFeatures(SequenceI gene)
289 * Note we include NMD_transcript_variant here because it behaves like
290 * 'transcript' in Ensembl, although strictly speaking it is not
291 * (it is a sub-type of sequence_variant)
293 String[] soTerms = new String[] {
294 SequenceOntologyI.NMD_TRANSCRIPT_VARIANT,
295 SequenceOntologyI.TRANSCRIPT, SequenceOntologyI.EXON,
296 SequenceOntologyI.CDS };
297 List<SequenceFeature> sfs = gene.getFeatures().getFeaturesByOntology(
299 for (SequenceFeature sf : sfs)
301 gene.deleteFeature(sf);
306 * Constructs a spliced transcript sequence by finding 'exon' features for the
307 * given id (or failing that 'CDS'). Copies features on to the new sequence.
308 * 'Aligns' the new sequence against the gene sequence by padding with gaps,
309 * and adds it to the alignment.
311 * @param transcriptFeature
313 * the alignment to which to add the new sequence
315 * the parent gene sequence, with features
318 SequenceI makeTranscript(SequenceFeature transcriptFeature, AlignmentI al,
321 String accId = getTranscriptId(transcriptFeature);
328 * NB we are mapping from gene sequence (not genome), so do not
329 * need to check for reverse strand (gene and transcript sequences
330 * are in forward sense)
334 * make a gene-length sequence filled with gaps
335 * we will fill in the bases for transcript regions
337 char[] seqChars = new char[gene.getLength()];
338 Arrays.fill(seqChars, al.getGapCharacter());
341 * look for exon features of the transcript, failing that for CDS
342 * (for example ENSG00000124610 has 1 CDS but no exon features)
344 String parentId = "transcript:" + accId;
345 List<SequenceFeature> splices = findFeatures(gene,
346 SequenceOntologyI.EXON, parentId);
347 if (splices.isEmpty())
349 splices = findFeatures(gene, SequenceOntologyI.CDS, parentId);
351 SequenceFeatures.sortFeatures(splices, true);
353 int transcriptLength = 0;
354 final char[] geneChars = gene.getSequence();
355 int offset = gene.getStart(); // to convert to 0-based positions
356 List<int[]> mappedFrom = new ArrayList<int[]>();
358 for (SequenceFeature sf : splices)
360 int start = sf.getBegin() - offset;
361 int end = sf.getEnd() - offset;
362 int spliceLength = end - start + 1;
363 System.arraycopy(geneChars, start, seqChars, start, spliceLength);
364 transcriptLength += spliceLength;
365 mappedFrom.add(new int[] { sf.getBegin(), sf.getEnd() });
368 Sequence transcript = new Sequence(accId, seqChars, 1,
372 * Ensembl has gene name as transcript Name
373 * EnsemblGenomes doesn't, but has a url-encoded description field
375 String description = (String) transcriptFeature.getValue(NAME);
376 if (description == null)
378 description = (String) transcriptFeature.getValue(DESCRIPTION);
380 if (description != null)
384 transcript.setDescription(URLDecoder.decode(description, "UTF-8"));
385 } catch (UnsupportedEncodingException e)
387 e.printStackTrace(); // as if
390 transcript.createDatasetSequence();
392 al.addSequence(transcript);
395 * transfer features to the new sequence; we use EnsemblCdna to do this,
396 * to filter out unwanted features types (see method retainFeature)
398 List<int[]> mapTo = new ArrayList<int[]>();
399 mapTo.add(new int[] { 1, transcriptLength });
400 MapList mapping = new MapList(mappedFrom, mapTo, 1, 1);
401 EnsemblCdna cdna = new EnsemblCdna(getDomain());
402 cdna.transferFeatures(gene.getFeatures().getPositionalFeatures(),
403 transcript.getDatasetSequence(), mapping, parentId);
405 mapTranscriptToChromosome(transcript, gene, mapping);
408 * fetch and save cross-references
410 cdna.getCrossReferences(transcript);
413 * and finally fetch the protein product and save as a cross-reference
415 cdna.addProteinProduct(transcript);
421 * If the gene has a mapping to chromosome coordinates, derive the transcript
422 * chromosome regions and save on the transcript sequence
427 * the mapping from gene to transcript positions
429 protected void mapTranscriptToChromosome(Sequence transcript,
430 SequenceI gene, MapList mapping)
432 GeneLoci loci = ((Sequence) gene).getGeneLoci();
439 * patch to ensure gene to chromosome mapping is complete
440 * (in case created before gene length was known)
442 MapList geneMapping = loci.mapping;
443 if (geneMapping.getFromRanges().get(0)[1] == 0)
445 geneMapping.getFromRanges().get(0)[0] = gene.getStart();
446 geneMapping.getFromRanges().get(0)[1] = gene.getEnd();
449 List<int[]> exons = mapping.getFromRanges();
450 List<int[]> transcriptLoci = new ArrayList<>();
452 for (int[] exon : exons) {
453 transcriptLoci.add(geneMapping.locateInTo(exon[0], exon[1]));
456 List<int[]> transcriptRange = Arrays.asList(new int[] {
457 transcript.getStart(), transcript.getEnd() });
458 MapList mapList = new MapList(transcriptRange, transcriptLoci, 1, 1);
459 GeneLoci gl = new GeneLoci(loci.species, loci.assembly,
460 loci.chromosome, mapList);
462 transcript.setGeneLoci(gl);
466 * Returns the 'transcript_id' property of the sequence feature (or null)
471 protected String getTranscriptId(SequenceFeature feature)
473 return (String) feature.getValue("transcript_id");
477 * Returns a list of the transcript features on the sequence whose Parent is
478 * the gene for the accession id.
481 * @param geneSequence
484 protected List<SequenceFeature> getTranscriptFeatures(String accId,
485 SequenceI geneSequence)
487 List<SequenceFeature> transcriptFeatures = new ArrayList<SequenceFeature>();
489 String parentIdentifier = GENE_PREFIX + accId;
490 // todo optimise here by transcript type!
491 List<SequenceFeature> sfs = geneSequence.getFeatures()
492 .getPositionalFeatures();
494 for (SequenceFeature sf : sfs)
496 if (isTranscript(sf.getType()))
498 String parent = (String) sf.getValue(PARENT);
499 if (parentIdentifier.equals(parent))
501 transcriptFeatures.add(sf);
506 return transcriptFeatures;
510 public String getDescription()
512 return "Fetches all transcripts and variant features for a gene or transcript";
516 * Default test query is a gene id (can also enter a transcript id)
519 public String getTestQuery()
521 return "ENSG00000157764"; // BRAF, 5 transcripts, reverse strand
522 // ENSG00000090266 // NDUFB2, 15 transcripts, forward strand
523 // ENSG00000101812 // H2BFM histone, 3 transcripts, forward strand
524 // ENSG00000123569 // H2BFWT histone, 2 transcripts, reverse strand
528 * Answers true for a feature of type 'gene' (or a sub-type of gene in the
529 * Sequence Ontology), whose ID is the accession we are retrieving
532 protected boolean identifiesSequence(SequenceFeature sf, String accId)
534 if (SequenceOntologyFactory.getInstance().isA(sf.getType(),
535 SequenceOntologyI.GENE))
537 String id = (String) sf.getValue(ID);
538 if ((GENE_PREFIX + accId).equals(id))
547 * Answers true unless feature type is 'gene', or 'transcript' with a parent
548 * which is a different gene. We need the gene features to identify the range,
549 * but it is redundant information on the gene sequence. Checking the parent
550 * allows us to drop transcript features which belong to different
551 * (overlapping) genes.
554 protected boolean retainFeature(SequenceFeature sf, String accessionId)
556 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
557 String type = sf.getType();
558 if (so.isA(type, SequenceOntologyI.GENE))
562 if (isTranscript(type))
564 String parent = (String) sf.getValue(PARENT);
565 if (!(GENE_PREFIX + accessionId).equals(parent))
574 * Answers false. This allows an optimisation - a single 'gene' feature is all
575 * that is needed to identify the positions of the gene on the genomic
579 protected boolean isSpliceable()
585 * Override to do nothing as Ensembl doesn't return a protein sequence for a
589 protected void addProteinProduct(SequenceI querySeq)
594 public Regex getAccessionValidator()
596 return ACCESSION_REGEX;
600 * Returns a descriptor for suitable feature display settings with
602 * <li>only exon or sequence_variant features (or their subtypes in the
603 * Sequence Ontology) visible</li>
604 * <li>variant features coloured red</li>
605 * <li>exon features coloured by label (exon name)</li>
606 * <li>variants displayed above (on top of) exons</li>
610 public FeatureSettingsModelI getFeatureColourScheme()
612 return new FeatureSettingsAdapter()
614 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
617 public boolean isFeatureDisplayed(String type)
619 return (so.isA(type, SequenceOntologyI.EXON)
620 || so.isA(type, SequenceOntologyI.SEQUENCE_VARIANT));
624 public FeatureColourI getFeatureColour(String type)
626 if (so.isA(type, SequenceOntologyI.EXON))
628 return new FeatureColour()
631 public boolean isColourByLabel()
637 if (so.isA(type, SequenceOntologyI.SEQUENCE_VARIANT))
639 return new FeatureColour()
643 public Color getColour()
653 * order to render sequence_variant after exon after the rest
656 public int compare(String feature1, String feature2)
658 if (so.isA(feature1, SequenceOntologyI.SEQUENCE_VARIANT))
662 if (so.isA(feature2, SequenceOntologyI.SEQUENCE_VARIANT))
666 if (so.isA(feature1, SequenceOntologyI.EXON))
670 if (so.isA(feature2, SequenceOntologyI.EXON))