JAL-3076 fetch Ensembl sequence as JSON instead of Fasta
[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.Sequence;
32 import jalview.datamodel.SequenceFeature;
33 import jalview.datamodel.SequenceI;
34 import jalview.datamodel.features.SequenceFeatures;
35 import jalview.exceptions.JalviewException;
36 import jalview.io.gff.SequenceOntologyFactory;
37 import jalview.io.gff.SequenceOntologyI;
38 import jalview.util.Comparison;
39 import jalview.util.DBRefUtils;
40 import jalview.util.IntRangeComparator;
41 import jalview.util.MapList;
42
43 import java.io.BufferedReader;
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 import org.json.simple.JSONObject;
53 import org.json.simple.parser.JSONParser;
54 import org.json.simple.parser.ParseException;
55
56 /**
57  * Base class for Ensembl sequence fetchers
58  * 
59  * @see http://rest.ensembl.org/documentation/info/sequence_id
60  * @author gmcarstairs
61  */
62 public abstract class EnsemblSeqProxy extends EnsemblRestClient
63 {
64   private static final String ALLELES = "alleles";
65
66   protected static final String NAME = "Name";
67
68   protected static final String DESCRIPTION = "description";
69
70   /*
71    * enum for 'type' parameter to the /sequence REST service
72    */
73   public enum EnsemblSeqType
74   {
75     /**
76      * type=genomic to fetch full dna including introns
77      */
78     GENOMIC("genomic"),
79
80     /**
81      * type=cdna to fetch coding dna including UTRs
82      */
83     CDNA("cdna"),
84
85     /**
86      * type=cds to fetch coding dna excluding UTRs
87      */
88     CDS("cds"),
89
90     /**
91      * type=protein to fetch peptide product sequence
92      */
93     PROTEIN("protein");
94
95     /*
96      * the value of the 'type' parameter to fetch this version of 
97      * an Ensembl sequence
98      */
99     private String type;
100
101     EnsemblSeqType(String t)
102     {
103       type = t;
104     }
105
106     public String getType()
107     {
108       return type;
109     }
110
111   }
112
113   /**
114    * Default constructor (to use rest.ensembl.org)
115    */
116   public EnsemblSeqProxy()
117   {
118     super();
119   }
120
121   /**
122    * Constructor given the target domain to fetch data from
123    */
124   public EnsemblSeqProxy(String d)
125   {
126     super(d);
127   }
128
129   /**
130    * Makes the sequence queries to Ensembl's REST service and returns an
131    * alignment consisting of the returned sequences.
132    */
133   @Override
134   public AlignmentI getSequenceRecords(String query) throws Exception
135   {
136     // TODO use a String... query vararg instead?
137
138     // danger: accession separator used as a regex here, a string elsewhere
139     // in this case it is ok (it is just a space), but (e.g.) '\' would not be
140     List<String> allIds = Arrays
141             .asList(query.split(getAccessionSeparator()));
142     AlignmentI alignment = null;
143     inProgress = true;
144
145     /*
146      * execute queries, if necessary in batches of the
147      * maximum allowed number of ids
148      */
149     int maxQueryCount = getMaximumQueryCount();
150     for (int v = 0, vSize = allIds.size(); v < vSize; v += maxQueryCount)
151     {
152       int p = Math.min(vSize, v + maxQueryCount);
153       List<String> ids = allIds.subList(v, p);
154       try
155       {
156         alignment = fetchSequences(ids, alignment);
157       } catch (Throwable r)
158       {
159         inProgress = false;
160         String msg = "Aborting ID retrieval after " + v
161                 + " chunks. Unexpected problem (" + r.getLocalizedMessage()
162                 + ")";
163         System.err.println(msg);
164         r.printStackTrace();
165         break;
166       }
167     }
168
169     if (alignment == null)
170     {
171       return null;
172     }
173
174     /*
175      * fetch and transfer genomic sequence features,
176      * fetch protein product and add as cross-reference
177      */
178     for (String accId : allIds)
179     {
180       addFeaturesAndProduct(accId, alignment);
181     }
182
183     for (SequenceI seq : alignment.getSequences())
184     {
185       getCrossReferences(seq);
186     }
187
188     return alignment;
189   }
190
191   /**
192    * Fetches Ensembl features using the /overlap REST endpoint, and adds them to
193    * the sequence in the alignment. Also fetches the protein product, maps it
194    * from the CDS features of the sequence, and saves it as a cross-reference of
195    * the dna sequence.
196    * 
197    * @param accId
198    * @param alignment
199    */
200   protected void addFeaturesAndProduct(String accId, AlignmentI alignment)
201   {
202     if (alignment == null)
203     {
204       return;
205     }
206
207     try
208     {
209       /*
210        * get 'dummy' genomic sequence with gene, transcript, 
211        * 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, true);
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     BufferedReader br = getSequenceReader(ids);
394     if (br == null)
395     {
396       return alignment;
397     }
398
399     List<SequenceI> seqs = parseSequenceJson(br);
400
401     if (seqs.isEmpty())
402     {
403       throw new IOException("No data returned for " + ids);
404     }
405
406     if (seqs.size() != ids.size())
407     {
408       System.out.println(String.format(
409               "Only retrieved %d sequences for %d query strings",
410               seqs.size(), ids.size()));
411     }
412
413     if (!seqs.isEmpty())
414     {
415       AlignmentI seqal = new Alignment(
416               seqs.toArray(new SequenceI[seqs.size()]));
417       for (SequenceI seq : seqs)
418       {
419         if (seq.getDescription() == null)
420         {
421           seq.setDescription(getDbName());
422         }
423         String name = seq.getName();
424         if (ids.contains(name)
425                 || ids.contains(name.replace("ENSP", "ENST")))
426         {
427           // TODO JAL-3077 use true accession version in dbref
428           DBRefEntry dbref = DBRefUtils.parseToDbRef(seq, getDbSource(),
429                   getEnsemblDataVersion(), name);
430           seq.addDBRef(dbref);
431         }
432       }
433       if (alignment == null)
434       {
435         alignment = seqal;
436       }
437       else
438       {
439         alignment.append(seqal);
440       }
441     }
442     return alignment;
443   }
444
445   /**
446    * Parses a JSON response into a list of sequences
447    * 
448    * @param br
449    * @return
450    * @see http://rest.ensembl.org/documentation/info/sequence_id
451    */
452   protected List<SequenceI> parseSequenceJson(BufferedReader br)
453   {
454     JSONParser jp = new JSONParser();
455     List<SequenceI> result = new ArrayList<>();
456     try
457     {
458       /*
459        * for now, assumes only one sequence returned; refactor if needed
460        * in future to handle a JSONArray with more than one
461        */
462       final JSONObject val = (JSONObject) jp.parse(br);
463       Object s = val.get("desc");
464       String desc = s == null ? null : s.toString();
465       s = val.get("id");
466       String id = s == null ? null : s.toString();
467       s = val.get("seq");
468       String seq = s == null ? null : s.toString();
469       Sequence sequence = new Sequence(id, seq);
470       if (desc != null)
471       {
472         sequence.setDescription(desc);
473       }
474       // todo JAL-3077 make a DBRefEntry with true accession version
475       // s = val.get("version");
476       // String version = s == null ? "0" : s.toString();
477       // DBRefEntry dbref = new DBRefEntry(getDbSource(), version, id);
478       // sequence.addDBRef(dbref);
479       result.add(sequence);
480     } catch (ParseException | IOException e)
481     {
482       System.err.println("Error processing JSON response: " + e.toString());
483       // ignore
484     }
485     return result;
486   }
487
488   /**
489    * Returns the URL for the REST call
490    * 
491    * @return
492    * @throws MalformedURLException
493    */
494   @Override
495   protected URL getUrl(List<String> ids) throws MalformedURLException
496   {
497     /*
498      * a single id is included in the URL path
499      * multiple ids go in the POST body instead
500      */
501     StringBuffer urlstring = new StringBuffer(128);
502     urlstring.append(getDomain() + "/sequence/id");
503     if (ids.size() == 1)
504     {
505       urlstring.append("/").append(ids.get(0));
506     }
507     // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
508     urlstring.append("?type=").append(getSourceEnsemblType().getType());
509     urlstring.append(("&Accept=application/json"));
510     urlstring.append(("&Content-Type=application/json"));
511
512     String objectType = getObjectType();
513     if (objectType != null)
514     {
515       urlstring.append("&").append(OBJECT_TYPE).append("=")
516               .append(objectType);
517     }
518
519     URL url = new URL(urlstring.toString());
520     return url;
521   }
522
523   /**
524    * Override this method to specify object_type request parameter
525    * 
526    * @return
527    */
528   protected String getObjectType()
529   {
530     return null;
531   }
532
533   /**
534    * A sequence/id POST request currently allows up to 50 queries
535    * 
536    * @see http://rest.ensembl.org/documentation/info/sequence_id_post
537    */
538   @Override
539   public int getMaximumQueryCount()
540   {
541     return 50;
542   }
543
544   @Override
545   protected boolean useGetRequest()
546   {
547     return false;
548   }
549
550   /**
551    * 
552    * @return the configured sequence return type for this source
553    */
554   protected abstract EnsemblSeqType getSourceEnsemblType();
555
556   /**
557    * Returns a list of [start, end] genomic ranges corresponding to the sequence
558    * being retrieved.
559    * 
560    * The correspondence between the frames of reference is made by locating
561    * those features on the genomic sequence which identify the retrieved
562    * sequence. Specifically
563    * <ul>
564    * <li>genomic sequence is identified by "transcript" features with
565    * ID=transcript:transcriptId</li>
566    * <li>cdna sequence is identified by "exon" features with
567    * Parent=transcript:transcriptId</li>
568    * <li>cds sequence is identified by "CDS" features with
569    * Parent=transcript:transcriptId</li>
570    * </ul>
571    * 
572    * The returned ranges are sorted to run forwards (for positive strand) or
573    * backwards (for negative strand). Aborts and returns null if both positive
574    * and negative strand are found (this should not normally happen).
575    * 
576    * @param sourceSequence
577    * @param accId
578    * @param start
579    *          the start position of the sequence we are mapping to
580    * @return
581    */
582   protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
583           String accId, int start)
584   {
585     List<SequenceFeature> sfs = sourceSequence.getFeatures()
586             .getPositionalFeatures();
587     if (sfs.isEmpty())
588     {
589       return null;
590     }
591
592     /*
593      * generously initial size for number of cds regions
594      * (worst case titin Q8WZ42 has c. 313 exons)
595      */
596     List<int[]> regions = new ArrayList<>(100);
597     int mappedLength = 0;
598     int direction = 1; // forward
599     boolean directionSet = false;
600
601     for (SequenceFeature sf : sfs)
602     {
603       /*
604        * accept the target feature type or a specialisation of it
605        * (e.g. coding_exon for exon)
606        */
607       if (identifiesSequence(sf, accId))
608       {
609         int strand = sf.getStrand();
610         strand = strand == 0 ? 1 : strand; // treat unknown as forward
611
612         if (directionSet && strand != direction)
613         {
614           // abort - mix of forward and backward
615           System.err.println(
616                   "Error: forward and backward strand for " + accId);
617           return null;
618         }
619         direction = strand;
620         directionSet = true;
621
622         /*
623          * add to CDS ranges, semi-sorted forwards/backwards
624          */
625         if (strand < 0)
626         {
627           regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
628         }
629         else
630         {
631           regions.add(new int[] { sf.getBegin(), sf.getEnd() });
632         }
633         mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
634
635         if (!isSpliceable())
636         {
637           /*
638            * 'gene' sequence is contiguous so we can stop as soon as its
639            * identifying feature has been found
640            */
641           break;
642         }
643       }
644     }
645
646     if (regions.isEmpty())
647     {
648       System.out.println("Failed to identify target sequence for " + accId
649               + " from genomic features");
650       return null;
651     }
652
653     /*
654      * a final sort is needed since Ensembl returns CDS sorted within source
655      * (havana / ensembl_havana)
656      */
657     Collections.sort(regions, direction == 1 ? IntRangeComparator.ASCENDING
658             : IntRangeComparator.DESCENDING);
659
660     List<int[]> to = Arrays
661             .asList(new int[]
662             { start, start + mappedLength - 1 });
663
664     return new MapList(regions, to, 1, 1);
665   }
666
667   /**
668    * Answers true if the sequence being retrieved may occupy discontiguous
669    * regions on the genomic sequence.
670    */
671   protected boolean isSpliceable()
672   {
673     return true;
674   }
675
676   /**
677    * Returns true if the sequence feature marks positions of the genomic
678    * sequence feature which are within the sequence being retrieved. For
679    * example, an 'exon' feature whose parent is the target transcript marks the
680    * cdna positions of the transcript.
681    * 
682    * @param sf
683    * @param accId
684    * @return
685    */
686   protected abstract boolean identifiesSequence(SequenceFeature sf,
687           String accId);
688
689   /**
690    * Transfers the sequence feature to the target sequence, locating its start
691    * and end range based on the mapping. Features which do not overlap the
692    * target sequence are ignored.
693    * 
694    * @param sf
695    * @param targetSequence
696    * @param mapping
697    *          mapping from the sequence feature's coordinates to the target
698    *          sequence
699    * @param forwardStrand
700    */
701   protected void transferFeature(SequenceFeature sf,
702           SequenceI targetSequence, MapList mapping, boolean forwardStrand)
703   {
704     int start = sf.getBegin();
705     int end = sf.getEnd();
706     int[] mappedRange = mapping.locateInTo(start, end);
707
708     if (mappedRange != null)
709     {
710       String group = sf.getFeatureGroup();
711       if (".".equals(group))
712       {
713         group = getDbSource();
714       }
715       int newBegin = Math.min(mappedRange[0], mappedRange[1]);
716       int newEnd = Math.max(mappedRange[0], mappedRange[1]);
717       SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
718               group, sf.getScore());
719       targetSequence.addSequenceFeature(copy);
720
721       /*
722        * for sequence_variant on reverse strand, have to convert the allele
723        * values to their complements
724        */
725       if (!forwardStrand && SequenceOntologyFactory.getInstance()
726               .isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
727       {
728         reverseComplementAlleles(copy);
729       }
730     }
731   }
732
733   /**
734    * Change the 'alleles' value of a feature by converting to complementary
735    * bases, and also update the feature description to match
736    * 
737    * @param sf
738    */
739   static void reverseComplementAlleles(SequenceFeature sf)
740   {
741     final String alleles = (String) sf.getValue(ALLELES);
742     if (alleles == null)
743     {
744       return;
745     }
746     StringBuilder complement = new StringBuilder(alleles.length());
747     for (String allele : alleles.split(","))
748     {
749       reverseComplementAllele(complement, allele);
750     }
751     String comp = complement.toString();
752     sf.setValue(ALLELES, comp);
753     sf.setDescription(comp);
754
755     /*
756      * replace value of "alleles=" in sf.ATTRIBUTES as well
757      * so 'output as GFF' shows reverse complement alleles
758      */
759     String atts = sf.getAttributes();
760     if (atts != null)
761     {
762       atts = atts.replace(ALLELES + "=" + alleles, ALLELES + "=" + comp);
763       sf.setAttributes(atts);
764     }
765   }
766
767   /**
768    * Makes the 'reverse complement' of the given allele and appends it to the
769    * buffer, after a comma separator if not the first
770    * 
771    * @param complement
772    * @param allele
773    */
774   static void reverseComplementAllele(StringBuilder complement,
775           String allele)
776   {
777     if (complement.length() > 0)
778     {
779       complement.append(",");
780     }
781
782     /*
783      * some 'alleles' are actually descriptive terms 
784      * e.g. HGMD_MUTATION, PhenCode_variation
785      * - we don't want to 'reverse complement' these
786      */
787     if (!Comparison.isNucleotideSequence(allele, true))
788     {
789       complement.append(allele);
790     }
791     else
792     {
793       for (int i = allele.length() - 1; i >= 0; i--)
794       {
795         complement.append(Dna.getComplement(allele.charAt(i)));
796       }
797     }
798   }
799
800   /**
801    * Transfers features from sourceSequence to targetSequence
802    * 
803    * @param accessionId
804    * @param sourceSequence
805    * @param targetSequence
806    * @return true if any features were transferred, else false
807    */
808   protected boolean transferFeatures(String accessionId,
809           SequenceI sourceSequence, SequenceI targetSequence)
810   {
811     if (sourceSequence == null || targetSequence == null)
812     {
813       return false;
814     }
815
816 //    long start = System.currentTimeMillis();
817     List<SequenceFeature> sfs = sourceSequence.getFeatures()
818             .getPositionalFeatures();
819     MapList mapping = getGenomicRangesFromFeatures(sourceSequence,
820             accessionId, targetSequence.getStart());
821     if (mapping == null)
822     {
823       return false;
824     }
825
826     boolean result = transferFeatures(sfs, targetSequence, mapping,
827             accessionId);
828 //    System.out.println("transferFeatures (" + (sfs.size()) + " --> "
829 //            + targetSequence.getFeatures().getFeatureCount(true) + ") to "
830 //            + targetSequence.getName() + " took "
831 //            + (System.currentTimeMillis() - start) + "ms");
832     return result;
833   }
834
835   /**
836    * Transfer features to the target sequence. The start/end positions are
837    * converted using the mapping. Features which do not overlap are ignored.
838    * Features whose parent is not the specified identifier are also ignored.
839    * 
840    * @param sfs
841    * @param targetSequence
842    * @param mapping
843    * @param parentId
844    * @return
845    */
846   protected boolean transferFeatures(List<SequenceFeature> sfs,
847           SequenceI targetSequence, MapList mapping, String parentId)
848   {
849     final boolean forwardStrand = mapping.isFromForwardStrand();
850
851     /*
852      * sort features by start position (which corresponds to end
853      * position descending if reverse strand) so as to add them in
854      * 'forwards' order to the target sequence
855      */
856     SequenceFeatures.sortFeatures(sfs, forwardStrand);
857
858     boolean transferred = false;
859     for (SequenceFeature sf : sfs)
860     {
861       if (retainFeature(sf, parentId))
862       {
863         transferFeature(sf, targetSequence, mapping, forwardStrand);
864         transferred = true;
865       }
866     }
867     return transferred;
868   }
869
870   /**
871    * Answers true if the feature type is one we want to keep for the sequence.
872    * Some features are only retrieved in order to identify the sequence range,
873    * and may then be discarded as redundant information (e.g. "CDS" feature for
874    * a CDS sequence).
875    */
876   @SuppressWarnings("unused")
877   protected boolean retainFeature(SequenceFeature sf, String accessionId)
878   {
879     return true; // override as required
880   }
881
882   /**
883    * Answers true if the feature has a Parent which refers to the given
884    * accession id, or if the feature has no parent. Answers false if the
885    * feature's Parent is for a different accession id.
886    * 
887    * @param sf
888    * @param identifier
889    * @return
890    */
891   protected boolean featureMayBelong(SequenceFeature sf, String identifier)
892   {
893     String parent = (String) sf.getValue(PARENT);
894     // using contains to allow for prefix "gene:", "transcript:" etc
895     if (parent != null
896             && !parent.toUpperCase().contains(identifier.toUpperCase()))
897     {
898       // this genomic feature belongs to a different transcript
899       return false;
900     }
901     return true;
902   }
903
904   @Override
905   public String getDescription()
906   {
907     return "Ensembl " + getSourceEnsemblType().getType()
908             + " sequence with variant features";
909   }
910
911   /**
912    * Returns a (possibly empty) list of features on the sequence which have the
913    * specified sequence ontology term (or a sub-type of it), and the given
914    * identifier as parent
915    * 
916    * @param sequence
917    * @param term
918    * @param parentId
919    * @return
920    */
921   protected List<SequenceFeature> findFeatures(SequenceI sequence,
922           String term, String parentId)
923   {
924     List<SequenceFeature> result = new ArrayList<>();
925
926     List<SequenceFeature> sfs = sequence.getFeatures()
927             .getFeaturesByOntology(term);
928     for (SequenceFeature sf : sfs)
929     {
930       String parent = (String) sf.getValue(PARENT);
931       if (parent != null && parent.equalsIgnoreCase(parentId))
932       {
933         result.add(sf);
934       }
935     }
936
937     return result;
938   }
939
940   /**
941    * Answers true if the feature type is either 'NMD_transcript_variant' or
942    * 'transcript' or one of its sub-types in the Sequence Ontology. This is
943    * needed because NMD_transcript_variant behaves like 'transcript' in Ensembl
944    * although strictly speaking it is not (it is a sub-type of
945    * sequence_variant).
946    * 
947    * @param featureType
948    * @return
949    */
950   public static boolean isTranscript(String featureType)
951   {
952     return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
953             || SequenceOntologyFactory.getInstance().isA(featureType,
954                     SequenceOntologyI.TRANSCRIPT);
955   }
956 }