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