JAL-2738 correct handling of reverse strand genes
[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(Sequence transcript,
430           SequenceI gene, MapList mapping)
431   {
432     GeneLoci loci = ((Sequence) 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       transcriptLoci.add(geneMapping.locateInTo(exon[0], exon[1]));
454     }
455
456     List<int[]> transcriptRange = Arrays.asList(new int[] {
457         transcript.getStart(), transcript.getEnd() });
458     MapList mapList = new MapList(transcriptRange, transcriptLoci, 1, 1);
459     GeneLoci gl = new GeneLoci(loci.species, loci.assembly,
460             loci.chromosome, mapList);
461
462     transcript.setGeneLoci(gl);
463   }
464
465   /**
466    * Returns the 'transcript_id' property of the sequence feature (or null)
467    * 
468    * @param feature
469    * @return
470    */
471   protected String getTranscriptId(SequenceFeature feature)
472   {
473     return (String) feature.getValue("transcript_id");
474   }
475
476   /**
477    * Returns a list of the transcript features on the sequence whose Parent is
478    * the gene for the accession id.
479    * 
480    * @param accId
481    * @param geneSequence
482    * @return
483    */
484   protected List<SequenceFeature> getTranscriptFeatures(String accId,
485           SequenceI geneSequence)
486   {
487     List<SequenceFeature> transcriptFeatures = new ArrayList<SequenceFeature>();
488
489     String parentIdentifier = GENE_PREFIX + accId;
490     // todo optimise here by transcript type!
491     List<SequenceFeature> sfs = geneSequence.getFeatures()
492             .getPositionalFeatures();
493
494     for (SequenceFeature sf : sfs)
495     {
496       if (isTranscript(sf.getType()))
497       {
498         String parent = (String) sf.getValue(PARENT);
499         if (parentIdentifier.equals(parent))
500         {
501           transcriptFeatures.add(sf);
502         }
503       }
504     }
505
506     return transcriptFeatures;
507   }
508
509   @Override
510   public String getDescription()
511   {
512     return "Fetches all transcripts and variant features for a gene or transcript";
513   }
514
515   /**
516    * Default test query is a gene id (can also enter a transcript id)
517    */
518   @Override
519   public String getTestQuery()
520   {
521     return "ENSG00000157764"; // BRAF, 5 transcripts, reverse strand
522     // ENSG00000090266 // NDUFB2, 15 transcripts, forward strand
523     // ENSG00000101812 // H2BFM histone, 3 transcripts, forward strand
524     // ENSG00000123569 // H2BFWT histone, 2 transcripts, reverse strand
525   }
526
527   /**
528    * Answers true for a feature of type 'gene' (or a sub-type of gene in the
529    * Sequence Ontology), whose ID is the accession we are retrieving
530    */
531   @Override
532   protected boolean identifiesSequence(SequenceFeature sf, String accId)
533   {
534     if (SequenceOntologyFactory.getInstance().isA(sf.getType(),
535             SequenceOntologyI.GENE))
536     {
537       String id = (String) sf.getValue(ID);
538       if ((GENE_PREFIX + accId).equals(id))
539       {
540         return true;
541       }
542     }
543     return false;
544   }
545
546   /**
547    * Answers true unless feature type is 'gene', or 'transcript' with a parent
548    * which is a different gene. We need the gene features to identify the range,
549    * but it is redundant information on the gene sequence. Checking the parent
550    * allows us to drop transcript features which belong to different
551    * (overlapping) genes.
552    */
553   @Override
554   protected boolean retainFeature(SequenceFeature sf, String accessionId)
555   {
556     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
557     String type = sf.getType();
558     if (so.isA(type, SequenceOntologyI.GENE))
559     {
560       return false;
561     }
562     if (isTranscript(type))
563     {
564       String parent = (String) sf.getValue(PARENT);
565       if (!(GENE_PREFIX + accessionId).equals(parent))
566       {
567         return false;
568       }
569     }
570     return true;
571   }
572
573   /**
574    * Answers false. This allows an optimisation - a single 'gene' feature is all
575    * that is needed to identify the positions of the gene on the genomic
576    * sequence.
577    */
578   @Override
579   protected boolean isSpliceable()
580   {
581     return false;
582   }
583
584   /**
585    * Override to do nothing as Ensembl doesn't return a protein sequence for a
586    * gene identifier
587    */
588   @Override
589   protected void addProteinProduct(SequenceI querySeq)
590   {
591   }
592
593   @Override
594   public Regex getAccessionValidator()
595   {
596     return ACCESSION_REGEX;
597   }
598
599   /**
600    * Returns a descriptor for suitable feature display settings with
601    * <ul>
602    * <li>only exon or sequence_variant features (or their subtypes in the
603    * Sequence Ontology) visible</li>
604    * <li>variant features coloured red</li>
605    * <li>exon features coloured by label (exon name)</li>
606    * <li>variants displayed above (on top of) exons</li>
607    * </ul>
608    */
609   @Override
610   public FeatureSettingsModelI getFeatureColourScheme()
611   {
612     return new FeatureSettingsAdapter()
613     {
614       SequenceOntologyI so = SequenceOntologyFactory.getInstance();
615
616       @Override
617       public boolean isFeatureDisplayed(String type)
618       {
619         return (so.isA(type, SequenceOntologyI.EXON)
620                 || so.isA(type, SequenceOntologyI.SEQUENCE_VARIANT));
621       }
622
623       @Override
624       public FeatureColourI getFeatureColour(String type)
625       {
626         if (so.isA(type, SequenceOntologyI.EXON))
627         {
628           return new FeatureColour()
629           {
630             @Override
631             public boolean isColourByLabel()
632             {
633               return true;
634             }
635           };
636         }
637         if (so.isA(type, SequenceOntologyI.SEQUENCE_VARIANT))
638         {
639           return new FeatureColour()
640           {
641
642             @Override
643             public Color getColour()
644             {
645               return Color.RED;
646             }
647           };
648         }
649         return null;
650       }
651
652       /**
653        * order to render sequence_variant after exon after the rest
654        */
655       @Override
656       public int compare(String feature1, String feature2)
657       {
658         if (so.isA(feature1, SequenceOntologyI.SEQUENCE_VARIANT))
659         {
660           return +1;
661         }
662         if (so.isA(feature2, SequenceOntologyI.SEQUENCE_VARIANT))
663         {
664           return -1;
665         }
666         if (so.isA(feature1, SequenceOntologyI.EXON))
667         {
668           return +1;
669         }
670         if (so.isA(feature2, SequenceOntologyI.EXON))
671         {
672           return -1;
673         }
674         return 0;
675       }
676     };
677   }
678
679 }