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