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