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