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