JAL-2582 comment about IDs being lost if they resembl ensembl IDs but can’t be resolv...
[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 or transcript
163    * identifiers, into a non-redundant list of gene identifiers.
164    * 
165    * @param accessions
166    * @return
167    */
168   List<String> getGeneIds(String accessions)
169   {
170     List<String> geneIds = new ArrayList<String>();
171
172     for (String acc : accessions.split(getAccessionSeparator()))
173     {
174       if (isGeneIdentifier(acc))
175       {
176         if (!geneIds.contains(acc))
177         {
178           geneIds.add(acc);
179         }
180       }
181
182       /*
183        * if given a transcript id, look up its gene parent
184        */
185       else if (isTranscriptIdentifier(acc))
186       {
187         String geneId = new EnsemblLookup(getDomain()).getParent(acc);
188         if (geneId != null && !geneIds.contains(geneId))
189         {
190           geneIds.add(geneId);
191         }
192       }
193       else if (isProteinIdentifier(acc))
194       {
195         String tscriptId = new EnsemblLookup(getDomain()).getParent(acc);
196         if (tscriptId != null)
197         {
198           String geneId = new EnsemblLookup(getDomain())
199                   .getParent(tscriptId);
200
201           if (geneId != null && !geneIds.contains(geneId))
202           {
203             geneIds.add(geneId);
204           }
205         }
206         // NOTE - acc is lost if it resembles an ENS.+ ID but isn't actually
207         // resolving to one... e.g. ENSMICP00000009241
208       }
209       /*
210        * if given a gene or other external name, lookup and fetch 
211        * the corresponding gene for all model organisms 
212        */
213       else
214       {
215         List<String> ids = new EnsemblSymbol(getDomain(), getDbSource(),
216                 getDbVersion()).getIds(acc);
217         for (String geneId : ids)
218         {
219           if (!geneIds.contains(geneId))
220           {
221             geneIds.add(geneId);
222           }
223         }
224       }
225     }
226     return geneIds;
227   }
228
229   /**
230    * Attempts to get Ensembl stable identifiers for model organisms for a gene
231    * name by calling the xrefs symbol REST service to resolve the gene name.
232    * 
233    * @param query
234    * @return
235    */
236   protected String getGeneIdentifiersForName(String query)
237   {
238     List<String> ids = new EnsemblSymbol(getDomain(), getDbSource(),
239             getDbVersion()).getIds(query);
240     if (ids != null)
241     {
242       for (String id : ids)
243       {
244         if (isGeneIdentifier(id))
245         {
246           return id;
247         }
248       }
249     }
250     return null;
251   }
252
253   /**
254    * Constructs all transcripts for the gene, as identified by "transcript"
255    * features whose Parent is the requested gene. The coding transcript
256    * sequences (i.e. with introns omitted) are added to the alignment.
257    * 
258    * @param al
259    * @param accId
260    * @throws Exception
261    */
262   protected void getTranscripts(AlignmentI al, String accId)
263           throws Exception
264   {
265     SequenceI gene = al.getSequenceAt(0);
266     List<SequenceFeature> transcriptFeatures = getTranscriptFeatures(accId,
267             gene);
268
269     for (SequenceFeature transcriptFeature : transcriptFeatures)
270     {
271       makeTranscript(transcriptFeature, al, gene);
272     }
273
274     clearGeneFeatures(gene);
275   }
276
277   /**
278    * Remove unwanted features (transcript, exon, CDS) from the gene sequence
279    * after we have used them to derive transcripts and transfer features
280    * 
281    * @param gene
282    */
283   protected void clearGeneFeatures(SequenceI gene)
284   {
285     SequenceFeature[] sfs = gene.getSequenceFeatures();
286     if (sfs != null)
287     {
288       SequenceOntologyI so = SequenceOntologyFactory.getInstance();
289       List<SequenceFeature> filtered = new ArrayList<SequenceFeature>();
290       for (SequenceFeature sf : sfs)
291       {
292         String type = sf.getType();
293         if (!isTranscript(type) && !so.isA(type, SequenceOntologyI.EXON)
294                 && !so.isA(type, SequenceOntologyI.CDS))
295         {
296           filtered.add(sf);
297         }
298       }
299       gene.setSequenceFeatures(filtered
300               .toArray(new SequenceFeature[filtered.size()]));
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,
318           AlignmentI al, 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
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.getSequenceFeatures(),
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     SequenceFeature[] sfs = geneSequence.getSequenceFeatures();
441
442     if (sfs != null)
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
457     return transcriptFeatures;
458   }
459
460   @Override
461   public String getDescription()
462   {
463     return "Fetches all transcripts and variant features for a gene or transcript";
464   }
465
466   /**
467    * Default test query is a gene id (can also enter a transcript id)
468    */
469   @Override
470   public String getTestQuery()
471   {
472     return "ENSG00000157764"; // BRAF, 5 transcripts, reverse strand
473     // ENSG00000090266 // NDUFB2, 15 transcripts, forward strand
474     // ENSG00000101812 // H2BFM histone, 3 transcripts, forward strand
475     // ENSG00000123569 // H2BFWT histone, 2 transcripts, reverse strand
476   }
477
478   /**
479    * Answers true for a feature of type 'gene' (or a sub-type of gene in the
480    * Sequence Ontology), whose ID is the accession we are retrieving
481    */
482   @Override
483   protected boolean identifiesSequence(SequenceFeature sf, String accId)
484   {
485     if (SequenceOntologyFactory.getInstance().isA(sf.getType(),
486             SequenceOntologyI.GENE))
487     {
488       String id = (String) sf.getValue(ID);
489       if ((GENE_PREFIX + accId).equals(id))
490       {
491         return true;
492       }
493     }
494     return false;
495   }
496
497   /**
498    * Answers true unless feature type is 'gene', or 'transcript' with a parent
499    * which is a different gene. We need the gene features to identify the range,
500    * but it is redundant information on the gene sequence. Checking the parent
501    * allows us to drop transcript features which belong to different
502    * (overlapping) genes.
503    */
504   @Override
505   protected boolean retainFeature(SequenceFeature sf, String accessionId)
506   {
507     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
508     String type = sf.getType();
509     if (so.isA(type, SequenceOntologyI.GENE))
510     {
511       return false;
512     }
513     if (isTranscript(type))
514     {
515       String parent = (String) sf.getValue(PARENT);
516       if (!(GENE_PREFIX + accessionId).equals(parent))
517       {
518         return false;
519       }
520     }
521     return true;
522   }
523
524   /**
525    * Answers false. This allows an optimisation - a single 'gene' feature is all
526    * that is needed to identify the positions of the gene on the genomic
527    * sequence.
528    */
529   @Override
530   protected boolean isSpliceable()
531   {
532     return false;
533   }
534
535   /**
536    * Override to do nothing as Ensembl doesn't return a protein sequence for a
537    * gene identifier
538    */
539   @Override
540   protected void addProteinProduct(SequenceI querySeq)
541   {
542   }
543
544   @Override
545   public Regex getAccessionValidator()
546   {
547     return ACCESSION_REGEX;
548   }
549
550   /**
551    * Returns a descriptor for suitable feature display settings with
552    * <ul>
553    * <li>only exon or sequence_variant features (or their subtypes in the
554    * Sequence Ontology) visible</li>
555    * <li>variant features coloured red</li>
556    * <li>exon features coloured by label (exon name)</li>
557    * <li>variants displayed above (on top of) exons</li>
558    * </ul>
559    */
560   @Override
561   public FeatureSettingsModelI getFeatureColourScheme()
562   {
563     return new FeatureSettingsAdapter()
564     {
565       SequenceOntologyI so = SequenceOntologyFactory.getInstance();
566
567       @Override
568       public boolean isFeatureDisplayed(String type)
569       {
570         return (so.isA(type, SequenceOntologyI.EXON) || so.isA(type,
571                 SequenceOntologyI.SEQUENCE_VARIANT));
572       }
573
574       @Override
575       public FeatureColourI getFeatureColour(String type)
576       {
577         if (so.isA(type, SequenceOntologyI.EXON))
578         {
579           return new FeatureColour()
580           {
581             @Override
582             public boolean isColourByLabel()
583             {
584               return true;
585             }
586           };
587         }
588         if (so.isA(type, SequenceOntologyI.SEQUENCE_VARIANT))
589         {
590           return new FeatureColour()
591           {
592
593             @Override
594             public Color getColour()
595             {
596               return Color.RED;
597             }
598           };
599         }
600         return null;
601       }
602
603       /**
604        * order to render sequence_variant after exon after the rest
605        */
606       @Override
607       public int compare(String feature1, String feature2)
608       {
609         if (so.isA(feature1, SequenceOntologyI.SEQUENCE_VARIANT))
610         {
611           return +1;
612         }
613         if (so.isA(feature2, SequenceOntologyI.SEQUENCE_VARIANT))
614         {
615           return -1;
616         }
617         if (so.isA(feature1, SequenceOntologyI.EXON))
618         {
619           return +1;
620         }
621         if (so.isA(feature2, SequenceOntologyI.EXON))
622         {
623           return -1;
624         }
625         return 0;
626       }
627     };
628   }
629
630 }