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