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