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