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