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