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