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