24e3e955fe442972c96f99ae6257cfaa0fecfa14
[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
194       /*
195        * if given a gene or other external name, lookup and fetch 
196        * the corresponding gene for all model organisms 
197        */
198       else
199       {
200         List<String> ids = new EnsemblSymbol(getDomain(), getDbSource(),
201                 getDbVersion()).getIds(acc);
202         for (String geneId : ids)
203         {
204           if (!geneIds.contains(geneId))
205           {
206             geneIds.add(geneId);
207           }
208         }
209       }
210     }
211     return geneIds;
212   }
213
214   /**
215    * Attempts to get Ensembl stable identifiers for model organisms for a gene
216    * name by calling the xrefs symbol REST service to resolve the gene name.
217    * 
218    * @param query
219    * @return
220    */
221   protected String getGeneIdentifiersForName(String query)
222   {
223     List<String> ids = new EnsemblSymbol(getDomain(), getDbSource(),
224             getDbVersion()).getIds(query);
225     if (ids != null)
226     {
227       for (String id : ids)
228       {
229         if (isGeneIdentifier(id))
230         {
231           return id;
232         }
233       }
234     }
235     return null;
236   }
237
238   /**
239    * Constructs all transcripts for the gene, as identified by "transcript"
240    * features whose Parent is the requested gene. The coding transcript
241    * sequences (i.e. with introns omitted) are added to the alignment.
242    * 
243    * @param al
244    * @param accId
245    * @throws Exception
246    */
247   protected void getTranscripts(AlignmentI al, String accId)
248           throws Exception
249   {
250     SequenceI gene = al.getSequenceAt(0);
251     List<SequenceFeature> transcriptFeatures = getTranscriptFeatures(accId,
252             gene);
253
254     for (SequenceFeature transcriptFeature : transcriptFeatures)
255     {
256       makeTranscript(transcriptFeature, al, gene);
257     }
258
259     clearGeneFeatures(gene);
260   }
261
262   /**
263    * Remove unwanted features (transcript, exon, CDS) from the gene sequence
264    * after we have used them to derive transcripts and transfer features
265    * 
266    * @param gene
267    */
268   protected void clearGeneFeatures(SequenceI gene)
269   {
270     SequenceFeature[] sfs = gene.getSequenceFeatures();
271     if (sfs != null)
272     {
273       SequenceOntologyI so = SequenceOntologyFactory.getInstance();
274       List<SequenceFeature> filtered = new ArrayList<SequenceFeature>();
275       for (SequenceFeature sf : sfs)
276       {
277         String type = sf.getType();
278         if (!isTranscript(type) && !so.isA(type, SequenceOntologyI.EXON)
279                 && !so.isA(type, SequenceOntologyI.CDS))
280         {
281           filtered.add(sf);
282         }
283       }
284       gene.setSequenceFeatures(filtered
285               .toArray(new SequenceFeature[filtered.size()]));
286     }
287   }
288
289   /**
290    * Constructs a spliced transcript sequence by finding 'exon' features for the
291    * given id (or failing that 'CDS'). Copies features on to the new sequence.
292    * 'Aligns' the new sequence against the gene sequence by padding with gaps,
293    * and adds it to the alignment.
294    * 
295    * @param transcriptFeature
296    * @param al
297    *          the alignment to which to add the new sequence
298    * @param gene
299    *          the parent gene sequence, with features
300    * @return
301    */
302   SequenceI makeTranscript(SequenceFeature transcriptFeature,
303           AlignmentI al, SequenceI gene)
304   {
305     String accId = getTranscriptId(transcriptFeature);
306     if (accId == null)
307     {
308       return null;
309     }
310
311     /*
312      * NB we are mapping from gene sequence (not genome), so do not
313      * need to check for reverse strand (gene and transcript sequences 
314      * are in forward sense)
315      */
316
317     /*
318      * make a gene-length sequence filled with gaps
319      * we will fill in the bases for transcript regions
320      */
321     char[] seqChars = new char[gene.getLength()];
322     Arrays.fill(seqChars, al.getGapCharacter());
323
324     /*
325      * look for exon features of the transcript, failing that for CDS
326      * (for example ENSG00000124610 has 1 CDS but no exon features)
327      */
328     String parentId = "transcript:" + accId;
329     List<SequenceFeature> splices = findFeatures(gene,
330             SequenceOntologyI.EXON, parentId);
331     if (splices.isEmpty())
332     {
333       splices = findFeatures(gene, SequenceOntologyI.CDS, parentId);
334     }
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.getSequenceFeatures(),
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     SequenceFeature[] sfs = geneSequence.getSequenceFeatures();
426
427     if (sfs != null)
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
442     return transcriptFeatures;
443   }
444
445   @Override
446   public String getDescription()
447   {
448     return "Fetches all transcripts and variant features for a gene or transcript";
449   }
450
451   /**
452    * Default test query is a gene id (can also enter a transcript id)
453    */
454   @Override
455   public String getTestQuery()
456   {
457     return "ENSG00000157764"; // BRAF, 5 transcripts, reverse strand
458     // ENSG00000090266 // NDUFB2, 15 transcripts, forward strand
459     // ENSG00000101812 // H2BFM histone, 3 transcripts, forward strand
460     // ENSG00000123569 // H2BFWT histone, 2 transcripts, reverse strand
461   }
462
463   /**
464    * Answers true for a feature of type 'gene' (or a sub-type of gene in the
465    * Sequence Ontology), whose ID is the accession we are retrieving
466    */
467   @Override
468   protected boolean identifiesSequence(SequenceFeature sf, String accId)
469   {
470     if (SequenceOntologyFactory.getInstance().isA(sf.getType(),
471             SequenceOntologyI.GENE))
472     {
473       String id = (String) sf.getValue(ID);
474       if ((GENE_PREFIX + accId).equals(id))
475       {
476         return true;
477       }
478     }
479     return false;
480   }
481
482   /**
483    * Answers true unless feature type is 'gene', or 'transcript' with a parent
484    * which is a different gene. We need the gene features to identify the range,
485    * but it is redundant information on the gene sequence. Checking the parent
486    * allows us to drop transcript features which belong to different
487    * (overlapping) genes.
488    */
489   @Override
490   protected boolean retainFeature(SequenceFeature sf, String accessionId)
491   {
492     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
493     String type = sf.getType();
494     if (so.isA(type, SequenceOntologyI.GENE))
495     {
496       return false;
497     }
498     if (isTranscript(type))
499     {
500       String parent = (String) sf.getValue(PARENT);
501       if (!(GENE_PREFIX + accessionId).equals(parent))
502       {
503         return false;
504       }
505     }
506     return true;
507   }
508
509   /**
510    * Answers false. This allows an optimisation - a single 'gene' feature is all
511    * that is needed to identify the positions of the gene on the genomic
512    * sequence.
513    */
514   @Override
515   protected boolean isSpliceable()
516   {
517     return false;
518   }
519
520   /**
521    * Override to do nothing as Ensembl doesn't return a protein sequence for a
522    * gene identifier
523    */
524   @Override
525   protected void addProteinProduct(SequenceI querySeq)
526   {
527   }
528
529   @Override
530   public Regex getAccessionValidator()
531   {
532     return ACCESSION_REGEX;
533   }
534
535   /**
536    * Returns a descriptor for suitable feature display settings with
537    * <ul>
538    * <li>only exon or sequence_variant features (or their subtypes in the
539    * Sequence Ontology) visible</li>
540    * <li>variant features coloured red</li>
541    * <li>exon features coloured by label (exon name)</li>
542    * <li>variants displayed above (on top of) exons</li>
543    * </ul>
544    */
545   @Override
546   public FeatureSettingsModelI getFeatureColourScheme()
547   {
548     return new FeatureSettingsAdapter()
549     {
550       SequenceOntologyI so = SequenceOntologyFactory.getInstance();
551
552       @Override
553       public boolean isFeatureDisplayed(String type)
554       {
555         return (so.isA(type, SequenceOntologyI.EXON) || so.isA(type,
556                 SequenceOntologyI.SEQUENCE_VARIANT));
557       }
558
559       @Override
560       public FeatureColourI getFeatureColour(String type)
561       {
562         if (so.isA(type, SequenceOntologyI.EXON))
563         {
564           return new FeatureColour()
565           {
566             @Override
567             public boolean isColourByLabel()
568             {
569               return true;
570             }
571           };
572         }
573         if (so.isA(type, SequenceOntologyI.SEQUENCE_VARIANT))
574         {
575           return new FeatureColour()
576           {
577
578             @Override
579             public Color getColour()
580             {
581               return Color.RED;
582             }
583           };
584         }
585         return null;
586       }
587
588       /**
589        * order to render sequence_variant after exon after the rest
590        */
591       @Override
592       public int compare(String feature1, String feature2)
593       {
594         if (so.isA(feature1, SequenceOntologyI.SEQUENCE_VARIANT))
595         {
596           return +1;
597         }
598         if (so.isA(feature2, SequenceOntologyI.SEQUENCE_VARIANT))
599         {
600           return -1;
601         }
602         if (so.isA(feature1, SequenceOntologyI.EXON))
603         {
604           return +1;
605         }
606         if (so.isA(feature2, SequenceOntologyI.EXON))
607         {
608           return -1;
609         }
610         return 0;
611       }
612     };
613   }
614
615 }