365c1c24fbc91e429fb08313a8e8487573de541c
[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 or transcript
165    * identifiers, into a non-redundant list of gene identifiers.
166    * 
167    * @param accessions
168    * @return
169    */
170   List<String> getGeneIds(String accessions)
171   {
172     List<String> geneIds = new ArrayList<String>();
173
174     for (String acc : accessions.split(getAccessionSeparator()))
175     {
176       if (isGeneIdentifier(acc))
177       {
178         if (!geneIds.contains(acc))
179         {
180           geneIds.add(acc);
181         }
182       }
183
184       /*
185        * if given a transcript id, look up its gene parent
186        */
187       else if (isTranscriptIdentifier(acc))
188       {
189         String geneId = new EnsemblLookup(getDomain()).getParent(acc);
190         if (geneId != null && !geneIds.contains(geneId))
191         {
192           geneIds.add(geneId);
193         }
194       }
195       else if (isProteinIdentifier(acc))
196       {
197         String tscriptId = new EnsemblLookup(getDomain()).getParent(acc);
198         if (tscriptId != null)
199         {
200           String geneId = new EnsemblLookup(getDomain())
201                   .getParent(tscriptId);
202
203           if (geneId != null && !geneIds.contains(geneId))
204           {
205             geneIds.add(geneId);
206           }
207         }
208         // NOTE - acc is lost if it resembles an ENS.+ ID but isn't actually
209         // resolving to one... e.g. ENSMICP00000009241
210       }
211       /*
212        * if given a gene or other external name, lookup and fetch 
213        * the corresponding gene for all model organisms 
214        */
215       else
216       {
217         List<String> ids = new EnsemblSymbol(getDomain(), getDbSource(),
218                 getDbVersion()).getIds(acc);
219         for (String geneId : ids)
220         {
221           if (!geneIds.contains(geneId))
222           {
223             geneIds.add(geneId);
224           }
225         }
226       }
227     }
228     return geneIds;
229   }
230
231   /**
232    * Attempts to get Ensembl stable identifiers for model organisms for a gene
233    * name by calling the xrefs symbol REST service to resolve the gene name.
234    * 
235    * @param query
236    * @return
237    */
238   protected String getGeneIdentifiersForName(String query)
239   {
240     List<String> ids = new EnsemblSymbol(getDomain(), getDbSource(),
241             getDbVersion()).getIds(query);
242     if (ids != null)
243     {
244       for (String id : ids)
245       {
246         if (isGeneIdentifier(id))
247         {
248           return id;
249         }
250       }
251     }
252     return null;
253   }
254
255   /**
256    * Constructs all transcripts for the gene, as identified by "transcript"
257    * features whose Parent is the requested gene. The coding transcript
258    * sequences (i.e. with introns omitted) are added to the alignment.
259    * 
260    * @param al
261    * @param accId
262    * @throws Exception
263    */
264   protected void getTranscripts(AlignmentI al, String accId)
265           throws Exception
266   {
267     SequenceI gene = al.getSequenceAt(0);
268     List<SequenceFeature> transcriptFeatures = getTranscriptFeatures(accId,
269             gene);
270
271     for (SequenceFeature transcriptFeature : transcriptFeatures)
272     {
273       makeTranscript(transcriptFeature, al, gene);
274     }
275
276     clearGeneFeatures(gene);
277   }
278
279   /**
280    * Remove unwanted features (transcript, exon, CDS) from the gene sequence
281    * after we have used them to derive transcripts and transfer features
282    * 
283    * @param gene
284    */
285   protected void clearGeneFeatures(SequenceI gene)
286   {
287     /*
288      * Note we include NMD_transcript_variant here because it behaves like 
289      * 'transcript' in Ensembl, although strictly speaking it is not 
290      * (it is a sub-type of sequence_variant)    
291      */
292     String[] soTerms = new String[] {
293         SequenceOntologyI.NMD_TRANSCRIPT_VARIANT,
294         SequenceOntologyI.TRANSCRIPT, SequenceOntologyI.EXON,
295         SequenceOntologyI.CDS };
296     List<SequenceFeature> sfs = gene.getFeatures().getFeaturesByOntology(
297             soTerms);
298     for (SequenceFeature sf : sfs)
299     {
300       gene.deleteFeature(sf);
301     }
302   }
303
304   /**
305    * Constructs a spliced transcript sequence by finding 'exon' features for the
306    * given id (or failing that 'CDS'). Copies features on to the new sequence.
307    * 'Aligns' the new sequence against the gene sequence by padding with gaps,
308    * and adds it to the alignment.
309    * 
310    * @param transcriptFeature
311    * @param al
312    *          the alignment to which to add the new sequence
313    * @param gene
314    *          the parent gene sequence, with features
315    * @return
316    */
317   SequenceI makeTranscript(SequenceFeature transcriptFeature, AlignmentI al,
318           SequenceI gene)
319   {
320     String accId = getTranscriptId(transcriptFeature);
321     if (accId == null)
322     {
323       return null;
324     }
325
326     /*
327      * NB we are mapping from gene sequence (not genome), so do not
328      * need to check for reverse strand (gene and transcript sequences 
329      * are in forward sense)
330      */
331
332     /*
333      * make a gene-length sequence filled with gaps
334      * we will fill in the bases for transcript regions
335      */
336     char[] seqChars = new char[gene.getLength()];
337     Arrays.fill(seqChars, al.getGapCharacter());
338
339     /*
340      * look for exon features of the transcript, failing that for CDS
341      * (for example ENSG00000124610 has 1 CDS but no exon features)
342      */
343     String parentId = "transcript:" + accId;
344     List<SequenceFeature> splices = findFeatures(gene,
345             SequenceOntologyI.EXON, parentId);
346     if (splices.isEmpty())
347     {
348       splices = findFeatures(gene, SequenceOntologyI.CDS, parentId);
349     }
350     SequenceFeatures.sortFeatures(splices, true);
351
352     int transcriptLength = 0;
353     final char[] geneChars = gene.getSequence();
354     int offset = gene.getStart(); // to convert to 0-based positions
355     List<int[]> mappedFrom = new ArrayList<int[]>();
356
357     for (SequenceFeature sf : splices)
358     {
359       int start = sf.getBegin() - offset;
360       int end = sf.getEnd() - offset;
361       int spliceLength = end - start + 1;
362       System.arraycopy(geneChars, start, seqChars, start, spliceLength);
363       transcriptLength += spliceLength;
364       mappedFrom.add(new int[] { sf.getBegin(), sf.getEnd() });
365     }
366
367     Sequence transcript = new Sequence(accId, seqChars, 1,
368             transcriptLength);
369
370     /*
371      * Ensembl has gene name as transcript Name
372      * EnsemblGenomes doesn't, but has a url-encoded description field
373      */
374     String description = (String) transcriptFeature.getValue(NAME);
375     if (description == null)
376     {
377       description = (String) transcriptFeature.getValue(DESCRIPTION);
378     }
379     if (description != null)
380     {
381       try
382       {
383         transcript.setDescription(URLDecoder.decode(description, "UTF-8"));
384       } catch (UnsupportedEncodingException e)
385       {
386         e.printStackTrace(); // as if
387       }
388     }
389     transcript.createDatasetSequence();
390
391     al.addSequence(transcript);
392
393     /*
394      * transfer features to the new sequence; we use EnsemblCdna to do this,
395      * to filter out unwanted features types (see method retainFeature)
396      */
397     List<int[]> mapTo = new ArrayList<int[]>();
398     mapTo.add(new int[] { 1, transcriptLength });
399     MapList mapping = new MapList(mappedFrom, mapTo, 1, 1);
400     EnsemblCdna cdna = new EnsemblCdna(getDomain());
401     cdna.transferFeatures(gene.getFeatures().getPositionalFeatures(),
402             transcript.getDatasetSequence(), mapping, parentId);
403
404     /*
405      * fetch and save cross-references
406      */
407     cdna.getCrossReferences(transcript);
408
409     /*
410      * and finally fetch the protein product and save as a cross-reference
411      */
412     cdna.addProteinProduct(transcript);
413
414     return transcript;
415   }
416
417   /**
418    * Returns the 'transcript_id' property of the sequence feature (or null)
419    * 
420    * @param feature
421    * @return
422    */
423   protected String getTranscriptId(SequenceFeature feature)
424   {
425     return (String) feature.getValue("transcript_id");
426   }
427
428   /**
429    * Returns a list of the transcript features on the sequence whose Parent is
430    * the gene for the accession id.
431    * 
432    * @param accId
433    * @param geneSequence
434    * @return
435    */
436   protected List<SequenceFeature> getTranscriptFeatures(String accId,
437           SequenceI geneSequence)
438   {
439     List<SequenceFeature> transcriptFeatures = new ArrayList<SequenceFeature>();
440
441     String parentIdentifier = GENE_PREFIX + accId;
442     // todo optimise here by transcript type!
443     List<SequenceFeature> sfs = geneSequence.getFeatures()
444             .getPositionalFeatures();
445
446     for (SequenceFeature sf : sfs)
447     {
448       if (isTranscript(sf.getType()))
449       {
450         String parent = (String) sf.getValue(PARENT);
451         if (parentIdentifier.equals(parent))
452         {
453           transcriptFeatures.add(sf);
454         }
455       }
456     }
457
458     return transcriptFeatures;
459   }
460
461   @Override
462   public String getDescription()
463   {
464     return "Fetches all transcripts and variant features for a gene or transcript";
465   }
466
467   /**
468    * Default test query is a gene id (can also enter a transcript id)
469    */
470   @Override
471   public String getTestQuery()
472   {
473     return "ENSG00000157764"; // BRAF, 5 transcripts, reverse strand
474     // ENSG00000090266 // NDUFB2, 15 transcripts, forward strand
475     // ENSG00000101812 // H2BFM histone, 3 transcripts, forward strand
476     // ENSG00000123569 // H2BFWT histone, 2 transcripts, reverse strand
477   }
478
479   /**
480    * Answers true for a feature of type 'gene' (or a sub-type of gene in the
481    * Sequence Ontology), whose ID is the accession we are retrieving
482    */
483   @Override
484   protected boolean identifiesSequence(SequenceFeature sf, String accId)
485   {
486     if (SequenceOntologyFactory.getInstance().isA(sf.getType(),
487             SequenceOntologyI.GENE))
488     {
489       String id = (String) sf.getValue(ID);
490       if ((GENE_PREFIX + accId).equals(id))
491       {
492         return true;
493       }
494     }
495     return false;
496   }
497
498   /**
499    * Answers true unless feature type is 'gene', or 'transcript' with a parent
500    * which is a different gene. We need the gene features to identify the range,
501    * but it is redundant information on the gene sequence. Checking the parent
502    * allows us to drop transcript features which belong to different
503    * (overlapping) genes.
504    */
505   @Override
506   protected boolean retainFeature(SequenceFeature sf, String accessionId)
507   {
508     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
509     String type = sf.getType();
510     if (so.isA(type, SequenceOntologyI.GENE))
511     {
512       return false;
513     }
514     if (isTranscript(type))
515     {
516       String parent = (String) sf.getValue(PARENT);
517       if (!(GENE_PREFIX + accessionId).equals(parent))
518       {
519         return false;
520       }
521     }
522     return true;
523   }
524
525   /**
526    * Answers false. This allows an optimisation - a single 'gene' feature is all
527    * that is needed to identify the positions of the gene on the genomic
528    * sequence.
529    */
530   @Override
531   protected boolean isSpliceable()
532   {
533     return false;
534   }
535
536   /**
537    * Override to do nothing as Ensembl doesn't return a protein sequence for a
538    * gene identifier
539    */
540   @Override
541   protected void addProteinProduct(SequenceI querySeq)
542   {
543   }
544
545   @Override
546   public Regex getAccessionValidator()
547   {
548     return ACCESSION_REGEX;
549   }
550
551   /**
552    * Returns a descriptor for suitable feature display settings with
553    * <ul>
554    * <li>only exon or sequence_variant features (or their subtypes in the
555    * Sequence Ontology) visible</li>
556    * <li>variant features coloured red</li>
557    * <li>exon features coloured by label (exon name)</li>
558    * <li>variants displayed above (on top of) exons</li>
559    * </ul>
560    */
561   @Override
562   public FeatureSettingsModelI getFeatureColourScheme()
563   {
564     return new FeatureSettingsAdapter()
565     {
566       SequenceOntologyI so = SequenceOntologyFactory.getInstance();
567
568       @Override
569       public boolean isFeatureDisplayed(String type)
570       {
571         return (so.isA(type, SequenceOntologyI.EXON)
572                 || so.isA(type, SequenceOntologyI.SEQUENCE_VARIANT));
573       }
574
575       @Override
576       public FeatureColourI getFeatureColour(String type)
577       {
578         if (so.isA(type, SequenceOntologyI.EXON))
579         {
580           return new FeatureColour()
581           {
582             @Override
583             public boolean isColourByLabel()
584             {
585               return true;
586             }
587           };
588         }
589         if (so.isA(type, SequenceOntologyI.SEQUENCE_VARIANT))
590         {
591           return new FeatureColour()
592           {
593
594             @Override
595             public Color getColour()
596             {
597               return Color.RED;
598             }
599           };
600         }
601         return null;
602       }
603
604       /**
605        * order to render sequence_variant after exon after the rest
606        */
607       @Override
608       public int compare(String feature1, String feature2)
609       {
610         if (so.isA(feature1, SequenceOntologyI.SEQUENCE_VARIANT))
611         {
612           return +1;
613         }
614         if (so.isA(feature2, SequenceOntologyI.SEQUENCE_VARIANT))
615         {
616           return -1;
617         }
618         if (so.isA(feature1, SequenceOntologyI.EXON))
619         {
620           return +1;
621         }
622         if (so.isA(feature2, SequenceOntologyI.EXON))
623         {
624           return -1;
625         }
626         return 0;
627       }
628     };
629   }
630
631 }