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.DBRefEntry;
27 import jalview.datamodel.GeneLociI;
28 import jalview.datamodel.Sequence;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceI;
31 import jalview.datamodel.features.SequenceFeatures;
32 import jalview.io.gff.SequenceOntologyFactory;
33 import jalview.io.gff.SequenceOntologyI;
34 import jalview.schemes.FeatureColour;
35 import jalview.schemes.FeatureSettingsAdapter;
36 import jalview.util.MapList;
38 import java.awt.Color;
39 import java.io.UnsupportedEncodingException;
40 import java.net.URLDecoder;
41 import java.util.ArrayList;
42 import java.util.Arrays;
43 import java.util.List;
45 import com.stevesoft.pat.Regex;
48 * A class that fetches genomic sequence and all transcripts for an Ensembl gene
52 public class EnsemblGene extends EnsemblSeqProxy
54 private static final String GENE_PREFIX = "gene:";
57 * accepts anything as we will attempt lookup of gene or
58 * transcript id or gene name
60 private static final Regex ACCESSION_REGEX = new Regex(".*");
62 private static final EnsemblFeatureType[] FEATURES_TO_FETCH = {
63 EnsemblFeatureType.gene, EnsemblFeatureType.transcript,
64 EnsemblFeatureType.exon, EnsemblFeatureType.cds,
65 EnsemblFeatureType.variation };
68 * Default constructor (to use rest.ensembl.org)
76 * Constructor given the target domain to fetch data from
80 public EnsemblGene(String d)
86 public String getDbName()
92 protected EnsemblFeatureType[] getFeaturesToFetch()
94 return FEATURES_TO_FETCH;
98 protected EnsemblSeqType getSourceEnsemblType()
100 return EnsemblSeqType.GENOMIC;
104 protected String getObjectType()
106 return OBJECT_TYPE_GENE;
110 * Returns an alignment containing the gene(s) for the given gene or
111 * transcript identifier, or external identifier (e.g. Uniprot id). If given a
112 * gene name or external identifier, returns any related gene sequences found
113 * for model organisms. If only a single gene is queried for, then its
114 * transcripts are also retrieved and added to the alignment. <br>
117 * <li>resolves a transcript identifier by looking up its parent gene id</li>
118 * <li>resolves an external identifier by looking up xref-ed gene ids</li>
119 * <li>fetches the gene sequence</li>
120 * <li>fetches features on the sequence</li>
121 * <li>identifies "transcript" features whose Parent is the requested
123 * <li>fetches the transcript sequence for each transcript</li>
124 * <li>makes a mapping from the gene to each transcript</li>
125 * <li>copies features from gene to transcript sequences</li>
126 * <li>fetches the protein sequence for each transcript, maps and saves it as
127 * a cross-reference</li>
128 * <li>aligns each transcript against the gene sequence based on the position
133 * a single gene or transcript identifier or gene name
134 * @return an alignment containing a gene, and possibly transcripts, or null
137 public AlignmentI getSequenceRecords(String query) throws Exception
140 * convert to a non-duplicated list of gene identifiers
142 List<String> geneIds = getGeneIds(query);
144 AlignmentI al = null;
145 for (String geneId : geneIds)
148 * fetch the gene sequence(s) with features and xrefs
150 AlignmentI geneAlignment = super.getSequenceRecords(geneId);
151 if (geneAlignment == null)
156 if (geneAlignment.getHeight() == 1)
158 // ensure id has 'correct' case for the Ensembl identifier
159 geneId = geneAlignment.getSequenceAt(0).getName();
161 findGeneLoci(geneAlignment.getSequenceAt(0), geneId);
163 getTranscripts(geneAlignment, geneId);
171 al.append(geneAlignment);
178 * Calls the /lookup/id REST service, parses the response for gene
179 * coordinates, and if successful, adds these to the sequence. If this fails,
180 * fall back on trying to parse the sequence description in case it is in
181 * Ensembl-gene format e.g. chromosome:GRCh38:17:45051610:45109016:1.
186 void findGeneLoci(SequenceI seq, String geneId)
188 GeneLociI geneLoci = new EnsemblLookup(getDomain()).getGeneLoci(geneId);
189 if (geneLoci != null)
191 seq.setGeneLoci(geneLoci.getSpeciesId(), geneLoci.getAssemblyId(),
192 geneLoci.getChromosomeId(), geneLoci.getMap());
196 parseChromosomeLocations(seq);
201 * Parses and saves fields of an Ensembl-style description e.g.
202 * chromosome:GRCh38:17:45051610:45109016:1
206 boolean parseChromosomeLocations(SequenceI seq)
208 String description = seq.getDescription();
209 if (description == null)
213 String[] tokens = description.split(":");
214 if (tokens.length == 6 && tokens[0].startsWith(DBRefEntry.CHROMOSOME))
216 String ref = tokens[1];
217 String chrom = tokens[2];
220 int chStart = Integer.parseInt(tokens[3]);
221 int chEnd = Integer.parseInt(tokens[4]);
222 boolean forwardStrand = "1".equals(tokens[5]);
223 String species = ""; // not known here
224 int[] from = new int[] { seq.getStart(), seq.getEnd() };
225 int[] to = new int[] { forwardStrand ? chStart : chEnd,
226 forwardStrand ? chEnd : chStart };
227 MapList map = new MapList(from, to, 1, 1);
228 seq.setGeneLoci(species, ref, chrom, map);
230 } catch (NumberFormatException e)
232 System.err.println("Bad integers in description " + description);
239 * Converts a query, which may contain one or more gene, transcript, or
240 * external (to Ensembl) identifiers, into a non-redundant list of gene
246 List<String> getGeneIds(String accessions)
248 List<String> geneIds = new ArrayList<>();
250 for (String acc : accessions.split(getAccessionSeparator()))
253 * First try lookup as an Ensembl (gene or transcript) identifier
255 String geneId = new EnsemblLookup(getDomain()).getGeneId(acc);
258 if (!geneIds.contains(geneId))
266 * if given a gene or other external name, lookup and fetch
267 * the corresponding gene for all model organisms
269 List<String> ids = new EnsemblSymbol(getDomain(), getDbSource(),
270 getDbVersion()).getGeneIds(acc);
271 for (String id : ids)
273 if (!geneIds.contains(id))
284 * Constructs all transcripts for the gene, as identified by "transcript"
285 * features whose Parent is the requested gene. The coding transcript
286 * sequences (i.e. with introns omitted) are added to the alignment.
292 protected void getTranscripts(AlignmentI al, String accId)
295 SequenceI gene = al.getSequenceAt(0);
296 List<SequenceFeature> transcriptFeatures = getTranscriptFeatures(accId,
299 for (SequenceFeature transcriptFeature : transcriptFeatures)
301 makeTranscript(transcriptFeature, al, gene);
304 clearGeneFeatures(gene);
308 * Remove unwanted features (transcript, exon, CDS) from the gene sequence
309 * after we have used them to derive transcripts and transfer features
313 protected void clearGeneFeatures(SequenceI gene)
316 * Note we include NMD_transcript_variant here because it behaves like
317 * 'transcript' in Ensembl, although strictly speaking it is not
318 * (it is a sub-type of sequence_variant)
320 String[] soTerms = new String[] {
321 SequenceOntologyI.NMD_TRANSCRIPT_VARIANT,
322 SequenceOntologyI.TRANSCRIPT, SequenceOntologyI.EXON,
323 SequenceOntologyI.CDS };
324 List<SequenceFeature> sfs = gene.getFeatures().getFeaturesByOntology(
326 for (SequenceFeature sf : sfs)
328 gene.deleteFeature(sf);
333 * Constructs a spliced transcript sequence by finding 'exon' features for the
334 * given id (or failing that 'CDS'). Copies features on to the new sequence.
335 * 'Aligns' the new sequence against the gene sequence by padding with gaps,
336 * and adds it to the alignment.
338 * @param transcriptFeature
340 * the alignment to which to add the new sequence
342 * the parent gene sequence, with features
345 SequenceI makeTranscript(SequenceFeature transcriptFeature, AlignmentI al,
348 String accId = getTranscriptId(transcriptFeature);
355 * NB we are mapping from gene sequence (not genome), so do not
356 * need to check for reverse strand (gene and transcript sequences
357 * are in forward sense)
361 * make a gene-length sequence filled with gaps
362 * we will fill in the bases for transcript regions
364 char[] seqChars = new char[gene.getLength()];
365 Arrays.fill(seqChars, al.getGapCharacter());
368 * look for exon features of the transcript, failing that for CDS
369 * (for example ENSG00000124610 has 1 CDS but no exon features)
371 String parentId = "transcript:" + accId;
372 List<SequenceFeature> splices = findFeatures(gene,
373 SequenceOntologyI.EXON, parentId);
374 if (splices.isEmpty())
376 splices = findFeatures(gene, SequenceOntologyI.CDS, parentId);
378 SequenceFeatures.sortFeatures(splices, true);
380 int transcriptLength = 0;
381 final char[] geneChars = gene.getSequence();
382 int offset = gene.getStart(); // to convert to 0-based positions
383 List<int[]> mappedFrom = new ArrayList<>();
385 for (SequenceFeature sf : splices)
387 int start = sf.getBegin() - offset;
388 int end = sf.getEnd() - offset;
389 int spliceLength = end - start + 1;
390 System.arraycopy(geneChars, start, seqChars, start, spliceLength);
391 transcriptLength += spliceLength;
392 mappedFrom.add(new int[] { sf.getBegin(), sf.getEnd() });
395 Sequence transcript = new Sequence(accId, seqChars, 1,
399 * Ensembl has gene name as transcript Name
400 * EnsemblGenomes doesn't, but has a url-encoded description field
402 String description = (String) transcriptFeature.getValue(NAME);
403 if (description == null)
405 description = (String) transcriptFeature.getValue(DESCRIPTION);
407 if (description != null)
411 transcript.setDescription(URLDecoder.decode(description, "UTF-8"));
412 } catch (UnsupportedEncodingException e)
414 e.printStackTrace(); // as if
417 transcript.createDatasetSequence();
419 al.addSequence(transcript);
422 * transfer features to the new sequence; we use EnsemblCdna to do this,
423 * to filter out unwanted features types (see method retainFeature)
425 List<int[]> mapTo = new ArrayList<>();
426 mapTo.add(new int[] { 1, transcriptLength });
427 MapList mapping = new MapList(mappedFrom, mapTo, 1, 1);
428 EnsemblCdna cdna = new EnsemblCdna(getDomain());
429 cdna.transferFeatures(gene.getFeatures().getPositionalFeatures(),
430 transcript.getDatasetSequence(), mapping, parentId);
432 mapTranscriptToChromosome(transcript, gene, mapping);
435 * fetch and save cross-references
437 cdna.getCrossReferences(transcript);
440 * and finally fetch the protein product and save as a cross-reference
442 cdna.addProteinProduct(transcript);
448 * If the gene has a mapping to chromosome coordinates, derive the transcript
449 * chromosome regions and save on the transcript sequence
454 * the mapping from gene to transcript positions
456 protected void mapTranscriptToChromosome(SequenceI transcript,
457 SequenceI gene, MapList mapping)
459 GeneLociI loci = gene.getGeneLoci();
465 MapList geneMapping = loci.getMap();
467 List<int[]> exons = mapping.getFromRanges();
468 List<int[]> transcriptLoci = new ArrayList<>();
470 for (int[] exon : exons)
472 transcriptLoci.add(geneMapping.locateInTo(exon[0], exon[1]));
475 List<int[]> transcriptRange = Arrays.asList(new int[] {
476 transcript.getStart(), transcript.getEnd() });
477 MapList mapList = new MapList(transcriptRange, transcriptLoci, 1, 1);
479 transcript.setGeneLoci(loci.getSpeciesId(), loci.getAssemblyId(),
480 loci.getChromosomeId(), mapList);
484 * Returns the 'transcript_id' property of the sequence feature (or null)
489 protected String getTranscriptId(SequenceFeature feature)
491 return (String) feature.getValue("transcript_id");
495 * Returns a list of the transcript features on the sequence whose Parent is
496 * the gene for the accession id.
498 * Transcript features are those of type "transcript", or any of its sub-types
499 * in the Sequence Ontology e.g. "mRNA", "processed_transcript". We also
500 * include "NMD_transcript_variant", because this type behaves like a
501 * transcript identifier in Ensembl, although strictly speaking it is not in
505 * @param geneSequence
508 protected List<SequenceFeature> getTranscriptFeatures(String accId,
509 SequenceI geneSequence)
511 List<SequenceFeature> transcriptFeatures = new ArrayList<>();
513 String parentIdentifier = GENE_PREFIX + accId;
515 List<SequenceFeature> sfs = geneSequence.getFeatures()
516 .getFeaturesByOntology(SequenceOntologyI.TRANSCRIPT);
517 sfs.addAll(geneSequence.getFeatures().getPositionalFeatures(
518 SequenceOntologyI.NMD_TRANSCRIPT_VARIANT));
520 for (SequenceFeature sf : sfs)
522 String parent = (String) sf.getValue(PARENT);
523 if (parentIdentifier.equalsIgnoreCase(parent))
525 transcriptFeatures.add(sf);
529 return transcriptFeatures;
533 public String getDescription()
535 return "Fetches all transcripts and variant features for a gene or transcript";
539 * Default test query is a gene id (can also enter a transcript id)
542 public String getTestQuery()
544 return "ENSG00000157764"; // BRAF, 5 transcripts, reverse strand
545 // ENSG00000090266 // NDUFB2, 15 transcripts, forward strand
546 // ENSG00000101812 // H2BFM histone, 3 transcripts, forward strand
547 // ENSG00000123569 // H2BFWT histone, 2 transcripts, reverse strand
551 * Answers true for a feature of type 'gene' (or a sub-type of gene in the
552 * Sequence Ontology), whose ID is the accession we are retrieving
555 protected boolean identifiesSequence(SequenceFeature sf, String accId)
557 if (SequenceOntologyFactory.getInstance().isA(sf.getType(),
558 SequenceOntologyI.GENE))
560 // NB features as gff use 'ID'; rest services return as 'id'
561 String id = (String) sf.getValue("ID");
562 if ((GENE_PREFIX + accId).equalsIgnoreCase(id))
571 * Answers true unless feature type is 'gene', or 'transcript' with a parent
572 * which is a different gene. We need the gene features to identify the range,
573 * but it is redundant information on the gene sequence. Checking the parent
574 * allows us to drop transcript features which belong to different
575 * (overlapping) genes.
578 protected boolean retainFeature(SequenceFeature sf, String accessionId)
580 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
581 String type = sf.getType();
582 if (so.isA(type, SequenceOntologyI.GENE))
586 if (isTranscript(type))
588 String parent = (String) sf.getValue(PARENT);
589 if (!(GENE_PREFIX + accessionId).equalsIgnoreCase(parent))
598 * Answers false. This allows an optimisation - a single 'gene' feature is all
599 * that is needed to identify the positions of the gene on the genomic
603 protected boolean isSpliceable()
609 * Override to do nothing as Ensembl doesn't return a protein sequence for a
613 protected void addProteinProduct(SequenceI querySeq)
618 public Regex getAccessionValidator()
620 return ACCESSION_REGEX;
624 * Returns a descriptor for suitable feature display settings with
626 * <li>only exon or sequence_variant features (or their subtypes in the
627 * Sequence Ontology) visible</li>
628 * <li>variant features coloured red</li>
629 * <li>exon features coloured by label (exon name)</li>
630 * <li>variants displayed above (on top of) exons</li>
634 public FeatureSettingsModelI getFeatureColourScheme()
636 return new FeatureSettingsAdapter()
638 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
641 public boolean isFeatureDisplayed(String type)
643 return (so.isA(type, SequenceOntologyI.EXON)
644 || so.isA(type, SequenceOntologyI.SEQUENCE_VARIANT));
648 public FeatureColourI getFeatureColour(String type)
650 if (so.isA(type, SequenceOntologyI.EXON))
652 return new FeatureColour()
655 public boolean isColourByLabel()
661 if (so.isA(type, SequenceOntologyI.SEQUENCE_VARIANT))
663 return new FeatureColour()
667 public Color getColour()
677 * order to render sequence_variant after exon after the rest
680 public int compare(String feature1, String feature2)
682 if (so.isA(feature1, SequenceOntologyI.SEQUENCE_VARIANT))
686 if (so.isA(feature2, SequenceOntologyI.SEQUENCE_VARIANT))
690 if (so.isA(feature1, SequenceOntologyI.EXON))
694 if (so.isA(feature2, SequenceOntologyI.EXON))