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