16b858a264324cbf0bacb8717fa6db9e59537eb6
[jalview.git] / src / jalview / ext / ensembl / EnsemblSeqProxy.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.analysis.AlignmentUtils;
24 import jalview.analysis.Dna;
25 import jalview.bin.Cache;
26 import jalview.datamodel.Alignment;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.DBRefEntry;
29 import jalview.datamodel.DBRefSource;
30 import jalview.datamodel.Mapping;
31 import jalview.datamodel.SequenceFeature;
32 import jalview.datamodel.SequenceI;
33 import jalview.exceptions.JalviewException;
34 import jalview.io.FastaFile;
35 import jalview.io.FileParse;
36 import jalview.io.gff.SequenceOntologyFactory;
37 import jalview.io.gff.SequenceOntologyI;
38 import jalview.util.Comparison;
39 import jalview.util.DBRefUtils;
40 import jalview.util.MapList;
41 import jalview.util.RangeComparator;
42
43 import java.io.IOException;
44 import java.net.MalformedURLException;
45 import java.net.URL;
46 import java.util.ArrayList;
47 import java.util.Arrays;
48 import java.util.Collections;
49 import java.util.Comparator;
50 import java.util.List;
51
52 /**
53  * Base class for Ensembl sequence fetchers
54  * 
55  * @see http://rest.ensembl.org/documentation/info/sequence_id
56  * @author gmcarstairs
57  */
58 public abstract class EnsemblSeqProxy extends EnsemblRestClient
59 {
60   private static final String ALLELES = "alleles";
61
62   protected static final String PARENT = "Parent";
63
64   protected static final String ID = "ID";
65
66   protected static final String NAME = "Name";
67
68   protected static final String DESCRIPTION = "description";
69
70   /*
71    * enum for 'type' parameter to the /sequence REST service
72    */
73   public enum EnsemblSeqType
74   {
75     /**
76      * type=genomic to fetch full dna including introns
77      */
78     GENOMIC("genomic"),
79
80     /**
81      * type=cdna to fetch coding dna including UTRs
82      */
83     CDNA("cdna"),
84
85     /**
86      * type=cds to fetch coding dna excluding UTRs
87      */
88     CDS("cds"),
89
90     /**
91      * type=protein to fetch peptide product sequence
92      */
93     PROTEIN("protein");
94
95     /*
96      * the value of the 'type' parameter to fetch this version of 
97      * an Ensembl sequence
98      */
99     private String type;
100
101     EnsemblSeqType(String t)
102     {
103       type = t;
104     }
105
106     public String getType()
107     {
108       return type;
109     }
110
111   }
112
113   /**
114    * Default constructor (to use rest.ensembl.org)
115    */
116   public EnsemblSeqProxy()
117   {
118     super();
119   }
120
121   /**
122    * Constructor given the target domain to fetch data from
123    */
124   public EnsemblSeqProxy(String d)
125   {
126     super(d);
127   }
128
129   /**
130    * Makes the sequence queries to Ensembl's REST service and returns an
131    * alignment consisting of the returned sequences.
132    */
133   @Override
134   public AlignmentI getSequenceRecords(String query) throws Exception
135   {
136     // TODO use a String... query vararg instead?
137
138     // danger: accession separator used as a regex here, a string elsewhere
139     // in this case it is ok (it is just a space), but (e.g.) '\' would not be
140     List<String> allIds = Arrays
141             .asList(query.split(getAccessionSeparator()));
142     AlignmentI alignment = null;
143     inProgress = true;
144
145     /*
146      * execute queries, if necessary in batches of the
147      * maximum allowed number of ids
148      */
149     int maxQueryCount = getMaximumQueryCount();
150     for (int v = 0, vSize = allIds.size(); v < vSize; v += maxQueryCount)
151     {
152       int p = Math.min(vSize, v + maxQueryCount);
153       List<String> ids = allIds.subList(v, p);
154       try
155       {
156         alignment = fetchSequences(ids, alignment);
157       } catch (Throwable r)
158       {
159         inProgress = false;
160         String msg = "Aborting ID retrieval after " + v
161                 + " chunks. Unexpected problem (" + r.getLocalizedMessage()
162                 + ")";
163         System.err.println(msg);
164         r.printStackTrace();
165         break;
166       }
167     }
168
169     if (alignment == null)
170     {
171       return null;
172     }
173
174     /*
175      * fetch and transfer genomic sequence features,
176      * fetch protein product and add as cross-reference
177      */
178     for (String accId : allIds)
179     {
180       addFeaturesAndProduct(accId, alignment);
181     }
182
183     for (SequenceI seq : alignment.getSequences())
184     {
185       getCrossReferences(seq);
186     }
187
188     return alignment;
189   }
190
191   /**
192    * Fetches Ensembl features using the /overlap REST endpoint, and adds them to
193    * the sequence in the alignment. Also fetches the protein product, maps it
194    * from the CDS features of the sequence, and saves it as a cross-reference of
195    * the dna sequence.
196    * 
197    * @param accId
198    * @param alignment
199    */
200   protected void addFeaturesAndProduct(String accId, AlignmentI alignment)
201   {
202     if (alignment == null)
203     {
204       return;
205     }
206
207     try
208     {
209       /*
210        * get 'dummy' genomic sequence with exon, cds and variation features
211        */
212       SequenceI genomicSequence = null;
213       EnsemblFeatures gffFetcher = new EnsemblFeatures(getDomain());
214       EnsemblFeatureType[] features = getFeaturesToFetch();
215       AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
216               features);
217       if (geneFeatures != null && geneFeatures.getHeight() > 0)
218       {
219         genomicSequence = geneFeatures.getSequenceAt(0);
220       }
221       if (genomicSequence != null)
222       {
223         /*
224          * transfer features to the query sequence
225          */
226         SequenceI querySeq = alignment.findName(accId);
227         if (transferFeatures(accId, genomicSequence, querySeq))
228         {
229
230           /*
231            * fetch and map protein product, and add it as a cross-reference
232            * of the retrieved sequence
233            */
234           addProteinProduct(querySeq);
235         }
236       }
237     } catch (IOException e)
238     {
239       System.err.println(
240               "Error transferring Ensembl features: " + e.getMessage());
241     }
242   }
243
244   /**
245    * Returns those sequence feature types to fetch from Ensembl. We may want
246    * features either because they are of interest to the user, or as means to
247    * identify the locations of the sequence on the genomic sequence (CDS
248    * features identify CDS, exon features identify cDNA etc).
249    * 
250    * @return
251    */
252   protected abstract EnsemblFeatureType[] getFeaturesToFetch();
253
254   /**
255    * Fetches and maps the protein product, and adds it as a cross-reference of
256    * the retrieved sequence
257    */
258   protected void addProteinProduct(SequenceI querySeq)
259   {
260     String accId = querySeq.getName();
261     try
262     {
263       AlignmentI protein = new EnsemblProtein(getDomain())
264               .getSequenceRecords(accId);
265       if (protein == null || protein.getHeight() == 0)
266       {
267         System.out.println("No protein product found for " + accId);
268         return;
269       }
270       SequenceI proteinSeq = protein.getSequenceAt(0);
271
272       /*
273        * need dataset sequences (to be the subject of mappings)
274        */
275       proteinSeq.createDatasetSequence();
276       querySeq.createDatasetSequence();
277
278       MapList mapList = AlignmentUtils.mapCdsToProtein(querySeq,
279               proteinSeq);
280       if (mapList != null)
281       {
282         // clunky: ensure Uniprot xref if we have one is on mapped sequence
283         SequenceI ds = proteinSeq.getDatasetSequence();
284         // TODO: Verify ensp primary ref is on proteinSeq.getDatasetSequence()
285         Mapping map = new Mapping(ds, mapList);
286         DBRefEntry dbr = new DBRefEntry(getDbSource(),
287                 getEnsemblDataVersion(), proteinSeq.getName(), map);
288         querySeq.getDatasetSequence().addDBRef(dbr);
289         DBRefEntry[] uprots = DBRefUtils.selectRefs(ds.getDBRefs(),
290                 new String[]
291                 { DBRefSource.UNIPROT });
292         DBRefEntry[] upxrefs = DBRefUtils.selectRefs(querySeq.getDBRefs(),
293                 new String[]
294                 { DBRefSource.UNIPROT });
295         if (uprots != null)
296         {
297           for (DBRefEntry up : uprots)
298           {
299             // locate local uniprot ref and map
300             List<DBRefEntry> upx = DBRefUtils.searchRefs(upxrefs,
301                     up.getAccessionId());
302             DBRefEntry upxref;
303             if (upx.size() != 0)
304             {
305               upxref = upx.get(0);
306
307               if (upx.size() > 1)
308               {
309                 Cache.log.warn(
310                         "Implementation issue - multiple uniprot acc on product sequence.");
311               }
312             }
313             else
314             {
315               upxref = new DBRefEntry(DBRefSource.UNIPROT,
316                       getEnsemblDataVersion(), up.getAccessionId());
317             }
318
319             Mapping newMap = new Mapping(ds, mapList);
320             upxref.setVersion(getEnsemblDataVersion());
321             upxref.setMap(newMap);
322             if (upx.size() == 0)
323             {
324               // add the new uniprot ref
325               querySeq.getDatasetSequence().addDBRef(upxref);
326             }
327
328           }
329         }
330
331         /*
332          * copy exon features to protein, compute peptide variants from dna 
333          * variants and add as features on the protein sequence ta-da
334          */
335         AlignmentUtils.computeProteinFeatures(querySeq, proteinSeq,
336                 mapList);
337       }
338     } catch (Exception e)
339     {
340       System.err
341               .println(String.format("Error retrieving protein for %s: %s",
342                       accId, e.getMessage()));
343     }
344   }
345
346   /**
347    * Get database xrefs from Ensembl, and attach them to the sequence
348    * 
349    * @param seq
350    */
351   protected void getCrossReferences(SequenceI seq)
352   {
353     while (seq.getDatasetSequence() != null)
354     {
355       seq = seq.getDatasetSequence();
356     }
357
358     EnsemblXref xrefFetcher = new EnsemblXref(getDomain(), getDbSource(),
359             getEnsemblDataVersion());
360     List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName());
361     for (DBRefEntry xref : xrefs)
362     {
363       seq.addDBRef(xref);
364     }
365
366     /*
367      * and add a reference to itself
368      */
369     DBRefEntry self = new DBRefEntry(getDbSource(), getEnsemblDataVersion(),
370             seq.getName());
371     seq.addDBRef(self);
372   }
373
374   /**
375    * Fetches sequences for the list of accession ids and adds them to the
376    * alignment. Returns the extended (or created) alignment.
377    * 
378    * @param ids
379    * @param alignment
380    * @return
381    * @throws JalviewException
382    * @throws IOException
383    */
384   protected AlignmentI fetchSequences(List<String> ids,
385           AlignmentI alignment) throws JalviewException, IOException
386   {
387     if (!isEnsemblAvailable())
388     {
389       inProgress = false;
390       throw new JalviewException("ENSEMBL Rest API not available.");
391     }
392     FileParse fp = getSequenceReader(ids);
393     if (fp == null)
394     {
395       return alignment;
396     }
397
398     FastaFile fr = new FastaFile(fp);
399     if (fr.hasWarningMessage())
400     {
401       System.out.println(
402               String.format("Warning when retrieving %d ids %s\n%s",
403                       ids.size(), ids.toString(), fr.getWarningMessage()));
404     }
405     else if (fr.getSeqs().size() != ids.size())
406     {
407       System.out.println(String.format(
408               "Only retrieved %d sequences for %d query strings",
409               fr.getSeqs().size(), ids.size()));
410     }
411
412     if (fr.getSeqs().size() == 1 && fr.getSeqs().get(0).getLength() == 0)
413     {
414       /*
415        * POST request has returned an empty FASTA file e.g. for invalid id
416        */
417       throw new IOException("No data returned for " + ids);
418     }
419
420     if (fr.getSeqs().size() > 0)
421     {
422       AlignmentI seqal = new Alignment(fr.getSeqsAsArray());
423       for (SequenceI sq : seqal.getSequences())
424       {
425         if (sq.getDescription() == null)
426         {
427           sq.setDescription(getDbName());
428         }
429         String name = sq.getName();
430         if (ids.contains(name)
431                 || ids.contains(name.replace("ENSP", "ENST")))
432         {
433           DBRefEntry dbref = DBRefUtils.parseToDbRef(sq, getDbSource(),
434                   getEnsemblDataVersion(), name);
435           sq.addDBRef(dbref);
436         }
437       }
438       if (alignment == null)
439       {
440         alignment = seqal;
441       }
442       else
443       {
444         alignment.append(seqal);
445       }
446     }
447     return alignment;
448   }
449
450   /**
451    * Returns the URL for the REST call
452    * 
453    * @return
454    * @throws MalformedURLException
455    */
456   @Override
457   protected URL getUrl(List<String> ids) throws MalformedURLException
458   {
459     /*
460      * a single id is included in the URL path
461      * multiple ids go in the POST body instead
462      */
463     StringBuffer urlstring = new StringBuffer(128);
464     urlstring.append(getDomain() + "/sequence/id");
465     if (ids.size() == 1)
466     {
467       urlstring.append("/").append(ids.get(0));
468     }
469     // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
470     urlstring.append("?type=").append(getSourceEnsemblType().getType());
471     urlstring.append(("&Accept=text/x-fasta"));
472
473     URL url = new URL(urlstring.toString());
474     return url;
475   }
476
477   /**
478    * A sequence/id POST request currently allows up to 50 queries
479    * 
480    * @see http://rest.ensembl.org/documentation/info/sequence_id_post
481    */
482   @Override
483   public int getMaximumQueryCount()
484   {
485     return 50;
486   }
487
488   @Override
489   protected boolean useGetRequest()
490   {
491     return false;
492   }
493
494   @Override
495   protected String getRequestMimeType(boolean multipleIds)
496   {
497     return multipleIds ? "application/json" : "text/x-fasta";
498   }
499
500   @Override
501   protected String getResponseMimeType()
502   {
503     return "text/x-fasta";
504   }
505
506   /**
507    * 
508    * @return the configured sequence return type for this source
509    */
510   protected abstract EnsemblSeqType getSourceEnsemblType();
511
512   /**
513    * Returns a list of [start, end] genomic ranges corresponding to the sequence
514    * being retrieved.
515    * 
516    * The correspondence between the frames of reference is made by locating
517    * those features on the genomic sequence which identify the retrieved
518    * sequence. Specifically
519    * <ul>
520    * <li>genomic sequence is identified by "transcript" features with
521    * ID=transcript:transcriptId</li>
522    * <li>cdna sequence is identified by "exon" features with
523    * Parent=transcript:transcriptId</li>
524    * <li>cds sequence is identified by "CDS" features with
525    * Parent=transcript:transcriptId</li>
526    * </ul>
527    * 
528    * The returned ranges are sorted to run forwards (for positive strand) or
529    * backwards (for negative strand). Aborts and returns null if both positive
530    * and negative strand are found (this should not normally happen).
531    * 
532    * @param sourceSequence
533    * @param accId
534    * @param start
535    *          the start position of the sequence we are mapping to
536    * @return
537    */
538   protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
539           String accId, int start)
540   {
541     SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
542     if (sfs == null)
543     {
544       return null;
545     }
546
547     /*
548      * generously initial size for number of cds regions
549      * (worst case titin Q8WZ42 has c. 313 exons)
550      */
551     List<int[]> regions = new ArrayList<int[]>(100);
552     int mappedLength = 0;
553     int direction = 1; // forward
554     boolean directionSet = false;
555
556     for (SequenceFeature sf : sfs)
557     {
558       /*
559        * accept the target feature type or a specialisation of it
560        * (e.g. coding_exon for exon)
561        */
562       if (identifiesSequence(sf, accId))
563       {
564         int strand = sf.getStrand();
565         strand = strand == 0 ? 1 : strand; // treat unknown as forward
566
567         if (directionSet && strand != direction)
568         {
569           // abort - mix of forward and backward
570           System.err.println(
571                   "Error: forward and backward strand for " + accId);
572           return null;
573         }
574         direction = strand;
575         directionSet = true;
576
577         /*
578          * add to CDS ranges, semi-sorted forwards/backwards
579          */
580         if (strand < 0)
581         {
582           regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
583         }
584         else
585         {
586           regions.add(new int[] { sf.getBegin(), sf.getEnd() });
587         }
588         mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
589
590         if (!isSpliceable())
591         {
592           /*
593            * 'gene' sequence is contiguous so we can stop as soon as its
594            * identifying feature has been found
595            */
596           break;
597         }
598       }
599     }
600
601     if (regions.isEmpty())
602     {
603       System.out.println("Failed to identify target sequence for " + accId
604               + " from genomic features");
605       return null;
606     }
607
608     /*
609      * a final sort is needed since Ensembl returns CDS sorted within source
610      * (havana / ensembl_havana)
611      */
612     Collections.sort(regions, new RangeComparator(direction == 1));
613
614     List<int[]> to = Arrays
615             .asList(new int[]
616             { start, start + mappedLength - 1 });
617
618     return new MapList(regions, to, 1, 1);
619   }
620
621   /**
622    * Answers true if the sequence being retrieved may occupy discontiguous
623    * regions on the genomic sequence.
624    */
625   protected boolean isSpliceable()
626   {
627     return true;
628   }
629
630   /**
631    * Returns true if the sequence feature marks positions of the genomic
632    * sequence feature which are within the sequence being retrieved. For
633    * example, an 'exon' feature whose parent is the target transcript marks the
634    * cdna positions of the transcript.
635    * 
636    * @param sf
637    * @param accId
638    * @return
639    */
640   protected abstract boolean identifiesSequence(SequenceFeature sf,
641           String accId);
642
643   /**
644    * Transfers the sequence feature to the target sequence, locating its start
645    * and end range based on the mapping. Features which do not overlap the
646    * target sequence are ignored.
647    * 
648    * @param sf
649    * @param targetSequence
650    * @param mapping
651    *          mapping from the sequence feature's coordinates to the target
652    *          sequence
653    * @param forwardStrand
654    */
655   protected void transferFeature(SequenceFeature sf,
656           SequenceI targetSequence, MapList mapping, boolean forwardStrand)
657   {
658     int start = sf.getBegin();
659     int end = sf.getEnd();
660     int[] mappedRange = mapping.locateInTo(start, end);
661
662     if (mappedRange != null)
663     {
664       SequenceFeature copy = new SequenceFeature(sf);
665       copy.setBegin(Math.min(mappedRange[0], mappedRange[1]));
666       copy.setEnd(Math.max(mappedRange[0], mappedRange[1]));
667       if (".".equals(copy.getFeatureGroup()))
668       {
669         copy.setFeatureGroup(getDbSource());
670       }
671       targetSequence.addSequenceFeature(copy);
672
673       /*
674        * for sequence_variant on reverse strand, have to convert the allele
675        * values to their complements
676        */
677       if (!forwardStrand && SequenceOntologyFactory.getInstance()
678               .isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
679       {
680         reverseComplementAlleles(copy);
681       }
682     }
683   }
684
685   /**
686    * Change the 'alleles' value of a feature by converting to complementary
687    * bases, and also update the feature description to match
688    * 
689    * @param sf
690    */
691   static void reverseComplementAlleles(SequenceFeature sf)
692   {
693     final String alleles = (String) sf.getValue(ALLELES);
694     if (alleles == null)
695     {
696       return;
697     }
698     StringBuilder complement = new StringBuilder(alleles.length());
699     for (String allele : alleles.split(","))
700     {
701       reverseComplementAllele(complement, allele);
702     }
703     String comp = complement.toString();
704     sf.setValue(ALLELES, comp);
705     sf.setDescription(comp);
706
707     /*
708      * replace value of "alleles=" in sf.ATTRIBUTES as well
709      * so 'output as GFF' shows reverse complement alleles
710      */
711     String atts = sf.getAttributes();
712     if (atts != null)
713     {
714       atts = atts.replace(ALLELES + "=" + alleles, ALLELES + "=" + comp);
715       sf.setAttributes(atts);
716     }
717   }
718
719   /**
720    * Makes the 'reverse complement' of the given allele and appends it to the
721    * buffer, after a comma separator if not the first
722    * 
723    * @param complement
724    * @param allele
725    */
726   static void reverseComplementAllele(StringBuilder complement,
727           String allele)
728   {
729     if (complement.length() > 0)
730     {
731       complement.append(",");
732     }
733
734     /*
735      * some 'alleles' are actually descriptive terms 
736      * e.g. HGMD_MUTATION, PhenCode_variation
737      * - we don't want to 'reverse complement' these
738      */
739     if (!Comparison.isNucleotideSequence(allele, true))
740     {
741       complement.append(allele);
742     }
743     else
744     {
745       for (int i = allele.length() - 1; i >= 0; i--)
746       {
747         complement.append(Dna.getComplement(allele.charAt(i)));
748       }
749     }
750   }
751
752   /**
753    * Transfers features from sourceSequence to targetSequence
754    * 
755    * @param accessionId
756    * @param sourceSequence
757    * @param targetSequence
758    * @return true if any features were transferred, else false
759    */
760   protected boolean transferFeatures(String accessionId,
761           SequenceI sourceSequence, SequenceI targetSequence)
762   {
763     if (sourceSequence == null || targetSequence == null)
764     {
765       return false;
766     }
767
768     // long start = System.currentTimeMillis();
769     SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
770     MapList mapping = getGenomicRangesFromFeatures(sourceSequence,
771             accessionId, targetSequence.getStart());
772     if (mapping == null)
773     {
774       return false;
775     }
776
777     boolean result = transferFeatures(sfs, targetSequence, mapping,
778             accessionId);
779     // System.out.println("transferFeatures (" + (sfs.length) + " --> "
780     // + targetSequence.getSequenceFeatures().length + ") to "
781     // + targetSequence.getName()
782     // + " took " + (System.currentTimeMillis() - start) + "ms");
783     return result;
784   }
785
786   /**
787    * Transfer features to the target sequence. The start/end positions are
788    * converted using the mapping. Features which do not overlap are ignored.
789    * Features whose parent is not the specified identifier are also ignored.
790    * 
791    * @param features
792    * @param targetSequence
793    * @param mapping
794    * @param parentId
795    * @return
796    */
797   protected boolean transferFeatures(SequenceFeature[] features,
798           SequenceI targetSequence, MapList mapping, String parentId)
799   {
800     final boolean forwardStrand = mapping.isFromForwardStrand();
801
802     /*
803      * sort features by start position (which corresponds to end
804      * position descending if reverse strand) so as to add them in
805      * 'forwards' order to the target sequence
806      */
807     sortFeatures(features, forwardStrand);
808
809     boolean transferred = false;
810     for (SequenceFeature sf : features)
811     {
812       if (retainFeature(sf, parentId))
813       {
814         transferFeature(sf, targetSequence, mapping, forwardStrand);
815         transferred = true;
816       }
817     }
818     return transferred;
819   }
820
821   /**
822    * Sort features by start position ascending (if on forward strand), or end
823    * position descending (if on reverse strand)
824    * 
825    * @param features
826    * @param forwardStrand
827    */
828   protected static void sortFeatures(SequenceFeature[] features,
829           final boolean forwardStrand)
830   {
831     Arrays.sort(features, new Comparator<SequenceFeature>()
832     {
833       @Override
834       public int compare(SequenceFeature o1, SequenceFeature o2)
835       {
836         if (forwardStrand)
837         {
838           return Integer.compare(o1.getBegin(), o2.getBegin());
839         }
840         else
841         {
842           return Integer.compare(o2.getEnd(), o1.getEnd());
843         }
844       }
845     });
846   }
847
848   /**
849    * Answers true if the feature type is one we want to keep for the sequence.
850    * Some features are only retrieved in order to identify the sequence range,
851    * and may then be discarded as redundant information (e.g. "CDS" feature for
852    * a CDS sequence).
853    */
854   @SuppressWarnings("unused")
855   protected boolean retainFeature(SequenceFeature sf, String accessionId)
856   {
857     return true; // override as required
858   }
859
860   /**
861    * Answers true if the feature has a Parent which refers to the given
862    * accession id, or if the feature has no parent. Answers false if the
863    * feature's Parent is for a different accession id.
864    * 
865    * @param sf
866    * @param identifier
867    * @return
868    */
869   protected boolean featureMayBelong(SequenceFeature sf, String identifier)
870   {
871     String parent = (String) sf.getValue(PARENT);
872     // using contains to allow for prefix "gene:", "transcript:" etc
873     if (parent != null && !parent.contains(identifier))
874     {
875       // this genomic feature belongs to a different transcript
876       return false;
877     }
878     return true;
879   }
880
881   @Override
882   public String getDescription()
883   {
884     return "Ensembl " + getSourceEnsemblType().getType()
885             + " sequence with variant features";
886   }
887
888   /**
889    * Returns a (possibly empty) list of features on the sequence which have the
890    * specified sequence ontology type (or a sub-type of it), and the given
891    * identifier as parent
892    * 
893    * @param sequence
894    * @param type
895    * @param parentId
896    * @return
897    */
898   protected List<SequenceFeature> findFeatures(SequenceI sequence,
899           String type, String parentId)
900   {
901     List<SequenceFeature> result = new ArrayList<SequenceFeature>();
902
903     SequenceFeature[] sfs = sequence.getSequenceFeatures();
904     if (sfs != null)
905     {
906       SequenceOntologyI so = SequenceOntologyFactory.getInstance();
907       for (SequenceFeature sf : sfs)
908       {
909         if (so.isA(sf.getType(), type))
910         {
911           String parent = (String) sf.getValue(PARENT);
912           if (parent.equals(parentId))
913           {
914             result.add(sf);
915           }
916         }
917       }
918     }
919     return result;
920   }
921
922   /**
923    * Answers true if the feature type is either 'NMD_transcript_variant' or
924    * 'transcript' or one of its sub-types in the Sequence Ontology. This is
925    * needed because NMD_transcript_variant behaves like 'transcript' in Ensembl
926    * although strictly speaking it is not (it is a sub-type of
927    * sequence_variant).
928    * 
929    * @param featureType
930    * @return
931    */
932   public static boolean isTranscript(String featureType)
933   {
934     return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
935             || SequenceOntologyFactory.getInstance().isA(featureType,
936                     SequenceOntologyI.TRANSCRIPT);
937   }
938 }