JAL-2679 use object_type=Transcript for lookup of Parent for Protein
[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 exon, cds and variation features
207        */
208       SequenceI genomicSequence = null;
209       EnsemblFeatures gffFetcher = new EnsemblFeatures(getDomain());
210       EnsemblFeatureType[] features = getFeaturesToFetch();
211       AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
212               features);
213       if (geneFeatures != null && geneFeatures.getHeight() > 0)
214       {
215         genomicSequence = geneFeatures.getSequenceAt(0);
216       }
217       if (genomicSequence != null)
218       {
219         /*
220          * transfer features to the query sequence
221          */
222         SequenceI querySeq = alignment.findName(accId);
223         if (transferFeatures(accId, genomicSequence, querySeq))
224         {
225
226           /*
227            * fetch and map protein product, and add it as a cross-reference
228            * of the retrieved sequence
229            */
230           addProteinProduct(querySeq);
231         }
232       }
233     } catch (IOException e)
234     {
235       System.err.println(
236               "Error transferring Ensembl features: " + e.getMessage());
237     }
238   }
239
240   /**
241    * Returns those sequence feature types to fetch from Ensembl. We may want
242    * features either because they are of interest to the user, or as means to
243    * identify the locations of the sequence on the genomic sequence (CDS
244    * features identify CDS, exon features identify cDNA etc).
245    * 
246    * @return
247    */
248   protected abstract EnsemblFeatureType[] getFeaturesToFetch();
249
250   /**
251    * Fetches and maps the protein product, and adds it as a cross-reference of
252    * the retrieved sequence
253    */
254   protected void addProteinProduct(SequenceI querySeq)
255   {
256     String accId = querySeq.getName();
257     try
258     {
259       AlignmentI protein = new EnsemblProtein(getDomain())
260               .getSequenceRecords(accId);
261       if (protein == null || protein.getHeight() == 0)
262       {
263         System.out.println("No protein product found for " + accId);
264         return;
265       }
266       SequenceI proteinSeq = protein.getSequenceAt(0);
267
268       /*
269        * need dataset sequences (to be the subject of mappings)
270        */
271       proteinSeq.createDatasetSequence();
272       querySeq.createDatasetSequence();
273
274       MapList mapList = AlignmentUtils.mapCdsToProtein(querySeq,
275               proteinSeq);
276       if (mapList != null)
277       {
278         // clunky: ensure Uniprot xref if we have one is on mapped sequence
279         SequenceI ds = proteinSeq.getDatasetSequence();
280         // TODO: Verify ensp primary ref is on proteinSeq.getDatasetSequence()
281         Mapping map = new Mapping(ds, mapList);
282         DBRefEntry dbr = new DBRefEntry(getDbSource(),
283                 getEnsemblDataVersion(), proteinSeq.getName(), map);
284         querySeq.getDatasetSequence().addDBRef(dbr);
285         DBRefEntry[] uprots = DBRefUtils.selectRefs(ds.getDBRefs(),
286                 new String[]
287                 { DBRefSource.UNIPROT });
288         DBRefEntry[] upxrefs = DBRefUtils.selectRefs(querySeq.getDBRefs(),
289                 new String[]
290                 { DBRefSource.UNIPROT });
291         if (uprots != null)
292         {
293           for (DBRefEntry up : uprots)
294           {
295             // locate local uniprot ref and map
296             List<DBRefEntry> upx = DBRefUtils.searchRefs(upxrefs,
297                     up.getAccessionId());
298             DBRefEntry upxref;
299             if (upx.size() != 0)
300             {
301               upxref = upx.get(0);
302
303               if (upx.size() > 1)
304               {
305                 Cache.log.warn(
306                         "Implementation issue - multiple uniprot acc on product sequence.");
307               }
308             }
309             else
310             {
311               upxref = new DBRefEntry(DBRefSource.UNIPROT,
312                       getEnsemblDataVersion(), up.getAccessionId());
313             }
314
315             Mapping newMap = new Mapping(ds, mapList);
316             upxref.setVersion(getEnsemblDataVersion());
317             upxref.setMap(newMap);
318             if (upx.size() == 0)
319             {
320               // add the new uniprot ref
321               querySeq.getDatasetSequence().addDBRef(upxref);
322             }
323
324           }
325         }
326
327         /*
328          * copy exon features to protein, compute peptide variants from dna 
329          * variants and add as features on the protein sequence ta-da
330          */
331         AlignmentUtils.computeProteinFeatures(querySeq, proteinSeq,
332                 mapList);
333       }
334     } catch (Exception e)
335     {
336       System.err
337               .println(String.format("Error retrieving protein for %s: %s",
338                       accId, e.getMessage()));
339     }
340   }
341
342   /**
343    * Get database xrefs from Ensembl, and attach them to the sequence
344    * 
345    * @param seq
346    */
347   protected void getCrossReferences(SequenceI seq)
348   {
349     while (seq.getDatasetSequence() != null)
350     {
351       seq = seq.getDatasetSequence();
352     }
353
354     EnsemblXref xrefFetcher = new EnsemblXref(getDomain(), getDbSource(),
355             getEnsemblDataVersion());
356     List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName());
357     for (DBRefEntry xref : xrefs)
358     {
359       seq.addDBRef(xref);
360     }
361
362     /*
363      * and add a reference to itself
364      */
365     DBRefEntry self = new DBRefEntry(getDbSource(), getEnsemblDataVersion(),
366             seq.getName());
367     seq.addDBRef(self);
368   }
369
370   /**
371    * Fetches sequences for the list of accession ids and adds them to the
372    * alignment. Returns the extended (or created) alignment.
373    * 
374    * @param ids
375    * @param alignment
376    * @return
377    * @throws JalviewException
378    * @throws IOException
379    */
380   protected AlignmentI fetchSequences(List<String> ids,
381           AlignmentI alignment) throws JalviewException, IOException
382   {
383     if (!isEnsemblAvailable())
384     {
385       inProgress = false;
386       throw new JalviewException("ENSEMBL Rest API not available.");
387     }
388     FileParse fp = getSequenceReader(ids);
389     if (fp == null)
390     {
391       return alignment;
392     }
393
394     FastaFile fr = new FastaFile(fp);
395     if (fr.hasWarningMessage())
396     {
397       System.out.println(
398               String.format("Warning when retrieving %d ids %s\n%s",
399                       ids.size(), ids.toString(), fr.getWarningMessage()));
400     }
401     else if (fr.getSeqs().size() != ids.size())
402     {
403       System.out.println(String.format(
404               "Only retrieved %d sequences for %d query strings",
405               fr.getSeqs().size(), ids.size()));
406     }
407
408     if (fr.getSeqs().size() == 1 && fr.getSeqs().get(0).getLength() == 0)
409     {
410       /*
411        * POST request has returned an empty FASTA file e.g. for invalid id
412        */
413       throw new IOException("No data returned for " + ids);
414     }
415
416     if (fr.getSeqs().size() > 0)
417     {
418       AlignmentI seqal = new Alignment(fr.getSeqsAsArray());
419       for (SequenceI sq : seqal.getSequences())
420       {
421         if (sq.getDescription() == null)
422         {
423           sq.setDescription(getDbName());
424         }
425         String name = sq.getName();
426         if (ids.contains(name)
427                 || ids.contains(name.replace("ENSP", "ENST")))
428         {
429           DBRefEntry dbref = DBRefUtils.parseToDbRef(sq, getDbSource(),
430                   getEnsemblDataVersion(), name);
431           sq.addDBRef(dbref);
432         }
433       }
434       if (alignment == null)
435       {
436         alignment = seqal;
437       }
438       else
439       {
440         alignment.append(seqal);
441       }
442     }
443     return alignment;
444   }
445
446   /**
447    * Returns the URL for the REST call
448    * 
449    * @return
450    * @throws MalformedURLException
451    */
452   @Override
453   protected URL getUrl(List<String> ids) throws MalformedURLException
454   {
455     /*
456      * a single id is included in the URL path
457      * multiple ids go in the POST body instead
458      */
459     StringBuffer urlstring = new StringBuffer(128);
460     urlstring.append(getDomain() + "/sequence/id");
461     if (ids.size() == 1)
462     {
463       urlstring.append("/").append(ids.get(0));
464     }
465     // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
466     urlstring.append("?type=").append(getSourceEnsemblType().getType());
467     urlstring.append(("&Accept=text/x-fasta"));
468
469     String objectType = getObjectType();
470     if (objectType != null)
471     {
472       urlstring.append("&").append(OBJECT_TYPE).append("=")
473               .append(objectType);
474     }
475
476     URL url = new URL(urlstring.toString());
477     return url;
478   }
479
480   /**
481    * Override this method to specify object_type request parameter
482    * 
483    * @return
484    */
485   protected String getObjectType()
486   {
487     return null;
488   }
489
490   /**
491    * A sequence/id POST request currently allows up to 50 queries
492    * 
493    * @see http://rest.ensembl.org/documentation/info/sequence_id_post
494    */
495   @Override
496   public int getMaximumQueryCount()
497   {
498     return 50;
499   }
500
501   @Override
502   protected boolean useGetRequest()
503   {
504     return false;
505   }
506
507   @Override
508   protected String getRequestMimeType(boolean multipleIds)
509   {
510     return multipleIds ? "application/json" : "text/x-fasta";
511   }
512
513   @Override
514   protected String getResponseMimeType()
515   {
516     return "text/x-fasta";
517   }
518
519   /**
520    * 
521    * @return the configured sequence return type for this source
522    */
523   protected abstract EnsemblSeqType getSourceEnsemblType();
524
525   /**
526    * Returns a list of [start, end] genomic ranges corresponding to the sequence
527    * being retrieved.
528    * 
529    * The correspondence between the frames of reference is made by locating
530    * those features on the genomic sequence which identify the retrieved
531    * sequence. Specifically
532    * <ul>
533    * <li>genomic sequence is identified by "transcript" features with
534    * ID=transcript:transcriptId</li>
535    * <li>cdna sequence is identified by "exon" features with
536    * Parent=transcript:transcriptId</li>
537    * <li>cds sequence is identified by "CDS" features with
538    * Parent=transcript:transcriptId</li>
539    * </ul>
540    * 
541    * The returned ranges are sorted to run forwards (for positive strand) or
542    * backwards (for negative strand). Aborts and returns null if both positive
543    * and negative strand are found (this should not normally happen).
544    * 
545    * @param sourceSequence
546    * @param accId
547    * @param start
548    *          the start position of the sequence we are mapping to
549    * @return
550    */
551   protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
552           String accId, int start)
553   {
554     List<SequenceFeature> sfs = sourceSequence.getFeatures()
555             .getPositionalFeatures();
556     if (sfs.isEmpty())
557     {
558       return null;
559     }
560
561     /*
562      * generously initial size for number of cds regions
563      * (worst case titin Q8WZ42 has c. 313 exons)
564      */
565     List<int[]> regions = new ArrayList<>(100);
566     int mappedLength = 0;
567     int direction = 1; // forward
568     boolean directionSet = false;
569
570     for (SequenceFeature sf : sfs)
571     {
572       /*
573        * accept the target feature type or a specialisation of it
574        * (e.g. coding_exon for exon)
575        */
576       if (identifiesSequence(sf, accId))
577       {
578         int strand = sf.getStrand();
579         strand = strand == 0 ? 1 : strand; // treat unknown as forward
580
581         if (directionSet && strand != direction)
582         {
583           // abort - mix of forward and backward
584           System.err.println(
585                   "Error: forward and backward strand for " + accId);
586           return null;
587         }
588         direction = strand;
589         directionSet = true;
590
591         /*
592          * add to CDS ranges, semi-sorted forwards/backwards
593          */
594         if (strand < 0)
595         {
596           regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
597         }
598         else
599         {
600           regions.add(new int[] { sf.getBegin(), sf.getEnd() });
601         }
602         mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
603
604         if (!isSpliceable())
605         {
606           /*
607            * 'gene' sequence is contiguous so we can stop as soon as its
608            * identifying feature has been found
609            */
610           break;
611         }
612       }
613     }
614
615     if (regions.isEmpty())
616     {
617       System.out.println("Failed to identify target sequence for " + accId
618               + " from genomic features");
619       return null;
620     }
621
622     /*
623      * a final sort is needed since Ensembl returns CDS sorted within source
624      * (havana / ensembl_havana)
625      */
626     Collections.sort(regions, direction == 1 ? IntRangeComparator.ASCENDING
627             : IntRangeComparator.DESCENDING);
628
629     List<int[]> to = Arrays
630             .asList(new int[]
631             { start, start + mappedLength - 1 });
632
633     return new MapList(regions, to, 1, 1);
634   }
635
636   /**
637    * Answers true if the sequence being retrieved may occupy discontiguous
638    * regions on the genomic sequence.
639    */
640   protected boolean isSpliceable()
641   {
642     return true;
643   }
644
645   /**
646    * Returns true if the sequence feature marks positions of the genomic
647    * sequence feature which are within the sequence being retrieved. For
648    * example, an 'exon' feature whose parent is the target transcript marks the
649    * cdna positions of the transcript.
650    * 
651    * @param sf
652    * @param accId
653    * @return
654    */
655   protected abstract boolean identifiesSequence(SequenceFeature sf,
656           String accId);
657
658   /**
659    * Transfers the sequence feature to the target sequence, locating its start
660    * and end range based on the mapping. Features which do not overlap the
661    * target sequence are ignored.
662    * 
663    * @param sf
664    * @param targetSequence
665    * @param mapping
666    *          mapping from the sequence feature's coordinates to the target
667    *          sequence
668    * @param forwardStrand
669    */
670   protected void transferFeature(SequenceFeature sf,
671           SequenceI targetSequence, MapList mapping, boolean forwardStrand)
672   {
673     int start = sf.getBegin();
674     int end = sf.getEnd();
675     int[] mappedRange = mapping.locateInTo(start, end);
676
677     if (mappedRange != null)
678     {
679       String group = sf.getFeatureGroup();
680       if (".".equals(group))
681       {
682         group = getDbSource();
683       }
684       int newBegin = Math.min(mappedRange[0], mappedRange[1]);
685       int newEnd = Math.max(mappedRange[0], mappedRange[1]);
686       SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
687               group, sf.getScore());
688       targetSequence.addSequenceFeature(copy);
689
690       /*
691        * for sequence_variant on reverse strand, have to convert the allele
692        * values to their complements
693        */
694       if (!forwardStrand && SequenceOntologyFactory.getInstance()
695               .isA(sf.getType(), 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     List<SequenceFeature> sfs = sourceSequence.getFeatures()
787             .getPositionalFeatures();
788     MapList mapping = getGenomicRangesFromFeatures(sourceSequence,
789             accessionId, targetSequence.getStart());
790     if (mapping == null)
791     {
792       return false;
793     }
794
795     boolean result = transferFeatures(sfs, targetSequence, mapping,
796             accessionId);
797 //    System.out.println("transferFeatures (" + (sfs.size()) + " --> "
798 //            + targetSequence.getFeatures().getFeatureCount(true) + ") to "
799 //            + targetSequence.getName() + " took "
800 //            + (System.currentTimeMillis() - start) + "ms");
801     return result;
802   }
803
804   /**
805    * Transfer features to the target sequence. The start/end positions are
806    * converted using the mapping. Features which do not overlap are ignored.
807    * Features whose parent is not the specified identifier are also ignored.
808    * 
809    * @param sfs
810    * @param targetSequence
811    * @param mapping
812    * @param parentId
813    * @return
814    */
815   protected boolean transferFeatures(List<SequenceFeature> sfs,
816           SequenceI targetSequence, MapList mapping, String parentId)
817   {
818     final boolean forwardStrand = mapping.isFromForwardStrand();
819
820     /*
821      * sort features by start position (which corresponds to end
822      * position descending if reverse strand) so as to add them in
823      * 'forwards' order to the target sequence
824      */
825     SequenceFeatures.sortFeatures(sfs, forwardStrand);
826
827     boolean transferred = false;
828     for (SequenceFeature sf : sfs)
829     {
830       if (retainFeature(sf, parentId))
831       {
832         transferFeature(sf, targetSequence, mapping, forwardStrand);
833         transferred = true;
834       }
835     }
836     return transferred;
837   }
838
839   /**
840    * Answers true if the feature type is one we want to keep for the sequence.
841    * Some features are only retrieved in order to identify the sequence range,
842    * and may then be discarded as redundant information (e.g. "CDS" feature for
843    * a CDS sequence).
844    */
845   @SuppressWarnings("unused")
846   protected boolean retainFeature(SequenceFeature sf, String accessionId)
847   {
848     return true; // override as required
849   }
850
851   /**
852    * Answers true if the feature has a Parent which refers to the given
853    * accession id, or if the feature has no parent. Answers false if the
854    * feature's Parent is for a different accession id.
855    * 
856    * @param sf
857    * @param identifier
858    * @return
859    */
860   protected boolean featureMayBelong(SequenceFeature sf, String identifier)
861   {
862     String parent = (String) sf.getValue(PARENT);
863     // using contains to allow for prefix "gene:", "transcript:" etc
864     if (parent != null && !parent.contains(identifier))
865     {
866       // this genomic feature belongs to a different transcript
867       return false;
868     }
869     return true;
870   }
871
872   @Override
873   public String getDescription()
874   {
875     return "Ensembl " + getSourceEnsemblType().getType()
876             + " sequence with variant features";
877   }
878
879   /**
880    * Returns a (possibly empty) list of features on the sequence which have the
881    * specified sequence ontology term (or a sub-type of it), and the given
882    * identifier as parent
883    * 
884    * @param sequence
885    * @param term
886    * @param parentId
887    * @return
888    */
889   protected List<SequenceFeature> findFeatures(SequenceI sequence,
890           String term, String parentId)
891   {
892     List<SequenceFeature> result = new ArrayList<>();
893
894     List<SequenceFeature> sfs = sequence.getFeatures()
895             .getFeaturesByOntology(term);
896     for (SequenceFeature sf : sfs)
897     {
898       String parent = (String) sf.getValue(PARENT);
899       if (parent != null && parent.equals(parentId))
900       {
901         result.add(sf);
902       }
903     }
904
905     return result;
906   }
907
908   /**
909    * Answers true if the feature type is either 'NMD_transcript_variant' or
910    * 'transcript' or one of its sub-types in the Sequence Ontology. This is
911    * needed because NMD_transcript_variant behaves like 'transcript' in Ensembl
912    * although strictly speaking it is not (it is a sub-type of
913    * sequence_variant).
914    * 
915    * @param featureType
916    * @return
917    */
918   public static boolean isTranscript(String featureType)
919   {
920     return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
921             || SequenceOntologyFactory.getInstance().isA(featureType,
922                     SequenceOntologyI.TRANSCRIPT);
923   }
924 }