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;
37 import jalview.util.Platform;
39 import java.awt.Color;
40 import java.io.UnsupportedEncodingException;
41 import java.net.URLDecoder;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.List;
46 import com.stevesoft.pat.Regex;
49 * A class that fetches genomic sequence and all transcripts for an Ensembl gene
53 public class EnsemblGene extends EnsemblSeqProxy
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 protected String getObjectType()
105 return OBJECT_TYPE_GENE;
109 * Returns an alignment containing the gene(s) for the given gene or
110 * transcript identifier, or external identifier (e.g. Uniprot id). If given a
111 * gene name or external identifier, returns any related gene sequences found
112 * for model organisms. If only a single gene is queried for, then its
113 * transcripts are also retrieved and added to the alignment. <br>
116 * <li>resolves a transcript identifier by looking up its parent gene id</li>
117 * <li>resolves an external identifier by looking up xref-ed gene ids</li>
118 * <li>fetches the gene sequence</li>
119 * <li>fetches features on the sequence</li>
120 * <li>identifies "transcript" features whose Parent is the requested
122 * <li>fetches the transcript sequence for each transcript</li>
123 * <li>makes a mapping from the gene to each transcript</li>
124 * <li>copies features from gene to transcript sequences</li>
125 * <li>fetches the protein sequence for each transcript, maps and saves it as
126 * a cross-reference</li>
127 * <li>aligns each transcript against the gene sequence based on the position
132 * a single gene or transcript identifier or gene name
133 * @return an alignment containing a gene, and possibly transcripts, or null
136 public AlignmentI getSequenceRecords(String query) throws Exception
139 * convert to a non-duplicated list of gene identifiers
141 List<String> geneIds = getGeneIds(query);
142 AlignmentI al = null;
143 for (String geneId : geneIds)
146 * fetch the gene sequence(s) with features and xrefs
148 AlignmentI geneAlignment = super.getSequenceRecords(geneId);
149 if (geneAlignment == null)
154 if (geneAlignment.getHeight() == 1)
156 // ensure id has 'correct' case for the Ensembl identifier
157 geneId = geneAlignment.getSequenceAt(0).getName();
158 findGeneLoci(geneAlignment.getSequenceAt(0), geneId);
159 getTranscripts(geneAlignment, geneId);
167 al.append(geneAlignment);
174 * Calls the /lookup/id REST service, parses the response for gene
175 * coordinates, and if successful, adds these to the sequence. If this fails,
176 * fall back on trying to parse the sequence description in case it is in
177 * Ensembl-gene format e.g. chromosome:GRCh38:17:45051610:45109016:1.
182 void findGeneLoci(SequenceI seq, String geneId)
184 GeneLociI geneLoci = new EnsemblLookup(getDomain()).getGeneLoci(geneId);
185 if (geneLoci != null)
187 seq.setGeneLoci(geneLoci.getSpeciesId(), geneLoci.getAssemblyId(),
188 geneLoci.getChromosomeId(), geneLoci.getMap());
192 parseChromosomeLocations(seq);
197 * Parses and saves fields of an Ensembl-style description e.g.
198 * chromosome:GRCh38:17:45051610:45109016:1
202 boolean parseChromosomeLocations(SequenceI seq)
204 String description = seq.getDescription();
205 if (description == null)
209 String[] tokens = description.split(":");
210 if (tokens.length == 6 && tokens[0].startsWith(DBRefEntry.CHROMOSOME))
212 String ref = tokens[1];
213 String chrom = tokens[2];
216 int chStart = Integer.parseInt(tokens[3]);
217 int chEnd = Integer.parseInt(tokens[4]);
218 boolean forwardStrand = "1".equals(tokens[5]);
219 String species = ""; // not known here
220 int[] from = new int[] { seq.getStart(), seq.getEnd() };
221 int[] to = new int[] { forwardStrand ? chStart : chEnd,
222 forwardStrand ? chEnd : chStart };
223 MapList map = new MapList(from, to, 1, 1);
224 seq.setGeneLoci(species, ref, chrom, map);
226 } catch (NumberFormatException e)
228 System.err.println("Bad integers in description " + description);
235 * Converts a query, which may contain one or more gene, transcript, or
236 * external (to Ensembl) identifiers, into a non-redundant list of gene
242 List<String> getGeneIds(String accessions)
244 List<String> geneIds = new ArrayList<>();
246 for (String acc : accessions.split(getAccessionSeparator()))
249 * First try lookup as an Ensembl (gene or transcript) identifier
251 String geneId = new EnsemblLookup(getDomain()).getGeneId(acc);
254 if (!geneIds.contains(geneId))
262 * if given a gene or other external name, lookup and fetch
263 * the corresponding gene for all model organisms
265 List<String> ids = new EnsemblSymbol(getDomain(), getDbSource(),
266 getDbVersion()).getGeneIds(acc);
267 for (String id : ids)
269 if (!geneIds.contains(id))
280 * Constructs all transcripts for the gene, as identified by "transcript"
281 * features whose Parent is the requested gene. The coding transcript
282 * sequences (i.e. with introns omitted) are added to the alignment.
288 protected void getTranscripts(AlignmentI al, String accId)
291 SequenceI gene = al.getSequenceAt(0);
292 List<SequenceFeature> transcriptFeatures = getTranscriptFeatures(accId,
295 for (SequenceFeature transcriptFeature : transcriptFeatures)
297 makeTranscript(transcriptFeature, al, gene);
300 clearGeneFeatures(gene);
304 * Remove unwanted features (transcript, exon, CDS) from the gene sequence
305 * after we have used them to derive transcripts and transfer features
309 protected void clearGeneFeatures(SequenceI gene)
312 * Note we include NMD_transcript_variant here because it behaves like
313 * 'transcript' in Ensembl, although strictly speaking it is not
314 * (it is a sub-type of sequence_variant)
316 String[] soTerms = new String[] {
317 SequenceOntologyI.NMD_TRANSCRIPT_VARIANT,
318 SequenceOntologyI.TRANSCRIPT, SequenceOntologyI.EXON,
319 SequenceOntologyI.CDS };
320 List<SequenceFeature> sfs = gene.getFeatures().getFeaturesByOntology(
322 for (SequenceFeature sf : sfs)
324 gene.deleteFeature(sf);
329 * Constructs a spliced transcript sequence by finding 'exon' features for the
330 * given id (or failing that 'CDS'). Copies features on to the new sequence.
331 * 'Aligns' the new sequence against the gene sequence by padding with gaps,
332 * and adds it to the alignment.
334 * @param transcriptFeature
336 * the alignment to which to add the new sequence
338 * the parent gene sequence, with features
341 SequenceI makeTranscript(SequenceFeature transcriptFeature, AlignmentI al,
344 String accId = getTranscriptId(transcriptFeature);
351 * NB we are mapping from gene sequence (not genome), so do not
352 * need to check for reverse strand (gene and transcript sequences
353 * are in forward sense)
357 * make a gene-length sequence filled with gaps
358 * we will fill in the bases for transcript regions
360 char[] seqChars = new char[gene.getLength()];
361 Arrays.fill(seqChars, al.getGapCharacter());
364 * look for exon features of the transcript, failing that for CDS
365 * (for example ENSG00000124610 has 1 CDS but no exon features)
367 String parentId = accId;
368 List<SequenceFeature> splices = findFeatures(gene,
369 SequenceOntologyI.EXON, parentId);
370 if (splices.isEmpty())
372 splices = findFeatures(gene, SequenceOntologyI.CDS, parentId);
374 SequenceFeatures.sortFeatures(splices, true);
376 int transcriptLength = 0;
377 final char[] geneChars = gene.getSequence();
378 int offset = gene.getStart(); // to convert to 0-based positions
379 List<int[]> mappedFrom = new ArrayList<>();
381 for (SequenceFeature sf : splices)
383 int start = sf.getBegin() - offset;
384 int end = sf.getEnd() - offset;
385 int spliceLength = end - start + 1;
386 System.arraycopy(geneChars, start, seqChars, start, spliceLength);
387 transcriptLength += spliceLength;
388 mappedFrom.add(new int[] { sf.getBegin(), sf.getEnd() });
391 Sequence transcript = new Sequence(accId, seqChars, 1,
395 * Ensembl has gene name as transcript Name
396 * EnsemblGenomes doesn't, but has a url-encoded description field
398 String description = transcriptFeature.getDescription();
399 if (description == null)
401 description = (String) transcriptFeature.getValue(DESCRIPTION);
403 if (description != null)
407 transcript.setDescription(URLDecoder.decode(description, "UTF-8"));
408 } catch (UnsupportedEncodingException e)
410 e.printStackTrace(); // as if
413 transcript.createDatasetSequence();
415 al.addSequence(transcript);
418 * transfer features to the new sequence; we use EnsemblCdna to do this,
419 * to filter out unwanted features types (see method retainFeature)
421 List<int[]> mapTo = new ArrayList<>();
422 mapTo.add(new int[] { 1, transcriptLength });
423 MapList mapping = new MapList(mappedFrom, mapTo, 1, 1);
424 EnsemblCdna cdna = new EnsemblCdna(getDomain());
425 cdna.transferFeatures(gene.getFeatures().getPositionalFeatures(),
426 transcript.getDatasetSequence(), mapping, parentId);
428 mapTranscriptToChromosome(transcript, gene, mapping);
431 * fetch and save cross-references
433 cdna.getCrossReferences(transcript);
436 * and finally fetch the protein product and save as a cross-reference
438 cdna.addProteinProduct(transcript);
444 * If the gene has a mapping to chromosome coordinates, derive the transcript
445 * chromosome regions and save on the transcript sequence
450 * the mapping from gene to transcript positions
452 protected void mapTranscriptToChromosome(SequenceI transcript,
453 SequenceI gene, MapList mapping)
455 GeneLociI loci = gene.getGeneLoci();
461 MapList geneMapping = loci.getMap();
463 List<int[]> exons = mapping.getFromRanges();
464 List<int[]> transcriptLoci = new ArrayList<>();
466 for (int[] exon : exons)
468 transcriptLoci.add(geneMapping.locateInTo(exon[0], exon[1]));
471 List<int[]> transcriptRange = Arrays.asList(new int[] {
472 transcript.getStart(), transcript.getEnd() });
473 MapList mapList = new MapList(transcriptRange, transcriptLoci, 1, 1);
475 transcript.setGeneLoci(loci.getSpeciesId(), loci.getAssemblyId(),
476 loci.getChromosomeId(), mapList);
480 * Returns the 'transcript_id' property of the sequence feature (or null)
485 protected String getTranscriptId(SequenceFeature feature)
487 return (String) feature.getValue(JSON_ID);
491 * Returns a list of the transcript features on the sequence whose Parent is
492 * the gene for the accession id.
494 * Transcript features are those of type "transcript", or any of its sub-types
495 * in the Sequence Ontology e.g. "mRNA", "processed_transcript". We also
496 * include "NMD_transcript_variant", because this type behaves like a
497 * transcript identifier in Ensembl, although strictly speaking it is not in
501 * @param geneSequence
504 protected List<SequenceFeature> getTranscriptFeatures(String accId,
505 SequenceI geneSequence)
507 List<SequenceFeature> transcriptFeatures = new ArrayList<>();
509 String parentIdentifier = accId;
511 List<SequenceFeature> sfs = geneSequence.getFeatures()
512 .getFeaturesByOntology(SequenceOntologyI.TRANSCRIPT);
513 sfs.addAll(geneSequence.getFeatures().getPositionalFeatures(
514 SequenceOntologyI.NMD_TRANSCRIPT_VARIANT));
516 for (SequenceFeature sf : sfs)
518 String parent = (String) sf.getValue(PARENT);
519 if (parentIdentifier.equalsIgnoreCase(parent))
521 transcriptFeatures.add(sf);
525 return transcriptFeatures;
529 public String getDescription()
531 return "Fetches all transcripts and variant features for a gene or transcript";
535 * Default test query is a gene id (can also enter a transcript id)
538 public String getTestQuery()
540 return Platform.isJS() ? "ENSG00000123569" : "ENSG00000157764";
541 // ENSG00000123569 // H2BFWT histone, 2 transcripts, reverse strand
542 // ENSG00000157764 // BRAF, 5 transcripts, reverse strand
543 // ENSG00000090266 // NDUFB2, 15 transcripts, forward strand
544 // ENSG00000101812 // H2BFM histone, 3 transcripts, forward strand
548 * Answers a list of sequence features (if any) whose type is 'gene' (or a
549 * subtype of gene in the Sequence Ontology), and whose ID is the accession we
553 protected List<SequenceFeature> getIdentifyingFeatures(SequenceI seq,
556 List<SequenceFeature> result = new ArrayList<>();
557 List<SequenceFeature> sfs = seq.getFeatures()
558 .getFeaturesByOntology(SequenceOntologyI.GENE);
559 for (SequenceFeature sf : sfs)
561 String id = (String) sf.getValue(JSON_ID);
562 if (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 (!accessionId.equalsIgnoreCase(parent))
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))