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