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