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