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