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