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