350c44e97a977e3ab94378c5cec12f410a8cdae5
[jalview.git] / src / jalview / datamodel / xdb / embl / EmblEntry.java
1 package jalview.datamodel.xdb.embl;
2
3 import jalview.datamodel.DBRefEntry;
4 import jalview.datamodel.DBRefSource;
5 import jalview.datamodel.FeatureProperties;
6 import jalview.datamodel.Mapping;
7 import jalview.datamodel.Sequence;
8 import jalview.datamodel.SequenceFeature;
9 import jalview.datamodel.SequenceI;
10
11 import java.util.Enumeration;
12 import java.util.Hashtable;
13 import java.util.Iterator;
14 import java.util.Vector;
15
16 public class EmblEntry
17 {
18   String accession;
19
20   String version;
21
22   String taxDivision;
23
24   String desc;
25
26   String rCreated;
27
28   String rLastUpdated;
29
30   String lastUpdated;
31
32   Vector keywords;
33
34   Vector refs;
35
36   Vector dbRefs;
37
38   Vector features;
39
40   EmblSequence sequence;
41
42   /**
43    * @return the accession
44    */
45   public String getAccession()
46   {
47     return accession;
48   }
49
50   /**
51    * @param accession
52    *          the accession to set
53    */
54   public void setAccession(String accession)
55   {
56     this.accession = accession;
57   }
58
59   /**
60    * @return the dbRefs
61    */
62   public Vector getDbRefs()
63   {
64     return dbRefs;
65   }
66
67   /**
68    * @param dbRefs
69    *          the dbRefs to set
70    */
71   public void setDbRefs(Vector dbRefs)
72   {
73     this.dbRefs = dbRefs;
74   }
75
76   /**
77    * @return the desc
78    */
79   public String getDesc()
80   {
81     return desc;
82   }
83
84   /**
85    * @param desc
86    *          the desc to set
87    */
88   public void setDesc(String desc)
89   {
90     this.desc = desc;
91   }
92
93   /**
94    * @return the features
95    */
96   public Vector getFeatures()
97   {
98     return features;
99   }
100
101   /**
102    * @param features
103    *          the features to set
104    */
105   public void setFeatures(Vector features)
106   {
107     this.features = features;
108   }
109
110   /**
111    * @return the keywords
112    */
113   public Vector getKeywords()
114   {
115     return keywords;
116   }
117
118   /**
119    * @param keywords
120    *          the keywords to set
121    */
122   public void setKeywords(Vector keywords)
123   {
124     this.keywords = keywords;
125   }
126
127   /**
128    * @return the lastUpdated
129    */
130   public String getLastUpdated()
131   {
132     return lastUpdated;
133   }
134
135   /**
136    * @param lastUpdated
137    *          the lastUpdated to set
138    */
139   public void setLastUpdated(String lastUpdated)
140   {
141     this.lastUpdated = lastUpdated;
142   }
143
144   /**
145    * @return the refs
146    */
147   public Vector getRefs()
148   {
149     return refs;
150   }
151
152   /**
153    * @param refs
154    *          the refs to set
155    */
156   public void setRefs(Vector refs)
157   {
158     this.refs = refs;
159   }
160
161   /**
162    * @return the releaseCreated
163    */
164   public String getRCreated()
165   {
166     return rCreated;
167   }
168
169   /**
170    * @param releaseCreated
171    *          the releaseCreated to set
172    */
173   public void setRcreated(String releaseCreated)
174   {
175     this.rCreated = releaseCreated;
176   }
177
178   /**
179    * @return the releaseLastUpdated
180    */
181   public String getRLastUpdated()
182   {
183     return rLastUpdated;
184   }
185
186   /**
187    * @param releaseLastUpdated
188    *          the releaseLastUpdated to set
189    */
190   public void setRLastUpdated(String releaseLastUpdated)
191   {
192     this.rLastUpdated = releaseLastUpdated;
193   }
194
195   /**
196    * @return the sequence
197    */
198   public EmblSequence getSequence()
199   {
200     return sequence;
201   }
202
203   /**
204    * @param sequence
205    *          the sequence to set
206    */
207   public void setSequence(EmblSequence sequence)
208   {
209     this.sequence = sequence;
210   }
211
212   /**
213    * @return the taxDivision
214    */
215   public String getTaxDivision()
216   {
217     return taxDivision;
218   }
219
220   /**
221    * @param taxDivision
222    *          the taxDivision to set
223    */
224   public void setTaxDivision(String taxDivision)
225   {
226     this.taxDivision = taxDivision;
227   }
228
229   /**
230    * @return the version
231    */
232   public String getVersion()
233   {
234     return version;
235   }
236
237   /**
238    * @param version
239    *          the version to set
240    */
241   public void setVersion(String version)
242   {
243     this.version = version;
244   }
245
246   /*
247    * EMBL Feature support is limited. The text below is included for the benefit
248    * of any developer working on improving EMBL feature import in Jalview.
249    * Extract from EMBL feature specification see
250    * http://www.embl-ebi.ac.uk/embl/Documentation/FT_definitions/feature_table.html
251    * 3.5 Location 3.5.1 Purpose
252    * 
253    * The location indicates the region of the presented sequence which
254    * corresponds to a feature.
255    * 
256    * 3.5.2 Format and conventions The location contains at least one sequence
257    * location descriptor and may contain one or more operators with one or more
258    * sequence location descriptors. Base numbers refer to the numbering in the
259    * entry. This numbering designates the first base (5' end) of the presented
260    * sequence as base 1. Base locations beyond the range of the presented
261    * sequence may not be used in location descriptors, the only exception being
262    * location in a remote entry (see 3.5.2.1, e).
263    * 
264    * Location operators and descriptors are discussed in more detail below.
265    * 
266    * 3.5.2.1 Location descriptors
267    * 
268    * The location descriptor can be one of the following: (a) a single base
269    * number (b) a site between two indicated adjoining bases (c) a single base
270    * chosen from within a specified range of bases (not allowed for new entries)
271    * (d) the base numbers delimiting a sequence span (e) a remote entry
272    * identifier followed by a local location descriptor (i.e., a-d)
273    * 
274    * A site between two adjoining nucleotides, such as endonucleolytic cleavage
275    * site, is indicated by listing the two points separated by a carat (^). The
276    * permitted formats for this descriptor are n^n+1 (for example 55^56), or,
277    * for circular molecules, n^1, where "n" is the full length of the molecule,
278    * ie 1000^1 for circular molecule with length 1000.
279    * 
280    * A single base chosen from a range of bases is indicated by the first base
281    * number and the last base number of the range separated by a single period
282    * (e.g., '12.21' indicates a single base taken from between the indicated
283    * points). From October 2006 the usage of this descriptor is restricted : it
284    * is illegal to use "a single base from a range" (c) either on its own or in
285    * combination with the "sequence span" (d) descriptor for newly created
286    * entries. The existing entries where such descriptors exist are going to be
287    * retrofitted.
288    * 
289    * Sequence spans are indicated by the starting base number and the ending
290    * base number separated by two periods (e.g., '34..456'). The '<' and '>'
291    * symbols may be used with the starting and ending base numbers to indicate
292    * that an end point is beyond the specified base number. The starting and
293    * ending base positions can be represented as distinct base numbers
294    * ('34..456') or a site between two indicated adjoining bases.
295    * 
296    * A location in a remote entry (not the entry to which the feature table
297    * belongs) can be specified by giving the accession-number and sequence
298    * version of the remote entry, followed by a colon ":", followed by a
299    * location descriptor which applies to that entry's sequence (i.e.
300    * J12345.1:1..15, see also examples below)
301    * 
302    * 3.5.2.2 Operators
303    * 
304    * The location operator is a prefix that specifies what must be done to the
305    * indicated sequence to find or construct the location corresponding to the
306    * feature. A list of operators is given below with their definitions and most
307    * common format.
308    * 
309    * complement(location) Find the complement of the presented sequence in the
310    * span specified by " location" (i.e., read the complement of the presented
311    * strand in its 5'-to-3' direction)
312    * 
313    * join(location,location, ... location) The indicated elements should be
314    * joined (placed end-to-end) to form one contiguous sequence
315    * 
316    * order(location,location, ... location) The elements can be found in the
317    * specified order (5' to 3' direction), but nothing is implied about the
318    * reasonableness about joining them
319    * 
320    * Note : location operator "complement" can be used in combination with
321    * either " join" or "order" within the same location; combinations of "join"
322    * and "order" within the same location (nested operators) are illegal.
323    * 
324    * 
325    * 
326    * 3.5.3 Location examples
327    * 
328    * The following is a list of common location descriptors with their meanings:
329    * 
330    * Location Description
331    * 
332    * 467 Points to a single base in the presented sequence
333    * 
334    * 340..565 Points to a continuous range of bases bounded by and including the
335    * starting and ending bases
336    * 
337    * <345..500 Indicates that the exact lower boundary point of a feature is
338    * unknown. The location begins at some base previous to the first base
339    * specified (which need not be contained in the presented sequence) and
340    * continues to and includes the ending base
341    * 
342    * <1..888 The feature starts before the first sequenced base and continues to
343    * and includes base 888
344    * 
345    * 1..>888 The feature starts at the first sequenced base and continues beyond
346    * base 888
347    * 
348    * 102.110 Indicates that the exact location is unknown but that it is one of
349    * the bases between bases 102 and 110, inclusive
350    * 
351    * 123^124 Points to a site between bases 123 and 124
352    * 
353    * join(12..78,134..202) Regions 12 to 78 and 134 to 202 should be joined to
354    * form one contiguous sequence
355    * 
356    * 
357    * complement(34..126) Start at the base complementary to 126 and finish at
358    * the base complementary to base 34 (the feature is on the strand
359    * complementary to the presented strand)
360    * 
361    * 
362    * complement(join(2691..4571,4918..5163)) Joins regions 2691 to 4571 and 4918
363    * to 5163, then complements the joined segments (the feature is on the strand
364    * complementary to the presented strand)
365    * 
366    * join(complement(4918..5163),complement(2691..4571)) Complements regions
367    * 4918 to 5163 and 2691 to 4571, then joins the complemented segments (the
368    * feature is on the strand complementary to the presented strand)
369    * 
370    * J00194.1:100..202 Points to bases 100 to 202, inclusive, in the entry (in
371    * this database) with primary accession number 'J00194'
372    * 
373    * join(1..100,J00194.1:100..202) Joins region 1..100 of the existing entry
374    * with the region 100..202 of remote entry J00194
375    * 
376    */
377   /**
378    * Recover annotated sequences from EMBL file
379    * 
380    * @param noNa
381    *          don't return nucleic acid sequences
382    * @param sourceDb
383    *          TODO
384    * @param noProtein
385    *          don't return any translated protein sequences marked in features
386    * @return dataset sequences with DBRefs and features - DNA always comes first
387    */
388   public jalview.datamodel.SequenceI[] getSequences(boolean noNa,
389           boolean noPeptide, String sourceDb)
390   { //TODO: ensure emblEntry.getSequences behaves correctly for returning all cases of noNa and noPeptide
391     Vector seqs = new Vector();
392     Sequence dna = null;
393     if (!noNa)
394     {
395       // In theory we still need to create this if noNa is set to avoid a null pointer exception
396       dna = new Sequence(sourceDb + "|" + accession, sequence.getSequence());
397       dna.setDescription(desc);
398       dna.addDBRef(new DBRefEntry(sourceDb, version, accession));
399       // TODO: add mapping for parentAccession attribute
400       // TODO: transform EMBL Database refs to canonical form
401       if (dbRefs != null)
402         for (Iterator i = dbRefs.iterator(); i.hasNext(); dna
403         .addDBRef((DBRefEntry) i.next()))
404         ;
405     }
406     try
407     {
408       for (Iterator i = features.iterator(); i.hasNext();)
409       {
410         EmblFeature feature = (EmblFeature) i.next();
411         if (!noNa)
412         {
413           if (feature.dbRefs != null && feature.dbRefs.size() > 0)
414           {
415             for (Iterator dbr = feature.dbRefs.iterator(); dbr.hasNext(); dna
416                     .addDBRef((DBRefEntry) dbr.next()))
417               ;
418           }
419         }
420         if (FeatureProperties.isCodingFeature(sourceDb, feature.getName()))
421         {
422           parseCodingFeature(feature, sourceDb, seqs, dna, noPeptide);
423         }
424         else
425         {
426           // General feature type.
427           if (!noNa)
428           {
429             if (feature.dbRefs != null && feature.dbRefs.size() > 0)
430             {
431               for (Iterator dbr = feature.dbRefs.iterator(); dbr.hasNext(); dna
432                       .addDBRef((DBRefEntry) dbr.next()))
433                 ;
434             }
435           }
436         }
437       }
438     } 
439     catch (Exception e)
440     {
441       System.err.println("EMBL Record Features parsing error!");
442       System.err
443               .println("Please report the following to help@jalview.org :");
444       System.err.println("EMBL Record " + accession);
445       System.err.println("Resulted in exception: " + e.getMessage());
446       e.printStackTrace(System.err);
447     }
448     if (!noNa && dna != null)
449     {
450       seqs.add(dna);
451     }
452     SequenceI[] sqs = new SequenceI[seqs.size()];
453     for (int i = 0, j = seqs.size(); i < j; i++)
454     {
455       sqs[i] = (SequenceI) seqs.elementAt(i);
456       seqs.set(i, null);
457     }
458     return sqs;
459   }
460
461   /**
462    * attempt to extract coding region and product from a feature and properly decorate it with annotations.
463    * @param feature coding feature
464    * @param sourceDb source database for the EMBLXML
465    * @param seqs place where sequences go
466    * @param dna parent dna sequence for this record
467    * @param noPeptide flag for generation of Peptide sequence objects
468    */
469   private void parseCodingFeature(EmblFeature feature, String sourceDb, Vector seqs, Sequence dna, boolean noPeptide)
470   {
471     boolean isEmblCdna = sourceDb.equals(DBRefSource.EMBLCDS);
472     // extract coding region(s)
473     jalview.datamodel.Mapping map = null;
474     int[] exon = null;
475     if (feature.locations != null && feature.locations.size() > 0)
476     {
477       for (Enumeration locs = feature.locations.elements(); locs
478               .hasMoreElements();)
479       {
480         EmblFeatureLocations loc = (EmblFeatureLocations) locs
481                 .nextElement();
482         int[] se = loc.getElementRanges(accession);
483         if (exon == null)
484         {
485           exon = se;
486         }
487         else
488         {
489           int[] t = new int[exon.length + se.length];
490           System.arraycopy(exon, 0, t, 0, exon.length);
491           System.arraycopy(se, 0, t, exon.length, se.length);
492           exon = t;
493         }
494       }
495     }
496     String prseq = null;
497     String prname = new String();
498     String prid = null;
499     Hashtable vals = new Hashtable();
500     int prstart = 1;
501     // get qualifiers
502     if (feature.getQualifiers() != null
503             && feature.getQualifiers().size() > 0)
504     {
505       for (Iterator quals = feature.getQualifiers().iterator(); quals
506               .hasNext();)
507       {
508         Qualifier q = (Qualifier) quals.next();
509         if (q.getName().equals("translation"))
510         {
511           StringBuffer prsq = new StringBuffer(q.getValues()[0]);
512           int p = prsq.indexOf(" ");
513           while (p > -1)
514           {
515             prsq.deleteCharAt(p);
516             p = prsq.indexOf(" ", p);
517           }
518           prseq = prsq.toString();
519           prsq = null;
520
521         }
522         else if (q.getName().equals("protein_id"))
523         {
524           prid = q.getValues()[0];
525         }
526         else if (q.getName().equals("codon_start"))
527         {
528           prstart = Integer.parseInt(q.getValues()[0]);
529         }
530         else if (q.getName().equals("product"))
531         {
532           prname = q.getValues()[0];
533         }
534         else
535         {
536           // throw anything else into the additional properties hash
537           vals.put(q.getName(), q.getValues().toString());
538         }
539       }
540     }
541     Sequence product = null;
542     if (prseq != null && prname != null && prid != null)
543     {
544       // extract proteins.
545       product = new Sequence(sourceDb + "|" + "EMBLCDS|" + prid
546               +((prname.length()==0) ? "" : " " + prname), prseq, prstart, prstart
547               + prseq.length() - 1);
548       product.setDescription("Protein Product from " + sourceDb);
549       
550       if (!noPeptide)
551       {
552         // Protein is also added to vector of sequences returned
553         seqs.add(product);
554       }
555       // we have everything - create the mapping and perhaps the protein
556       // sequence
557       if (exon == null || exon.length == 0)
558       {
559         System.err
560                 .println("Implementation Notice: EMBLCDS records not properly supported yet - Making up the CDNA region of this sequence... may be incorrect ("
561                         + sourceDb + ":" + getAccession() + ")");
562         if (prseq.length() * 3 == dna.getSequence().length)
563         {
564           // this might occur for CDS sequences where no features are
565           // marked.
566           exon = new int[]
567           { dna.getStart(), dna.getEnd() };
568           map = new jalview.datamodel.Mapping(product, exon,
569                   new int[]
570                   { prstart, prstart + prseq.length() - 1 }, 3, 1);
571         }
572         if ((prseq.length() + 1) * 3 == dna.getSequence().length)
573         {
574           exon = new int[]
575           { dna.getStart(), dna.getEnd() - 3 };
576           map = new jalview.datamodel.Mapping(product, exon,
577                   new int[]
578                   { prstart, prstart + prseq.length() - 1 }, 3, 1);
579         }
580       }
581       else
582       {
583         if (isEmblCdna)
584         {
585           // TODO: Add a DbRef back to the parent EMBL sequence with the exon
586           // map
587
588           // make a new feature annotating the coding contig
589         }
590         else
591         {
592           map = new jalview.datamodel.Mapping(product, exon,
593                   new int[]
594                   { prstart, prstart + prseq.length() - 1 }, 3, 1);
595           // reconstruct the EMBLCDS entry
596           DBRefEntry pcdnaref = new DBRefEntry();
597           pcdnaref.setAccessionId(prid);
598           pcdnaref.setSource(DBRefSource.EMBLCDS);
599           pcdnaref.setVersion(getVersion()); // same as parent EMBL version.
600           jalview.util.MapList mp = new jalview.util.MapList(new int[]
601           { 1+(prstart-1)*3, 1+(prstart-1)*3 + (prseq.length()-1)*3 }, new int[] { prstart, prstart+prseq.length() - 1 }, 3, 1);
602           pcdnaref.setMap(new Mapping(mp));
603           if (product!=null)
604             product.addDBRef(pcdnaref);
605           
606         }
607       }
608       // add cds feature to dna seq - this may include the stop codon
609       for (int xint = 0; exon != null && xint < exon.length; xint += 2)
610       {
611         SequenceFeature sf = new SequenceFeature();
612         sf.setBegin(exon[xint]);
613         sf.setEnd(exon[xint + 1]);
614         sf.setType(feature.getName());
615         sf.setFeatureGroup(sourceDb);
616         sf.setDescription("Exon " + (1 + xint) + " for protein '"
617                 + prname + "' EMBLCDS:" + prid);
618         sf.setValue(FeatureProperties.EXONPOS, new Integer(1 + xint));
619         sf.setValue(FeatureProperties.EXONPRODUCT, prname);
620         if (vals != null && vals.size() > 0)
621         {
622           Enumeration kv = vals.elements();
623           while (kv.hasMoreElements())
624           {
625             Object key = kv.nextElement();
626             if (key != null)
627               sf.setValue(key.toString(), vals.get(key));
628           }
629         }
630         dna.addSequenceFeature(sf);
631       }
632     }
633     // add dbRefs to sequence
634     if (feature.dbRefs != null && feature.dbRefs.size() > 0)
635     {
636       for (Iterator dbr = feature.dbRefs.iterator(); dbr.hasNext();)
637       {
638         DBRefEntry ref = (DBRefEntry) dbr.next();
639         ref.setSource(jalview.util.DBRefUtils.getCanonicalName(ref
640                 .getSource()));
641         // Hard code the kind of protein product accessions that EMBL cite
642         if (ref.getSource().equals(
643                 jalview.datamodel.DBRefSource.UNIPROT))
644         {
645           ref.setMap(map);
646           if (map!=null && map.getTo()!=null)
647           {
648             map.getTo().addDBRef(new DBRefEntry(ref.getSource(), ref.getVersion(), ref.getAccessionId())); // don't copy map over.
649           }
650         }
651         if (product != null)
652         {
653           DBRefEntry pref = new DBRefEntry(ref.getSource(), ref
654                 .getVersion(), ref.getAccessionId());
655           pref.setMap(null); // reference is direct
656           product.addDBRef(pref);
657           // Add converse mapping reference
658           if (map != null)
659           {
660             Mapping pmap = new Mapping(dna, map.getMap().getInverse());
661             pref = new DBRefEntry(sourceDb, getVersion(), this
662                     .getAccession());
663             pref.setMap(pmap);
664             if (map.getTo()!=null)
665             {
666               map.getTo().addDBRef(pref);
667             }
668           }
669         }
670         dna.addDBRef(ref);
671       }
672     }
673   }
674 }