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