JAL-2113 embl_mapping.xml and code updated for EMBL XML v1.2
[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.setFeatureGroup(sourceDb);
514         dna.addSequenceFeature(sf);
515       }
516     }
517
518     /*
519      * add dbRefs to sequence, and mappings for Uniprot xrefs
520      */
521     if (feature.dbRefs != null)
522     {
523       boolean mappingUsed = false;
524       for (DBRefEntry ref : feature.dbRefs)
525       {
526         ref.setSource(DBRefUtils.getCanonicalName(ref.getSource()));
527         if (ref.getSource().equals(DBRefSource.UNIPROT))
528         {
529           String proteinSeqName = DBRefSource.UNIPROT + "|"
530                   + ref.getAccessionId();
531           if (map != null && map.getTo() != null)
532           {
533             if (mappingUsed)
534             {
535               /*
536                * two or more Uniprot xrefs for the same CDS - 
537                * each needs a distinct Mapping (as to a different sequence)
538                */
539               map = new Mapping(map);
540             }
541             mappingUsed = true;
542
543             /*
544              * try to locate the protein mapped to (possibly by a 
545              * previous CDS feature)
546              */
547             SequenceI proteinSeq = matcher.findIdMatch(proteinSeqName);
548             if (proteinSeq == null)
549             {
550               proteinSeq = new Sequence(proteinSeqName,
551                       product.getSequenceAsString());
552               matcher.add(proteinSeq);
553               peptides.add(proteinSeq);
554             }
555             map.setTo(proteinSeq);
556             map.getTo().addDBRef(
557                     new DBRefEntry(ref.getSource(), ref.getVersion(), ref
558                             .getAccessionId()));
559             ref.setMap(map);
560           }
561           noProteinDbref = false;
562         }
563         if (product != null)
564         {
565           DBRefEntry pref = new DBRefEntry(ref.getSource(),
566                   ref.getVersion(), ref.getAccessionId());
567           pref.setMap(null); // reference is direct
568           product.addDBRef(pref);
569           // Add converse mapping reference
570           if (map != null)
571           {
572             Mapping pmap = new Mapping(dna, map.getMap().getInverse());
573             pref = new DBRefEntry(sourceDb, getSequenceVersion(),
574                     this.getAccession());
575             pref.setMap(pmap);
576             if (map.getTo() != null)
577             {
578               map.getTo().addDBRef(pref);
579             }
580           }
581         }
582         dna.addDBRef(ref);
583       }
584       if (noProteinDbref && product != null)
585       {
586         // add protein coding reference to dna sequence so xref matches
587         if (protEMBLCDS == null)
588         {
589           protEMBLCDS = new DBRefEntry();
590           protEMBLCDS.setAccessionId(prid);
591           protEMBLCDS.setSource(DBRefSource.EMBLCDSProduct);
592           protEMBLCDS.setVersion(getSequenceVersion());
593           protEMBLCDS
594                   .setMap(new Mapping(product, map.getMap().getInverse()));
595         }
596         product.addDBRef(protEMBLCDS);
597
598         // Add converse mapping reference
599         if (map != null)
600         {
601           Mapping pmap = new Mapping(product, protEMBLCDS.getMap().getMap()
602                   .getInverse());
603           DBRefEntry ncMap = new DBRefEntry(protEMBLCDS);
604           ncMap.setMap(pmap);
605           if (map.getTo() != null)
606           {
607             dna.addDBRef(ncMap);
608           }
609         }
610       }
611     }
612   }
613
614   /**
615    * Helper method to construct a SequenceFeature for one cds range
616    * 
617    * @param exons
618    *          array of cds [start, end, ...] positions
619    * @param exonStartIndex
620    *          offset into the exons array
621    * @param proteinName
622    * @param proteinAccessionId
623    * @param vals
624    *          map of 'miscellaneous values' for feature
625    * @param codonStart
626    *          codon start position for CDS (1/2/3, normally 1)
627    * @return
628    */
629   protected SequenceFeature makeCdsFeature(int[] exons, int exonStartIndex,
630           String proteinName, String proteinAccessionId,
631           Map<String, String> vals, int codonStart)
632   {
633     int exonNumber = exonStartIndex / 2 + 1;
634     SequenceFeature sf = new SequenceFeature();
635     sf.setBegin(Math.min(exons[exonStartIndex], exons[exonStartIndex + 1]));
636     sf.setEnd(Math.max(exons[exonStartIndex], exons[exonStartIndex + 1]));
637     sf.setDescription(String.format("Exon %d for protein '%s' EMBLCDS:%s",
638             exonNumber, proteinName, proteinAccessionId));
639     sf.setPhase(String.valueOf(codonStart - 1));
640     sf.setStrand(exons[exonStartIndex] <= exons[exonStartIndex + 1] ? "+"
641             : "-");
642     sf.setValue(FeatureProperties.EXONPOS, exonNumber);
643     sf.setValue(FeatureProperties.EXONPRODUCT, proteinName);
644     if (!vals.isEmpty())
645     {
646       StringBuilder sb = new StringBuilder();
647       boolean first = true;
648       for (Entry<String, String> val : vals.entrySet())
649       {
650         if (!first)
651         {
652           sb.append(";");
653         }
654         sb.append(val.getKey()).append("=").append(val.getValue());
655         first = false;
656         sf.setValue(val.getKey(), val.getValue());
657       }
658       sf.setAttributes(sb.toString());
659     }
660     return sf;
661   }
662
663   /**
664    * Returns the CDS positions as a list of [start, end, start, end...]
665    * positions. If on the reverse strand, these will be in descending order.
666    * 
667    * @param feature
668    * @return
669    */
670   protected int[] getCdsRanges(EmblFeature feature)
671   {
672     if (feature.location == null)
673     {
674       return new int[] {};
675     }
676     List<int[]> ranges = DnaUtils.parseLocation(feature.location);
677     return ranges == null ? new int[] {} : listToArray(ranges);
678   }
679
680   /**
681    * Converts a list of [start, end] ranges to a single array of [start, end,
682    * start, end ...]
683    * 
684    * @param ranges
685    * @return
686    */
687   int[] listToArray(List<int[]> ranges)
688   {
689     int[] result = new int[ranges.size() * 2];
690     int i = 0;
691     for (int[] range : ranges)
692     {
693       result[i++] = range[0];
694       result[i++] = range[1];
695     }
696     return result;
697   }
698
699   /**
700    * truncate the last exon interval to the prlength'th codon
701    * 
702    * @param prlength
703    * @param exon
704    * @return new exon
705    */
706   static int[] adjustForProteinLength(int prlength, int[] exon)
707   {
708     if (prlength <= 0 || exon == null)
709     {
710       return exon;
711     }
712     int desiredCdsLength = prlength * 3;
713     int exonLength = MappingUtils.getLength(Arrays.asList(exon));
714
715     /*
716      * assuming here exon might include stop codon in addition to protein codons
717      */
718     if (desiredCdsLength == exonLength
719             || desiredCdsLength == exonLength - 3)
720     {
721       return exon;
722     }
723
724     int origxon[];
725     int sxpos = -1;
726     int endxon = 0;
727     origxon = new int[exon.length];
728     System.arraycopy(exon, 0, origxon, 0, exon.length);
729     int cdspos = 0;
730     for (int x = 0; x < exon.length; x += 2)
731     {
732       cdspos += Math.abs(exon[x + 1] - exon[x]) + 1;
733       if (desiredCdsLength <= cdspos)
734       {
735         // advanced beyond last codon.
736         sxpos = x;
737         if (desiredCdsLength != cdspos)
738         {
739           // System.err
740           // .println("Truncating final exon interval on region by "
741           // + (cdspos - cdslength));
742         }
743
744         /*
745          * shrink the final exon - reduce end position if forward
746          * strand, increase it if reverse
747          */
748         if (exon[x + 1] >= exon[x])
749         {
750           endxon = exon[x + 1] - cdspos + desiredCdsLength;
751         }
752         else
753         {
754           endxon = exon[x + 1] + cdspos - desiredCdsLength;
755         }
756         break;
757       }
758     }
759
760     if (sxpos != -1)
761     {
762       // and trim the exon interval set if necessary
763       int[] nxon = new int[sxpos + 2];
764       System.arraycopy(exon, 0, nxon, 0, sxpos + 2);
765       nxon[sxpos + 1] = endxon; // update the end boundary for the new exon
766                                 // set
767       exon = nxon;
768     }
769     return exon;
770   }
771
772   public String getSequenceVersion()
773   {
774     return sequenceVersion;
775   }
776
777   public void setSequenceVersion(String sequenceVersion)
778   {
779     this.sequenceVersion = sequenceVersion;
780   }
781
782   public String getMoleculeType()
783   {
784     return moleculeType;
785   }
786
787   public void setMoleculeType(String moleculeType)
788   {
789     this.moleculeType = moleculeType;
790   }
791
792   public String getTopology()
793   {
794     return topology;
795   }
796
797   public void setTopology(String topology)
798   {
799     this.topology = topology;
800   }
801
802   public String getSequenceLength()
803   {
804     return sequenceLength;
805   }
806
807   public void setSequenceLength(String sequenceLength)
808   {
809     this.sequenceLength = sequenceLength;
810   }
811
812   public String getrCreated()
813   {
814     return rCreated;
815   }
816
817   public void setrCreated(String rCreated)
818   {
819     this.rCreated = rCreated;
820   }
821
822   public String getrLastUpdated()
823   {
824     return rLastUpdated;
825   }
826
827   public void setrLastUpdated(String rLastUpdated)
828   {
829     this.rLastUpdated = rLastUpdated;
830   }
831 }