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