JAL-2110 JAL-1705 handle not found (400) better
[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.mapCdsToProtein(querySeq, proteinSeq);
278       if (mapList != null)
279       {
280         // clunky: ensure Uniprot xref if we have one is on mapped sequence
281         SequenceI ds = proteinSeq.getDatasetSequence();
282         // TODO: Verify ensp primary ref is on proteinSeq.getDatasetSequence()
283         Mapping map = new Mapping(ds, mapList);
284         DBRefEntry dbr = new DBRefEntry(getDbSource(),
285                 getEnsemblDataVersion(), proteinSeq.getName(), map);
286         querySeq.getDatasetSequence().addDBRef(dbr);
287         DBRefEntry[] uprots = DBRefUtils.selectRefs(ds.getDBRefs(),
288                 new String[] { DBRefSource.UNIPROT });
289         DBRefEntry[] upxrefs = DBRefUtils.selectRefs(querySeq.getDBRefs(),
290                 new String[] { DBRefSource.UNIPROT });
291         if (uprots != null)
292         {
293           for (DBRefEntry up : uprots)
294           {
295             // locate local uniprot ref and map
296             List<DBRefEntry> upx = DBRefUtils.searchRefs(upxrefs, up.getAccessionId());
297             DBRefEntry upxref;
298             if (upx.size() != 0)
299             {
300               upxref = upx.get(0);
301
302               if (upx.size() > 1)
303               {
304                 Cache.log
305                         .warn("Implementation issue - multiple uniprot acc on product sequence.");
306               }
307             }
308             else
309             {
310               upxref = new DBRefEntry(DBRefSource.UNIPROT,
311                     getEnsemblDataVersion(), up.getAccessionId());
312             }
313
314             Mapping newMap = new Mapping(ds, mapList);
315             upxref.setVersion(getEnsemblDataVersion());
316             upxref.setMap(newMap);
317             if (upx.size() == 0)
318             {
319               // add the new uniprot ref
320               querySeq.getDatasetSequence().addDBRef(upxref);
321             }
322             
323           }
324         }
325         
326         /*
327          * copy exon features to protein, compute peptide variants from dna 
328          * variants and add as features on the protein sequence ta-da
329          */
330         AlignmentUtils.computeProteinFeatures(querySeq, proteinSeq, mapList);
331       }
332     } catch (Exception e)
333     {
334       System.err
335               .println(String.format("Error retrieving protein for %s: %s",
336                       accId, e.getMessage()));
337     }
338   }
339
340   /**
341    * Get database xrefs from Ensembl, and attach them to the sequence
342    * 
343    * @param seq
344    */
345   protected void getCrossReferences(SequenceI seq)
346   {
347     while (seq.getDatasetSequence() != null)
348     {
349       seq = seq.getDatasetSequence();
350     }
351
352     EnsemblXref xrefFetcher = new EnsemblXref(getDomain(), getDbSource(),
353             getEnsemblDataVersion());
354     List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName());
355     for (DBRefEntry xref : xrefs)
356     {
357       seq.addDBRef(xref);
358     }
359
360     /*
361      * and add a reference to itself
362      */
363     DBRefEntry self = new DBRefEntry(getDbSource(),
364             getEnsemblDataVersion(), seq.getName());
365     seq.addDBRef(self);
366   }
367
368   /**
369    * Fetches sequences for the list of accession ids and adds them to the
370    * alignment. Returns the extended (or created) alignment.
371    * 
372    * @param ids
373    * @param alignment
374    * @return
375    * @throws JalviewException
376    * @throws IOException
377    */
378   protected AlignmentI fetchSequences(List<String> ids, AlignmentI alignment)
379           throws JalviewException, IOException
380   {
381     if (!isEnsemblAvailable())
382     {
383       inProgress = false;
384       throw new JalviewException("ENSEMBL Rest API not available.");
385     }
386     FileParse fp = getSequenceReader(ids);
387     if (fp == null)
388     {
389       return alignment;
390     }
391
392     FastaFile fr = new FastaFile(fp);
393     if (fr.hasWarningMessage())
394     {
395       System.out.println(String.format(
396               "Warning when retrieving %d ids %s\n%s", ids.size(),
397               ids.toString(), fr.getWarningMessage()));
398     }
399     else if (fr.getSeqs().size() != ids.size())
400     {
401       System.out.println(String.format(
402               "Only retrieved %d sequences for %d query strings", fr
403                       .getSeqs().size(), ids.size()));
404     }
405
406     if (fr.getSeqs().size() == 1 && fr.getSeqs().get(0).getLength() == 0)
407     {
408       /*
409        * POST request has returned an empty FASTA file e.g. for invalid id
410        */
411       throw new IOException("No data returned for " + ids);
412     }
413
414     if (fr.getSeqs().size() > 0)
415     {
416       AlignmentI seqal = new Alignment(
417               fr.getSeqsAsArray());
418       for (SequenceI sq:seqal.getSequences())
419       {
420         if (sq.getDescription() == null)
421         {
422           sq.setDescription(getDbName());
423         }
424         String name = sq.getName();
425         if (ids.contains(name)
426                 || ids.contains(name.replace("ENSP", "ENST")))
427         {
428           DBRefEntry dbref = DBRefUtils.parseToDbRef(sq, getDbSource(),
429                   getEnsemblDataVersion(), name);
430           sq.addDBRef(dbref);
431         }
432       }
433       if (alignment == null)
434       {
435         alignment = seqal;
436       }
437       else
438       {
439         alignment.append(seqal);
440       }
441     }
442     return alignment;
443   }
444
445   /**
446    * Returns the URL for the REST call
447    * 
448    * @return
449    * @throws MalformedURLException
450    */
451   @Override
452   protected URL getUrl(List<String> ids) throws MalformedURLException
453   {
454     /*
455      * a single id is included in the URL path
456      * multiple ids go in the POST body instead
457      */
458     StringBuffer urlstring = new StringBuffer(128);
459     urlstring.append(getDomain() + "/sequence/id");
460     if (ids.size() == 1)
461     {
462       urlstring.append("/").append(ids.get(0));
463     }
464     // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
465     urlstring.append("?type=").append(getSourceEnsemblType().getType());
466     urlstring.append(("&Accept=text/x-fasta"));
467
468     URL url = new URL(urlstring.toString());
469     return url;
470   }
471
472   /**
473    * A sequence/id POST request currently allows up to 50 queries
474    * 
475    * @see http://rest.ensembl.org/documentation/info/sequence_id_post
476    */
477   @Override
478   public int getMaximumQueryCount()
479   {
480     return 50;
481   }
482
483   @Override
484   protected boolean useGetRequest()
485   {
486     return false;
487   }
488
489   @Override
490   protected String getRequestMimeType(boolean multipleIds)
491   {
492     return multipleIds ? "application/json" : "text/x-fasta";
493   }
494
495   @Override
496   protected String getResponseMimeType()
497   {
498     return "text/x-fasta";
499   }
500
501   /**
502    * 
503    * @return the configured sequence return type for this source
504    */
505   protected abstract EnsemblSeqType getSourceEnsemblType();
506
507   /**
508    * Returns a list of [start, end] genomic ranges corresponding to the sequence
509    * being retrieved.
510    * 
511    * The correspondence between the frames of reference is made by locating
512    * those features on the genomic sequence which identify the retrieved
513    * sequence. Specifically
514    * <ul>
515    * <li>genomic sequence is identified by "transcript" features with
516    * ID=transcript:transcriptId</li>
517    * <li>cdna sequence is identified by "exon" features with
518    * Parent=transcript:transcriptId</li>
519    * <li>cds sequence is identified by "CDS" features with
520    * Parent=transcript:transcriptId</li>
521    * </ul>
522    * 
523    * The returned ranges are sorted to run forwards (for positive strand) or
524    * backwards (for negative strand). Aborts and returns null if both positive
525    * and negative strand are found (this should not normally happen).
526    * 
527    * @param sourceSequence
528    * @param accId
529    * @param start
530    *          the start position of the sequence we are mapping to
531    * @return
532    */
533   protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
534           String accId, int start)
535   {
536     SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
537     if (sfs == null)
538     {
539       return null;
540     }
541
542     /*
543      * generously initial size for number of cds regions
544      * (worst case titin Q8WZ42 has c. 313 exons)
545      */
546     List<int[]> regions = new ArrayList<int[]>(100);
547     int mappedLength = 0;
548     int direction = 1; // forward
549     boolean directionSet = false;
550   
551     for (SequenceFeature sf : sfs)
552     {
553       /*
554        * accept the target feature type or a specialisation of it
555        * (e.g. coding_exon for exon)
556        */
557       if (identifiesSequence(sf, accId))
558       {
559         int strand = sf.getStrand();
560         strand = strand == 0 ? 1 : strand; // treat unknown as forward
561
562         if (directionSet && strand != direction)
563         {
564           // abort - mix of forward and backward
565           System.err.println("Error: forward and backward strand for "
566                   + accId);
567             return null;
568           }
569           direction = strand;
570           directionSet = true;
571   
572           /*
573            * add to CDS ranges, semi-sorted forwards/backwards
574            */
575           if (strand < 0)
576           {
577             regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
578           }
579           else
580           {
581           regions.add(new int[] { sf.getBegin(), sf.getEnd() });
582         }
583         mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
584
585         if (!isSpliceable())
586         {
587           /*
588            * 'gene' sequence is contiguous so we can stop as soon as its
589            * identifying feature has been found
590            */
591           break;
592         }
593       }
594     }
595   
596     if (regions.isEmpty())
597     {
598       System.out.println("Failed to identify target sequence for " + accId
599               + " from genomic features");
600       return null;
601     }
602
603     /*
604      * a final sort is needed since Ensembl returns CDS sorted within source
605      * (havana / ensembl_havana)
606      */
607     Collections.sort(regions, new RangeSorter(direction == 1));
608   
609     List<int[]> to = Arrays.asList(new int[] { start,
610         start + mappedLength - 1 });
611   
612     return new MapList(regions, to, 1, 1);
613   }
614
615   /**
616    * Answers true if the sequence being retrieved may occupy discontiguous
617    * regions on the genomic sequence.
618    */
619   protected boolean isSpliceable()
620   {
621     return true;
622   }
623
624   /**
625    * Returns true if the sequence feature marks positions of the genomic
626    * sequence feature which are within the sequence being retrieved. For
627    * example, an 'exon' feature whose parent is the target transcript marks the
628    * cdna positions of the transcript.
629    * 
630    * @param sf
631    * @param accId
632    * @return
633    */
634   protected abstract boolean identifiesSequence(SequenceFeature sf,
635           String accId);
636
637   /**
638    * Transfers the sequence feature to the target sequence, locating its start
639    * and end range based on the mapping. Features which do not overlap the
640    * target sequence are ignored.
641    * 
642    * @param sf
643    * @param targetSequence
644    * @param mapping
645    *          mapping from the sequence feature's coordinates to the target
646    *          sequence
647    * @param forwardStrand
648    */
649   protected void transferFeature(SequenceFeature sf,
650           SequenceI targetSequence, MapList mapping, boolean forwardStrand)
651   {
652     int start = sf.getBegin();
653     int end = sf.getEnd();
654     int[] mappedRange = mapping.locateInTo(start, end);
655   
656     if (mappedRange != null)
657     {
658       SequenceFeature copy = new SequenceFeature(sf);
659       copy.setBegin(Math.min(mappedRange[0], mappedRange[1]));
660       copy.setEnd(Math.max(mappedRange[0], mappedRange[1]));
661       if (".".equals(copy.getFeatureGroup()))
662       {
663         copy.setFeatureGroup(getDbSource());
664       }
665       targetSequence.addSequenceFeature(copy);
666
667       /*
668        * for sequence_variant on reverse strand, have to convert the allele
669        * values to their complements
670        */
671       if (!forwardStrand
672               && SequenceOntologyFactory.getInstance().isA(sf.getType(),
673                       SequenceOntologyI.SEQUENCE_VARIANT))
674       {
675         reverseComplementAlleles(copy);
676       }
677     }
678   }
679
680   /**
681    * Change the 'alleles' value of a feature by converting to complementary
682    * bases, and also update the feature description to match
683    * 
684    * @param sf
685    */
686   static void reverseComplementAlleles(SequenceFeature sf)
687   {
688     final String alleles = (String) sf.getValue(ALLELES);
689     if (alleles == null)
690     {
691       return;
692     }
693     StringBuilder complement = new StringBuilder(alleles.length());
694     for (String allele : alleles.split(","))
695     {
696       reverseComplementAllele(complement, allele);
697     }
698     String comp = complement.toString();
699     sf.setValue(ALLELES, comp);
700     sf.setDescription(comp);
701
702     /*
703      * replace value of "alleles=" in sf.ATTRIBUTES as well
704      * so 'output as GFF' shows reverse complement alleles
705      */
706     String atts = sf.getAttributes();
707     if (atts != null)
708     {
709       atts = atts.replace(ALLELES + "=" + alleles, ALLELES + "=" + comp);
710       sf.setAttributes(atts);
711     }
712   }
713
714   /**
715    * Makes the 'reverse complement' of the given allele and appends it to the
716    * buffer, after a comma separator if not the first
717    * 
718    * @param complement
719    * @param allele
720    */
721   static void reverseComplementAllele(StringBuilder complement,
722           String allele)
723   {
724     if (complement.length() > 0)
725     {
726       complement.append(",");
727     }
728
729     /*
730      * some 'alleles' are actually descriptive terms 
731      * e.g. HGMD_MUTATION, PhenCode_variation
732      * - we don't want to 'reverse complement' these
733      */
734     if (!Comparison.isNucleotideSequence(allele, true))
735     {
736       complement.append(allele);
737     }
738     else
739     {
740       for (int i = allele.length() - 1; i >= 0; i--)
741       {
742         complement.append(Dna.getComplement(allele.charAt(i)));
743       }
744     }
745   }
746
747   /**
748    * Transfers features from sourceSequence to targetSequence
749    * 
750    * @param accessionId
751    * @param sourceSequence
752    * @param targetSequence
753    * @return true if any features were transferred, else false
754    */
755   protected boolean transferFeatures(String accessionId,
756           SequenceI sourceSequence, SequenceI targetSequence)
757   {
758     if (sourceSequence == null || targetSequence == null)
759     {
760       return false;
761     }
762
763     // long start = System.currentTimeMillis();
764     SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
765     MapList mapping = getGenomicRangesFromFeatures(sourceSequence, accessionId,
766             targetSequence.getStart());
767     if (mapping == null)
768     {
769       return false;
770     }
771
772     boolean result = transferFeatures(sfs, targetSequence, mapping,
773             accessionId);
774     // System.out.println("transferFeatures (" + (sfs.length) + " --> "
775     // + targetSequence.getSequenceFeatures().length + ") to "
776     // + targetSequence.getName()
777     // + " took " + (System.currentTimeMillis() - start) + "ms");
778     return result;
779   }
780
781   /**
782    * Transfer features to the target sequence. The start/end positions are
783    * converted using the mapping. Features which do not overlap are ignored.
784    * Features whose parent is not the specified identifier are also ignored.
785    * 
786    * @param features
787    * @param targetSequence
788    * @param mapping
789    * @param parentId
790    * @return
791    */
792   protected boolean transferFeatures(SequenceFeature[] features,
793           SequenceI targetSequence, MapList mapping, String parentId)
794   {
795     final boolean forwardStrand = mapping.isFromForwardStrand();
796
797     /*
798      * sort features by start position (which corresponds to end
799      * position descending if reverse strand) so as to add them in
800      * 'forwards' order to the target sequence
801      */
802     sortFeatures(features, forwardStrand);
803
804     boolean transferred = false;
805     for (SequenceFeature sf : features)
806     {
807       if (retainFeature(sf, parentId))
808       {
809         transferFeature(sf, targetSequence, mapping, forwardStrand);
810         transferred = true;
811       }
812     }
813     return transferred;
814   }
815
816   /**
817    * Sort features by start position ascending (if on forward strand), or end
818    * position descending (if on reverse strand)
819    * 
820    * @param features
821    * @param forwardStrand
822    */
823   protected static void sortFeatures(SequenceFeature[] features,
824           final boolean forwardStrand)
825   {
826     Arrays.sort(features, new Comparator<SequenceFeature>()
827     {
828       @Override
829       public int compare(SequenceFeature o1, SequenceFeature o2)
830       {
831         if (forwardStrand)
832         {
833           return Integer.compare(o1.getBegin(), o2.getBegin());
834         }
835         else
836         {
837           return Integer.compare(o2.getEnd(), o1.getEnd());
838         }
839       }
840     });
841   }
842
843   /**
844    * Answers true if the feature type is one we want to keep for the sequence.
845    * Some features are only retrieved in order to identify the sequence range,
846    * and may then be discarded as redundant information (e.g. "CDS" feature for
847    * a CDS sequence).
848    */
849   @SuppressWarnings("unused")
850   protected boolean retainFeature(SequenceFeature sf, String accessionId)
851   {
852     return true; // override as required
853   }
854
855   /**
856    * Answers true if the feature has a Parent which refers to the given
857    * accession id, or if the feature has no parent. Answers false if the
858    * feature's Parent is for a different accession id.
859    * 
860    * @param sf
861    * @param identifier
862    * @return
863    */
864   protected boolean featureMayBelong(SequenceFeature sf, String identifier)
865   {
866     String parent = (String) sf.getValue(PARENT);
867     // using contains to allow for prefix "gene:", "transcript:" etc
868     if (parent != null && !parent.contains(identifier))
869     {
870       // this genomic feature belongs to a different transcript
871       return false;
872     }
873     return true;
874   }
875
876   @Override
877   public String getDescription()
878   {
879     return "Ensembl " + getSourceEnsemblType().getType()
880             + " sequence with variant features";
881   }
882
883   /**
884    * Returns a (possibly empty) list of features on the sequence which have the
885    * specified sequence ontology type (or a sub-type of it), and the given
886    * identifier as parent
887    * 
888    * @param sequence
889    * @param type
890    * @param parentId
891    * @return
892    */
893   protected List<SequenceFeature> findFeatures(SequenceI sequence,
894           String type, String parentId)
895   {
896     List<SequenceFeature> result = new ArrayList<SequenceFeature>();
897     
898     SequenceFeature[] sfs = sequence.getSequenceFeatures();
899     if (sfs != null) {
900       SequenceOntologyI so = SequenceOntologyFactory.getInstance();
901       for (SequenceFeature sf :sfs) {
902         if (so.isA(sf.getType(), type))
903         {
904           String parent = (String) sf.getValue(PARENT);
905           if (parent.equals(parentId))
906           {
907             result.add(sf);
908           }
909         }
910       }
911     }
912     return result;
913   }
914
915   /**
916    * Answers true if the feature type is either 'NMD_transcript_variant' or
917    * 'transcript' or one of its sub-types in the Sequence Ontology. This is
918    * needed because NMD_transcript_variant behaves like 'transcript' in Ensembl
919    * although strictly speaking it is not (it is a sub-type of
920    * sequence_variant).
921    * 
922    * @param featureType
923    * @return
924    */
925   public static boolean isTranscript(String featureType)
926   {
927     return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
928             || SequenceOntologyFactory.getInstance().isA(featureType,
929                     SequenceOntologyI.TRANSCRIPT);
930   }
931 }