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