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