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