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
55 * accepts anything as we will attempt lookup of gene or
56 * transcript id or gene name
58 private static final Regex ACCESSION_REGEX = new Regex(".*");
60 private static final EnsemblFeatureType[] FEATURES_TO_FETCH = {
61 EnsemblFeatureType.gene, EnsemblFeatureType.transcript,
62 EnsemblFeatureType.exon, EnsemblFeatureType.cds,
63 EnsemblFeatureType.variation };
66 * Default constructor (to use rest.ensembl.org)
74 public String getDbName()
80 protected EnsemblFeatureType[] getFeaturesToFetch()
82 return FEATURES_TO_FETCH;
86 protected EnsemblSeqType getSourceEnsemblType()
88 return EnsemblSeqType.GENOMIC;
92 protected String getObjectType()
94 return OBJECT_TYPE_GENE;
98 * Returns an alignment containing the gene(s) for the given gene or
99 * transcript identifier, or external identifier (e.g. Uniprot id). If given a
100 * gene name or external identifier, returns any related gene sequences found
101 * for model organisms. If only a single gene is queried for, then its
102 * transcripts are also retrieved and added to the alignment. <br>
105 * <li>resolves a transcript identifier by looking up its parent gene id</li>
106 * <li>resolves an external identifier by looking up xref-ed gene ids</li>
107 * <li>fetches the gene sequence</li>
108 * <li>fetches features on the sequence</li>
109 * <li>identifies "transcript" features whose Parent is the requested
111 * <li>fetches the transcript sequence for each transcript</li>
112 * <li>makes a mapping from the gene to each transcript</li>
113 * <li>copies features from gene to transcript sequences</li>
114 * <li>fetches the protein sequence for each transcript, maps and saves it as
115 * a cross-reference</li>
116 * <li>aligns each transcript against the gene sequence based on the position
121 * a single gene or transcript identifier or gene name
122 * @return an alignment containing a gene, and possibly transcripts, or null
125 public AlignmentI getSequenceRecords(String query) throws Exception
128 * convert to a non-duplicated list of gene identifiers
130 List<String> geneIds = getGeneIds(query);
132 AlignmentI al = null;
133 for (String geneId : geneIds)
136 * fetch the gene sequence(s) with features and xrefs
138 AlignmentI geneAlignment = super.getSequenceRecords(geneId);
139 if (geneAlignment == null)
144 if (geneAlignment.getHeight() == 1)
146 // ensure id has 'correct' case for the Ensembl identifier
147 geneId = geneAlignment.getSequenceAt(0).getName();
149 findGeneLoci(geneAlignment.getSequenceAt(0), geneId);
151 getTranscripts(geneAlignment, geneId);
159 al.append(geneAlignment);
166 * Calls the /lookup/id REST service, parses the response for gene
167 * coordinates, and if successful, adds these to the sequence. If this fails,
168 * fall back on trying to parse the sequence description in case it is in
169 * Ensembl-gene format e.g. chromosome:GRCh38:17:45051610:45109016:1.
174 void findGeneLoci(SequenceI seq, String geneId)
176 GeneLociI geneLoci = new EnsemblLookup().getGeneLoci(geneId);
177 if (geneLoci != null)
179 seq.setGeneLoci(geneLoci.getSpeciesId(), geneLoci.getAssemblyId(),
180 geneLoci.getChromosomeId(), geneLoci.getMap());
184 parseChromosomeLocations(seq);
189 * Parses and saves fields of an Ensembl-style description e.g.
190 * chromosome:GRCh38:17:45051610:45109016:1
194 boolean parseChromosomeLocations(SequenceI seq)
196 String description = seq.getDescription();
197 if (description == null)
201 String[] tokens = description.split(":");
202 if (tokens.length == 6 && tokens[0].startsWith(DBRefEntry.CHROMOSOME))
204 String ref = tokens[1];
205 String chrom = tokens[2];
208 int chStart = Integer.parseInt(tokens[3]);
209 int chEnd = Integer.parseInt(tokens[4]);
210 boolean forwardStrand = "1".equals(tokens[5]);
211 String species = ""; // not known here
212 int[] from = new int[] { seq.getStart(), seq.getEnd() };
213 int[] to = new int[] { forwardStrand ? chStart : chEnd,
214 forwardStrand ? chEnd : chStart };
215 MapList map = new MapList(from, to, 1, 1);
216 seq.setGeneLoci(species, ref, chrom, map);
218 } catch (NumberFormatException e)
220 System.err.println("Bad integers in description " + description);
227 * Converts a query, which may contain one or more gene, transcript, or
228 * external (to Ensembl) identifiers, into a non-redundant list of gene
234 List<String> getGeneIds(String accessions)
236 List<String> geneIds = new ArrayList<>();
238 for (String acc : accessions.split(getAccessionSeparator()))
241 * First try lookup as an Ensembl (gene or transcript) identifier
243 String geneId = new EnsemblLookup().getGeneId(acc);
246 if (!geneIds.contains(geneId))
254 * if given a gene or other external name, lookup and fetch
255 * the corresponding gene for all model organisms
257 List<String> ids = new EnsemblSymbol(getDbSource(), getDbVersion())
259 for (String id : ids)
261 if (!geneIds.contains(id))
272 * Constructs all transcripts for the gene, as identified by "transcript"
273 * features whose Parent is the requested gene. The coding transcript
274 * sequences (i.e. with introns omitted) are added to the alignment.
280 protected void getTranscripts(AlignmentI al, String accId)
283 SequenceI gene = al.getSequenceAt(0);
284 List<SequenceFeature> transcriptFeatures = getTranscriptFeatures(accId,
287 for (SequenceFeature transcriptFeature : transcriptFeatures)
289 makeTranscript(transcriptFeature, al, gene);
292 clearGeneFeatures(gene);
296 * Remove unwanted features (transcript, exon, CDS) from the gene sequence
297 * after we have used them to derive transcripts and transfer features
301 protected void clearGeneFeatures(SequenceI gene)
304 * Note we include NMD_transcript_variant here because it behaves like
305 * 'transcript' in Ensembl, although strictly speaking it is not
306 * (it is a sub-type of sequence_variant)
308 String[] soTerms = new String[] {
309 SequenceOntologyI.NMD_TRANSCRIPT_VARIANT,
310 SequenceOntologyI.TRANSCRIPT, SequenceOntologyI.EXON,
311 SequenceOntologyI.CDS };
312 List<SequenceFeature> sfs = gene.getFeatures().getFeaturesByOntology(
314 for (SequenceFeature sf : sfs)
316 gene.deleteFeature(sf);
321 * Constructs a spliced transcript sequence by finding 'exon' features for the
322 * given id (or failing that 'CDS'). Copies features on to the new sequence.
323 * 'Aligns' the new sequence against the gene sequence by padding with gaps,
324 * and adds it to the alignment.
326 * @param transcriptFeature
328 * the alignment to which to add the new sequence
330 * the parent gene sequence, with features
333 SequenceI makeTranscript(SequenceFeature transcriptFeature, AlignmentI al,
336 String accId = getTranscriptId(transcriptFeature);
343 * NB we are mapping from gene sequence (not genome), so do not
344 * need to check for reverse strand (gene and transcript sequences
345 * are in forward sense)
349 * make a gene-length sequence filled with gaps
350 * we will fill in the bases for transcript regions
352 char[] seqChars = new char[gene.getLength()];
353 Arrays.fill(seqChars, al.getGapCharacter());
356 * look for exon features of the transcript, failing that for CDS
357 * (for example ENSG00000124610 has 1 CDS but no exon features)
359 String parentId = accId;
360 List<SequenceFeature> splices = findFeatures(gene,
361 SequenceOntologyI.EXON, parentId);
362 if (splices.isEmpty())
364 splices = findFeatures(gene, SequenceOntologyI.CDS, parentId);
366 SequenceFeatures.sortFeatures(splices, true);
368 int transcriptLength = 0;
369 final char[] geneChars = gene.getSequence();
370 int offset = gene.getStart(); // to convert to 0-based positions
371 List<int[]> mappedFrom = new ArrayList<>();
373 for (SequenceFeature sf : splices)
375 int start = sf.getBegin() - offset;
376 int end = sf.getEnd() - offset;
377 int spliceLength = end - start + 1;
378 System.arraycopy(geneChars, start, seqChars, start, spliceLength);
379 transcriptLength += spliceLength;
380 mappedFrom.add(new int[] { sf.getBegin(), sf.getEnd() });
383 Sequence transcript = new Sequence(accId, seqChars, 1,
387 * Ensembl has gene name as transcript Name
388 * EnsemblGenomes doesn't, but has a url-encoded description field
390 String description = transcriptFeature.getDescription();
391 if (description == null)
393 description = (String) transcriptFeature.getValue(DESCRIPTION);
395 if (description != null)
399 transcript.setDescription(URLDecoder.decode(description, "UTF-8"));
400 } catch (UnsupportedEncodingException e)
402 e.printStackTrace(); // as if
405 transcript.createDatasetSequence();
407 al.addSequence(transcript);
410 * transfer features to the new sequence; we use EnsemblCdna to do this,
411 * to filter out unwanted features types (see method retainFeature)
413 List<int[]> mapTo = new ArrayList<>();
414 mapTo.add(new int[] { 1, transcriptLength });
415 MapList mapping = new MapList(mappedFrom, mapTo, 1, 1);
416 EnsemblCdna cdna = new EnsemblCdna();
417 cdna.transferFeatures(gene.getFeatures().getPositionalFeatures(),
418 transcript.getDatasetSequence(), mapping, parentId);
420 mapTranscriptToChromosome(transcript, gene, mapping);
423 * fetch and save cross-references
425 cdna.getCrossReferences(transcript);
428 * and finally fetch the protein product and save as a cross-reference
430 cdna.addProteinProduct(transcript);
436 * If the gene has a mapping to chromosome coordinates, derive the transcript
437 * chromosome regions and save on the transcript sequence
442 * the mapping from gene to transcript positions
444 protected void mapTranscriptToChromosome(SequenceI transcript,
445 SequenceI gene, MapList mapping)
447 GeneLociI loci = gene.getGeneLoci();
453 MapList geneMapping = loci.getMap();
455 List<int[]> exons = mapping.getFromRanges();
456 List<int[]> transcriptLoci = new ArrayList<>();
458 for (int[] exon : exons)
460 transcriptLoci.add(geneMapping.locateInTo(exon[0], exon[1]));
463 List<int[]> transcriptRange = Arrays.asList(new int[] {
464 transcript.getStart(), transcript.getEnd() });
465 MapList mapList = new MapList(transcriptRange, transcriptLoci, 1, 1);
467 transcript.setGeneLoci(loci.getSpeciesId(), loci.getAssemblyId(),
468 loci.getChromosomeId(), mapList);
472 * Returns the 'transcript_id' property of the sequence feature (or null)
477 protected String getTranscriptId(SequenceFeature feature)
479 return (String) feature.getValue(JSON_ID);
483 * Returns a list of the transcript features on the sequence whose Parent is
484 * the gene for the accession id.
486 * Transcript features are those of type "transcript", or any of its sub-types
487 * in the Sequence Ontology e.g. "mRNA", "processed_transcript". We also
488 * include "NMD_transcript_variant", because this type behaves like a
489 * transcript identifier in Ensembl, although strictly speaking it is not in
493 * @param geneSequence
496 protected List<SequenceFeature> getTranscriptFeatures(String accId,
497 SequenceI geneSequence)
499 List<SequenceFeature> transcriptFeatures = new ArrayList<>();
501 String parentIdentifier = accId;
503 List<SequenceFeature> sfs = geneSequence.getFeatures()
504 .getFeaturesByOntology(SequenceOntologyI.TRANSCRIPT);
505 sfs.addAll(geneSequence.getFeatures().getPositionalFeatures(
506 SequenceOntologyI.NMD_TRANSCRIPT_VARIANT));
508 for (SequenceFeature sf : sfs)
510 String parent = (String) sf.getValue(PARENT);
511 if (parentIdentifier.equalsIgnoreCase(parent))
513 transcriptFeatures.add(sf);
517 return transcriptFeatures;
521 public String getDescription()
523 return "Fetches all transcripts and variant features for a gene or transcript";
527 * Default test query is a gene id (can also enter a transcript id)
530 public String getTestQuery()
532 return "ENSG00000157764"; // BRAF, 5 transcripts, reverse strand
533 // ENSG00000090266 // NDUFB2, 15 transcripts, forward strand
534 // ENSG00000101812 // H2BFM histone, 3 transcripts, forward strand
535 // ENSG00000123569 // H2BFWT histone, 2 transcripts, reverse strand
539 * Answers a list of sequence features (if any) whose type is 'gene' (or a
540 * subtype of gene in the Sequence Ontology), and whose ID is the accession we
544 protected List<SequenceFeature> getIdentifyingFeatures(SequenceI seq,
547 List<SequenceFeature> result = new ArrayList<>();
548 List<SequenceFeature> sfs = seq.getFeatures()
549 .getFeaturesByOntology(SequenceOntologyI.GENE);
550 for (SequenceFeature sf : sfs)
552 String id = (String) sf.getValue(JSON_ID);
553 if (accId.equalsIgnoreCase(id))
562 * Answers true unless feature type is 'gene', or 'transcript' with a parent
563 * which is a different gene. We need the gene features to identify the range,
564 * but it is redundant information on the gene sequence. Checking the parent
565 * allows us to drop transcript features which belong to different
566 * (overlapping) genes.
569 protected boolean retainFeature(SequenceFeature sf, String accessionId)
571 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
572 String type = sf.getType();
573 if (so.isA(type, SequenceOntologyI.GENE))
577 if (isTranscript(type))
579 String parent = (String) sf.getValue(PARENT);
580 if (!accessionId.equalsIgnoreCase(parent))
589 * Override to do nothing as Ensembl doesn't return a protein sequence for a
593 protected void addProteinProduct(SequenceI querySeq)
598 public Regex getAccessionValidator()
600 return ACCESSION_REGEX;
604 * Returns a descriptor for suitable feature display settings with
606 * <li>only exon or sequence_variant features (or their subtypes in the
607 * Sequence Ontology) visible</li>
608 * <li>variant features coloured red</li>
609 * <li>exon features coloured by label (exon name)</li>
610 * <li>variants displayed above (on top of) exons</li>
614 public FeatureSettingsModelI getFeatureColourScheme()
616 return new FeatureSettingsAdapter()
618 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
621 public boolean isFeatureDisplayed(String type)
623 return (so.isA(type, SequenceOntologyI.EXON)
624 || so.isA(type, SequenceOntologyI.SEQUENCE_VARIANT));
628 public FeatureColourI getFeatureColour(String type)
630 if (so.isA(type, SequenceOntologyI.EXON))
632 return new FeatureColour()
635 public boolean isColourByLabel()
641 if (so.isA(type, SequenceOntologyI.SEQUENCE_VARIANT))
643 return new FeatureColour()
647 public Color getColour()
657 * order to render sequence_variant after exon after the rest
660 public int compare(String feature1, String feature2)
662 if (so.isA(feature1, SequenceOntologyI.SEQUENCE_VARIANT))
666 if (so.isA(feature2, SequenceOntologyI.SEQUENCE_VARIANT))
670 if (so.isA(feature1, SequenceOntologyI.EXON))
674 if (so.isA(feature2, SequenceOntologyI.EXON))