JAL-1705 further unit tests
[jalview.git] / src / jalview / ext / ensembl / EnsemblSeqProxy.java
1 package jalview.ext.ensembl;
2
3 import jalview.analysis.AlignmentUtils;
4 import jalview.datamodel.Alignment;
5 import jalview.datamodel.AlignmentI;
6 import jalview.datamodel.DBRefEntry;
7 import jalview.datamodel.DBRefSource;
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.schemes.ResidueProperties;
17 import jalview.util.DBRefUtils;
18 import jalview.util.MapList;
19 import jalview.util.MappingUtils;
20 import jalview.util.StringUtils;
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.LinkedHashMap;
30 import java.util.List;
31 import java.util.Map.Entry;
32
33 /**
34  * Base class for Ensembl sequence fetchers
35  * 
36  * @author gmcarstairs
37  */
38 public abstract class EnsemblSeqProxy extends EnsemblRestClient
39 {
40   private static final List<String> CROSS_REFERENCES = Arrays
41           .asList(new String[] { "CCDS" });
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   public enum EnsemblSeqType
52   {
53     /**
54      * type=genomic for the full dna including introns
55      */
56     GENOMIC("genomic"),
57
58     /**
59      * type=cdna for transcribed dna including UTRs
60      */
61     CDNA("cdna"),
62
63     /**
64      * type=cds for coding dna excluding UTRs
65      */
66     CDS("cds"),
67
68     /**
69      * type=protein for the peptide product sequence
70      */
71     PROTEIN("protein");
72
73     /*
74      * the value of the 'type' parameter to fetch this version of 
75      * an Ensembl sequence
76      */
77     private String type;
78
79     EnsemblSeqType(String t)
80     {
81       type = t;
82     }
83
84     public String getType()
85     {
86       return type;
87     }
88
89   }
90
91   /**
92    * A comparator to sort ranges into ascending start position order
93    */
94   private class RangeSorter implements Comparator<int[]>
95   {
96     boolean forwards;
97
98     RangeSorter(boolean forward)
99     {
100       forwards = forward;
101     }
102
103     @Override
104     public int compare(int[] o1, int[] o2)
105     {
106       return (forwards ? 1 : -1) * Integer.compare(o1[0], o2[0]);
107     }
108
109   }
110
111   /**
112    * Constructor
113    */
114   public EnsemblSeqProxy()
115   {
116   }
117
118   /**
119    * Makes the sequence queries to Ensembl's REST service and returns an
120    * alignment consisting of the returned sequences.
121    */
122   @Override
123   public AlignmentI getSequenceRecords(String query) throws Exception
124   {
125     // TODO use a String... query vararg instead?
126
127     // danger: accession separator used as a regex here, a string elsewhere
128     // in this case it is ok (it is just a space), but (e.g.) '\' would not be
129     List<String> allIds = Arrays.asList(query
130             .split(getAccessionSeparator()));
131     AlignmentI alignment = null;
132     inProgress = true;
133
134     /*
135      * execute queries, if necessary in batches of the
136      * maximum allowed number of ids
137      */
138     int maxQueryCount = getMaximumQueryCount();
139     for (int v = 0, vSize = allIds.size(); v < vSize; v += maxQueryCount)
140     {
141       int p = Math.min(vSize, v + maxQueryCount);
142       List<String> ids = allIds.subList(v, p);
143       try
144       {
145         alignment = fetchSequences(ids, alignment);
146       } catch (Throwable r)
147       {
148         inProgress = false;
149         String msg = "Aborting ID retrieval after " + v
150                 + " chunks. Unexpected problem (" + r.getLocalizedMessage()
151                 + ")";
152         System.err.println(msg);
153         break;
154         // if (alignment != null)
155         // {
156         // break; // return what we got
157         // }
158         // else
159         // {
160         // throw new JalviewException(msg, r);
161         // }
162       }
163     }
164
165     /*
166      * fetch and transfer genomic sequence features,
167      * fetch protein product and add as cross-reference
168      */
169     for (String accId : allIds)
170     {
171       addFeaturesAndProduct(accId, alignment);
172     }
173
174     for (SequenceI seq : alignment.getSequences())
175     {
176       getCrossReferences(seq);
177     }
178
179     return alignment;
180   }
181
182   /**
183    * Fetches Ensembl features using the /overlap REST endpoint, and adds them to
184    * the sequence in the alignment. Also fetches the protein product, maps it
185    * from the CDS features of the sequence, and saves it as a cross-reference of
186    * the dna sequence.
187    * 
188    * @param accId
189    * @param alignment
190    */
191   protected void addFeaturesAndProduct(String accId, AlignmentI alignment)
192   {
193     if (alignment == null)
194     {
195       return;
196     }
197
198     try
199     {
200       /*
201        * get 'dummy' genomic sequence with exon, cds and variation features
202        */
203       SequenceI genomicSequence = null;
204       EnsemblOverlap gffFetcher = new EnsemblOverlap();
205       EnsemblFeatureType[] features = getFeaturesToFetch();
206       AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
207               features);
208       if (geneFeatures.getHeight() > 0)
209       {
210         genomicSequence = geneFeatures.getSequenceAt(0);
211       }
212       if (genomicSequence != null)
213       {
214         /*
215          * transfer features to the query sequence
216          */
217         SequenceI querySeq = alignment.findName(accId);
218         if (transferFeatures(accId, genomicSequence, querySeq))
219         {
220
221           /*
222            * fetch and map protein product, and add it as a cross-reference
223            * of the retrieved sequence
224            */
225           addProteinProduct(querySeq);
226         }
227       }
228     } catch (IOException e)
229     {
230       System.err.println("Error transferring Ensembl features: "
231               + e.getMessage());
232     }
233   }
234
235   /**
236    * Returns those sequence feature types to fetch from Ensembl. We may want
237    * features either because they are of interest to the user, or as means to
238    * identify the locations of the sequence on the genomic sequence (CDS
239    * features identify CDS, exon features identify cDNA etc).
240    * 
241    * @return
242    */
243   protected abstract EnsemblFeatureType[] getFeaturesToFetch();
244
245   /**
246    * Fetches and maps the protein product, and adds it as a cross-reference of
247    * the retrieved sequence
248    */
249   protected void addProteinProduct(SequenceI querySeq)
250   {
251     String accId = querySeq.getName();
252     try
253     {
254       AlignmentI protein = new EnsemblProtein().getSequenceRecords(accId);
255       if (protein == null || protein.getHeight() == 0)
256       {
257         System.out.println("Failed to retrieve protein for " + accId);
258         return;
259       }
260       SequenceI proteinSeq = protein.getSequenceAt(0);
261
262       /*
263        * need dataset sequences (to be the subject of mappings)
264        */
265       proteinSeq.createDatasetSequence();
266       querySeq.createDatasetSequence();
267
268       MapList mapList = mapCdsToProtein(querySeq, proteinSeq);
269       if (mapList != null)
270       {
271         Mapping map = new Mapping(proteinSeq.getDatasetSequence(), mapList);
272         DBRefEntry dbr = new DBRefEntry(getDbSource(), getDbVersion(),
273                 accId, map);
274         querySeq.getDatasetSequence().addDBRef(dbr);
275         
276         /*
277          * compute peptide variants from dna variants and add as 
278          * sequence features on the protein sequence ta-da
279          */
280         computeProteinFeatures(querySeq, proteinSeq, mapList);
281       }
282     } catch (Exception e)
283     {
284       System.err
285               .println(String.format("Error retrieving protein for %s: %s",
286                       accId, e.getMessage()));
287     }
288   }
289
290   /**
291    * Get Uniprot and PDB xrefs from Ensembl, and attach them to the protein
292    * sequence
293    * 
294    * @param seq
295    */
296   protected void getCrossReferences(SequenceI seq)
297   {
298     while (seq.getDatasetSequence() != null)
299     {
300       seq = seq.getDatasetSequence();
301     }
302
303     EnsemblXref xrefFetcher = new EnsemblXref();
304     List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName(),
305             getCrossReferenceDatabases());
306     for (DBRefEntry xref : xrefs)
307     {
308       seq.addDBRef(xref);
309       /*
310        * Save any Uniprot xref to be the reference for SIFTS mapping
311        */
312       if (DBRefSource.UNIPROT.equals(xref.getSource()))
313       {
314         seq.setSourceDBRef(xref);
315       }
316     }
317   }
318
319   /**
320    * Returns a list of database names to be used when fetching cross-references.
321    * 
322    * @return
323    */
324   protected List<String> getCrossReferenceDatabases()
325   {
326     return CROSS_REFERENCES;
327   }
328
329   /**
330    * Returns a mapping from dna to protein by inspecting sequence features of
331    * type "CDS" on the dna.
332    * 
333    * @param dnaSeq
334    * @param proteinSeq
335    * @return
336    */
337   protected MapList mapCdsToProtein(SequenceI dnaSeq, SequenceI proteinSeq)
338   {
339     List<int[]> ranges = new ArrayList<int[]>(50);
340
341     int mappedDnaLength = getCdsRanges(dnaSeq, ranges);
342
343     int proteinLength = proteinSeq.getLength();
344     List<int[]> proteinRange = new ArrayList<int[]>();
345     int proteinStart = 1;
346
347     /*
348      * incomplete start codon may mean X at start of peptide
349      * we ignore both for mapping purposes
350      */
351     if (proteinSeq.getCharAt(0) == 'X')
352     {
353       proteinStart = 2;
354       proteinLength--;
355     }
356     proteinRange.add(new int[] { proteinStart, proteinLength });
357
358     /*
359      * dna length should map to protein (or protein plus stop codon)
360      */
361     int codesForResidues = mappedDnaLength / 3;
362     if (codesForResidues == proteinLength
363             || codesForResidues == (proteinLength + 1))
364     {
365       return new MapList(ranges, proteinRange, 3, 1);
366     }
367     return null;
368   }
369
370   /**
371    * Adds CDS ranges to the ranges list, and returns the total length mapped
372    * from.
373    * 
374    * No need to worry about reverse strand dna, here since the retrieved
375    * sequence is as transcribed (reverse complement for reverse strand), i.e in
376    * the same sense as the peptide.
377    * 
378    * @param dnaSeq
379    * @param ranges
380    * @return
381    */
382   protected int getCdsRanges(SequenceI dnaSeq, List<int[]> ranges)
383   {
384     SequenceFeature[] sfs = dnaSeq.getSequenceFeatures();
385     if (sfs == null)
386     {
387       return 0;
388     }
389     int mappedDnaLength = 0;
390     for (SequenceFeature sf : sfs)
391     {
392       /*
393        * process a CDS feature (or a sub-type of CDS)
394        */
395       if (SequenceOntologyFactory.getInstance().isA(sf.getType(),
396               SequenceOntologyI.CDS))
397       {
398         int phase = 0;
399         try {
400           phase = Integer.parseInt(sf.getPhase());
401         } catch (NumberFormatException e)
402         {
403           // ignore
404         }
405         /*
406          * phase > 0 on first codon means 5' incomplete - skip to the start
407          * of the next codon; example ENST00000496384
408          */
409         int begin = sf.getBegin();
410         int end = sf.getEnd();
411         if (ranges.isEmpty() && phase > 0)
412         {
413           begin += phase;
414           if (begin > end)
415           {
416             continue; // shouldn't happen?
417           }
418         }
419         ranges.add(new int[] { begin, end });
420         mappedDnaLength += Math.abs(end - begin) + 1;
421       }
422     }
423     return mappedDnaLength;
424   }
425
426   /**
427    * Fetches sequences for the list of accession ids and adds them to the
428    * alignment. Returns the extended (or created) alignment.
429    * 
430    * @param ids
431    * @param alignment
432    * @return
433    * @throws JalviewException
434    * @throws IOException
435    */
436   protected AlignmentI fetchSequences(List<String> ids, AlignmentI alignment)
437           throws JalviewException, IOException
438   {
439     if (!isEnsemblAvailable())
440     {
441       inProgress = false;
442       throw new JalviewException("ENSEMBL Rest API not available.");
443     }
444     FileParse fp = getSequenceReader(ids);
445     FastaFile fr = new FastaFile(fp);
446     if (fr.hasWarningMessage())
447     {
448       System.out.println(String.format(
449               "Warning when retrieving %d ids %s\n%s", ids.size(),
450               ids.toString(), fr.getWarningMessage()));
451     }
452     else if (fr.getSeqs().size() != ids.size())
453     {
454       System.out.println(String.format(
455               "Only retrieved %d sequences for %d query strings", fr
456                       .getSeqs().size(), ids.size()));
457     }
458
459     if (fr.getSeqs().size() == 1 && fr.getSeqs().get(0).getLength() == 0)
460     {
461       /*
462        * POST request has returned an empty FASTA file e.g. for invalid id
463        */
464       throw new IOException("No data returned for " + ids);
465     }
466
467     if (fr.getSeqs().size() > 0)
468     {
469       AlignmentI seqal = new Alignment(
470               fr.getSeqsAsArray());
471       for (SequenceI sq:seqal.getSequences())
472       {
473         if (sq.getDescription() == null)
474         {
475           sq.setDescription(getDbName());
476         }
477         String name = sq.getName();
478         if (ids.contains(name)
479                 || ids.contains(name.replace("ENSP", "ENST")))
480         {
481           DBRefUtils.parseToDbRef(sq, DBRefSource.ENSEMBL, "0", name);
482         }
483       }
484       if (alignment == null)
485       {
486         alignment = seqal;
487       }
488       else
489       {
490         alignment.append(seqal);
491       }
492     }
493     return alignment;
494   }
495
496   /**
497    * Returns the URL for the REST call
498    * 
499    * @return
500    * @throws MalformedURLException
501    */
502   @Override
503   protected URL getUrl(List<String> ids) throws MalformedURLException
504   {
505     /*
506      * a single id is included in the URL path
507      * multiple ids go in the POST body instead
508      */
509     StringBuffer urlstring = new StringBuffer(128);
510     urlstring.append(SEQUENCE_ID_URL);
511     if (ids.size() == 1)
512     {
513       urlstring.append("/").append(ids.get(0));
514     }
515     // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
516     urlstring.append("?type=").append(getSourceEnsemblType().getType());
517     urlstring.append(("&Accept=text/x-fasta"));
518
519     URL url = new URL(urlstring.toString());
520     return url;
521   }
522
523   /**
524    * A sequence/id POST request currently allows up to 50 queries
525    * 
526    * @see http://rest.ensembl.org/documentation/info/sequence_id_post
527    */
528   @Override
529   public int getMaximumQueryCount()
530   {
531     return 50;
532   }
533
534   @Override
535   protected boolean useGetRequest()
536   {
537     return false;
538   }
539
540   @Override
541   protected String getRequestMimeType(boolean multipleIds)
542   {
543     return multipleIds ? "application/json" : "text/x-fasta";
544   }
545
546   @Override
547   protected String getResponseMimeType()
548   {
549     return "text/x-fasta";
550   }
551
552   /**
553    * 
554    * @return the configured sequence return type for this source
555    */
556   protected abstract EnsemblSeqType getSourceEnsemblType();
557
558   /**
559    * Returns a list of [start, end] genomic ranges corresponding to the sequence
560    * being retrieved.
561    * 
562    * The correspondence between the frames of reference is made by locating
563    * those features on the genomic sequence which identify the retrieved
564    * sequence. Specifically
565    * <ul>
566    * <li>genomic sequence is identified by "transcript" features with
567    * ID=transcript:transcriptId</li>
568    * <li>cdna sequence is identified by "exon" features with
569    * Parent=transcript:transcriptId</li>
570    * <li>cds sequence is identified by "CDS" features with
571    * Parent=transcript:transcriptId</li>
572    * </ul>
573    * 
574    * The returned ranges are sorted to run forwards (for positive strand) or
575    * backwards (for negative strand). Aborts and returns null if both positive
576    * and negative strand are found (this should not normally happen).
577    * 
578    * @param sourceSequence
579    * @param accId
580    * @param start
581    *          the start position of the sequence we are mapping to
582    * @return
583    */
584   protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
585           String accId, int start)
586   {
587     SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
588     if (sfs == null)
589     {
590       return null;
591     }
592
593     /*
594      * generously initial size for number of cds regions
595      * (worst case titin Q8WZ42 has c. 313 exons)
596      */
597     List<int[]> regions = new ArrayList<int[]>(100);
598     int mappedLength = 0;
599     int direction = 1; // forward
600     boolean directionSet = false;
601   
602     for (SequenceFeature sf : sfs)
603     {
604       /*
605        * accept the target feature type or a specialisation of it
606        * (e.g. coding_exon for exon)
607        */
608       if (identifiesSequence(sf, accId))
609       {
610         int strand = sf.getStrand();
611         strand = strand == 0 ? 1 : strand; // treat unknown as forward
612
613         if (directionSet && strand != direction)
614         {
615           // abort - mix of forward and backward
616           System.err.println("Error: forward and backward strand for "
617                   + accId);
618             return null;
619           }
620           direction = strand;
621           directionSet = true;
622   
623           /*
624            * add to CDS ranges, semi-sorted forwards/backwards
625            */
626           if (strand < 0)
627           {
628             regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
629           }
630           else
631           {
632           regions.add(new int[] { sf.getBegin(), sf.getEnd() });
633         }
634         mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
635
636         if (!isSpliceable())
637         {
638           /*
639            * 'gene' sequence is contiguous so we can stop as soon as its
640            * identifying feature has been found
641            */
642           break;
643         }
644       }
645     }
646   
647     if (regions.isEmpty())
648     {
649       System.out.println("Failed to identify target sequence for " + accId
650               + " from genomic features");
651       return null;
652     }
653
654     /*
655      * a final sort is needed since Ensembl returns CDS sorted within source
656      * (havana / ensembl_havana)
657      */
658     Collections.sort(regions, new RangeSorter(direction == 1));
659   
660     List<int[]> to = Arrays.asList(new int[] { start,
661         start + mappedLength - 1 });
662   
663     return new MapList(regions, to, 1, 1);
664   }
665
666   /**
667    * Answers true if the sequence being retrieved may occupy discontiguous
668    * regions on the genomic sequence.
669    */
670   protected boolean isSpliceable()
671   {
672     return true;
673   }
674
675   /**
676    * Returns true if the sequence feature marks positions of the genomic
677    * sequence feature which are within the sequence being retrieved. For
678    * example, an 'exon' feature whose parent is the target transcript marks the
679    * cdna positions of the transcript.
680    * 
681    * @param sf
682    * @param accId
683    * @return
684    */
685   protected abstract boolean identifiesSequence(SequenceFeature sf,
686           String accId);
687
688   /**
689    * Transfers the sequence feature to the target sequence, locating its start
690    * and end range based on the mapping. Features which do not overlap the
691    * target sequence are ignored.
692    * 
693    * @param sf
694    * @param targetSequence
695    * @param mapping
696    *          mapping from the sequence feature's coordinates to the target
697    *          sequence
698    */
699   protected void transferFeature(SequenceFeature sf,
700           SequenceI targetSequence, MapList mapping)
701   {
702     int start = sf.getBegin();
703     int end = sf.getEnd();
704     int[] mappedRange = mapping.locateInTo(start, end);
705   
706     if (mappedRange != null)
707     {
708       SequenceFeature copy = new SequenceFeature(sf);
709       copy.setBegin(Math.min(mappedRange[0], mappedRange[1]));
710       copy.setEnd(Math.max(mappedRange[0], mappedRange[1]));
711       targetSequence.addSequenceFeature(copy);
712
713       /*
714        * for sequence_variant, make an additional feature with consequence
715        */
716       if (SequenceOntologyFactory.getInstance().isA(sf.getType(),
717               SequenceOntologyI.SEQUENCE_VARIANT))
718       {
719         String consequence = (String) sf.getValue(CONSEQUENCE_TYPE);
720         if (consequence != null)
721         {
722           SequenceFeature sf2 = new SequenceFeature("consequence",
723                   consequence, copy.getBegin(), copy.getEnd(), 0f,
724                   null);
725           targetSequence.addSequenceFeature(sf2);
726         }
727       }
728     }
729   }
730
731   /**
732    * Transfers features from sourceSequence to targetSequence
733    * 
734    * @param accessionId
735    * @param sourceSequence
736    * @param targetSequence
737    * @return true if any features were transferred, else false
738    */
739   protected boolean transferFeatures(String accessionId,
740           SequenceI sourceSequence, SequenceI targetSequence)
741   {
742     if (sourceSequence == null || targetSequence == null)
743     {
744       return false;
745     }
746
747     SequenceFeature[] sfs = sourceSequence.getSequenceFeatures();
748     MapList mapping = getGenomicRangesFromFeatures(sourceSequence, accessionId,
749             targetSequence.getStart());
750     if (mapping == null)
751     {
752       return false;
753     }
754
755     return transferFeatures(sfs, targetSequence, mapping, accessionId);
756   }
757
758   /**
759    * Transfer features to the target sequence. The start/end positions are
760    * converted using the mapping. Features which do not overlap are ignored.
761    * Features whose parent is not the specified identifier are also ignored.
762    * 
763    * @param features
764    * @param targetSequence
765    * @param mapping
766    * @param parentId
767    * @return
768    */
769   protected boolean transferFeatures(SequenceFeature[] features,
770           SequenceI targetSequence, MapList mapping, String parentId)
771   {
772     final boolean forwardStrand = mapping.isFromForwardStrand();
773
774     /*
775      * sort features by start position (descending if reverse strand) 
776      * before transferring (in forwards order) to the target sequence
777      */
778     Arrays.sort(features, new Comparator<SequenceFeature>()
779     {
780       @Override
781       public int compare(SequenceFeature o1, SequenceFeature o2)
782       {
783         int c = Integer.compare(o1.getBegin(), o2.getBegin());
784         return forwardStrand ? c : -c;
785       }
786     });
787
788     boolean transferred = false;
789     for (SequenceFeature sf : features)
790     {
791       if (retainFeature(sf, parentId))
792       {
793         transferFeature(sf, targetSequence, mapping);
794         transferred = true;
795       }
796     }
797     return transferred;
798   }
799
800   /**
801    * Answers true if the feature type is one we want to keep for the sequence.
802    * Some features are only retrieved in order to identify the sequence range,
803    * and may then be discarded as redundant information (e.g. "CDS" feature for
804    * a CDS sequence).
805    */
806   @SuppressWarnings("unused")
807   protected boolean retainFeature(SequenceFeature sf, String accessionId)
808   {
809     return true; // override as required
810   }
811
812   /**
813    * Answers true if the feature has a Parent which refers to the given
814    * accession id, or if the feature has no parent. Answers false if the
815    * feature's Parent is for a different accession id.
816    * 
817    * @param sf
818    * @param identifier
819    * @return
820    */
821   protected boolean featureMayBelong(SequenceFeature sf, String identifier)
822   {
823     String parent = (String) sf.getValue(PARENT);
824     // using contains to allow for prefix "gene:", "transcript:" etc
825     if (parent != null && !parent.contains(identifier))
826     {
827       // this genomic feature belongs to a different transcript
828       return false;
829     }
830     return true;
831   }
832
833   @Override
834   public String getDescription()
835   {
836     return "Ensembl " + getSourceEnsemblType().getType()
837             + " sequence with variant features";
838   }
839
840   /**
841    * Returns a (possibly empty) list of features on the sequence which have the
842    * specified sequence ontology type (or a sub-type of it), and the given
843    * identifier as parent
844    * 
845    * @param sequence
846    * @param type
847    * @param parentId
848    * @return
849    */
850   protected List<SequenceFeature> findFeatures(SequenceI sequence,
851           String type, String parentId)
852   {
853     List<SequenceFeature> result = new ArrayList<SequenceFeature>();
854     
855     SequenceFeature[] sfs = sequence.getSequenceFeatures();
856     if (sfs != null) {
857       SequenceOntologyI so = SequenceOntologyFactory.getInstance();
858       for (SequenceFeature sf :sfs) {
859         if (so.isA(sf.getType(), type))
860         {
861           String parent = (String) sf.getValue(PARENT);
862           if (parent.equals(parentId))
863           {
864             result.add(sf);
865           }
866         }
867       }
868     }
869     return result;
870   }
871
872   /**
873    * Maps exon features from dna to protein, and computes variants in peptide
874    * product generated by variants in dna, and adds them as sequence_variant
875    * features on the protein sequence. Returns the number of variant features
876    * added.
877    * 
878    * @param dnaSeq
879    * @param peptide
880    * @param dnaToProtein
881    */
882   static int computeProteinFeatures(SequenceI dnaSeq,
883           SequenceI peptide, MapList dnaToProtein)
884   {
885     while (dnaSeq.getDatasetSequence() != null)
886     {
887       dnaSeq = dnaSeq.getDatasetSequence();
888     }
889     while (peptide.getDatasetSequence() != null)
890     {
891       peptide = peptide.getDatasetSequence();
892     }
893   
894     AlignmentUtils.transferFeatures(dnaSeq, peptide, dnaToProtein,
895             SequenceOntologyI.EXON);
896
897     LinkedHashMap<Integer, String[][]> variants = buildDnaVariantsMap(
898             dnaSeq, dnaToProtein);
899   
900     /*
901      * scan codon variations, compute peptide variants and add to peptide sequence
902      */
903     int count = 0;
904     for (Entry<Integer, String[][]> variant : variants.entrySet())
905     {
906       int peptidePos = variant.getKey();
907       String[][] codonVariants = variant.getValue();
908       String residue = String.valueOf(peptide.getCharAt(peptidePos - 1)); // 0-based
909       List<String> peptideVariants = computePeptideVariants(codonVariants,
910               residue);
911       if (!peptideVariants.isEmpty())
912       {
913         String desc = StringUtils.listToDelimitedString(peptideVariants,
914                 ", ");
915         SequenceFeature sf = new SequenceFeature(
916                 SequenceOntologyI.SEQUENCE_VARIANT, desc, peptidePos,
917                 peptidePos, 0f, null);
918         peptide.addSequenceFeature(sf);
919         count++;
920       }
921     }
922     return count;
923   }
924
925   /**
926    * Builds a map whose key is position in the protein sequence, and value is an
927    * array of all variants for the coding codon positions
928    * 
929    * @param dnaSeq
930    * @param dnaToProtein
931    * @return
932    */
933   static LinkedHashMap<Integer, String[][]> buildDnaVariantsMap(
934           SequenceI dnaSeq, MapList dnaToProtein)
935   {
936     /*
937      * map from peptide position to all variant features of the codon for it
938      * LinkedHashMap ensures we add the peptide features in sequence order
939      */
940     LinkedHashMap<Integer, String[][]> variants = new LinkedHashMap<Integer, String[][]>();
941     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
942   
943     SequenceFeature[] dnaFeatures = dnaSeq.getSequenceFeatures();
944     if (dnaFeatures == null)
945     {
946       return variants;
947     }
948   
949     int dnaStart = dnaSeq.getStart();
950     int[] lastCodon = null;
951     int lastPeptidePostion = 0;
952   
953     /*
954      * build a map of codon variations for peptides
955      */
956     for (SequenceFeature sf : dnaFeatures)
957     {
958       int dnaCol = sf.getBegin();
959       if (dnaCol != sf.getEnd())
960       {
961         // not handling multi-locus variant features
962         continue;
963       }
964       if (so.isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
965       {
966         int[] mapsTo = dnaToProtein.locateInTo(dnaCol, dnaCol);
967         if (mapsTo == null)
968         {
969           // feature doesn't lie within coding region
970           continue;
971         }
972         int peptidePosition = mapsTo[0];
973         String[][] codonVariants = variants.get(peptidePosition);
974         if (codonVariants == null)
975         {
976           codonVariants = new String[3][];
977           variants.put(peptidePosition, codonVariants);
978         }
979   
980         /*
981          * extract dna variants to a string array
982          */
983         String alls = (String) sf.getValue("alleles");
984         if (alls == null)
985         {
986           continue;
987         }
988         String[] alleles = alls.split(",");
989   
990         /*
991          * get this peptides codon positions e.g. [3, 4, 5] or [4, 7, 10]
992          */
993         int[] codon = peptidePosition == lastPeptidePostion ? lastCodon
994                 : MappingUtils.flattenRanges(dnaToProtein.locateInFrom(
995                         peptidePosition, peptidePosition));
996         lastPeptidePostion = peptidePosition;
997         lastCodon = codon;
998   
999         /*
1000          * save nucleotide (and this variant) for each codon position
1001          */
1002         for (int codonPos = 0; codonPos < 3; codonPos++)
1003         {
1004           String nucleotide = String.valueOf(dnaSeq
1005                   .getCharAt(codon[codonPos] - dnaStart));
1006           if (codon[codonPos] == dnaCol)
1007           {
1008             /*
1009              * record current dna base and its alleles
1010              */
1011             String[] dnaVariants = new String[alleles.length + 1];
1012             dnaVariants[0] = nucleotide;
1013             System.arraycopy(alleles, 0, dnaVariants, 1, alleles.length);
1014             codonVariants[codonPos] = dnaVariants;
1015           }
1016           else if (codonVariants[codonPos] == null)
1017           {
1018             /*
1019              * record current dna base only 
1020              * (at least until we find any variation and overwrite it)
1021              */
1022             codonVariants[codonPos] = new String[] { nucleotide };
1023           }
1024         }
1025       }
1026     }
1027     return variants;
1028   }
1029
1030   /**
1031    * Returns a sorted, non-redundant list of all peptide translations generated
1032    * by the given dna variants, excluding the current residue value
1033    * 
1034    * @param codonVariants
1035    *          an array of base values (acgtACGT) for codon positions 1, 2, 3
1036    * @param residue
1037    *          the current residue translation
1038    * @return
1039    */
1040   static List<String> computePeptideVariants(
1041           String[][] codonVariants, String residue)
1042   {
1043     List<String> result = new ArrayList<String>();
1044     for (String base1 : codonVariants[0])
1045     {
1046       for (String base2 : codonVariants[1])
1047       {
1048         for (String base3 : codonVariants[2])
1049         {
1050           String codon = base1 + base2 + base3;
1051           // TODO: report frameshift/insertion/deletion
1052           // and multiple-base variants?!
1053           String peptide = codon.contains("-") ? "-" : ResidueProperties
1054                   .codonTranslate(codon);
1055           if (peptide != null && !result.contains(peptide)
1056                   && !peptide.equalsIgnoreCase(residue))
1057           {
1058             result.add(peptide);
1059           }
1060         }
1061       }
1062     }
1063
1064     /*
1065      * sort alphabetically with STOP at the end
1066      */
1067     Collections.sort(result, new Comparator<String>()
1068     {
1069
1070       @Override
1071       public int compare(String o1, String o2)
1072       {
1073         if ("STOP".equals(o1))
1074         {
1075           return 1;
1076         }
1077         else if ("STOP".equals(o2))
1078         {
1079           return -1;
1080         }
1081         else
1082         {
1083           return o1.compareTo(o2);
1084         }
1085       }
1086     });
1087     return result;
1088   }
1089
1090   /**
1091    * Answers true if the feature type is either 'NMD_transcript_variant' or
1092    * 'transcript' or one of its sub-types in the Sequence Ontology. This is
1093    * needed because NMD_transcript_variant behaves like 'transcript' in Ensembl
1094    * although strictly speaking it is not (it is a sub-type of
1095    * sequence_variant).
1096    * 
1097    * @param featureType
1098    * @return
1099    */
1100   public static boolean isTranscript(String featureType)
1101   {
1102     return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
1103             || SequenceOntologyFactory.getInstance().isA(featureType,
1104                     SequenceOntologyI.TRANSCRIPT);
1105   }
1106 }