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