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
201
202     /*
203      * transform EMBL Database refs to canonical form
204      */
205     if (dbRefs != null)
206     {
207       for (DBRefEntry dbref : dbRefs)
208       {
209         dbref.setSource(DBRefUtils.getCanonicalName(dbref.getSource()));
210         dna.addDBRef(dbref);
211       }
212     }
213
214     SequenceIdMatcher matcher = new SequenceIdMatcher(peptides);
215     try
216     {
217       for (EmblFeature feature : features)
218       {
219         if (FeatureProperties.isCodingFeature(sourceDb, feature.getName()))
220         {
221           parseCodingFeature(feature, sourceDb, dna, peptides, matcher);
222         }
223       }
224     } catch (Exception e)
225     {
226       System.err.println("EMBL Record Features parsing error!");
227       System.err
228               .println("Please report the following to help@jalview.org :");
229       System.err.println("EMBL Record " + accession);
230       System.err.println("Resulted in exception: " + e.getMessage());
231       e.printStackTrace(System.err);
232     }
233
234     return dna;
235   }
236
237   /**
238    * Extracts coding region and product from a CDS feature and properly decorate
239    * it with annotations.
240    * 
241    * @param feature
242    *          coding feature
243    * @param sourceDb
244    *          source database for the EMBLXML
245    * @param dna
246    *          parent dna sequence for this record
247    * @param peptides
248    *          list of protein product sequences for Embl entry
249    * @param matcher
250    *          helper to match xrefs in already retrieved sequences
251    */
252   void parseCodingFeature(EmblFeature feature, String sourceDb,
253           SequenceI dna, List<SequenceI> peptides, SequenceIdMatcher matcher)
254   {
255     boolean isEmblCdna = sourceDb.equals(DBRefSource.EMBLCDS);
256
257     int[] exon = getCdsRanges(feature);
258
259     String prseq = null;
260     String prname = "";
261     String prid = null;
262     Map<String, String> vals = new Hashtable<String, String>();
263
264     /*
265      * codon_start 1/2/3 in EMBL corresponds to phase 0/1/2 in CDS
266      * (phase is required for CDS features in GFF3 format)
267      */
268     int codonStart = 1;
269
270     /*
271      * parse qualifiers, saving protein translation, protein id,
272      * codon start position, product (name), and 'other values'
273      */
274     if (feature.getQualifiers() != null)
275     {
276       for (Qualifier q : feature.getQualifiers())
277       {
278         String qname = q.getName();
279         if (qname.equals("translation"))
280         {
281           // remove all spaces (precompiled String.replaceAll(" ", ""))
282           prseq = SPACE_PATTERN.matcher(q.getValues()[0]).replaceAll("");
283         }
284         else if (qname.equals("protein_id"))
285         {
286           prid = q.getValues()[0].trim();
287         }
288         else if (qname.equals("codon_start"))
289         {
290           try
291           {
292             codonStart = Integer.parseInt(q.getValues()[0].trim());
293           } catch (NumberFormatException e)
294           {
295             System.err.println("Invalid codon_start in XML for "
296                     + accession + ": " + e.getMessage());
297           }
298         }
299         else if (qname.equals("product"))
300         {
301           // sometimes name is returned e.g. for V00488
302           prname = q.getValues()[0].trim();
303         }
304         else
305         {
306           // throw anything else into the additional properties hash
307           String[] qvals = q.getValues();
308           if (qvals != null)
309           {
310             String commaSeparated = StringUtils.arrayToSeparatorList(qvals,
311                     ",");
312             vals.put(qname, commaSeparated);
313           }
314         }
315       }
316     }
317
318     DBRefEntry protEMBLCDS = null;
319     exon = MappingUtils.removeStartPositions(codonStart - 1, exon);
320     boolean noProteinDbref = true;
321
322     SequenceI product = null;
323     Mapping map = null;
324     if (prseq != null && prname != null && prid != null)
325     {
326       /*
327        * look for product in peptides list, if not found, add it
328        */
329       product = matcher.findIdMatch(prid);
330       if (product == null)
331       {
332         product = new Sequence(prid, prseq, 1, prseq.length());
333         product.setDescription(((prname.length() == 0) ? "Protein Product from "
334                 + sourceDb
335                 : prname));
336         peptides.add(product);
337         matcher.add(product);
338       }
339
340       // we have everything - create the mapping and perhaps the protein
341       // sequence
342       if (exon == null || exon.length == 0)
343       {
344         System.err
345                 .println("Implementation Notice: EMBLCDS records not properly supported yet - Making up the CDNA region of this sequence... may be incorrect ("
346                         + sourceDb + ":" + getAccession() + ")");
347         if (prseq.length() * 3 == (1 - codonStart + dna.getSequence().length))
348         {
349           System.err
350                   .println("Not allowing for additional stop codon at end of cDNA fragment... !");
351           // this might occur for CDS sequences where no features are
352           // marked.
353           exon = new int[] { dna.getStart() + (codonStart - 1),
354               dna.getEnd() };
355           map = new Mapping(product, exon, new int[] { 1, prseq.length() },
356                   3, 1);
357         }
358         if ((prseq.length() + 1) * 3 == (1 - codonStart + dna.getSequence().length))
359         {
360           System.err
361                   .println("Allowing for additional stop codon at end of cDNA fragment... will probably cause an error in VAMSAs!");
362           exon = new int[] { dna.getStart() + (codonStart - 1),
363               dna.getEnd() - 3 };
364           map = new Mapping(product, exon, new int[] { 1, prseq.length() },
365                   3, 1);
366         }
367       }
368       else
369       {
370         // Trim the exon mapping if necessary - the given product may only be a
371         // fragment of a larger protein. (EMBL:AY043181 is an example)
372
373         if (isEmblCdna)
374         {
375           // TODO: Add a DbRef back to the parent EMBL sequence with the exon
376           // map
377           // if given a dataset reference, search dataset for parent EMBL
378           // sequence if it exists and set its map
379           // make a new feature annotating the coding contig
380         }
381         else
382         {
383           // final product length truncation check
384           // TODO should from range include stop codon even if not in protein
385           // in order to include stop codon in CDS sequence (as done for
386           // Ensembl)?
387           int[] cdsRanges = adjustForProteinLength(prseq.length(), exon);
388           map = new Mapping(product, cdsRanges, new int[] { 1,
389               prseq.length() }, 3, 1);
390           // reconstruct the EMBLCDS entry
391           // TODO: this is only necessary when there codon annotation is
392           // complete (I think JBPNote)
393           DBRefEntry pcdnaref = new DBRefEntry();
394           pcdnaref.setAccessionId(prid);
395           pcdnaref.setSource(DBRefSource.EMBLCDS);
396           pcdnaref.setVersion(getSequenceVersion()); // same as parent EMBL
397                                                      // version.
398           MapList mp = new MapList(new int[] { 1, prseq.length() },
399                   new int[] { 1 + (codonStart - 1),
400                       (codonStart - 1) + 3 * prseq.length() }, 1, 3);
401           pcdnaref.setMap(new Mapping(mp));
402           if (product != null)
403           {
404             product.addDBRef(pcdnaref);
405             protEMBLCDS = new DBRefEntry(pcdnaref);
406             protEMBLCDS.setSource(DBRefSource.EMBLCDSProduct);
407             product.addDBRef(protEMBLCDS);
408           }
409         }
410       }
411       // add cds feature to dna seq - this may include the stop codon
412       for (int xint = 0; exon != null && xint < exon.length; xint += 2)
413       {
414         SequenceFeature sf = makeCdsFeature(exon, xint, prname, prid, vals,
415                 codonStart);
416         sf.setType(feature.getName()); // "CDS"
417         sf.setEnaLocation(feature.getLocation());
418         sf.setFeatureGroup(sourceDb);
419         dna.addSequenceFeature(sf);
420       }
421     }
422
423     /*
424      * add dbRefs to sequence, and mappings for Uniprot xrefs
425      */
426     if (feature.dbRefs != null)
427     {
428       boolean mappingUsed = false;
429       for (DBRefEntry ref : feature.dbRefs)
430       {
431         /*
432          * ensure UniProtKB/Swiss-Prot converted to UNIPROT
433          */
434         ref.setSource(DBRefUtils.getCanonicalName(ref.getSource()));
435         if (ref.getSource().equals(DBRefSource.UNIPROT))
436         {
437           String proteinSeqName = DBRefSource.UNIPROT + "|"
438                   + ref.getAccessionId();
439           if (map != null && map.getTo() != null)
440           {
441             if (mappingUsed)
442             {
443               /*
444                * two or more Uniprot xrefs for the same CDS - 
445                * each needs a distinct Mapping (as to a different sequence)
446                */
447               map = new Mapping(map);
448             }
449             mappingUsed = true;
450
451             /*
452              * try to locate the protein mapped to (possibly by a 
453              * previous CDS feature)
454              */
455             SequenceI proteinSeq = matcher.findIdMatch(proteinSeqName);
456             if (proteinSeq == null)
457             {
458               proteinSeq = new Sequence(proteinSeqName,
459                       product.getSequenceAsString());
460               matcher.add(proteinSeq);
461               peptides.add(proteinSeq);
462             }
463             map.setTo(proteinSeq);
464             map.getTo().addDBRef(
465                     new DBRefEntry(ref.getSource(), ref.getVersion(), ref
466                             .getAccessionId()));
467             ref.setMap(map);
468           }
469           noProteinDbref = false;
470         }
471         if (product != null)
472         {
473           DBRefEntry pref = new DBRefEntry(ref.getSource(),
474                   ref.getVersion(), ref.getAccessionId());
475           pref.setMap(null); // reference is direct
476           product.addDBRef(pref);
477           // Add converse mapping reference
478           if (map != null)
479           {
480             Mapping pmap = new Mapping(dna, map.getMap().getInverse());
481             pref = new DBRefEntry(sourceDb, getSequenceVersion(),
482                     this.getAccession());
483             pref.setMap(pmap);
484             if (map.getTo() != null)
485             {
486               map.getTo().addDBRef(pref);
487             }
488           }
489         }
490         dna.addDBRef(ref);
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 }