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