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