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 * Returns an alignment containing the gene(s) for the given gene or
105 * transcript identifier, or external identifier (e.g. Uniprot id). If given a
106 * gene name or external identifier, returns any related gene sequences found
107 * for model organisms. If only a single gene is queried for, then its
108 * transcripts are also retrieved and added to the alignment. <br>
111 * <li>resolves a transcript identifier by looking up its parent gene id</li>
112 * <li>resolves an external identifier by looking up xref-ed gene ids</li>
113 * <li>fetches the gene sequence</li>
114 * <li>fetches features on the sequence</li>
115 * <li>identifies "transcript" features whose Parent is the requested
117 * <li>fetches the transcript sequence for each transcript</li>
118 * <li>makes a mapping from the gene to each transcript</li>
119 * <li>copies features from gene to transcript sequences</li>
120 * <li>fetches the protein sequence for each transcript, maps and saves it as
121 * a cross-reference</li>
122 * <li>aligns each transcript against the gene sequence based on the position
127 * a single gene or transcript identifier or gene name
128 * @return an alignment containing a gene, and possibly transcripts, or null
131 public AlignmentI getSequenceRecords(String query) throws Exception
134 * convert to a non-duplicated list of gene identifiers
136 List<String> geneIds = getGeneIds(query);
138 AlignmentI al = null;
139 for (String geneId : geneIds)
142 * fetch the gene sequence(s) with features and xrefs
144 AlignmentI geneAlignment = super.getSequenceRecords(geneId);
145 if (geneAlignment == null)
150 if (geneAlignment.getHeight() == 1)
152 findGeneLoci(geneAlignment.getSequenceAt(0), geneId);
153 getTranscripts(geneAlignment, geneId);
161 al.append(geneAlignment);
168 * Calls the /lookup/id REST service, parses the response for gene
169 * coordinates, and if successful, adds these to the sequence. If this fails,
170 * fall back on trying to parse the sequence description in case it is in
171 * Ensembl-gene format e.g. chromosome:GRCh38:17:45051610:45109016:1.
176 void findGeneLoci(SequenceI seq, String geneId)
178 GeneLociI geneLoci = new EnsemblLookup(getDomain()).getGeneLoci(geneId);
179 if (geneLoci != null)
181 seq.setGeneLoci(geneLoci.getSpeciesId(), geneLoci.getAssemblyId(),
182 geneLoci.getChromosomeId(), geneLoci.getMap());
186 parseChromosomeLocations(seq);
191 * Parses and saves fields of an Ensembl-style description e.g.
192 * chromosome:GRCh38:17:45051610:45109016:1
196 boolean parseChromosomeLocations(SequenceI seq)
198 String description = seq.getDescription();
199 if (description == null)
203 String[] tokens = description.split(":");
204 if (tokens.length == 6 && tokens[0].startsWith(DBRefEntry.CHROMOSOME))
206 String ref = tokens[1];
207 String chrom = tokens[2];
210 int chStart = Integer.parseInt(tokens[3]);
211 int chEnd = Integer.parseInt(tokens[4]);
212 boolean forwardStrand = "1".equals(tokens[5]);
213 String species = ""; // not known here
214 int[] from = new int[] { seq.getStart(), seq.getEnd() };
215 int[] to = new int[] { forwardStrand ? chStart : chEnd,
216 forwardStrand ? chEnd : chStart };
217 MapList map = new MapList(from, to, 1, 1);
218 seq.setGeneLoci(species, ref, chrom, map);
220 } catch (NumberFormatException e)
222 System.err.println("Bad integers in description " + description);
229 * Converts a query, which may contain one or more gene, transcript, or
230 * external (to Ensembl) identifiers, into a non-redundant list of gene
236 List<String> getGeneIds(String accessions)
238 List<String> geneIds = new ArrayList<String>();
240 for (String acc : accessions.split(getAccessionSeparator()))
243 * First try lookup as an Ensembl (gene or transcript) identifier
245 String geneId = new EnsemblLookup(getDomain()).getGeneId(acc);
248 if (!geneIds.contains(geneId))
256 * if given a gene or other external name, lookup and fetch
257 * the corresponding gene for all model organisms
259 List<String> ids = new EnsemblSymbol(getDomain(), getDbSource(),
260 getDbVersion()).getGeneIds(acc);
261 for (String id : ids)
263 if (!geneIds.contains(id))
274 * Constructs all transcripts for the gene, as identified by "transcript"
275 * features whose Parent is the requested gene. The coding transcript
276 * sequences (i.e. with introns omitted) are added to the alignment.
282 protected void getTranscripts(AlignmentI al, String accId)
285 SequenceI gene = al.getSequenceAt(0);
286 List<SequenceFeature> transcriptFeatures = getTranscriptFeatures(accId,
289 for (SequenceFeature transcriptFeature : transcriptFeatures)
291 makeTranscript(transcriptFeature, al, gene);
294 clearGeneFeatures(gene);
298 * Remove unwanted features (transcript, exon, CDS) from the gene sequence
299 * after we have used them to derive transcripts and transfer features
303 protected void clearGeneFeatures(SequenceI gene)
306 * Note we include NMD_transcript_variant here because it behaves like
307 * 'transcript' in Ensembl, although strictly speaking it is not
308 * (it is a sub-type of sequence_variant)
310 String[] soTerms = new String[] {
311 SequenceOntologyI.NMD_TRANSCRIPT_VARIANT,
312 SequenceOntologyI.TRANSCRIPT, SequenceOntologyI.EXON,
313 SequenceOntologyI.CDS };
314 List<SequenceFeature> sfs = gene.getFeatures().getFeaturesByOntology(
316 for (SequenceFeature sf : sfs)
318 gene.deleteFeature(sf);
323 * Constructs a spliced transcript sequence by finding 'exon' features for the
324 * given id (or failing that 'CDS'). Copies features on to the new sequence.
325 * 'Aligns' the new sequence against the gene sequence by padding with gaps,
326 * and adds it to the alignment.
328 * @param transcriptFeature
330 * the alignment to which to add the new sequence
332 * the parent gene sequence, with features
335 SequenceI makeTranscript(SequenceFeature transcriptFeature, AlignmentI al,
338 String accId = getTranscriptId(transcriptFeature);
345 * NB we are mapping from gene sequence (not genome), so do not
346 * need to check for reverse strand (gene and transcript sequences
347 * are in forward sense)
351 * make a gene-length sequence filled with gaps
352 * we will fill in the bases for transcript regions
354 char[] seqChars = new char[gene.getLength()];
355 Arrays.fill(seqChars, al.getGapCharacter());
358 * look for exon features of the transcript, failing that for CDS
359 * (for example ENSG00000124610 has 1 CDS but no exon features)
361 String parentId = "transcript:" + accId;
362 List<SequenceFeature> splices = findFeatures(gene,
363 SequenceOntologyI.EXON, parentId);
364 if (splices.isEmpty())
366 splices = findFeatures(gene, SequenceOntologyI.CDS, parentId);
368 SequenceFeatures.sortFeatures(splices, true);
370 int transcriptLength = 0;
371 final char[] geneChars = gene.getSequence();
372 int offset = gene.getStart(); // to convert to 0-based positions
373 List<int[]> mappedFrom = new ArrayList<int[]>();
375 for (SequenceFeature sf : splices)
377 int start = sf.getBegin() - offset;
378 int end = sf.getEnd() - offset;
379 int spliceLength = end - start + 1;
380 System.arraycopy(geneChars, start, seqChars, start, spliceLength);
381 transcriptLength += spliceLength;
382 mappedFrom.add(new int[] { sf.getBegin(), sf.getEnd() });
385 Sequence transcript = new Sequence(accId, seqChars, 1,
389 * Ensembl has gene name as transcript Name
390 * EnsemblGenomes doesn't, but has a url-encoded description field
392 String description = (String) transcriptFeature.getValue(NAME);
393 if (description == null)
395 description = (String) transcriptFeature.getValue(DESCRIPTION);
397 if (description != null)
401 transcript.setDescription(URLDecoder.decode(description, "UTF-8"));
402 } catch (UnsupportedEncodingException e)
404 e.printStackTrace(); // as if
407 transcript.createDatasetSequence();
409 al.addSequence(transcript);
412 * transfer features to the new sequence; we use EnsemblCdna to do this,
413 * to filter out unwanted features types (see method retainFeature)
415 List<int[]> mapTo = new ArrayList<int[]>();
416 mapTo.add(new int[] { 1, transcriptLength });
417 MapList mapping = new MapList(mappedFrom, mapTo, 1, 1);
418 EnsemblCdna cdna = new EnsemblCdna(getDomain());
419 cdna.transferFeatures(gene.getFeatures().getPositionalFeatures(),
420 transcript.getDatasetSequence(), mapping, parentId);
422 mapTranscriptToChromosome(transcript, gene, mapping);
425 * fetch and save cross-references
427 cdna.getCrossReferences(transcript);
430 * and finally fetch the protein product and save as a cross-reference
432 cdna.addProteinProduct(transcript);
438 * If the gene has a mapping to chromosome coordinates, derive the transcript
439 * chromosome regions and save on the transcript sequence
444 * the mapping from gene to transcript positions
446 protected void mapTranscriptToChromosome(SequenceI transcript,
447 SequenceI gene, MapList mapping)
449 GeneLociI loci = gene.getGeneLoci();
455 MapList geneMapping = loci.getMap();
457 List<int[]> exons = mapping.getFromRanges();
458 List<int[]> transcriptLoci = new ArrayList<>();
460 for (int[] exon : exons)
462 transcriptLoci.add(geneMapping.locateInTo(exon[0], exon[1]));
465 List<int[]> transcriptRange = Arrays.asList(new int[] {
466 transcript.getStart(), transcript.getEnd() });
467 MapList mapList = new MapList(transcriptRange, transcriptLoci, 1, 1);
469 transcript.setGeneLoci(loci.getSpeciesId(), loci.getAssemblyId(),
470 loci.getChromosomeId(), mapList);
474 * Returns the 'transcript_id' property of the sequence feature (or null)
479 protected String getTranscriptId(SequenceFeature feature)
481 return (String) feature.getValue("transcript_id");
485 * Returns a list of the transcript features on the sequence whose Parent is
486 * the gene for the accession id.
488 * Transcript features are those of type "transcript", or any of its sub-types
489 * in the Sequence Ontology e.g. "mRNA", "processed_transcript". We also
490 * include "NMD_transcript_variant", because this type behaves like a
491 * transcript identifier in Ensembl, although strictly speaking it is not in
495 * @param geneSequence
498 protected List<SequenceFeature> getTranscriptFeatures(String accId,
499 SequenceI geneSequence)
501 List<SequenceFeature> transcriptFeatures = new ArrayList<SequenceFeature>();
503 String parentIdentifier = GENE_PREFIX + accId;
505 List<SequenceFeature> sfs = geneSequence.getFeatures()
506 .getFeaturesByOntology(SequenceOntologyI.TRANSCRIPT);
507 sfs.addAll(geneSequence.getFeatures().getPositionalFeatures(
508 SequenceOntologyI.NMD_TRANSCRIPT_VARIANT));
510 for (SequenceFeature sf : sfs)
512 String parent = (String) sf.getValue(PARENT);
513 if (parentIdentifier.equals(parent))
515 transcriptFeatures.add(sf);
519 return transcriptFeatures;
523 public String getDescription()
525 return "Fetches all transcripts and variant features for a gene or transcript";
529 * Default test query is a gene id (can also enter a transcript id)
532 public String getTestQuery()
534 return "ENSG00000157764"; // BRAF, 5 transcripts, reverse strand
535 // ENSG00000090266 // NDUFB2, 15 transcripts, forward strand
536 // ENSG00000101812 // H2BFM histone, 3 transcripts, forward strand
537 // ENSG00000123569 // H2BFWT histone, 2 transcripts, reverse strand
541 * Answers true for a feature of type 'gene' (or a sub-type of gene in the
542 * Sequence Ontology), whose ID is the accession we are retrieving
545 protected boolean identifiesSequence(SequenceFeature sf, String accId)
547 if (SequenceOntologyFactory.getInstance().isA(sf.getType(),
548 SequenceOntologyI.GENE))
550 String id = (String) sf.getValue(ID);
551 if ((GENE_PREFIX + accId).equals(id))
560 * Answers true unless feature type is 'gene', or 'transcript' with a parent
561 * which is a different gene. We need the gene features to identify the range,
562 * but it is redundant information on the gene sequence. Checking the parent
563 * allows us to drop transcript features which belong to different
564 * (overlapping) genes.
567 protected boolean retainFeature(SequenceFeature sf, String accessionId)
569 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
570 String type = sf.getType();
571 if (so.isA(type, SequenceOntologyI.GENE))
575 if (isTranscript(type))
577 String parent = (String) sf.getValue(PARENT);
578 if (!(GENE_PREFIX + accessionId).equals(parent))
587 * Answers false. This allows an optimisation - a single 'gene' feature is all
588 * that is needed to identify the positions of the gene on the genomic
592 protected boolean isSpliceable()
598 * Override to do nothing as Ensembl doesn't return a protein sequence for a
602 protected void addProteinProduct(SequenceI querySeq)
607 public Regex getAccessionValidator()
609 return ACCESSION_REGEX;
613 * Returns a descriptor for suitable feature display settings with
615 * <li>only exon or sequence_variant features (or their subtypes in the
616 * Sequence Ontology) visible</li>
617 * <li>variant features coloured red</li>
618 * <li>exon features coloured by label (exon name)</li>
619 * <li>variants displayed above (on top of) exons</li>
623 public FeatureSettingsModelI getFeatureColourScheme()
625 return new FeatureSettingsAdapter()
627 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
630 public boolean isFeatureDisplayed(String type)
632 return (so.isA(type, SequenceOntologyI.EXON)
633 || so.isA(type, SequenceOntologyI.SEQUENCE_VARIANT));
637 public FeatureColourI getFeatureColour(String type)
639 if (so.isA(type, SequenceOntologyI.EXON))
641 return new FeatureColour()
644 public boolean isColourByLabel()
650 if (so.isA(type, SequenceOntologyI.SEQUENCE_VARIANT))
652 return new FeatureColour()
656 public Color getColour()
666 * order to render sequence_variant after exon after the rest
669 public int compare(String feature1, String feature2)
671 if (so.isA(feature1, SequenceOntologyI.SEQUENCE_VARIANT))
675 if (so.isA(feature2, SequenceOntologyI.SEQUENCE_VARIANT))
679 if (so.isA(feature1, SequenceOntologyI.EXON))
683 if (so.isA(feature2, SequenceOntologyI.EXON))