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