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