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