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