115ecd43de4a7cb977fb49674be0e5406d9a91c7
[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 or transcript
209    * identifiers, into a non-redundant list of gene identifiers.
210    * 
211    * @param accessions
212    * @return
213    */
214   List<String> getGeneIds(String accessions)
215   {
216     List<String> geneIds = new ArrayList<String>();
217
218     for (String acc : accessions.split(getAccessionSeparator()))
219     {
220       if (isGeneIdentifier(acc))
221       {
222         if (!geneIds.contains(acc))
223         {
224           geneIds.add(acc);
225         }
226       }
227
228       /*
229        * if given a transcript id, look up its gene parent
230        */
231       else if (isTranscriptIdentifier(acc))
232       {
233         String geneId = new EnsemblLookup(getDomain()).getParent(acc);
234         if (geneId != null && !geneIds.contains(geneId))
235         {
236           geneIds.add(geneId);
237         }
238       }
239       else if (isProteinIdentifier(acc))
240       {
241         String tscriptId = new EnsemblLookup(getDomain()).getParent(acc);
242         if (tscriptId != null)
243         {
244           String geneId = new EnsemblLookup(getDomain())
245                   .getParent(tscriptId);
246
247           if (geneId != null && !geneIds.contains(geneId))
248           {
249             geneIds.add(geneId);
250           }
251         }
252         // NOTE - acc is lost if it resembles an ENS.+ ID but isn't actually
253         // resolving to one... e.g. ENSMICP00000009241
254       }
255       /*
256        * if given a gene or other external name, lookup and fetch 
257        * the corresponding gene for all model organisms 
258        */
259       else
260       {
261         List<String> ids = new EnsemblSymbol(getDomain(), getDbSource(),
262                 getDbVersion()).getIds(acc);
263         for (String geneId : ids)
264         {
265           if (!geneIds.contains(geneId))
266           {
267             geneIds.add(geneId);
268           }
269         }
270       }
271     }
272     return geneIds;
273   }
274
275   /**
276    * Attempts to get Ensembl stable identifiers for model organisms for a gene
277    * name by calling the xrefs symbol REST service to resolve the gene name.
278    * 
279    * @param query
280    * @return
281    */
282   protected String getGeneIdentifiersForName(String query)
283   {
284     List<String> ids = new EnsemblSymbol(getDomain(), getDbSource(),
285             getDbVersion()).getIds(query);
286     if (ids != null)
287     {
288       for (String id : ids)
289       {
290         if (isGeneIdentifier(id))
291         {
292           return id;
293         }
294       }
295     }
296     return null;
297   }
298
299   /**
300    * Constructs all transcripts for the gene, as identified by "transcript"
301    * features whose Parent is the requested gene. The coding transcript
302    * sequences (i.e. with introns omitted) are added to the alignment.
303    * 
304    * @param al
305    * @param accId
306    * @throws Exception
307    */
308   protected void getTranscripts(AlignmentI al, String accId)
309           throws Exception
310   {
311     SequenceI gene = al.getSequenceAt(0);
312     List<SequenceFeature> transcriptFeatures = getTranscriptFeatures(accId,
313             gene);
314
315     for (SequenceFeature transcriptFeature : transcriptFeatures)
316     {
317       makeTranscript(transcriptFeature, al, gene);
318     }
319
320     clearGeneFeatures(gene);
321   }
322
323   /**
324    * Remove unwanted features (transcript, exon, CDS) from the gene sequence
325    * after we have used them to derive transcripts and transfer features
326    * 
327    * @param gene
328    */
329   protected void clearGeneFeatures(SequenceI gene)
330   {
331     /*
332      * Note we include NMD_transcript_variant here because it behaves like 
333      * 'transcript' in Ensembl, although strictly speaking it is not 
334      * (it is a sub-type of sequence_variant)    
335      */
336     String[] soTerms = new String[] {
337         SequenceOntologyI.NMD_TRANSCRIPT_VARIANT,
338         SequenceOntologyI.TRANSCRIPT, SequenceOntologyI.EXON,
339         SequenceOntologyI.CDS };
340     List<SequenceFeature> sfs = gene.getFeatures().getFeaturesByOntology(
341             soTerms);
342     for (SequenceFeature sf : sfs)
343     {
344       gene.deleteFeature(sf);
345     }
346   }
347
348   /**
349    * Constructs a spliced transcript sequence by finding 'exon' features for the
350    * given id (or failing that 'CDS'). Copies features on to the new sequence.
351    * 'Aligns' the new sequence against the gene sequence by padding with gaps,
352    * and adds it to the alignment.
353    * 
354    * @param transcriptFeature
355    * @param al
356    *          the alignment to which to add the new sequence
357    * @param gene
358    *          the parent gene sequence, with features
359    * @return
360    */
361   SequenceI makeTranscript(SequenceFeature transcriptFeature, AlignmentI al,
362           SequenceI gene)
363   {
364     String accId = getTranscriptId(transcriptFeature);
365     if (accId == null)
366     {
367       return null;
368     }
369
370     /*
371      * NB we are mapping from gene sequence (not genome), so do not
372      * need to check for reverse strand (gene and transcript sequences 
373      * are in forward sense)
374      */
375
376     /*
377      * make a gene-length sequence filled with gaps
378      * we will fill in the bases for transcript regions
379      */
380     char[] seqChars = new char[gene.getLength()];
381     Arrays.fill(seqChars, al.getGapCharacter());
382
383     /*
384      * look for exon features of the transcript, failing that for CDS
385      * (for example ENSG00000124610 has 1 CDS but no exon features)
386      */
387     String parentId = "transcript:" + accId;
388     List<SequenceFeature> splices = findFeatures(gene,
389             SequenceOntologyI.EXON, parentId);
390     if (splices.isEmpty())
391     {
392       splices = findFeatures(gene, SequenceOntologyI.CDS, parentId);
393     }
394     SequenceFeatures.sortFeatures(splices, true);
395
396     int transcriptLength = 0;
397     final char[] geneChars = gene.getSequence();
398     int offset = gene.getStart(); // to convert to 0-based positions
399     List<int[]> mappedFrom = new ArrayList<int[]>();
400
401     for (SequenceFeature sf : splices)
402     {
403       int start = sf.getBegin() - offset;
404       int end = sf.getEnd() - offset;
405       int spliceLength = end - start + 1;
406       System.arraycopy(geneChars, start, seqChars, start, spliceLength);
407       transcriptLength += spliceLength;
408       mappedFrom.add(new int[] { sf.getBegin(), sf.getEnd() });
409     }
410
411     Sequence transcript = new Sequence(accId, seqChars, 1,
412             transcriptLength);
413
414     /*
415      * Ensembl has gene name as transcript Name
416      * EnsemblGenomes doesn't, but has a url-encoded description field
417      */
418     String description = (String) transcriptFeature.getValue(NAME);
419     if (description == null)
420     {
421       description = (String) transcriptFeature.getValue(DESCRIPTION);
422     }
423     if (description != null)
424     {
425       try
426       {
427         transcript.setDescription(URLDecoder.decode(description, "UTF-8"));
428       } catch (UnsupportedEncodingException e)
429       {
430         e.printStackTrace(); // as if
431       }
432     }
433     transcript.createDatasetSequence();
434
435     al.addSequence(transcript);
436
437     /*
438      * transfer features to the new sequence; we use EnsemblCdna to do this,
439      * to filter out unwanted features types (see method retainFeature)
440      */
441     List<int[]> mapTo = new ArrayList<int[]>();
442     mapTo.add(new int[] { 1, transcriptLength });
443     MapList mapping = new MapList(mappedFrom, mapTo, 1, 1);
444     EnsemblCdna cdna = new EnsemblCdna(getDomain());
445     cdna.transferFeatures(gene.getFeatures().getPositionalFeatures(),
446             transcript.getDatasetSequence(), mapping, parentId);
447
448     mapTranscriptToChromosome(transcript, gene, mapping);
449
450     /*
451      * fetch and save cross-references
452      */
453     cdna.getCrossReferences(transcript);
454
455     /*
456      * and finally fetch the protein product and save as a cross-reference
457      */
458     cdna.addProteinProduct(transcript);
459
460     return transcript;
461   }
462
463   /**
464    * If the gene has a mapping to chromosome coordinates, derive the transcript
465    * chromosome regions and save on the transcript sequence
466    * 
467    * @param transcript
468    * @param gene
469    * @param mapping
470    *          the mapping from gene to transcript positions
471    */
472   protected void mapTranscriptToChromosome(SequenceI transcript,
473           SequenceI gene, MapList mapping)
474   {
475     GeneLociI loci = gene.getGeneLoci();
476     if (loci == null)
477     {
478       return;
479     }
480
481     MapList geneMapping = loci.getMap();
482
483     List<int[]> exons = mapping.getFromRanges();
484     List<int[]> transcriptLoci = new ArrayList<>();
485
486     for (int[] exon : exons)
487     {
488       transcriptLoci.add(geneMapping.locateInTo(exon[0], exon[1]));
489     }
490
491     List<int[]> transcriptRange = Arrays.asList(new int[] {
492         transcript.getStart(), transcript.getEnd() });
493     MapList mapList = new MapList(transcriptRange, transcriptLoci, 1, 1);
494
495     transcript.setGeneLoci(loci.getSpeciesId(), loci.getAssemblyId(),
496             loci.getChromosomeId(), mapList);
497   }
498
499   /**
500    * Returns the 'transcript_id' property of the sequence feature (or null)
501    * 
502    * @param feature
503    * @return
504    */
505   protected String getTranscriptId(SequenceFeature feature)
506   {
507     return (String) feature.getValue("transcript_id");
508   }
509
510   /**
511    * Returns a list of the transcript features on the sequence whose Parent is
512    * the gene for the accession id.
513    * <p>
514    * Transcript features are those of type "transcript", or any of its sub-types
515    * in the Sequence Ontology e.g. "mRNA", "processed_transcript". We also
516    * include "NMD_transcript_variant", because this type behaves like a
517    * transcript identifier in Ensembl, although strictly speaking it is not in
518    * the SO.
519    * 
520    * @param accId
521    * @param geneSequence
522    * @return
523    */
524   protected List<SequenceFeature> getTranscriptFeatures(String accId,
525           SequenceI geneSequence)
526   {
527     List<SequenceFeature> transcriptFeatures = new ArrayList<SequenceFeature>();
528
529     String parentIdentifier = GENE_PREFIX + accId;
530
531     List<SequenceFeature> sfs = geneSequence.getFeatures()
532             .getFeaturesByOntology(SequenceOntologyI.TRANSCRIPT);
533     sfs.addAll(geneSequence.getFeatures().getPositionalFeatures(
534             SequenceOntologyI.NMD_TRANSCRIPT_VARIANT));
535
536     for (SequenceFeature sf : sfs)
537     {
538       String parent = (String) sf.getValue(PARENT);
539       if (parentIdentifier.equals(parent))
540       {
541         transcriptFeatures.add(sf);
542       }
543     }
544
545     return transcriptFeatures;
546   }
547
548   @Override
549   public String getDescription()
550   {
551     return "Fetches all transcripts and variant features for a gene or transcript";
552   }
553
554   /**
555    * Default test query is a gene id (can also enter a transcript id)
556    */
557   @Override
558   public String getTestQuery()
559   {
560     return "ENSG00000157764"; // BRAF, 5 transcripts, reverse strand
561     // ENSG00000090266 // NDUFB2, 15 transcripts, forward strand
562     // ENSG00000101812 // H2BFM histone, 3 transcripts, forward strand
563     // ENSG00000123569 // H2BFWT histone, 2 transcripts, reverse strand
564   }
565
566   /**
567    * Answers true for a feature of type 'gene' (or a sub-type of gene in the
568    * Sequence Ontology), whose ID is the accession we are retrieving
569    */
570   @Override
571   protected boolean identifiesSequence(SequenceFeature sf, String accId)
572   {
573     if (SequenceOntologyFactory.getInstance().isA(sf.getType(),
574             SequenceOntologyI.GENE))
575     {
576       String id = (String) sf.getValue(ID);
577       if ((GENE_PREFIX + accId).equals(id))
578       {
579         return true;
580       }
581     }
582     return false;
583   }
584
585   /**
586    * Answers true unless feature type is 'gene', or 'transcript' with a parent
587    * which is a different gene. We need the gene features to identify the range,
588    * but it is redundant information on the gene sequence. Checking the parent
589    * allows us to drop transcript features which belong to different
590    * (overlapping) genes.
591    */
592   @Override
593   protected boolean retainFeature(SequenceFeature sf, String accessionId)
594   {
595     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
596     String type = sf.getType();
597     if (so.isA(type, SequenceOntologyI.GENE))
598     {
599       return false;
600     }
601     if (isTranscript(type))
602     {
603       String parent = (String) sf.getValue(PARENT);
604       if (!(GENE_PREFIX + accessionId).equals(parent))
605       {
606         return false;
607       }
608     }
609     return true;
610   }
611
612   /**
613    * Answers false. This allows an optimisation - a single 'gene' feature is all
614    * that is needed to identify the positions of the gene on the genomic
615    * sequence.
616    */
617   @Override
618   protected boolean isSpliceable()
619   {
620     return false;
621   }
622
623   /**
624    * Override to do nothing as Ensembl doesn't return a protein sequence for a
625    * gene identifier
626    */
627   @Override
628   protected void addProteinProduct(SequenceI querySeq)
629   {
630   }
631
632   @Override
633   public Regex getAccessionValidator()
634   {
635     return ACCESSION_REGEX;
636   }
637
638   /**
639    * Returns a descriptor for suitable feature display settings with
640    * <ul>
641    * <li>only exon or sequence_variant features (or their subtypes in the
642    * Sequence Ontology) visible</li>
643    * <li>variant features coloured red</li>
644    * <li>exon features coloured by label (exon name)</li>
645    * <li>variants displayed above (on top of) exons</li>
646    * </ul>
647    */
648   @Override
649   public FeatureSettingsModelI getFeatureColourScheme()
650   {
651     return new FeatureSettingsAdapter()
652     {
653       SequenceOntologyI so = SequenceOntologyFactory.getInstance();
654
655       @Override
656       public boolean isFeatureDisplayed(String type)
657       {
658         return (so.isA(type, SequenceOntologyI.EXON)
659                 || so.isA(type, SequenceOntologyI.SEQUENCE_VARIANT));
660       }
661
662       @Override
663       public FeatureColourI getFeatureColour(String type)
664       {
665         if (so.isA(type, SequenceOntologyI.EXON))
666         {
667           return new FeatureColour()
668           {
669             @Override
670             public boolean isColourByLabel()
671             {
672               return true;
673             }
674           };
675         }
676         if (so.isA(type, SequenceOntologyI.SEQUENCE_VARIANT))
677         {
678           return new FeatureColour()
679           {
680
681             @Override
682             public Color getColour()
683             {
684               return Color.RED;
685             }
686           };
687         }
688         return null;
689       }
690
691       /**
692        * order to render sequence_variant after exon after the rest
693        */
694       @Override
695       public int compare(String feature1, String feature2)
696       {
697         if (so.isA(feature1, SequenceOntologyI.SEQUENCE_VARIANT))
698         {
699           return +1;
700         }
701         if (so.isA(feature2, SequenceOntologyI.SEQUENCE_VARIANT))
702         {
703           return -1;
704         }
705         if (so.isA(feature1, SequenceOntologyI.EXON))
706         {
707           return +1;
708         }
709         if (so.isA(feature2, SequenceOntologyI.EXON))
710         {
711           return -1;
712         }
713         return 0;
714       }
715     };
716   }
717
718 }