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