Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: joelib/io/types/HIN.java


1   ///////////////////////////////////////////////////////////////////////////////
2   //  Filename: $RCSfile: HIN.java,v $
3   //  Purpose:  Reader/Writer for Undefined files.
4   //  Language: Java
5   //  Compiler: JDK 1.4
6   //  Authors:  Joerg K. Wegner
7   //  Version:  $Revision: 1.5 $
8   //            $Date: 2003/10/13 08:16:58 $
9   //            $Author: wegner $
10  //  Original Author: ???, OpenEye Scientific Software
11  //  Original Version: babel 2.0a1
12  //
13  //  Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany
14  //
15  //  This program is free software; you can redistribute it and/or modify
16  //  it under the terms of the GNU General Public License as published by
17  //  the Free Software Foundation version 2 of the License.
18  //
19  //  This program is distributed in the hope that it will be useful,
20  //  but WITHOUT ANY WARRANTY; without even the implied warranty of
21  //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  //  GNU General Public License for more details.
23  ///////////////////////////////////////////////////////////////////////////////
24  package joelib.io.types;
25  
26  import cformat.PrintfFormat;
27  import cformat.PrintfStream;
28  
29  import joelib.data.JOEElementTable;
30  import joelib.data.JOETypeTable;
31  
32  import joelib.io.MoleculeFileType;
33  import joelib.io.MoleculeIOException;
34  
35  import joelib.molecule.JOEAtom;
36  import joelib.molecule.JOEBond;
37  import joelib.molecule.JOEMol;
38  
39  import joelib.util.JHM;
40  
41  import joelib.util.iterator.BondIterator;
42  
43  /*==========================================================================*
44   * IMPORTS
45   *==========================================================================*/
46  import java.io.IOException;
47  import java.io.InputStream;
48  import java.io.InputStreamReader;
49  import java.io.LineNumberReader;
50  import java.io.OutputStream;
51  
52  import java.util.Vector;
53  
54  import org.apache.log4j.Category;
55  
56  
57  /*==========================================================================*
58   * CLASS DECLARATION
59   *==========================================================================*/
60  
61  /**
62   * Atom representation.
63   */
64  public class HIN implements MoleculeFileType
65  {
66      //~ Static fields/initializers /////////////////////////////////////////////
67  
68      /*-------------------------------------------------------------------------*
69       * private static member variables
70       *-------------------------------------------------------------------------*/
71  
72      /**
73       *  Obtain a suitable logger.
74       */
75      private static Category logger = Category.getInstance("joelib.io.types.HIN");
76      private static final String description = new String("Hyperchem");
77      private static final String[] extensions = new String[]{"hin"};
78  
79      //~ Instance fields ////////////////////////////////////////////////////////
80  
81      private LineNumberReader lnr;
82      private PrintfStream ps;
83      private boolean forceUnixStyle = true;
84      private int moleculeEntry = 1;
85  
86      //~ Constructors ///////////////////////////////////////////////////////////
87  
88      /*-------------------------------------------------------------------------*
89       * constructor
90       *-------------------------------------------------------------------------*/
91      public HIN()
92      {
93          if (logger.isDebugEnabled())
94          {
95              logger.debug("Initialize " + this.getClass().getName());
96          }
97      }
98  
99      //~ Methods ////////////////////////////////////////////////////////////////
100 
101     /**
102      *  Description of the Method
103      *
104      * @exception  IOException  Description of the Exception
105      */
106     public void closeReader() throws IOException
107     {
108         lnr.close();
109     }
110 
111     /**
112      *  Description of the Method
113      *
114      * @exception  IOException  Description of the Exception
115      */
116     public void closeWriter() throws IOException
117     {
118         ps.close();
119     }
120 
121     public void initReader(InputStream is) throws IOException
122     {
123         lnr = new LineNumberReader(new InputStreamReader( /*(ZipInputStream)*/
124                     is));
125     }
126 
127     /**
128      *  Description of the Method
129      *
130      * @param  os               Description of the Parameter
131      * @exception  IOException  Description of the Exception
132      */
133     public void initWriter(OutputStream os) throws IOException
134     {
135         ps = new PrintfStream(os);
136     }
137 
138     /*-------------------------------------------------------------------------*
139      * public static methods
140      *-------------------------------------------------------------------------*/
141     public String inputDescription()
142     {
143         return description;
144     }
145 
146     public String[] inputFileExtensions()
147     {
148         return extensions;
149     }
150 
151     public String outputDescription()
152     {
153         return description;
154     }
155 
156     public String[] outputFileExtensions()
157     {
158         return extensions;
159     }
160 
161     /**
162      *  Reads an molecule entry as (unparsed) <tt>String</tt> representation.
163      *
164      * @return                  <tt>null</tt> if the reader contains no more
165      *      relevant data. Otherwise the <tt>String</tt> representation of the
166      *      whole molecule entry is returned.
167      * @exception  IOException  typical IOException
168      */
169     public String read() throws IOException
170     {
171         StringBuffer molecule = new StringBuffer(10000);
172         String delimiter = "endmol";
173         String line;
174 
175         while ((line = lnr.readLine()) != null)
176         {
177             if ((line.length() > 0) && (line.charAt(0) == delimiter.charAt(0)) &&
178                     (line.indexOf(delimiter) != -1))
179             {
180                 molecule.append(line);
181                 molecule.append(JHM.eol);
182 
183                 break;
184             }
185 
186             molecule.append(line);
187             molecule.append(JHM.eol);
188         }
189 
190         if (line == null)
191         {
192             return null;
193         }
194         else
195         {
196             return molecule.toString();
197         }
198     }
199 
200     /**
201      *  Description of the Method
202      *
203      * @param  mol                      Description of the Parameter
204      * @return                          Description of the Return Value
205      * @exception  IOException          Description of the Exception
206      * @exception  MoleculeIOException  Description of the Exception
207      */
208     public synchronized boolean read(JOEMol mol)
209         throws IOException, MoleculeIOException
210     {
211         return read(mol, null);
212     }
213 
214     /**
215      *  Loads an molecule in MDL SD-MOL format and sets the title. If <tt>title
216      *  </tt> is <tt>null</tt> the title line in the molecule file is used.
217      *
218      * @param  mol                      Description of the Parameter
219      * @param  title                    Description of the Parameter
220      * @return                          Description of the Return Value
221      * @exception  IOException          Description of the Exception
222      * @exception  MoleculeIOException  Description of the Exception
223      */
224     public synchronized boolean read(JOEMol mol, String title)
225         throws IOException, MoleculeIOException
226     {
227         // Right now only read in the first molecule
228         String line;
229         Vector tmpV = new Vector();
230         JOETypeTable.instance().setFromType("XYZ");
231 
232         while (((line = lnr.readLine()) != null) &&
233                 (line.startsWith("mol") == false))
234         {
235             if (line == null)
236             {
237                 return false;
238             }
239         }
240 
241         if (line == null)
242         {
243             return false;
244         }
245 
246         //System.out.println(line);
247         JHM.tokenize(tmpV, line, " \t\r\n");
248 
249         if (tmpV.size() > 2)
250         {
251             // there seems to be a molecule title
252             // set molecule title
253             if (title == null)
254             {
255                 mol.setTitle((String) tmpV.get(2));
256             }
257             else
258             {
259                 mol.setTitle(title);
260             }
261         }
262 
263         // start reading atom informations
264         mol.beginModify();
265 
266         int atomLine = 1;
267         JOEAtom atom;
268         JOETypeTable.instance().setToType("INT");
269 
270         double x;
271         double y;
272         double z;
273         int bo;
274         int max;
275         int end;
276 
277         while (((line = lnr.readLine()) != null) &&
278                 (line.startsWith("endmol") == false))
279         {
280             //System.out.println(line);
281             if (line == null)
282             {
283                 throw new MoleculeIOException("Missing 'endmol' tag.");
284             }
285 
286             //Don't really know how long it'll be
287             JHM.tokenize(tmpV, line, " \t\r\n");
288 
289             if (tmpV.size() <= 11)
290             {
291                 skipReaderEntry();
292                 throw new MoleculeIOException("Corrupted atom line " +
293                     atomLine + ".");
294             }
295 
296             try
297             {
298                 atom = mol.newAtom();
299                 atom.setAtomicNum(JOEElementTable.instance().getAtomicNum((String) tmpV.get(
300                             3)));
301                 x = Double.parseDouble((String) tmpV.get(6));
302                 y = Double.parseDouble((String) tmpV.get(7));
303                 z = Double.parseDouble((String) tmpV.get(8));
304                 atom.setVector(x, y, z);
305                 atom.setType(JOETypeTable.instance().translate((String) tmpV.get(
306                             3)));
307 
308                 // resolve bond informations
309                 max = 11 + (2 * Integer.parseInt((String) tmpV.get(10)));
310 
311                 for (int i = 11; i < max; i += 2)
312                 {
313                     switch (((String) tmpV.get(i + 1)).charAt(0))
314                     {
315                     case 's':
316                         bo = 1;
317 
318                         break;
319 
320                     case 'd':
321                         bo = 2;
322 
323                         break;
324 
325                     case 't':
326                         bo = 3;
327 
328                         break;
329 
330                     case 'a':
331                         bo = 5;
332 
333                         break;
334 
335                     default:
336                         bo = 1;
337 
338                         break;
339                     }
340 
341                     end = Integer.parseInt((String) tmpV.get(i));
342 
343                     //          System.out.println(
344                     //            "add bond: " + mol.numAtoms() + " " + end);
345                     // add only bonds, where inverse does not exists
346                     if (mol.existsBond(end, mol.numAtoms()) == false)
347                     {
348                         mol.addBond(mol.numAtoms(), end, bo);
349                     }
350                 }
351             }
352              catch (Exception ex)
353             {
354                 skipReaderEntry();
355                 throw new MoleculeIOException("Error in atom line " + atomLine +
356                     ": " + ex.getMessage());
357             }
358 
359             atomLine++;
360         }
361 
362         if (line == null)
363         {
364             throw new MoleculeIOException("Missing 'endmol' tag.");
365         }
366 
367         mol.endModify();
368 
369         return (true);
370     }
371 
372     public boolean readable()
373     {
374         return true;
375     }
376 
377     public void resetMoleculeEntryNumber()
378     {
379         moleculeEntry = 1;
380     }
381 
382     /**
383      *  Description of the Method
384      *
385      * @return                  Description of the Return Value
386      * @exception  IOException  Description of the Exception
387      */
388     public boolean skipReaderEntry() throws IOException
389     {
390         String line;
391 
392         while ((line = lnr.readLine()) != null)
393         {
394             if ((line.length() > 0) && (line.charAt(0) == 'e') &&
395                     (line.indexOf("endmol") != -1))
396             {
397                 break;
398             }
399         }
400 
401         return true;
402     }
403 
404     /**
405      *  Description of the Method
406      *
407      * @param  mol              Description of the Parameter
408      * @return                  Description of the Return Value
409      * @exception  IOException  Description of the Exception
410      */
411     public boolean write(JOEMol mol) throws IOException
412     {
413         return write(mol, null);
414     }
415 
416     /**
417      *  Description of the Method
418      *
419      * @param  mol              Description of the Parameter
420      * @param  title            Description of the Parameter
421      * @return                  Description of the Return Value
422      * @exception  IOException  Description of the Exception
423      */
424     public boolean write(JOEMol mol, String title) throws IOException
425     {
426         int i;
427         PrintfFormat f8_5 = new PrintfFormat("%8.5f");
428         PrintfFormat s3 = new PrintfFormat("%-3s");
429 
430         ps.print("mol ");
431         ps.print(moleculeEntry);
432         ps.print(" ");
433 
434         if (title == null)
435         {
436             ps.print(mol.getTitle());
437         }
438         else
439         {
440             ps.print(title);
441         }
442 
443         if (forceUnixStyle)
444         {
445             ps.print('\n');
446         }
447         else
448         {
449             ps.println();
450         }
451 
452         JOETypeTable.instance().setFromType("INT");
453         JOETypeTable.instance().setToType("XYZ");
454 
455         JOEAtom atom;
456 
457         for (i = 1; i <= mol.numAtoms(); i++)
458         {
459             atom = mol.getAtom(i);
460 
461             //      ps.printf(
462             //        s3,
463             //        JOEElementTable.instance().getSymbol(atom.getAtomicNum()));
464             //      ps.printf(f15_5, atom.getZ());
465             //      ps.println();
466             ps.print("atom ");
467             ps.print(i);
468             ps.print(" - ");
469             ps.printf(s3,
470                 JOEElementTable.instance().getSymbol(atom.getAtomicNum()));
471             ps.print(" **  - ");
472             ps.printf(f8_5, atom.getX());
473             ps.print(' ');
474             ps.printf(f8_5, atom.getY());
475             ps.print(' ');
476             ps.print(' ');
477             ps.printf(f8_5, atom.getZ());
478             ps.print(' ');
479             ps.print(' ');
480             ps.printf(f8_5, atom.getPartialCharge());
481             ps.print(' ');
482             ps.print(atom.getValence());
483             ps.print(' ');
484 
485             BondIterator bit = atom.bondIterator();
486             JOEBond bond;
487             char bondCharacter;
488 
489             while (bit.hasNext())
490             {
491                 bond = bit.nextBond();
492 
493                 switch (bond.getBO())
494                 {
495                 case 1:
496                     bondCharacter = 's';
497 
498                     break;
499 
500                 case 2:
501                     bondCharacter = 'd';
502 
503                     break;
504 
505                 case 3:
506                     bondCharacter = 't';
507 
508                     break;
509 
510                 case 5:
511                     bondCharacter = 'a';
512 
513                     break;
514 
515                 default:
516                     bondCharacter = 's';
517 
518                     break;
519                 }
520 
521                 ps.print(bond.getNbrAtom(atom).getIdx());
522                 ps.print(' ');
523                 ps.print(bondCharacter);
524                 ps.print(' ');
525             }
526 
527             if (forceUnixStyle)
528             {
529                 ps.print('\n');
530             }
531             else
532             {
533                 ps.println();
534             }
535         }
536 
537         ps.print("endmol ");
538         ps.print(moleculeEntry);
539 
540         if (forceUnixStyle)
541         {
542             ps.print('\n');
543         }
544         else
545         {
546             ps.println();
547         }
548 
549         moleculeEntry++;
550 
551         return (true);
552     }
553 
554     public boolean writeable()
555     {
556         return true;
557     }
558 }
559 ///////////////////////////////////////////////////////////////////////////////
560 //  END OF FILE.
561 ///////////////////////////////////////////////////////////////////////////////