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