9229379788f2661c7b380d0a465ab2d12d55a482
[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
53 /**
54  * Base class for Ensembl sequence fetchers
55  * 
56  * @see http://rest.ensembl.org/documentation/info/sequence_id
57  * @author gmcarstairs
58  */
59 public abstract class EnsemblSeqProxy extends EnsemblRestClient
60 {
61   protected static final String NAME = "Name";
62
63   protected static final String DESCRIPTION = "description";
64
65   /*
66    * enum for 'type' parameter to the /sequence REST service
67    */
68   public enum EnsemblSeqType
69   {
70     /**
71      * type=genomic to fetch full dna including introns
72      */
73     GENOMIC("genomic"),
74
75     /**
76      * type=cdna to fetch coding dna including UTRs
77      */
78     CDNA("cdna"),
79
80     /**
81      * type=cds to fetch coding dna excluding UTRs
82      */
83     CDS("cds"),
84
85     /**
86      * type=protein to fetch peptide product sequence
87      */
88     PROTEIN("protein");
89
90     /*
91      * the value of the 'type' parameter to fetch this version of 
92      * an Ensembl sequence
93      */
94     private String type;
95
96     EnsemblSeqType(String t)
97     {
98       type = t;
99     }
100
101     public String getType()
102     {
103       return type;
104     }
105
106   }
107
108   /**
109    * Default constructor (to use rest.ensembl.org)
110    */
111   public EnsemblSeqProxy()
112   {
113     super();
114   }
115
116   /**
117    * Constructor given the target domain to fetch data from
118    */
119   public EnsemblSeqProxy(String d)
120   {
121     super(d);
122   }
123
124   /**
125    * Makes the sequence queries to Ensembl's REST service and returns an
126    * alignment consisting of the returned sequences.
127    */
128   @Override
129   public AlignmentI getSequenceRecords(String query) throws Exception
130   {
131     // TODO use a String... query vararg instead?
132
133     // danger: accession separator used as a regex here, a string elsewhere
134     // in this case it is ok (it is just a space), but (e.g.) '\' would not be
135     List<String> allIds = Arrays
136             .asList(query.split(getAccessionSeparator()));
137     AlignmentI alignment = null;
138     inProgress = true;
139
140     /*
141      * execute queries, if necessary in batches of the
142      * maximum allowed number of ids
143      */
144     int maxQueryCount = getMaximumQueryCount();
145     for (int v = 0, vSize = allIds.size(); v < vSize; v += maxQueryCount)
146     {
147       int p = Math.min(vSize, v + maxQueryCount);
148       List<String> ids = allIds.subList(v, p);
149       try
150       {
151         alignment = fetchSequences(ids, alignment);
152       } catch (Throwable r)
153       {
154         inProgress = false;
155         String msg = "Aborting ID retrieval after " + v
156                 + " chunks. Unexpected problem (" + r.getLocalizedMessage()
157                 + ")";
158         System.err.println(msg);
159         r.printStackTrace();
160         break;
161       }
162     }
163
164     if (alignment == null)
165     {
166       return null;
167     }
168
169     /*
170      * fetch and transfer genomic sequence features,
171      * fetch protein product and add as cross-reference
172      */
173     for (String accId : allIds)
174     {
175       addFeaturesAndProduct(accId, alignment);
176     }
177
178     for (SequenceI seq : alignment.getSequences())
179     {
180       getCrossReferences(seq);
181     }
182
183     return alignment;
184   }
185
186   /**
187    * Fetches Ensembl features using the /overlap REST endpoint, and adds them to
188    * the sequence in the alignment. Also fetches the protein product, maps it
189    * from the CDS features of the sequence, and saves it as a cross-reference of
190    * the dna sequence.
191    * 
192    * @param accId
193    * @param alignment
194    */
195   protected void addFeaturesAndProduct(String accId, AlignmentI alignment)
196   {
197     if (alignment == null)
198     {
199       return;
200     }
201
202     try
203     {
204       /*
205        * get 'dummy' genomic sequence with gene, transcript, 
206        * 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, true);
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(Gff3Helper.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(Gff3Helper.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(Gff3Helper.ALLELES + "=" + alleles,
732               Gff3Helper.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 }