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