9a3453ffcc17a453ea3a05988d01b1fabee2ae52
[jalview.git] / src / jalview / io / ModellerDescription.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.io;
22
23 import jalview.datamodel.DBRefEntry;
24 import jalview.datamodel.DBRefSource;
25 import jalview.datamodel.SequenceI;
26
27 import com.stevesoft.pat.Regex;
28
29 public class ModellerDescription
30 {
31   /**
32    * Translates between a String containing a set of colon-separated values on a
33    * single line, and sequence start/end and other properties. See PIRFile IO
34    * for its use.
35    */
36   final String[] seqTypes =
37   { "sequence", "structure", "structureX", "structureN" };
38
39   final String[] Fields =
40   { "objectType", "objectId", "startField", "startCode", "endField",
41       "endCode", "description1", "description2", "resolutionField",
42       "tailField" };
43
44   final int TYPE = 0;
45
46   final int LOCALID = 1;
47
48   final int START = 2;
49
50   final int START_CHAIN = 3;
51
52   final int END = 4;
53
54   final int END_CHAIN = 5;
55
56   final int DESCRIPTION1 = 6;
57
58   final int DESCRIPTION2 = 7;
59
60   final int RESOLUTION = 8;
61
62   final int TAIL = 9;
63
64   /**
65    * 0 is free text or empty 1 is something that parses to an integer, or \@
66    */
67   final int Types[] =
68   { 0, 0, 1, 0, 1, 0, 0, 0, 0, 0 };
69
70   final char Padding[] =
71   { ' ', ' ', ' ', '.', ' ', '.', '.', '.', '.', '.' };
72
73   java.util.Hashtable fields = new java.util.Hashtable();
74
75   ModellerDescription()
76   {
77     fields.put(Fields[TAIL], "");
78   }
79
80   class resCode
81   {
82     Integer val;
83
84     String field;
85
86     resCode(String f, Integer v)
87     {
88       val = v;
89       field = f;
90     }
91
92     resCode(int v)
93     {
94       val = new Integer(v);
95       field = val.toString();
96     }
97   };
98
99   private resCode validResidueCode(String field)
100   {
101     Integer val = null;
102     Regex r = new Regex("\\s*((([-0-9]+).?)|FIRST|LAST|@)");
103
104     if (!r.search(field))
105     {
106       return null; // invalid
107     }
108     String value = r.stringMatched(3);
109     if (value == null)
110     {
111       value = r.stringMatched(1);
112     }
113     // Cache.log.debug("from '" + field + "' matched '" + value +
114     // "'");
115     try
116     {
117       val = Integer.valueOf(value);
118       return new resCode(field, val); // successful numeric extraction
119     } catch (Exception e)
120     {
121     }
122     return new resCode(field, null);
123   }
124
125   private java.util.Hashtable parseDescription(String desc)
126   {
127     java.util.Hashtable fields = new java.util.Hashtable();
128     java.util.StringTokenizer st = new java.util.StringTokenizer(desc, ":",
129             true);
130
131     String field;
132     int type = -1;
133     if (st.countTokens() > 0)
134     {
135       // parse colon-fields
136       int i = 0;
137       field = st.nextToken(":");
138       do
139       {
140         if (seqTypes[i].equalsIgnoreCase(field))
141         {
142           break;
143         }
144       } while (++i < seqTypes.length);
145
146       if (i < seqTypes.length)
147       {
148         st.nextToken(); // skip ':'
149         // valid seqType for modeller
150         type = i;
151         i = 1; // continue parsing fields
152         while (i < TAIL && st.hasMoreTokens())
153         {
154           if ((field = st.nextToken(":")) != null)
155           {
156             if (!field.equals(":"))
157             {
158               // validate residue field value
159               if (Types[i] == 1)
160               {
161                 resCode val = validResidueCode(field);
162                 if (val != null)
163                 {
164                   fields.put(new String(Fields[i] + "num"), val);
165                 }
166                 else
167                 {
168                   // Cache.log.debug(
169                   // "Ignoring non-Modeller description: invalid integer-like
170                   // field '" + field + "'");
171                   type = -1; /* invalid field! - throw the FieldSet away */
172                 }
173                 ;
174               }
175               fields.put(Fields[i++], field);
176               if (st.hasMoreTokens())
177               {
178                 st.nextToken(); // skip token sep.
179               }
180             }
181             else
182             {
183               i++;
184             }
185           }
186         }
187         if (i == TAIL)
188         {
189           // slurp remaining fields
190           while (st.hasMoreTokens())
191           {
192             String tl = st.nextToken(":");
193             field += tl.equals(":") ? tl : (":" + tl);
194           }
195           fields.put(Fields[TAIL], field);
196         }
197       }
198     }
199     if (type == -1)
200     {
201       // object is not a proper ModellerPIR object
202       fields = new java.util.Hashtable();
203       fields.put(Fields[TAIL], new String(desc));
204     }
205     else
206     {
207       fields.put(Fields[TYPE], seqTypes[type]);
208     }
209     return fields;
210   }
211
212   ModellerDescription(String desc)
213   {
214     if (desc == null)
215     {
216       desc = "";
217     }
218     fields = parseDescription(desc);
219   }
220
221   void setStartCode(int v)
222   {
223     resCode r;
224     fields.put(Fields[START] + "num", r = new resCode(v));
225     fields.put(Fields[START], r.field);
226   }
227
228   void setEndCode(int v)
229   {
230     resCode r;
231     fields.put(Fields[END] + "num", r = new resCode(v));
232     fields.put(Fields[END], r.field);
233   }
234
235   /**
236    * make a possibly updated modeller field line for the sequence object
237    * 
238    * @param seq
239    *          SequenceI
240    */
241   ModellerDescription(SequenceI seq)
242   {
243
244     if (seq.getDescription() != null)
245     {
246       fields = parseDescription(seq.getDescription());
247     }
248
249     if (isModellerFieldset())
250     {
251       // Set start and end before we update the type (in the case of a
252       // synthesized field set)
253       if (getStartCode() == null
254               || (getStartNum() != seq.getStart() && getStartCode().val != null))
255       {
256         // unset or user updated sequence start position
257         setStartCode(seq.getStart());
258       }
259
260       if (getEndCode() == null
261               || (getEndNum() != seq.getEnd() && getStartCode() != null && getStartCode().val != null))
262       {
263         setEndCode(seq.getEnd());
264       }
265     }
266     else
267     {
268       // synthesize fields
269       setStartCode(seq.getStart());
270       setEndCode(seq.getEnd());
271       fields.put(Fields[LOCALID], seq.getName()); // this may be overwritten
272       // below...
273       // type - decide based on evidence of PDB database references - this also
274       // sets the local reference field
275       int t = 0; // sequence
276       if (seq.getDatasetSequence() != null
277               && seq.getDatasetSequence().getDBRef() != null)
278       {
279         DBRefEntry[] dbr = seq.getDatasetSequence().getDBRef();
280         int i, j;
281         for (i = 0, j = dbr.length; i < j; i++)
282         {
283           if (dbr[i] != null)
284           {
285             // JBPNote PDB dbRefEntry needs properties to propagate onto
286             // ModellerField
287             // JBPNote Need to get info from the user about whether the sequence
288             // is the one being modelled, or if it is a template.
289             if (dbr[i].getSource().equals(DBRefSource.PDB))
290             {
291               fields.put(Fields[LOCALID], dbr[i].getAccessionId());
292               t = 2;
293               break;
294             }
295           }
296         }
297       }
298       fields.put(Fields[TYPE], seqTypes[t]);
299     }
300
301   }
302
303   /**
304    * Indicate if fields parsed to a modeller-like colon-separated value line
305    * 
306    * @return boolean
307    */
308   boolean isModellerFieldset()
309   {
310     return (fields.containsKey(Fields[TYPE]));
311   }
312
313   String getDescriptionLine()
314   {
315     String desc = "";
316     int lastfield = Fields.length - 1;
317
318     if (isModellerFieldset())
319     {
320       String value;
321       // try to write a minimal modeller field set, so..
322
323       // find the last valid field in the entry
324
325       for (; lastfield > 6; lastfield--)
326       {
327         if (fields.containsKey(Fields[lastfield]))
328         {
329           break;
330         }
331       }
332
333       for (int i = 0; i < lastfield; i++)
334       {
335         value = (String) fields.get(Fields[i]);
336         if (value != null && value.length() > 0)
337         {
338           desc += ((String) fields.get(Fields[i])) + ":";
339         }
340         else
341         {
342           desc += Padding[i] + ":";
343         }
344       }
345     }
346     // just return the last field if no others were defined.
347     if (fields.containsKey(Fields[lastfield]))
348     {
349       desc += (String) fields.get(Fields[lastfield]);
350     }
351     else
352     {
353       desc += ".";
354     }
355     return desc;
356   }
357
358   int getStartNum()
359   {
360     int start = 0;
361     resCode val = getStartCode();
362     if (val != null && val.val != null)
363     {
364       return val.val.intValue();
365     }
366     return start;
367   }
368
369   resCode getStartCode()
370   {
371     if (isModellerFieldset() && fields.containsKey(Fields[START] + "num"))
372     {
373       return (resCode) fields.get(Fields[START] + "num");
374     }
375     return null;
376   }
377
378   resCode getEndCode()
379   {
380     if (isModellerFieldset() && fields.containsKey(Fields[END] + "num"))
381     {
382       return (resCode) fields.get(Fields[END] + "num");
383     }
384     return null;
385   }
386
387   int getEndNum()
388   {
389     int end = 0;
390     resCode val = getEndCode();
391     if (val != null && val.val != null)
392     {
393       return val.val.intValue();
394     }
395     return end;
396   }
397
398   /**
399    * returns true if sequence object was modifed with a valid modellerField set
400    * 
401    * @param newSeq
402    *          SequenceI
403    * @return boolean
404    */
405   boolean updateSequenceI(SequenceI newSeq)
406   {
407     if (isModellerFieldset())
408     {
409       resCode rc = getStartCode();
410       if (rc != null && rc.val != null)
411       {
412         newSeq.setStart(getStartNum());
413       }
414       else
415       {
416         newSeq.setStart(1);
417       }
418       rc = getEndCode();
419       if (rc != null && rc.val != null)
420       {
421         newSeq.setEnd(getEndNum());
422       }
423       else
424       {
425         newSeq.setEnd(newSeq.getStart() + newSeq.getLength());
426       }
427       return true;
428     }
429     return false;
430   }
431 }