50dfa908778093da87dbca01b020cbd3b9a67d43
[jalview.git] / src / jalview / ext / ensembl / EnsemblGene.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.ext.ensembl;
22
23 import jalview.api.FeatureColourI;
24 import jalview.api.FeatureSettingsModelI;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.Sequence;
27 import jalview.datamodel.SequenceFeature;
28 import jalview.datamodel.SequenceI;
29 import jalview.datamodel.features.SequenceFeatures;
30 import jalview.io.gff.SequenceOntologyFactory;
31 import jalview.io.gff.SequenceOntologyI;
32 import jalview.schemes.FeatureColour;
33 import jalview.schemes.FeatureSettingsAdapter;
34 import jalview.util.MapList;
35
36 import java.awt.Color;
37 import java.io.UnsupportedEncodingException;
38 import java.net.URLDecoder;
39 import java.util.ArrayList;
40 import java.util.Arrays;
41 import java.util.List;
42
43 import com.stevesoft.pat.Regex;
44
45 /**
46  * A class that fetches genomic sequence and all transcripts for an Ensembl gene
47  * 
48  * @author gmcarstairs
49  */
50 public class EnsemblGene extends EnsemblSeqProxy
51 {
52   private static final String GENE_PREFIX = "gene:";
53
54   /*
55    * accepts anything as we will attempt lookup of gene or 
56    * transcript id or gene name
57    */
58   private static final Regex ACCESSION_REGEX = new Regex(".*");
59
60   private static final EnsemblFeatureType[] FEATURES_TO_FETCH = {
61       EnsemblFeatureType.gene, EnsemblFeatureType.transcript,
62       EnsemblFeatureType.exon, EnsemblFeatureType.cds,
63       EnsemblFeatureType.variation };
64
65   /**
66    * Default constructor (to use rest.ensembl.org)
67    */
68   public EnsemblGene()
69   {
70     super();
71   }
72
73   /**
74    * Constructor given the target domain to fetch data from
75    * 
76    * @param d
77    */
78   public EnsemblGene(String d)
79   {
80     super(d);
81   }
82
83   @Override
84   public String getDbName()
85   {
86     return "ENSEMBL";
87   }
88
89   @Override
90   protected EnsemblFeatureType[] getFeaturesToFetch()
91   {
92     return FEATURES_TO_FETCH;
93   }
94
95   @Override
96   protected EnsemblSeqType getSourceEnsemblType()
97   {
98     return EnsemblSeqType.GENOMIC;
99   }
100
101   /**
102    * Returns an alignment containing the gene(s) for the given gene or
103    * transcript identifier, or external identifier (e.g. Uniprot id). If given a
104    * gene name or external identifier, returns any related gene sequences found
105    * for model organisms. If only a single gene is queried for, then its
106    * transcripts are also retrieved and added to the alignment. <br>
107    * Method:
108    * <ul>
109    * <li>resolves a transcript identifier by looking up its parent gene id</li>
110    * <li>resolves an external identifier by looking up xref-ed gene ids</li>
111    * <li>fetches the gene sequence</li>
112    * <li>fetches features on the sequence</li>
113    * <li>identifies "transcript" features whose Parent is the requested
114    * gene</li>
115    * <li>fetches the transcript sequence for each transcript</li>
116    * <li>makes a mapping from the gene to each transcript</li>
117    * <li>copies features from gene to transcript sequences</li>
118    * <li>fetches the protein sequence for each transcript, maps and saves it as
119    * a cross-reference</li>
120    * <li>aligns each transcript against the gene sequence based on the position
121    * mappings</li>
122    * </ul>
123    * 
124    * @param query
125    *          a single gene or transcript identifier or gene name
126    * @return an alignment containing a gene, and possibly transcripts, or null
127    */
128   @Override
129   public AlignmentI getSequenceRecords(String query) throws Exception
130   {
131     /*
132      * convert to a non-duplicated list of gene identifiers
133      */
134     List<String> geneIds = getGeneIds(query);
135
136     AlignmentI al = null;
137     for (String geneId : geneIds)
138     {
139       /*
140        * fetch the gene sequence(s) with features and xrefs
141        */
142       AlignmentI geneAlignment = super.getSequenceRecords(geneId);
143       if (geneAlignment == null)
144       {
145         continue;
146       }
147       if (geneAlignment.getHeight() == 1)
148       {
149         getTranscripts(geneAlignment, geneId);
150       }
151       if (al == null)
152       {
153         al = geneAlignment;
154       }
155       else
156       {
157         al.append(geneAlignment);
158       }
159     }
160     return al;
161   }
162
163   /**
164    * Converts a query, which may contain one or more gene, transcript, or
165    * external (to Ensembl) identifiers, into a non-redundant list of gene
166    * identifiers.
167    * 
168    * @param accessions
169    * @return
170    */
171   List<String> getGeneIds(String accessions)
172   {
173     List<String> geneIds = new ArrayList<String>();
174
175     for (String acc : accessions.split(getAccessionSeparator()))
176     {
177       /*
178        * First try lookup as an Ensembl (gene or transcript) identifier
179        */
180       String geneId = new EnsemblLookup(getDomain()).getGeneId(acc);
181       if (geneId != null)
182       {
183         if (!geneIds.contains(geneId))
184         {
185           geneIds.add(geneId);
186         }
187       }
188       else
189       {
190         /*
191          * if given a gene or other external name, lookup and fetch 
192          * the corresponding gene for all model organisms 
193          */
194         List<String> ids = new EnsemblSymbol(getDomain(), getDbSource(),
195                 getDbVersion()).getGeneIds(acc);
196         for (String id : ids)
197         {
198           if (!geneIds.contains(id))
199           {
200             geneIds.add(id);
201           }
202         }
203       }
204     }
205     return geneIds;
206   }
207
208   /**
209    * Constructs all transcripts for the gene, as identified by "transcript"
210    * features whose Parent is the requested gene. The coding transcript
211    * sequences (i.e. with introns omitted) are added to the alignment.
212    * 
213    * @param al
214    * @param accId
215    * @throws Exception
216    */
217   protected void getTranscripts(AlignmentI al, String accId)
218           throws Exception
219   {
220     SequenceI gene = al.getSequenceAt(0);
221     List<SequenceFeature> transcriptFeatures = getTranscriptFeatures(accId,
222             gene);
223
224     for (SequenceFeature transcriptFeature : transcriptFeatures)
225     {
226       makeTranscript(transcriptFeature, al, gene);
227     }
228
229     clearGeneFeatures(gene);
230   }
231
232   /**
233    * Remove unwanted features (transcript, exon, CDS) from the gene sequence
234    * after we have used them to derive transcripts and transfer features
235    * 
236    * @param gene
237    */
238   protected void clearGeneFeatures(SequenceI gene)
239   {
240     /*
241      * Note we include NMD_transcript_variant here because it behaves like 
242      * 'transcript' in Ensembl, although strictly speaking it is not 
243      * (it is a sub-type of sequence_variant)    
244      */
245     String[] soTerms = new String[] {
246         SequenceOntologyI.NMD_TRANSCRIPT_VARIANT,
247         SequenceOntologyI.TRANSCRIPT, SequenceOntologyI.EXON,
248         SequenceOntologyI.CDS };
249     List<SequenceFeature> sfs = gene.getFeatures().getFeaturesByOntology(
250             soTerms);
251     for (SequenceFeature sf : sfs)
252     {
253       gene.deleteFeature(sf);
254     }
255   }
256
257   /**
258    * Constructs a spliced transcript sequence by finding 'exon' features for the
259    * given id (or failing that 'CDS'). Copies features on to the new sequence.
260    * 'Aligns' the new sequence against the gene sequence by padding with gaps,
261    * and adds it to the alignment.
262    * 
263    * @param transcriptFeature
264    * @param al
265    *          the alignment to which to add the new sequence
266    * @param gene
267    *          the parent gene sequence, with features
268    * @return
269    */
270   SequenceI makeTranscript(SequenceFeature transcriptFeature, AlignmentI al,
271           SequenceI gene)
272   {
273     String accId = getTranscriptId(transcriptFeature);
274     if (accId == null)
275     {
276       return null;
277     }
278
279     /*
280      * NB we are mapping from gene sequence (not genome), so do not
281      * need to check for reverse strand (gene and transcript sequences 
282      * are in forward sense)
283      */
284
285     /*
286      * make a gene-length sequence filled with gaps
287      * we will fill in the bases for transcript regions
288      */
289     char[] seqChars = new char[gene.getLength()];
290     Arrays.fill(seqChars, al.getGapCharacter());
291
292     /*
293      * look for exon features of the transcript, failing that for CDS
294      * (for example ENSG00000124610 has 1 CDS but no exon features)
295      */
296     String parentId = "transcript:" + accId;
297     List<SequenceFeature> splices = findFeatures(gene,
298             SequenceOntologyI.EXON, parentId);
299     if (splices.isEmpty())
300     {
301       splices = findFeatures(gene, SequenceOntologyI.CDS, parentId);
302     }
303     SequenceFeatures.sortFeatures(splices, true);
304
305     int transcriptLength = 0;
306     final char[] geneChars = gene.getSequence();
307     int offset = gene.getStart(); // to convert to 0-based positions
308     List<int[]> mappedFrom = new ArrayList<int[]>();
309
310     for (SequenceFeature sf : splices)
311     {
312       int start = sf.getBegin() - offset;
313       int end = sf.getEnd() - offset;
314       int spliceLength = end - start + 1;
315       System.arraycopy(geneChars, start, seqChars, start, spliceLength);
316       transcriptLength += spliceLength;
317       mappedFrom.add(new int[] { sf.getBegin(), sf.getEnd() });
318     }
319
320     Sequence transcript = new Sequence(accId, seqChars, 1,
321             transcriptLength);
322
323     /*
324      * Ensembl has gene name as transcript Name
325      * EnsemblGenomes doesn't, but has a url-encoded description field
326      */
327     String description = (String) transcriptFeature.getValue(NAME);
328     if (description == null)
329     {
330       description = (String) transcriptFeature.getValue(DESCRIPTION);
331     }
332     if (description != null)
333     {
334       try
335       {
336         transcript.setDescription(URLDecoder.decode(description, "UTF-8"));
337       } catch (UnsupportedEncodingException e)
338       {
339         e.printStackTrace(); // as if
340       }
341     }
342     transcript.createDatasetSequence();
343
344     al.addSequence(transcript);
345
346     /*
347      * transfer features to the new sequence; we use EnsemblCdna to do this,
348      * to filter out unwanted features types (see method retainFeature)
349      */
350     List<int[]> mapTo = new ArrayList<int[]>();
351     mapTo.add(new int[] { 1, transcriptLength });
352     MapList mapping = new MapList(mappedFrom, mapTo, 1, 1);
353     EnsemblCdna cdna = new EnsemblCdna(getDomain());
354     cdna.transferFeatures(gene.getFeatures().getPositionalFeatures(),
355             transcript.getDatasetSequence(), mapping, parentId);
356
357     /*
358      * fetch and save cross-references
359      */
360     cdna.getCrossReferences(transcript);
361
362     /*
363      * and finally fetch the protein product and save as a cross-reference
364      */
365     cdna.addProteinProduct(transcript);
366
367     return transcript;
368   }
369
370   /**
371    * Returns the 'transcript_id' property of the sequence feature (or null)
372    * 
373    * @param feature
374    * @return
375    */
376   protected String getTranscriptId(SequenceFeature feature)
377   {
378     return (String) feature.getValue("transcript_id");
379   }
380
381   /**
382    * Returns a list of the transcript features on the sequence whose Parent is
383    * the gene for the accession id.
384    * <p>
385    * Transcript features are those of type "transcript", or any of its sub-types
386    * in the Sequence Ontology e.g. "mRNA", "processed_transcript". We also
387    * include "NMD_transcript_variant", because this type behaves like a
388    * transcript identifier in Ensembl, although strictly speaking it is not in
389    * the SO.
390    * 
391    * @param accId
392    * @param geneSequence
393    * @return
394    */
395   protected List<SequenceFeature> getTranscriptFeatures(String accId,
396           SequenceI geneSequence)
397   {
398     List<SequenceFeature> transcriptFeatures = new ArrayList<SequenceFeature>();
399
400     String parentIdentifier = GENE_PREFIX + accId;
401
402     List<SequenceFeature> sfs = geneSequence.getFeatures()
403             .getFeaturesByOntology(SequenceOntologyI.TRANSCRIPT);
404     sfs.addAll(geneSequence.getFeatures().getPositionalFeatures(
405             SequenceOntologyI.NMD_TRANSCRIPT_VARIANT));
406
407     for (SequenceFeature sf : sfs)
408     {
409       String parent = (String) sf.getValue(PARENT);
410       if (parentIdentifier.equals(parent))
411       {
412         transcriptFeatures.add(sf);
413       }
414     }
415
416     return transcriptFeatures;
417   }
418
419   @Override
420   public String getDescription()
421   {
422     return "Fetches all transcripts and variant features for a gene or transcript";
423   }
424
425   /**
426    * Default test query is a gene id (can also enter a transcript id)
427    */
428   @Override
429   public String getTestQuery()
430   {
431     return "ENSG00000157764"; // BRAF, 5 transcripts, reverse strand
432     // ENSG00000090266 // NDUFB2, 15 transcripts, forward strand
433     // ENSG00000101812 // H2BFM histone, 3 transcripts, forward strand
434     // ENSG00000123569 // H2BFWT histone, 2 transcripts, reverse strand
435   }
436
437   /**
438    * Answers true for a feature of type 'gene' (or a sub-type of gene in the
439    * Sequence Ontology), whose ID is the accession we are retrieving
440    */
441   @Override
442   protected boolean identifiesSequence(SequenceFeature sf, String accId)
443   {
444     if (SequenceOntologyFactory.getInstance().isA(sf.getType(),
445             SequenceOntologyI.GENE))
446     {
447       String id = (String) sf.getValue(ID);
448       if ((GENE_PREFIX + accId).equals(id))
449       {
450         return true;
451       }
452     }
453     return false;
454   }
455
456   /**
457    * Answers true unless feature type is 'gene', or 'transcript' with a parent
458    * which is a different gene. We need the gene features to identify the range,
459    * but it is redundant information on the gene sequence. Checking the parent
460    * allows us to drop transcript features which belong to different
461    * (overlapping) genes.
462    */
463   @Override
464   protected boolean retainFeature(SequenceFeature sf, String accessionId)
465   {
466     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
467     String type = sf.getType();
468     if (so.isA(type, SequenceOntologyI.GENE))
469     {
470       return false;
471     }
472     if (isTranscript(type))
473     {
474       String parent = (String) sf.getValue(PARENT);
475       if (!(GENE_PREFIX + accessionId).equals(parent))
476       {
477         return false;
478       }
479     }
480     return true;
481   }
482
483   /**
484    * Answers false. This allows an optimisation - a single 'gene' feature is all
485    * that is needed to identify the positions of the gene on the genomic
486    * sequence.
487    */
488   @Override
489   protected boolean isSpliceable()
490   {
491     return false;
492   }
493
494   /**
495    * Override to do nothing as Ensembl doesn't return a protein sequence for a
496    * gene identifier
497    */
498   @Override
499   protected void addProteinProduct(SequenceI querySeq)
500   {
501   }
502
503   @Override
504   public Regex getAccessionValidator()
505   {
506     return ACCESSION_REGEX;
507   }
508
509   /**
510    * Returns a descriptor for suitable feature display settings with
511    * <ul>
512    * <li>only exon or sequence_variant features (or their subtypes in the
513    * Sequence Ontology) visible</li>
514    * <li>variant features coloured red</li>
515    * <li>exon features coloured by label (exon name)</li>
516    * <li>variants displayed above (on top of) exons</li>
517    * </ul>
518    */
519   @Override
520   public FeatureSettingsModelI getFeatureColourScheme()
521   {
522     return new FeatureSettingsAdapter()
523     {
524       SequenceOntologyI so = SequenceOntologyFactory.getInstance();
525
526       @Override
527       public boolean isFeatureDisplayed(String type)
528       {
529         return (so.isA(type, SequenceOntologyI.EXON)
530                 || so.isA(type, SequenceOntologyI.SEQUENCE_VARIANT));
531       }
532
533       @Override
534       public FeatureColourI getFeatureColour(String type)
535       {
536         if (so.isA(type, SequenceOntologyI.EXON))
537         {
538           return new FeatureColour()
539           {
540             @Override
541             public boolean isColourByLabel()
542             {
543               return true;
544             }
545           };
546         }
547         if (so.isA(type, SequenceOntologyI.SEQUENCE_VARIANT))
548         {
549           return new FeatureColour()
550           {
551
552             @Override
553             public Color getColour()
554             {
555               return Color.RED;
556             }
557           };
558         }
559         return null;
560       }
561
562       /**
563        * order to render sequence_variant after exon after the rest
564        */
565       @Override
566       public int compare(String feature1, String feature2)
567       {
568         if (so.isA(feature1, SequenceOntologyI.SEQUENCE_VARIANT))
569         {
570           return +1;
571         }
572         if (so.isA(feature2, SequenceOntologyI.SEQUENCE_VARIANT))
573         {
574           return -1;
575         }
576         if (so.isA(feature1, SequenceOntologyI.EXON))
577         {
578           return +1;
579         }
580         if (so.isA(feature2, SequenceOntologyI.EXON))
581         {
582           return -1;
583         }
584         return 0;
585       }
586     };
587   }
588
589 }