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