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