Clover icon

Coverage Report

  1. Project Clover database Thu Aug 13 2020 12:04:21 BST
  2. Package jalview.ext.ensembl

File EnsemblGene.java

 

Coverage histogram

../../../img/srcFileCovDistChart3.png
47% of files have more coverage

Code metrics

56
161
28
1
693
407
59
0.37
5.75
28
2.11

Classes

Class Line # Actions
EnsemblGene 52 161 59
0.2938775429.4%
 

Contributing tests

This file is covered by 103 tests. .

Source view

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