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