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