Merge branch 'develop' into features/JAL-2295setChimeraAttributes
[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.asList(query
141             .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("Error transferring Ensembl features: "
240               + 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
279               .mapCdsToProtein(querySeq, 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[] { DBRefSource.UNIPROT });
291         DBRefEntry[] upxrefs = DBRefUtils.selectRefs(querySeq.getDBRefs(),
292                 new String[] { DBRefSource.UNIPROT });
293         if (uprots != null)
294         {
295           for (DBRefEntry up : uprots)
296           {
297             // locate local uniprot ref and map
298             List<DBRefEntry> upx = DBRefUtils.searchRefs(upxrefs,
299                     up.getAccessionId());
300             DBRefEntry upxref;
301             if (upx.size() != 0)
302             {
303               upxref = upx.get(0);
304
305               if (upx.size() > 1)
306               {
307                 Cache.log
308                         .warn("Implementation issue - multiple uniprot acc on product sequence.");
309               }
310             }
311             else
312             {
313               upxref = new DBRefEntry(DBRefSource.UNIPROT,
314                       getEnsemblDataVersion(), up.getAccessionId());
315             }
316
317             Mapping newMap = new Mapping(ds, mapList);
318             upxref.setVersion(getEnsemblDataVersion());
319             upxref.setMap(newMap);
320             if (upx.size() == 0)
321             {
322               // add the new uniprot ref
323               querySeq.getDatasetSequence().addDBRef(upxref);
324             }
325
326           }
327         }
328
329         /*
330          * copy exon features to protein, compute peptide variants from dna 
331          * variants and add as features on the protein sequence ta-da
332          */
333         AlignmentUtils
334                 .computeProteinFeatures(querySeq, proteinSeq, mapList);
335       }
336     } catch (Exception e)
337     {
338       System.err
339               .println(String.format("Error retrieving protein for %s: %s",
340                       accId, e.getMessage()));
341     }
342   }
343
344   /**
345    * Get database xrefs from Ensembl, and attach them to the sequence
346    * 
347    * @param seq
348    */
349   protected void getCrossReferences(SequenceI seq)
350   {
351     while (seq.getDatasetSequence() != null)
352     {
353       seq = seq.getDatasetSequence();
354     }
355
356     EnsemblXref xrefFetcher = new EnsemblXref(getDomain(), getDbSource(),
357             getEnsemblDataVersion());
358     List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName());
359     for (DBRefEntry xref : xrefs)
360     {
361       seq.addDBRef(xref);
362     }
363
364     /*
365      * and add a reference to itself
366      */
367     DBRefEntry self = new DBRefEntry(getDbSource(),
368             getEnsemblDataVersion(), seq.getName());
369     seq.addDBRef(self);
370   }
371
372   /**
373    * Fetches sequences for the list of accession ids and adds them to the
374    * alignment. Returns the extended (or created) alignment.
375    * 
376    * @param ids
377    * @param alignment
378    * @return
379    * @throws JalviewException
380    * @throws IOException
381    */
382   protected AlignmentI fetchSequences(List<String> ids, AlignmentI alignment)
383           throws JalviewException, IOException
384   {
385     if (!isEnsemblAvailable())
386     {
387       inProgress = false;
388       throw new JalviewException("ENSEMBL Rest API not available.");
389     }
390     FileParse fp = getSequenceReader(ids);
391     if (fp == null)
392     {
393       return alignment;
394     }
395
396     FastaFile fr = new FastaFile(fp);
397     if (fr.hasWarningMessage())
398     {
399       System.out.println(String.format(
400               "Warning when retrieving %d ids %s\n%s", ids.size(),
401               ids.toString(), fr.getWarningMessage()));
402     }
403     else if (fr.getSeqs().size() != ids.size())
404     {
405       System.out.println(String.format(
406               "Only retrieved %d sequences for %d query strings", fr
407                       .getSeqs().size(), ids.size()));
408     }
409
410     if (fr.getSeqs().size() == 1 && fr.getSeqs().get(0).getLength() == 0)
411     {
412       /*
413        * POST request has returned an empty FASTA file e.g. for invalid id
414        */
415       throw new IOException("No data returned for " + ids);
416     }
417
418     if (fr.getSeqs().size() > 0)
419     {
420       AlignmentI seqal = new Alignment(fr.getSeqsAsArray());
421       for (SequenceI sq : seqal.getSequences())
422       {
423         if (sq.getDescription() == null)
424         {
425           sq.setDescription(getDbName());
426         }
427         String name = sq.getName();
428         if (ids.contains(name)
429                 || ids.contains(name.replace("ENSP", "ENST")))
430         {
431           DBRefEntry dbref = DBRefUtils.parseToDbRef(sq, getDbSource(),
432                   getEnsemblDataVersion(), name);
433           sq.addDBRef(dbref);
434         }
435       }
436       if (alignment == null)
437       {
438         alignment = seqal;
439       }
440       else
441       {
442         alignment.append(seqal);
443       }
444     }
445     return alignment;
446   }
447
448   /**
449    * Returns the URL for the REST call
450    * 
451    * @return
452    * @throws MalformedURLException
453    */
454   @Override
455   protected URL getUrl(List<String> ids) throws MalformedURLException
456   {
457     /*
458      * a single id is included in the URL path
459      * multiple ids go in the POST body instead
460      */
461     StringBuffer urlstring = new StringBuffer(128);
462     urlstring.append(getDomain() + "/sequence/id");
463     if (ids.size() == 1)
464     {
465       urlstring.append("/").append(ids.get(0));
466     }
467     // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
468     urlstring.append("?type=").append(getSourceEnsemblType().getType());
469     urlstring.append(("&Accept=text/x-fasta"));
470
471     URL url = new URL(urlstring.toString());
472     return url;
473   }
474
475   /**
476    * A sequence/id POST request currently allows up to 50 queries
477    * 
478    * @see http://rest.ensembl.org/documentation/info/sequence_id_post
479    */
480   @Override
481   public int getMaximumQueryCount()
482   {
483     return 50;
484   }
485
486   @Override
487   protected boolean useGetRequest()
488   {
489     return false;
490   }
491
492   @Override
493   protected String getRequestMimeType(boolean multipleIds)
494   {
495     return multipleIds ? "application/json" : "text/x-fasta";
496   }
497
498   @Override
499   protected String getResponseMimeType()
500   {
501     return "text/x-fasta";
502   }
503
504   /**
505    * 
506    * @return the configured sequence return type for this source
507    */
508   protected abstract EnsemblSeqType getSourceEnsemblType();
509
510   /**
511    * Returns a list of [start, end] genomic ranges corresponding to the sequence
512    * being retrieved.
513    * 
514    * The correspondence between the frames of reference is made by locating
515    * those features on the genomic sequence which identify the retrieved
516    * sequence. Specifically
517    * <ul>
518    * <li>genomic sequence is identified by "transcript" features with
519    * ID=transcript:transcriptId</li>
520    * <li>cdna sequence is identified by "exon" features with
521    * Parent=transcript:transcriptId</li>
522    * <li>cds sequence is identified by "CDS" features with
523    * Parent=transcript:transcriptId</li>
524    * </ul>
525    * 
526    * The returned ranges are sorted to run forwards (for positive strand) or
527    * backwards (for negative strand). Aborts and returns null if both positive
528    * and negative strand are found (this should not normally happen).
529    * 
530    * @param sourceSequence
531    * @param accId
532    * @param start
533    *          the start position of the sequence we are mapping to
534    * @return
535    */
536   protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
537           String accId, int start)
538   {
539     SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
540     if (sfs == null)
541     {
542       return null;
543     }
544
545     /*
546      * generously initial size for number of cds regions
547      * (worst case titin Q8WZ42 has c. 313 exons)
548      */
549     List<int[]> regions = new ArrayList<int[]>(100);
550     int mappedLength = 0;
551     int direction = 1; // forward
552     boolean directionSet = false;
553
554     for (SequenceFeature sf : sfs)
555     {
556       /*
557        * accept the target feature type or a specialisation of it
558        * (e.g. coding_exon for exon)
559        */
560       if (identifiesSequence(sf, accId))
561       {
562         int strand = sf.getStrand();
563         strand = strand == 0 ? 1 : strand; // treat unknown as forward
564
565         if (directionSet && strand != direction)
566         {
567           // abort - mix of forward and backward
568           System.err.println("Error: forward and backward strand for "
569                   + accId);
570           return null;
571         }
572         direction = strand;
573         directionSet = true;
574
575         /*
576          * add to CDS ranges, semi-sorted forwards/backwards
577          */
578         if (strand < 0)
579         {
580           regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
581         }
582         else
583         {
584           regions.add(new int[] { sf.getBegin(), sf.getEnd() });
585         }
586         mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
587
588         if (!isSpliceable())
589         {
590           /*
591            * 'gene' sequence is contiguous so we can stop as soon as its
592            * identifying feature has been found
593            */
594           break;
595         }
596       }
597     }
598
599     if (regions.isEmpty())
600     {
601       System.out.println("Failed to identify target sequence for " + accId
602               + " from genomic features");
603       return null;
604     }
605
606     /*
607      * a final sort is needed since Ensembl returns CDS sorted within source
608      * (havana / ensembl_havana)
609      */
610     Collections.sort(regions, new RangeComparator(direction == 1));
611
612     List<int[]> to = Arrays.asList(new int[] { start,
613         start + mappedLength - 1 });
614
615     return new MapList(regions, to, 1, 1);
616   }
617
618   /**
619    * Answers true if the sequence being retrieved may occupy discontiguous
620    * regions on the genomic sequence.
621    */
622   protected boolean isSpliceable()
623   {
624     return true;
625   }
626
627   /**
628    * Returns true if the sequence feature marks positions of the genomic
629    * sequence feature which are within the sequence being retrieved. For
630    * example, an 'exon' feature whose parent is the target transcript marks the
631    * cdna positions of the transcript.
632    * 
633    * @param sf
634    * @param accId
635    * @return
636    */
637   protected abstract boolean identifiesSequence(SequenceFeature sf,
638           String accId);
639
640   /**
641    * Transfers the sequence feature to the target sequence, locating its start
642    * and end range based on the mapping. Features which do not overlap the
643    * target sequence are ignored.
644    * 
645    * @param sf
646    * @param targetSequence
647    * @param mapping
648    *          mapping from the sequence feature's coordinates to the target
649    *          sequence
650    * @param forwardStrand
651    */
652   protected void transferFeature(SequenceFeature sf,
653           SequenceI targetSequence, MapList mapping, boolean forwardStrand)
654   {
655     int start = sf.getBegin();
656     int end = sf.getEnd();
657     int[] mappedRange = mapping.locateInTo(start, end);
658
659     if (mappedRange != null)
660     {
661       SequenceFeature copy = new SequenceFeature(sf);
662       copy.setBegin(Math.min(mappedRange[0], mappedRange[1]));
663       copy.setEnd(Math.max(mappedRange[0], mappedRange[1]));
664       if (".".equals(copy.getFeatureGroup()))
665       {
666         copy.setFeatureGroup(getDbSource());
667       }
668       targetSequence.addSequenceFeature(copy);
669
670       /*
671        * for sequence_variant on reverse strand, have to convert the allele
672        * values to their complements
673        */
674       if (!forwardStrand
675               && SequenceOntologyFactory.getInstance().isA(sf.getType(),
676                       SequenceOntologyI.SEQUENCE_VARIANT))
677       {
678         reverseComplementAlleles(copy);
679       }
680     }
681   }
682
683   /**
684    * Change the 'alleles' value of a feature by converting to complementary
685    * bases, and also update the feature description to match
686    * 
687    * @param sf
688    */
689   static void reverseComplementAlleles(SequenceFeature sf)
690   {
691     final String alleles = (String) sf.getValue(ALLELES);
692     if (alleles == null)
693     {
694       return;
695     }
696     StringBuilder complement = new StringBuilder(alleles.length());
697     for (String allele : alleles.split(","))
698     {
699       reverseComplementAllele(complement, allele);
700     }
701     String comp = complement.toString();
702     sf.setValue(ALLELES, comp);
703     sf.setDescription(comp);
704
705     /*
706      * replace value of "alleles=" in sf.ATTRIBUTES as well
707      * so 'output as GFF' shows reverse complement alleles
708      */
709     String atts = sf.getAttributes();
710     if (atts != null)
711     {
712       atts = atts.replace(ALLELES + "=" + alleles, ALLELES + "=" + comp);
713       sf.setAttributes(atts);
714     }
715   }
716
717   /**
718    * Makes the 'reverse complement' of the given allele and appends it to the
719    * buffer, after a comma separator if not the first
720    * 
721    * @param complement
722    * @param allele
723    */
724   static void reverseComplementAllele(StringBuilder complement,
725           String allele)
726   {
727     if (complement.length() > 0)
728     {
729       complement.append(",");
730     }
731
732     /*
733      * some 'alleles' are actually descriptive terms 
734      * e.g. HGMD_MUTATION, PhenCode_variation
735      * - we don't want to 'reverse complement' these
736      */
737     if (!Comparison.isNucleotideSequence(allele, true))
738     {
739       complement.append(allele);
740     }
741     else
742     {
743       for (int i = allele.length() - 1; i >= 0; i--)
744       {
745         complement.append(Dna.getComplement(allele.charAt(i)));
746       }
747     }
748   }
749
750   /**
751    * Transfers features from sourceSequence to targetSequence
752    * 
753    * @param accessionId
754    * @param sourceSequence
755    * @param targetSequence
756    * @return true if any features were transferred, else false
757    */
758   protected boolean transferFeatures(String accessionId,
759           SequenceI sourceSequence, SequenceI targetSequence)
760   {
761     if (sourceSequence == null || targetSequence == null)
762     {
763       return false;
764     }
765
766     // long start = System.currentTimeMillis();
767     SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
768     MapList mapping = getGenomicRangesFromFeatures(sourceSequence,
769             accessionId, targetSequence.getStart());
770     if (mapping == null)
771     {
772       return false;
773     }
774
775     boolean result = transferFeatures(sfs, targetSequence, mapping,
776             accessionId);
777     // System.out.println("transferFeatures (" + (sfs.length) + " --> "
778     // + targetSequence.getSequenceFeatures().length + ") to "
779     // + targetSequence.getName()
780     // + " took " + (System.currentTimeMillis() - start) + "ms");
781     return result;
782   }
783
784   /**
785    * Transfer features to the target sequence. The start/end positions are
786    * converted using the mapping. Features which do not overlap are ignored.
787    * Features whose parent is not the specified identifier are also ignored.
788    * 
789    * @param features
790    * @param targetSequence
791    * @param mapping
792    * @param parentId
793    * @return
794    */
795   protected boolean transferFeatures(SequenceFeature[] features,
796           SequenceI targetSequence, MapList mapping, String parentId)
797   {
798     final boolean forwardStrand = mapping.isFromForwardStrand();
799
800     /*
801      * sort features by start position (which corresponds to end
802      * position descending if reverse strand) so as to add them in
803      * 'forwards' order to the target sequence
804      */
805     sortFeatures(features, forwardStrand);
806
807     boolean transferred = false;
808     for (SequenceFeature sf : features)
809     {
810       if (retainFeature(sf, parentId))
811       {
812         transferFeature(sf, targetSequence, mapping, forwardStrand);
813         transferred = true;
814       }
815     }
816     return transferred;
817   }
818
819   /**
820    * Sort features by start position ascending (if on forward strand), or end
821    * position descending (if on reverse strand)
822    * 
823    * @param features
824    * @param forwardStrand
825    */
826   protected static void sortFeatures(SequenceFeature[] features,
827           final boolean forwardStrand)
828   {
829     Arrays.sort(features, new Comparator<SequenceFeature>()
830     {
831       @Override
832       public int compare(SequenceFeature o1, SequenceFeature o2)
833       {
834         if (forwardStrand)
835         {
836           return Integer.compare(o1.getBegin(), o2.getBegin());
837         }
838         else
839         {
840           return Integer.compare(o2.getEnd(), o1.getEnd());
841         }
842       }
843     });
844   }
845
846   /**
847    * Answers true if the feature type is one we want to keep for the sequence.
848    * Some features are only retrieved in order to identify the sequence range,
849    * and may then be discarded as redundant information (e.g. "CDS" feature for
850    * a CDS sequence).
851    */
852   @SuppressWarnings("unused")
853   protected boolean retainFeature(SequenceFeature sf, String accessionId)
854   {
855     return true; // override as required
856   }
857
858   /**
859    * Answers true if the feature has a Parent which refers to the given
860    * accession id, or if the feature has no parent. Answers false if the
861    * feature's Parent is for a different accession id.
862    * 
863    * @param sf
864    * @param identifier
865    * @return
866    */
867   protected boolean featureMayBelong(SequenceFeature sf, String identifier)
868   {
869     String parent = (String) sf.getValue(PARENT);
870     // using contains to allow for prefix "gene:", "transcript:" etc
871     if (parent != null && !parent.contains(identifier))
872     {
873       // this genomic feature belongs to a different transcript
874       return false;
875     }
876     return true;
877   }
878
879   @Override
880   public String getDescription()
881   {
882     return "Ensembl " + getSourceEnsemblType().getType()
883             + " sequence with variant features";
884   }
885
886   /**
887    * Returns a (possibly empty) list of features on the sequence which have the
888    * specified sequence ontology type (or a sub-type of it), and the given
889    * identifier as parent
890    * 
891    * @param sequence
892    * @param type
893    * @param parentId
894    * @return
895    */
896   protected List<SequenceFeature> findFeatures(SequenceI sequence,
897           String type, String parentId)
898   {
899     List<SequenceFeature> result = new ArrayList<SequenceFeature>();
900
901     SequenceFeature[] sfs = sequence.getSequenceFeatures();
902     if (sfs != null)
903     {
904       SequenceOntologyI so = SequenceOntologyFactory.getInstance();
905       for (SequenceFeature sf : sfs)
906       {
907         if (so.isA(sf.getType(), type))
908         {
909           String parent = (String) sf.getValue(PARENT);
910           if (parent.equals(parentId))
911           {
912             result.add(sf);
913           }
914         }
915       }
916     }
917     return result;
918   }
919
920   /**
921    * Answers true if the feature type is either 'NMD_transcript_variant' or
922    * 'transcript' or one of its sub-types in the Sequence Ontology. This is
923    * needed because NMD_transcript_variant behaves like 'transcript' in Ensembl
924    * although strictly speaking it is not (it is a sub-type of
925    * sequence_variant).
926    * 
927    * @param featureType
928    * @return
929    */
930   public static boolean isTranscript(String featureType)
931   {
932     return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
933             || SequenceOntologyFactory.getInstance().isA(featureType,
934                     SequenceOntologyI.TRANSCRIPT);
935   }
936 }