JAL-2114 save 'raw' ENA location as a sequence feature attribute
[jalview.git] / src / jalview / datamodel / xdb / embl / EmblEntry.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.datamodel.xdb.embl;
22
23 import jalview.analysis.SequenceIdMatcher;
24 import jalview.datamodel.DBRefEntry;
25 import jalview.datamodel.DBRefSource;
26 import jalview.datamodel.FeatureProperties;
27 import jalview.datamodel.Mapping;
28 import jalview.datamodel.Sequence;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceI;
31 import jalview.util.DBRefUtils;
32 import jalview.util.DnaUtils;
33 import jalview.util.MapList;
34 import jalview.util.MappingUtils;
35 import jalview.util.StringUtils;
36
37 import java.util.Arrays;
38 import java.util.Hashtable;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.Map.Entry;
42 import java.util.Vector;
43 import java.util.regex.Pattern;
44
45 /**
46  * Data model for one entry returned from an EMBL query, as marshalled by a
47  * Castor binding file
48  * 
49  * For example:
50  * http://www.ebi.ac.uk/Tools/dbfetch/dbfetch?db=ena_sequence&id=J03321
51  * &format=emblxml
52  * 
53  * @see embl_mapping.xml
54  */
55 public class EmblEntry
56 {
57   private static final Pattern SPACE_PATTERN = Pattern.compile(" ");
58
59   String accession;
60
61   String entryVersion;
62
63   String sequenceVersion;
64
65   String moleculeType;
66
67   String topology;
68
69   String sequenceLength;
70
71   String taxDivision;
72
73   String desc;
74
75   String rCreated;
76
77   String rLastUpdated;
78
79   String lastUpdated;
80
81   Vector<String> keywords;
82
83   Vector<DBRefEntry> dbRefs;
84
85   Vector<EmblFeature> features;
86
87   EmblSequence sequence;
88
89   /**
90    * @return the accession
91    */
92   public String getAccession()
93   {
94     return accession;
95   }
96
97   /**
98    * @param accession
99    *          the accession to set
100    */
101   public void setAccession(String accession)
102   {
103     this.accession = accession;
104   }
105
106   /**
107    * @return the dbRefs
108    */
109   public Vector<DBRefEntry> getDbRefs()
110   {
111     return dbRefs;
112   }
113
114   /**
115    * @param dbRefs
116    *          the dbRefs to set
117    */
118   public void setDbRefs(Vector<DBRefEntry> dbRefs)
119   {
120     this.dbRefs = dbRefs;
121   }
122
123   /**
124    * @return the desc
125    */
126   public String getDesc()
127   {
128     return desc;
129   }
130
131   /**
132    * @param desc
133    *          the desc to set
134    */
135   public void setDesc(String desc)
136   {
137     this.desc = desc;
138   }
139
140   /**
141    * @return the features
142    */
143   public Vector<EmblFeature> getFeatures()
144   {
145     return features;
146   }
147
148   /**
149    * @param features
150    *          the features to set
151    */
152   public void setFeatures(Vector<EmblFeature> features)
153   {
154     this.features = features;
155   }
156
157   /**
158    * @return the keywords
159    */
160   public Vector<String> getKeywords()
161   {
162     return keywords;
163   }
164
165   /**
166    * @param keywords
167    *          the keywords to set
168    */
169   public void setKeywords(Vector<String> keywords)
170   {
171     this.keywords = keywords;
172   }
173
174   /**
175    * @return the lastUpdated
176    */
177   public String getLastUpdated()
178   {
179     return lastUpdated;
180   }
181
182   /**
183    * @param lastUpdated
184    *          the lastUpdated to set
185    */
186   public void setLastUpdated(String lastUpdated)
187   {
188     this.lastUpdated = lastUpdated;
189   }
190
191   /**
192    * @return the releaseCreated
193    */
194   public String getRCreated()
195   {
196     return rCreated;
197   }
198
199   /**
200    * @param releaseCreated
201    *          the releaseCreated to set
202    */
203   public void setRCreated(String releaseCreated)
204   {
205     this.rCreated = releaseCreated;
206   }
207
208   /**
209    * @return the releaseLastUpdated
210    */
211   public String getRLastUpdated()
212   {
213     return rLastUpdated;
214   }
215
216   /**
217    * @param releaseLastUpdated
218    *          the releaseLastUpdated to set
219    */
220   public void setRLastUpdated(String releaseLastUpdated)
221   {
222     this.rLastUpdated = releaseLastUpdated;
223   }
224
225   /**
226    * @return the sequence
227    */
228   public EmblSequence getSequence()
229   {
230     return sequence;
231   }
232
233   /**
234    * @param sequence
235    *          the sequence to set
236    */
237   public void setSequence(EmblSequence sequence)
238   {
239     this.sequence = sequence;
240   }
241
242   /**
243    * @return the taxDivision
244    */
245   public String getTaxDivision()
246   {
247     return taxDivision;
248   }
249
250   /**
251    * @param taxDivision
252    *          the taxDivision to set
253    */
254   public void setTaxDivision(String taxDivision)
255   {
256     this.taxDivision = taxDivision;
257   }
258
259   /**
260    * @return the entry version
261    */
262   public String getEntryVersion()
263   {
264     return entryVersion;
265   }
266
267   /**
268    * @param version
269    *          the version to set
270    */
271   public void setEntryVersion(String version)
272   {
273     this.entryVersion = version;
274   }
275
276   /**
277    * Recover annotated sequences from EMBL file
278    * 
279    * @param sourceDb
280    * @param peptides
281    *          a list of protein products found so far (to add to)
282    * @return dna dataset sequence with DBRefs and features
283    */
284   public SequenceI getSequence(String sourceDb, List<SequenceI> peptides)
285   {
286     SequenceI dna = new Sequence(sourceDb + "|" + accession,
287             sequence.getSequence());
288     dna.setDescription(desc);
289     DBRefEntry retrievedref = new DBRefEntry(sourceDb,
290             getSequenceVersion(), accession);
291     dna.addDBRef(retrievedref);
292     // add map to indicate the sequence is a valid coordinate frame for the
293     // dbref
294     retrievedref.setMap(new Mapping(null, new int[] { 1, dna.getLength() },
295             new int[] { 1, dna.getLength() }, 1, 1));
296     // TODO: transform EMBL Database refs to canonical form
297     if (dbRefs != null)
298     {
299       for (DBRefEntry dbref : dbRefs)
300       {
301         dna.addDBRef(dbref);
302       }
303     }
304
305     try
306     {
307       for (EmblFeature feature : features)
308       {
309         if (feature.dbRefs != null)
310         {
311           for (DBRefEntry dbref : feature.dbRefs)
312           {
313             dna.addDBRef(dbref);
314           }
315         }
316         if (FeatureProperties.isCodingFeature(sourceDb, feature.getName()))
317         {
318           parseCodingFeature(feature, sourceDb, dna, peptides);
319         }
320       }
321     } catch (Exception e)
322     {
323       System.err.println("EMBL Record Features parsing error!");
324       System.err
325               .println("Please report the following to help@jalview.org :");
326       System.err.println("EMBL Record " + accession);
327       System.err.println("Resulted in exception: " + e.getMessage());
328       e.printStackTrace(System.err);
329     }
330
331     return dna;
332   }
333
334   /**
335    * Extracts coding region and product from a CDS feature and properly decorate
336    * it with annotations.
337    * 
338    * @param feature
339    *          coding feature
340    * @param sourceDb
341    *          source database for the EMBLXML
342    * @param dna
343    *          parent dna sequence for this record
344    * @param peptides
345    *          list of protein product sequences for Embl entry
346    */
347   void parseCodingFeature(EmblFeature feature, String sourceDb,
348           SequenceI dna, List<SequenceI> peptides)
349   {
350     boolean isEmblCdna = sourceDb.equals(DBRefSource.EMBLCDS);
351
352     int[] exon = getCdsRanges(feature);
353
354     String prseq = null;
355     String prname = "";
356     String prid = null;
357     Map<String, String> vals = new Hashtable<String, String>();
358     SequenceIdMatcher matcher = new SequenceIdMatcher(peptides);
359
360     /*
361      * codon_start 1/2/3 in EMBL corresponds to phase 0/1/2 in CDS
362      * (phase is required for CDS features in GFF3 format)
363      */
364     int codonStart = 1;
365
366     /*
367      * parse qualifiers, saving protein translation, protein id,
368      * codon start position, product (name), and 'other values'
369      */
370     if (feature.getQualifiers() != null)
371     {
372       for (Qualifier q : feature.getQualifiers())
373       {
374         String qname = q.getName();
375         if (qname.equals("translation"))
376         {
377           // remove all spaces (precompiled String.replaceAll(" ", ""))
378           prseq = SPACE_PATTERN.matcher(q.getValues()[0]).replaceAll("");
379         }
380         else if (qname.equals("protein_id"))
381         {
382           prid = q.getValues()[0];
383         }
384         else if (qname.equals("codon_start"))
385         {
386           try
387           {
388             codonStart = Integer.parseInt(q.getValues()[0]);
389           } catch (NumberFormatException e)
390           {
391             System.err.println("Invalid codon_start in XML for "
392                     + accession + ": " + e.getMessage());
393           }
394         }
395         else if (qname.equals("product"))
396         {
397           // sometimes name is returned e.g. for V00488
398           prname = q.getValues()[0];
399         }
400         else
401         {
402           // throw anything else into the additional properties hash
403           String[] qvals = q.getValues();
404           if (qvals != null)
405           {
406             String commaSeparated = StringUtils.arrayToSeparatorList(qvals,
407                     ",");
408             vals.put(qname, commaSeparated);
409           }
410         }
411       }
412     }
413
414     DBRefEntry protEMBLCDS = null;
415     exon = MappingUtils.removeStartPositions(codonStart - 1, exon);
416     boolean noProteinDbref = true;
417
418     SequenceI product = null;
419     Mapping map = null;
420     if (prseq != null && prname != null && prid != null)
421     {
422       /*
423        * look for product in peptides list, if not found, add it
424        */
425       product = matcher.findIdMatch(prid);
426       if (product == null)
427       {
428         product = new Sequence(prid, prseq, 1, prseq.length());
429         product.setDescription(((prname.length() == 0) ? "Protein Product from "
430                 + sourceDb
431                 : prname));
432         peptides.add(product);
433         matcher.add(product);
434       }
435
436       // we have everything - create the mapping and perhaps the protein
437       // sequence
438       if (exon == null || exon.length == 0)
439       {
440         System.err
441                 .println("Implementation Notice: EMBLCDS records not properly supported yet - Making up the CDNA region of this sequence... may be incorrect ("
442                         + sourceDb + ":" + getAccession() + ")");
443         if (prseq.length() * 3 == (1 - codonStart + dna.getSequence().length))
444         {
445           System.err
446                   .println("Not allowing for additional stop codon at end of cDNA fragment... !");
447           // this might occur for CDS sequences where no features are
448           // marked.
449           exon = new int[] { dna.getStart() + (codonStart - 1),
450               dna.getEnd() };
451           map = new Mapping(product, exon, new int[] { 1, prseq.length() },
452                   3, 1);
453         }
454         if ((prseq.length() + 1) * 3 == (1 - codonStart + dna.getSequence().length))
455         {
456           System.err
457                   .println("Allowing for additional stop codon at end of cDNA fragment... will probably cause an error in VAMSAs!");
458           exon = new int[] { dna.getStart() + (codonStart - 1),
459               dna.getEnd() - 3 };
460           map = new Mapping(product, exon, new int[] { 1, prseq.length() },
461                   3, 1);
462         }
463       }
464       else
465       {
466         // Trim the exon mapping if necessary - the given product may only be a
467         // fragment of a larger protein. (EMBL:AY043181 is an example)
468
469         if (isEmblCdna)
470         {
471           // TODO: Add a DbRef back to the parent EMBL sequence with the exon
472           // map
473           // if given a dataset reference, search dataset for parent EMBL
474           // sequence if it exists and set its map
475           // make a new feature annotating the coding contig
476         }
477         else
478         {
479           // final product length truncation check
480           // TODO should from range include stop codon even if not in protein
481           // in order to include stop codon in CDS sequence (as done for
482           // Ensembl)?
483           int[] cdsRanges = adjustForProteinLength(prseq.length(), exon);
484           map = new Mapping(product, cdsRanges, new int[] { 1,
485               prseq.length() }, 3, 1);
486           // reconstruct the EMBLCDS entry
487           // TODO: this is only necessary when there codon annotation is
488           // complete (I think JBPNote)
489           DBRefEntry pcdnaref = new DBRefEntry();
490           pcdnaref.setAccessionId(prid);
491           pcdnaref.setSource(DBRefSource.EMBLCDS);
492           pcdnaref.setVersion(getSequenceVersion()); // same as parent EMBL
493                                                      // version.
494           MapList mp = new MapList(new int[] { 1, prseq.length() },
495                   new int[] { 1 + (codonStart - 1),
496                       (codonStart - 1) + 3 * prseq.length() }, 1, 3);
497           pcdnaref.setMap(new Mapping(mp));
498           if (product != null)
499           {
500             product.addDBRef(pcdnaref);
501             protEMBLCDS = new DBRefEntry(pcdnaref);
502             protEMBLCDS.setSource(DBRefSource.EMBLCDSProduct);
503             product.addDBRef(protEMBLCDS);
504           }
505         }
506       }
507       // add cds feature to dna seq - this may include the stop codon
508       for (int xint = 0; exon != null && xint < exon.length; xint += 2)
509       {
510         SequenceFeature sf = makeCdsFeature(exon, xint, prname, prid, vals,
511                 codonStart);
512         sf.setType(feature.getName()); // "CDS"
513         sf.setEnaLocation(feature.getLocation());
514         sf.setFeatureGroup(sourceDb);
515         dna.addSequenceFeature(sf);
516       }
517     }
518
519     /*
520      * add dbRefs to sequence, and mappings for Uniprot xrefs
521      */
522     if (feature.dbRefs != null)
523     {
524       boolean mappingUsed = false;
525       for (DBRefEntry ref : feature.dbRefs)
526       {
527         ref.setSource(DBRefUtils.getCanonicalName(ref.getSource()));
528         if (ref.getSource().equals(DBRefSource.UNIPROT))
529         {
530           String proteinSeqName = DBRefSource.UNIPROT + "|"
531                   + ref.getAccessionId();
532           if (map != null && map.getTo() != null)
533           {
534             if (mappingUsed)
535             {
536               /*
537                * two or more Uniprot xrefs for the same CDS - 
538                * each needs a distinct Mapping (as to a different sequence)
539                */
540               map = new Mapping(map);
541             }
542             mappingUsed = true;
543
544             /*
545              * try to locate the protein mapped to (possibly by a 
546              * previous CDS feature)
547              */
548             SequenceI proteinSeq = matcher.findIdMatch(proteinSeqName);
549             if (proteinSeq == null)
550             {
551               proteinSeq = new Sequence(proteinSeqName,
552                       product.getSequenceAsString());
553               matcher.add(proteinSeq);
554               peptides.add(proteinSeq);
555             }
556             map.setTo(proteinSeq);
557             map.getTo().addDBRef(
558                     new DBRefEntry(ref.getSource(), ref.getVersion(), ref
559                             .getAccessionId()));
560             ref.setMap(map);
561           }
562           noProteinDbref = false;
563         }
564         if (product != null)
565         {
566           DBRefEntry pref = new DBRefEntry(ref.getSource(),
567                   ref.getVersion(), ref.getAccessionId());
568           pref.setMap(null); // reference is direct
569           product.addDBRef(pref);
570           // Add converse mapping reference
571           if (map != null)
572           {
573             Mapping pmap = new Mapping(dna, map.getMap().getInverse());
574             pref = new DBRefEntry(sourceDb, getSequenceVersion(),
575                     this.getAccession());
576             pref.setMap(pmap);
577             if (map.getTo() != null)
578             {
579               map.getTo().addDBRef(pref);
580             }
581           }
582         }
583         dna.addDBRef(ref);
584       }
585       if (noProteinDbref && product != null)
586       {
587         // add protein coding reference to dna sequence so xref matches
588         if (protEMBLCDS == null)
589         {
590           protEMBLCDS = new DBRefEntry();
591           protEMBLCDS.setAccessionId(prid);
592           protEMBLCDS.setSource(DBRefSource.EMBLCDSProduct);
593           protEMBLCDS.setVersion(getSequenceVersion());
594           protEMBLCDS
595                   .setMap(new Mapping(product, map.getMap().getInverse()));
596         }
597         product.addDBRef(protEMBLCDS);
598
599         // Add converse mapping reference
600         if (map != null)
601         {
602           Mapping pmap = new Mapping(product, protEMBLCDS.getMap().getMap()
603                   .getInverse());
604           DBRefEntry ncMap = new DBRefEntry(protEMBLCDS);
605           ncMap.setMap(pmap);
606           if (map.getTo() != null)
607           {
608             dna.addDBRef(ncMap);
609           }
610         }
611       }
612     }
613   }
614
615   /**
616    * Helper method to construct a SequenceFeature for one cds range
617    * 
618    * @param exons
619    *          array of cds [start, end, ...] positions
620    * @param exonStartIndex
621    *          offset into the exons array
622    * @param proteinName
623    * @param proteinAccessionId
624    * @param vals
625    *          map of 'miscellaneous values' for feature
626    * @param codonStart
627    *          codon start position for CDS (1/2/3, normally 1)
628    * @return
629    */
630   protected SequenceFeature makeCdsFeature(int[] exons, int exonStartIndex,
631           String proteinName, String proteinAccessionId,
632           Map<String, String> vals, int codonStart)
633   {
634     int exonNumber = exonStartIndex / 2 + 1;
635     SequenceFeature sf = new SequenceFeature();
636     sf.setBegin(Math.min(exons[exonStartIndex], exons[exonStartIndex + 1]));
637     sf.setEnd(Math.max(exons[exonStartIndex], exons[exonStartIndex + 1]));
638     sf.setDescription(String.format("Exon %d for protein '%s' EMBLCDS:%s",
639             exonNumber, proteinName, proteinAccessionId));
640     sf.setPhase(String.valueOf(codonStart - 1));
641     sf.setStrand(exons[exonStartIndex] <= exons[exonStartIndex + 1] ? "+"
642             : "-");
643     sf.setValue(FeatureProperties.EXONPOS, exonNumber);
644     sf.setValue(FeatureProperties.EXONPRODUCT, proteinName);
645     if (!vals.isEmpty())
646     {
647       StringBuilder sb = new StringBuilder();
648       boolean first = true;
649       for (Entry<String, String> val : vals.entrySet())
650       {
651         if (!first)
652         {
653           sb.append(";");
654         }
655         sb.append(val.getKey()).append("=").append(val.getValue());
656         first = false;
657         sf.setValue(val.getKey(), val.getValue());
658       }
659       sf.setAttributes(sb.toString());
660     }
661     return sf;
662   }
663
664   /**
665    * Returns the CDS positions as a list of [start, end, start, end...]
666    * positions. If on the reverse strand, these will be in descending order.
667    * 
668    * @param feature
669    * @return
670    */
671   protected int[] getCdsRanges(EmblFeature feature)
672   {
673     if (feature.location == null)
674     {
675       return new int[] {};
676     }
677     List<int[]> ranges = DnaUtils.parseLocation(feature.location);
678     return ranges == null ? new int[] {} : listToArray(ranges);
679   }
680
681   /**
682    * Converts a list of [start, end] ranges to a single array of [start, end,
683    * start, end ...]
684    * 
685    * @param ranges
686    * @return
687    */
688   int[] listToArray(List<int[]> ranges)
689   {
690     int[] result = new int[ranges.size() * 2];
691     int i = 0;
692     for (int[] range : ranges)
693     {
694       result[i++] = range[0];
695       result[i++] = range[1];
696     }
697     return result;
698   }
699
700   /**
701    * truncate the last exon interval to the prlength'th codon
702    * 
703    * @param prlength
704    * @param exon
705    * @return new exon
706    */
707   static int[] adjustForProteinLength(int prlength, int[] exon)
708   {
709     if (prlength <= 0 || exon == null)
710     {
711       return exon;
712     }
713     int desiredCdsLength = prlength * 3;
714     int exonLength = MappingUtils.getLength(Arrays.asList(exon));
715
716     /*
717      * assuming here exon might include stop codon in addition to protein codons
718      */
719     if (desiredCdsLength == exonLength
720             || desiredCdsLength == exonLength - 3)
721     {
722       return exon;
723     }
724
725     int origxon[];
726     int sxpos = -1;
727     int endxon = 0;
728     origxon = new int[exon.length];
729     System.arraycopy(exon, 0, origxon, 0, exon.length);
730     int cdspos = 0;
731     for (int x = 0; x < exon.length; x += 2)
732     {
733       cdspos += Math.abs(exon[x + 1] - exon[x]) + 1;
734       if (desiredCdsLength <= cdspos)
735       {
736         // advanced beyond last codon.
737         sxpos = x;
738         if (desiredCdsLength != cdspos)
739         {
740           // System.err
741           // .println("Truncating final exon interval on region by "
742           // + (cdspos - cdslength));
743         }
744
745         /*
746          * shrink the final exon - reduce end position if forward
747          * strand, increase it if reverse
748          */
749         if (exon[x + 1] >= exon[x])
750         {
751           endxon = exon[x + 1] - cdspos + desiredCdsLength;
752         }
753         else
754         {
755           endxon = exon[x + 1] + cdspos - desiredCdsLength;
756         }
757         break;
758       }
759     }
760
761     if (sxpos != -1)
762     {
763       // and trim the exon interval set if necessary
764       int[] nxon = new int[sxpos + 2];
765       System.arraycopy(exon, 0, nxon, 0, sxpos + 2);
766       nxon[sxpos + 1] = endxon; // update the end boundary for the new exon
767                                 // set
768       exon = nxon;
769     }
770     return exon;
771   }
772
773   public String getSequenceVersion()
774   {
775     return sequenceVersion;
776   }
777
778   public void setSequenceVersion(String sequenceVersion)
779   {
780     this.sequenceVersion = sequenceVersion;
781   }
782
783   public String getMoleculeType()
784   {
785     return moleculeType;
786   }
787
788   public void setMoleculeType(String moleculeType)
789   {
790     this.moleculeType = moleculeType;
791   }
792
793   public String getTopology()
794   {
795     return topology;
796   }
797
798   public void setTopology(String topology)
799   {
800     this.topology = topology;
801   }
802
803   public String getSequenceLength()
804   {
805     return sequenceLength;
806   }
807
808   public void setSequenceLength(String sequenceLength)
809   {
810     this.sequenceLength = sequenceLength;
811   }
812
813   public String getrCreated()
814   {
815     return rCreated;
816   }
817
818   public void setrCreated(String rCreated)
819   {
820     this.rCreated = rCreated;
821   }
822
823   public String getrLastUpdated()
824   {
825     return rLastUpdated;
826   }
827
828   public void setrLastUpdated(String rLastUpdated)
829   {
830     this.rLastUpdated = rLastUpdated;
831   }
832 }