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