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