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