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