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